我按照教程创建了一个自定义 Zend_form_element 以获得一些自定义输入数据。一切都或多或少没问题,它显示正确等等。我需要做的是在我显示要更新的表单或在未通过验证时显示表单时填充它。这是我的自定义元素的代码:
class ZC_Form_Element_TabellaRendite
extends Zend_Form_Element_Xhtml
{
public $helper = "tabellaRenditeElement";
private $_data;
// the second paramater was added by me, i'll explain why below
function __construct($spec, $data = null){
$this->_data = $data;
parent::__construct($spec);
}
public function setValue() {
}
public function getValue() {
return $this->_data;
}
}
这是辅助功能
class ZC_View_Helper_TabellaRenditeElement
extends Zend_View_Helper_FormElement
{
protected $html = '';
public function tabellaRenditeElement ($name, $value=null, $attribs = null){
//Here the $attribs are correctly the $specs i passed, the $value only has some value because of the workaround i explain below
$helper = new Zend_View_Helper_FormText();
$helper->setView($this->view);
fb($value, 'value in ');
fb($name, 'name');
$options = array('class'=> 'somma','size'=> 4);
$optionsReadonly = array('readonly' => 1, 'class'=> 'totale', 'size'=> 4);
if (!$attribs['modificabile']){
$options['readonly'] = 1;
}
$this->html .= "
<table class='display datatablesRendite' id='tableRendite' style='border:1px solid;'>
<thead>
<tr bgcolor='#B8D3E8'>
<th>RENDITA da LOCAZIONI (canone di locazione - manutenzione)</th>
<th>Importo</th>
</tr>
</thead>
<tbody>";
$this->html .= '<tr>';
$this->html .= '<td>LOCALI COMMERCIALI - IMPIANTI SPORTIVI</td>';
$this->html .= '<td>';
$this->html .= $helper->formText("renditaImpianti",$value['renditaImpianti'], $options);
$this->html .= '</td>';
$this->html .= '</tr>';
$this->html .= '<tr>';
$this->html .= '<td>LOCALI COMMERCIALI - AGGIUNTI (servizio di ristorazione)</td>';
$this->html .= '<td>';
$this->html .= $helper->formText("renditaAggiunte", $value['renditaAggiunte'], $options);
$this->html .= '</td>';
$this->html .= '</tr>';
$this->html .= '</tbody></table>';
return $this->html;
}
}
我对 zend_framework 完全陌生,这显然是错误的,正如您所见,我在元素的 __construct 中添加了第二个名为 data 的参数:我这样做是因为当我创建表单并传递数据以填充它时,我不知道如何将其传递给助手。因此,我提出了将数据直接传递给构造函数中的自定义 zend_form_element 的解决方法,并且(我不知道为什么)它可以工作。
这意味着如果我这样做
$form = new My_Form();
$form->populate($data);
或者
$form = new My_Form();
$form->isValid($_POST);
帮助程序中的 $value 为空。
因此,在表单的 init() 函数中,我将 $data 传递给自定义元素,如下所示:
$myCustomElement = new My_custom_element($specs, $data);
我将数据传递给创建时的表单
$form = new My_Form($data);//this way i pass the data to populate custom elements
$form->populate($data);//this way i populate all the standard elements
isValid() 也一样
$form = new My_Form($_POST);//this way i pass the data to populate custom elements
$form->isValid($_POST);//this way i populate all the standard elements
这样一切正常,但我确信这是非常错误的:我的老板终于给了我半天的时间来重构代码,所以我想用 $form->populate() 和 $ 填充自定义和标准字段表单->isValid()。
PS也许我做错了一切,这不是做我想做的事情的正确方法:随时指出正确的方法,我是框架的新手,我没有时间完全理解它。