user3209287
user3209287

Reputation: 219

How to validate user must choose at least one value radio button in CakePHP?

I have a code in view file about radio button (CakePHP) :

echo $this->Form->input('publish_flg', array(
                'type' => 'radio',
                'div' => false,
                'label' => false,
                'fieldset' => false,
                'legend' => false,
                'hiddenField' => false,
                'required' => false,
                'separator'=> '</div><div class="radio-inline">',
                'before' => '<div class="radio-inline">',
                'after' => '</div>',
                'options' => array(1 => 'Yes', 0=> 'No'),
                'error' => array(
                    'attributes' => array('wrap' => 'div', 'class' => 'alert alert-danger', 'escape' => 'false')
                )
            ));

Now I want user must check at least one value in radio button, but both validate I write in model also not successfull :

Solution 1 (It always return message error both I check or not check radio button)

public $validate = array(
     'publish_flg' => array(
         'notEmpty' => array(
            'required' => true,
            'message' => 'ERROR VALIDATE'
          )
      )
);

Solution 2 (It not validate, then if I don't check any radio button, it also submit data to database)

public $validate = array(
         'publish_flg' => array(
                'rule' => 'notEmpty',
                'message' => 'ERROR VALIDATE'
              )
    );

Can anyone give me a solution for this ? , thanks.

In controller, I don't use $this->Model->save() to validate, I used $this->Model->validates(), is it wrong ?

Upvotes: 1

Views: 912

Answers (1)

Arno
Arno

Reputation: 1253

notEmpty validation should work, but you could also try inList, since you specify the values to be either 0 for No and 1 for Yes in the FormHelper.

If you're not sure about your syntax, you could always try to bake the model and create the validation rules that way.

Upvotes: 0

Related Questions