1

バリデーターを使用してZend_Form_Element_Textを拡張するカスタムフォーム要素を作成しようとしています(したがって、特定の要素を使用するときにバリデーターを設定し続ける必要はありません)。とにかく、メインフォームでインスタンス化するときに$maxChars変数を渡すのに問題があります。以下に短縮コードを提供しました

これは以下の私のカスタム要素です

class My_Form_Custom_Element extends Zend_Form_Element_Text
{

public $maxChars

public function init()
{
    $this->addValidator('StringLength', true, array(0, $this->maxChars))
}

public function setProperties($maxChars)
{
    $this->maxChars= $maxChars;
}
}

ここで、カスタムフォーム要素をインスタンス化します。

class My_Form_Abc extends Zend_Form
{
public function __construct($options = null)
{
    parent::__construct($options);
    $this->setName('abc');

    $customElement = new My_Form_Custom_Element('myCustomElement');
    $customElement->setProperties(100); //**<----This is where i set the $maxChars**

    $submit = new Zend_Form_Element_Submit('submit');
    $submit ->  setAttrib('id', 'submitbutton');

    $this->addElements(array($customElement ,$submit));
}
}

フォームで$customElement->setProperties(100)を使用して「100」を渡そうとすると、StringLengthバリデーターに正しく渡されません。バリデーターがInitで呼び出されているからだと思いますか?どうすればこれを修正できますか?

4

1 に答える 1

0

init()要素を作成するときに呼び出されるので、呼び出す前にsetProperties()$maxCharsは設定されません。

私は2つの解決策を見ます:

1-削除してメソッドinit()に移動addValidator()setProperties()ます:

public function setProperties($name, $value)
{
    switch( $name ) {
        case 'maxChars':
            $this->addValidator('StringLength', true, array(0, $value));
            break;
    }
    return $this;
}

2-で行ったことを実行しますinit()-render()要素は最後にレンダリングされます。

public function render()
{
    $this->addValidator('StringLength', true, array(0, $this->maxChars))
    return parent::render();
}

私は最初がより良いものだと思います。

于 2010-04-22T09:29:17.347 に答える