Search code examples
phpyii2custom-validatorsyii2-basic-app

Custom Validation Not Working- Yii2-app-basic-Yii2


I Posted one question yesterday regarding custom validation for radio button Textfield Mandatory On Radio Button. I got answer. But, that was not exact answer. But, it solved one problem of mine.

Actually, I've 2 radio button.

  • Individual
  • Firm

When, Radio Button having "Individual" value is selected, CompanyName textbox should not be mandatory. But, when Radio Button having "Firm" value is selected, CompanyName textbox should be mandatory.

Now what happening is, When i select radio button 'Firm' and not filling any value for CompanyName textbox, data is not inserting in database table. FINE. Which is OK. But, Error message is not displaying in form. Error message should be displayed as CompanyName Textbox is mandatory after selecting Radio Button Firm.

I'm not getting where i'm doing mistake. Here is my View, Controller And Model Code. Please Help me.

register.php (VIEW)

<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;
use yii\bootstrap\Modal;
use yii\helpers\Url;
?>

<?php $form = ActiveForm::begin(['id' => 'register-form']); ?>
    .
    .
    .
    <?= $form->field($model, 'AdminType')
            ->radioList(array('Individual'=>'An Individual', 'Firm'=>'Firm/Company'))
            ->label('Are You')?>
    <?= $form->field($model, 'CompanyName')->textInput()->label('Company Name')->error() ?>
    .
    .
<?php ActiveForm::end(); ?>

SiteController.php (CONTROLLER)

<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;
use app\models\RegisterForm;

public function actionRegister()
{
    // Register Model
    $model = new RegisterForm();
    if ($model->load(Yii::$app->request->post())) 
    {
        $post = Yii::$app->request->post('RegisterForm');
        if ($model->validate())
        {

        }
        else
        {
            // HERE YOU CAN PRINT THE ERRORS OF MODEL
            echo "<pre>";
            print_r($model->getErrors());
            echo "</pre>";
        }
        return $this->refresh();
    }

}

RegisterForm.php (MODEL)

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use kartik\password\StrengthValidator;


class RegisterForm extends Model
{
    public $fname;
    public $lname;
    public $email;
    public $password;
    public $confirmPassword;
    public $AdminType;
    public $CompanyName;
    public $verifyCode;

    public function rules()
    {
        return [
                [['fname','lname', 'email', 'password','confirmPassword','verifyCode','AdminType'], 'required'],
                ['email', 'email'],
            ['confirmPassword', 'compare', 'compareAttribute' => 'password'], 
                ['verifyCode', 'captcha'],

        //add rule that uses the validator function
                ['AdminType','radioValidator'],
        ];
    }

    //implement the validator
    public function radioValidator($attribute)
    {
        if($this->$attribute === 'Firm')
            return $this->addError('CompanyName', 'Company Name cannot be blank');
    }
}

Solution

  • Atlast, i got my answer

         //company_name
          ['company_name', 'required', 'when' => function($model){
            return ($model->user_type == 'Firm' ? true : false);
          }, 'whenClient' => "function (attribute, value) {
              return $('input[type=\"radio\"][name=\"Users[user_type]\"]:checked').val() == 'Firm';
          }"],