Textfield Mandatory On basis of radio button selection- Yii2

和自甴很熟 提交于 2020-01-05 02:03:08

问题


I'm having radio button with two value i.e, Individual and Firm. I am looking for one scenario where if radio button having value Firm is selected, then CompanyName textinput should act as mandatory (required) field. And, when radio button having value Individual is selected, Then CompanyName textinput should act as Optional field.

I was not getting how to do it. I tried to add addAttribute in CompanyName textinput as mandatory. but it didn't worked as RegisterForm.php (model) is having few rules specified.

So, any idea how to do it. I'm not getting. Any help ?

register.php (view)

<?php $form = ActiveForm::begin(['id' => 'register-form']); ?>
    .
    .
    .
    <?= $form->field($model, 'AdminType')
            ->radioList(array('Individual'=>'An Individual', 'Firm'=>'Firm/Company/Group of Employees'))
            ->label('Are You')?>
    <?= $form->field($model, 'CompanyName')->textInput()->label('Company Name') ?>
    <div class="form-group">
        <?= Html::submitButton('Register', ['class' => 'btn btn-success', 'name' => 'register-button' ]) ?>
    </div>
<?php ActiveForm::end(); ?>

<script>
    $('input[type="radio"]').click(function()
    {
        if($(this).attr("value")=="Firm")
        {
            $('#registerform-companyname').addAttribute("required");
        }
    });
</script>

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'],
        ];
    }

回答1:


First of all, having any kind of front end validation is BAD, as i can circumvent it by generating a post programmatically, and it will save the record without any problems, making a possibility of inconsistent records a reality.

What you want to do instead is create a custom validation rule function in your model, as well as add the rule to the validation array:

<?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, $params)
    {
        if($this->$attribute === 'Firm' && empty($this->$attribute))
            $this->addError('CompanyName', 'CompanyName cannot be blank');
    }
}
?>

Now your field generating code should look like this

 <?= $form->field($model, 'CompanyName')->textInput()->label('Company Name')->error() ?>

Hope this helps you

Edit: As I am used to working with AR classes(which generally, when generated with gii, have validation automatically ), it did not cross my mind that you are using just a form model ( the one that was given as an example in the basic app)

forget the ->error() in the field, also make sure you have the row

if ($model->load(Yii::$app->request->post()) && $model->validate()) {...}

in your action




回答2:


At last I Got,

 ['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';
  }"],


来源:https://stackoverflow.com/questions/32956293/textfield-mandatory-on-basis-of-radio-button-selection-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!