开发者

set the attributes in PHP 5

开发者 https://www.devze.com 2023-02-12 02:42 出处:网络
In my Zend framework I have two row one rows contains state dropdown with label state and the other contains a text box with label other state. Below is the code:

In my Zend framework I have two row one rows contains state dropdown with label state and the other contains a text box with label other state. Below is the code:

'state' => array('select', array(
            'required' => true,
            'decorators' => $elementDecorators,
            'label' => 'State:'开发者_运维百科,
            'multiOptions' => $values["state"] 
        )),
        'other_state' => array('text', array(
            'required' => true,
            'filters'    => array('StringTrim'),
            'decorators' => $elementDecorators,
            'label' => 'Other State:',
            'class' => 'other_state', 
        ))

Here the other state is set as required. I need it required only when the user select "Other" value from the state drop down.


Client Side:

jQuery solution:

Showing your HTML output would have been a help here. But the following will add the attribute required if other is selected - this will also enable the input and disable it so the user can only enter something in other state, if they select other:

$("#state").change(function(){
    if ($(this).val() == "other"){
        $("#other_state").removeAttr("disabled");
        $("#other_state").attr("required", "required");
    }
    else {
        $("#other_state").removeAttr("required");
        $("#other_state").attr("disabled", "true");
    }
});

See a demo here

The above will do the validation on the clients side - with jQuery, however if the user has javascript turned off, it would allow the user to select other and leave other_state blank!


Server Side:

Zend solution:

What you should also do is add some validation to the zend_form. However, you can't add them the normal way - if you added a validator to say other_state can't be empty - you would have an error when a state is selected and you want it to be empty.

In your form class you could override the isValid call to add your custom validation, see the discussion here: There is another example on how to do this here

    /** 
    /* override the isValid function of Zend_Form 
    /* to set a required field based on a condition 
     */ 

    public function isValid($value) {
            // Check the key exists in the stack, and if its set to other: 
            if (array_key_exists('state', $value) && $value['state'] == 'other') { 
                    // It is so make sure other_state is a required field:
                    $this->other_state->setRequired(true); 
            } 
            parent::isValid($value); 
    } 
0

精彩评论

暂无评论...
验证码 换一张
取 消