Search code examples
phpzend-frameworkzend-formzend-form-element

Need a Zend_Form_Element that only stores a value


I have an array of options for a select list.

$options = array( 1=>'Option1', 2=>... );

But if I only have one option, I rather want either:

  1. A hidden <input type="hidden" name="opt" value="2"/> with a validator requiring the posted value to be 2

  2. No output. The value will only be stored in the form_element/form until requested by $form->getValues()

This code is a non-working example of what I want: ($this is a Zend_Form object)

$first_val = reset(array_keys($options));

if( count($options) > 1 )
    $this->addElement('select', 'opt', array(
        'multiOptions' => $options,
        'label' => 'Options',
        'value' => $first_val,              
        'required' => true ));
else
    $this->addElement('hidden', 'opt', array(
        'required' => true,
        'value' => $first_val ));

However, the value will not validate to $first_val. Anyone may change the hidden value, allowing them to inject invalid values. This is not acceptable.

Help?


Solution

  • I created a custom Zend_Form_Element that does exactly what I want. Maybe someone else might find it useful:

    <?php
    require_once 'Zend/Form/Element.php';
    
    /**
    * Class that will automatically validate against currently set value.
     */
    class myApp_Element_Stored extends Zend_Form_Element
    {
        /**
         * Use formHidden view helper by default
         * @var string
         */
        public $helper = 'formHidden';
    
        /**
         * Locks the current value for validation
         */
        public function lockValue()
        {
            $this->addValidator('Identical', true, (string)$this->getValue());
            return $this;
        }
    
        public function isValid($value, $context = null)
        {
            $this->lockValue();
            return parent::isValid($value, $context);
        }
    }
    ?>