2010-04-22 141 views
1

我试图创建一个自定义表单元素,它使用验证器来扩展Zend_Form_Element_Text(所以我不必在使用某些元素时继续设置验证器)。无论如何,当我在我的Main窗体中实例化时,我无法将$ maxChars变量传递给它。我在下面提供将变量传递给自定义Zend表单元素

我缩短代码这是低于

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

当我试图通过 '100' 使用$ customElement-> setProperties方法(100),它没有得到正确传递给我的StringLength校验。我认为这是因为验证器在Init中被调用?我怎样才能解决这个问题?

回答

0

init()当你创建一个元素时被调用,所以在你调用setProperties()之前,你的$maxChars没有被设置。

我看到两个解决方案:

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

我觉得第一个比较好。

+0

谢谢队友,我不知道为什么我没有想到第一个解决方案。第二种解决方案对我而言虽然是新东西,但它们都运行良好。干杯=) – user322003 2010-04-22 09:45:39

相关问题