1

「あなたはMr./Mrs。ですか?」というフォームがあると想像してみてください。回答値に応じて、さらに検証を実装します。

たとえば、Mr>お気に入りの車のモデルを検証するMrs>お気に入りの花を検証する

isValid機能を上書きしても大丈夫ですか?たぶん、ベストプラクティスのいくつかの例ですか?

4

1 に答える 1

1

カスタムバリデーターを作成し、提供された$context変数を使用します。

簡単な例

コントローラ

class MyController extends Zend_Controller_Action {
    public function indexAction() {
        $form = new Application_Form_Gender();
        $this->view->form = $form;

        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                /*...*/
            }
        }
    }
}

class Application_Form_Gender extends Zend_Form {

    public function init()
    {
        $this->addElement('radio', 'radio1', array('multiOptions' => array('m' => 'male', 'w' => 'female')));
        $this->getElement('radio1')->isRequired(true);
        $this->getElement('radio1')->setAllowEmpty(false);

        $this->addElement('text', 'textm', array('label' => 'If you are male enter something here');
        $this->getElement('textm')->setAllowEmpty(false)->addValidator(new MyValidator('m'));

        $this->addElement('text', 'textf', array('label' => 'If you are female enter something here'));     
        $this->getElement('textf')->setAllowEmpty(false)->addValidator(new MyValidator('f'));

        $this->addElement('submit', 'submit');
    }

バリデーター

class MyValidator extends Zend_Validate_Abstract {
    const ERROR = 'error';
    protected $_gender;
    protected $_messageTemplates = array(
        self::ERROR      => "Your gender is %gender%, so you have to enter something here",
    );
    protected $_messageVariables = array('gender' => '_gender');

    function __construct($gender) {
        $this->_gender = $gender;
    }

    function isValid( $value, $context = null ) {
        if (!isset($context['radio1'])) {
            return true;
        }
        if ($context['radio1'] != $this->_gender) {
            return true;
        }
        if (empty($context[sprintf('text%s', $this->_gender)])) {
            $this->_error(self::ERROR);
            return false;
        }
        return true;
    }
}

この例でわかるように、で提供されるすべてのデータは変数を$form->isValid()介して利用可能に$contextなり、それを使用して任意のチェックを実行できます。

于 2012-07-31T17:28:50.527 に答える