I want to display a Zend Form with one of the elements shown as disabled. I'm setting the value so the user can see it, but I want to disable it so the user can't edit it. This may also involve 开发者_高级运维some sort of css/javascript to ensure that it looks like, and is not editable by the user. This is my element:
$this->addElement('text', 'username', array(
'label' => 'Username:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
array('StringLength', false, array(2, 50))
)
));
You should be able to use:
$this->username->setAttrib('disabled', 'disabled');
I think you can as well:
$this->addElement('text', 'username', array(
'label' => 'Username:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
array('StringLength', false, array(2, 50))
),
'attribs' => array('disabled' => 'disabled')
));
This works fine... Just to complete the help: If you are in a controller you can do:
$form->selRole->setAttribs(array('disable' => 'disable'));
selRole is the name of a select field
In latest zf2.2.1 you can do this in your controller;
$form->get('username')->setAttributes(array(
'disabled' => 'disabled',
));
$form->getElement("username")->setAttribs(array('disabled' => 'disabled', ));
or
$form->getElement("username")->setAttrib('disabled', 'disabled');
$var->setAttribs(array('disabled' => 'disabled'));
Apply this code into your Application
$formelement->setAttrib('readonly', 'true');
$formelement->setAttrib('style', 'pointer-events: none');
Only this was working for me, when using a file element
when setting after form was submitted:
$element->setValueDisabled(true);
// disable checkbox using JS add-on
$checkbox->setAttribute('onclick', 'return false');
Benefit: retains the original color of the box but does not let the user change the value of the box.
Using disabled
method of other answers changes the color of checkbox to "grayed out". Method described here, does not.
@Dennis:
Disabling Javascript is enough to enable the form again, so you can't truly rely on Javascript. Using native HTML disables it better, but is also simply worked around, by removing the disabled attribute.
Best option is showing the values you want instead of the form itself and disable the form and/or it's elements.
Wish I could add the comment directly to your post, but I'm some rep short.
精彩评论