PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 4, 2022

[FIXED] Validation with scenario not working Yii 2

 March 04, 2022     php, yii, yii2     No comments   

Issue

The idea here is to insert in two different tables parameters using SCENARIO, first register the customer with their parameters and then register the order that belongs to a customer, all in just one form.

I'm sending a form with several parameters, some will be used in the insertion of a customer using scenario, and the other parameters I will use in order (I did this so I do not have to create two forms) the parameters are being correctly sent through POST together with the csrf.

public function createOrder()
{
    //$customer = Customer::find()->where(['email' => $params->email])->limit(1)->asArray()->all();
    $customer = new Customer;
    $customer->load(Yii::$app->request->post());
    $customer->scenario = 'create';
    if($customer->validate()){
        $customer->save();
        vdp($customer);
    } else{
        vdpd($customer->getErrors());
    }

    die;

}

This returns me an array saying that the Name, email, address, cell, phone, city, etc parameters can not be left blank.

In my customer model:

const SCENARIO_CREATE = 'create';

public function scenarios()
{
    $scenarios = parent::scenarios();
    $scenarios[self::SCENARIO_CREATE] = ['name', 'email', 'public_place', 'cell_phone', 'phone', 'city', 'cep', 'state', 'neighborhood', 'number', 'complement'];
    return $scenarios;
}

Solution

Controller

public function actionCreateOrder()
{
   $customer = new Customer;
   $customer->setScenario(Customer::SCENARIO_CREATE);
   if($customer->load(Yii::$app->request->post())
      if($customer->save()){
          vdp($customer);
      } else {
          vdpd($customer->getErrors());
      }
   }
   die;
}

MODEL

const SCENARIO_CREATE = 'create';

public function rules()
{
    return [
       [['name', 'email', 'address'], 'required', 'on' => self::SCENARIO_CREATE], // Add more required fields on 'create' scenario.
       ... // some more rules
    ];
}

public function scenarios()
{
    $scenarios = parent::scenarios();
    $scenarios[self::SCENARIO_CREATE] = ['name', 'email', 'public_place', 'cell_phone', 'phone', 'city', 'cep', 'state', 'neighborhood', 'number', 'complement'];
    return $scenarios;
}


Answered By - Insane Skull
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing