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
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.