开发者

Need a Zend_Form_Element that only stores a value

开发者 https://www.devze.com 2023-03-29 12:15 出处:网络
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:

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(
        'multiOpti开发者_如何学运维ons' => $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?


your code is missing a validator, e.g. Zend_Validate_Identical


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);
    }
}
?>
0

精彩评论

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