Jsparo30
Jsparo30

Reputation: 405

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?

Upvotes: 0

Views: 14930

Answers (2)

Sohel Ahmed Mesaniya
Sohel Ahmed Mesaniya

Reputation: 3450

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_model, '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 input are in same one form.

Upvotes: 4

Naisa purushotham
Naisa purushotham

Reputation: 913

Use enableClientValidation to validate those fields

$form = ActiveForm::begin([
    'id' => 'register-form',
    'enableClientValidation' => true,
    'options' => [
        'validateOnSubmit' => true,
        'class' => 'form'
    ],
])

Upvotes: 2

Related Questions