在不起作用的情况下进行验证Yii 2

时间:2018-06-23 22:09:26

标签: php yii yii2

这里的想法是使用SCENARIO在两个不同的表中插入参数,首先使用其参数注册客户,然后以一种形式注册属于客户的订单。

我正在发送带有多个参数的表单,其中一些将用于插入使用场景的客户,而其他参数将按顺序使用(我这样做是为了不必创建两个表单)参数已通过POST与csrf一起正确发送。

.col-md-6
  .form-group
    span.smart-form
      input :name=="fieldName('owner_type')" type="hidden" value="trainer"
      label.toggle
        input :id=="fieldId('owner_type_toggle')" type="checkbox" value="client"
        i data-swchon-text="Trainer" data-swchoff-text="Client"
        span My Location
    span.smart-form style="margin-left: 9px; font-size: 15px; color: #404040;"
      input :name=="fieldName('owner_type')" type="hidden" value="client"
        span Client (Onsite Training)

这将返回一个数组,说明名称,电子邮件,地址,手机,电话,城市等参数不能留空

在我的客户模型中:

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;

}

3 个答案:

答案 0 :(得分:1)

1)createOrder()应该在控制器中而不是模型中是actionCreateOrder()

2)

$customer->load(Yii::$app->request->post());
$customer->scenario = 'create';
if ($customer->validate()) {
...

应该是

$customer->scenario = Customer::SCENARIO_CREATE;
if ($customer->load(Yii::$app->request->post()) && $customer->validate()) { ... }

因为load方法将加载当前方案的属性,因此在加载模型之前无需运行验证。参见example

3)为Customer模型中的属性声明rules

答案 1 :(得分:1)

控制器

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;
}

模型

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;
}

答案 2 :(得分:0)

您需要在$scenario通话之前设置load()。方案定义了可以由load()设置的属性,因此您做得太迟了,它无效。试试这个:

$customer = new Customer;
$customer->scenario = 'create';
$customer->load(Yii::$app->request->post());
相关问题