Jsparo30 February 2016

How to add required field validation to custmizable field in YII2 (Advanced Template)?

I have an insert form for a specific model and the required fields validations are works well through rules function in that model. I want to add another field in the form from another table and give its required validation. How to do this?

Answers


SohelAhmedM February 2016

Consider following example

Contact.php // model1

...
class Contact extends Model
{
    public function rules()
    {
        return [
            ['contact_name', 'string', 'required'],
            // other attributes
        ];
    }
    ...

Users.php // model2

...
class Users extends Model
{
    public function rules()
    {
        return [
            ['user_name', 'string', 'required'],
            // other attributes
        ];
    }
    ...

ContactController.php

...
use \app\models\Users;
...
class ContactController extends Controller
{
    public function actionCreate()
    {
        $contact_model = new Contact;
        $users_model = new Users;
        if($contact_model->load(Yii::$app->request->post()) && $users_model->load(Yii::$app->request->post()))
        {
            // saving code
        }
        else
        {
            return $this->render('create', ['contact_model'=>$contact_model, 'users_model'=>$users_model]);
        }
    }
    ...

in views/contact/_form.php

...
<?php $form = ActiveForm::begin(); ?>

        <?= $form->field($contact_model, 'contact_name')->textInput(['maxlength' => 255]) ?>

        <?= $form->field($user_name, 'user_name')->textarea(['rows' => 6]) ?>

        <!-- other inputs here -->

        <?= Html::submitButton($contact_model->isNewRecord ? Yii::t('app', 'Create') 
            : Yii::t('app', 'Update'), ['class' => $contact_model->isNewRecord 
            ? 'btn btn-success' : 'btn btn-primary']) ?>

        <?= Html::a(Yii::t('app', 'Cancel'), ['article/index'], ['class' => 'btn btn-default']) ?>

<?php ActiveForm::end(); ?>
...

Here input from two different models get validated too, and make sure that both in

Post Status

Asked in February 2016
Viewed 3,217 times
Voted 8
Answered 1 times

Search




Leave an answer