How to disable a form element in a Zend Form?

Andrew picture Andrew · Nov 18, 2009 · Viewed 35.6k times · Source

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))
        )
    ));

Answer

smack0007 picture smack0007 · Nov 18, 2009

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')
));