0
votes

I have inserting data from activeForm in yii

<?php $form = ActiveForm::begin([
    'id'          => 'register-form',
    'options'     => ['class' => 'form-horizontal'],
    'fieldConfig' => [
        'template'     => "<div class=\"\">{label}{input}</div>\n<div class=\"col-lg-8\">{error}</div>",
        'labelOptions' => ['class' => 'col-lg-1 control-label'],
    ],
]);?>

<?= $form->field($model, 'firstname')->textInput(['placeholder' => 'First Name']) ?>
<?= $form->field($model, 'middlename')->textInput(['placeholder' => 'Middle Name']) ?>
<?= $form->field($model, 'lastname')->textInput(['placeholder' => 'Last Name']) ?>

Then i created a model and insert a data into db by createCommand

$db = Yii::$app->db->createCommand();
$db->insert('person', [..])->execute();

Here i have giving rules(required) for firstname and lastname. So middle name value coming as NULL

If i give required for middlename, Then value is stored in db. otherwise it is NULL

1
Could you show your model rules() array? - Pavel Bariev
Why you use a db createCommand and not a $modelSave() in a controller. Could you show the controller action related to your problem? - ScaisEdge
AFAIK $db->insert() will not use validation. You should use $model->save() or $model->validate(). Do it like it should be done. See here. - robsch
If i use $model->save(), It is showing id is not NULL Value. Im using id as auto increment in db - Deen

1 Answers

0
votes

You always need to have some validation rule for attribute you want to save via mass assignment. E.g. just add one more rule and your middlename will be saved:

public function rules()
{
    return [
         [['firstname', 'lastname'], 'required'],
         ['middlename', 'string'], // rule for middlename
    ];
}