我使用jquery动态创建一个文本框(基于用户选择)..有没有办法从zend形式提供该文本框的验证..?
答案 0 :(得分:2)
是的。
大多数学分转到jeremy kendall,请参阅http://www.jeremykendall.net/2009/01/19/dynamically-adding-elements-to-zend-form/
我解决它的方法是通过对一个动作执行jquery / ajax调用来添加一个表单元素,如:
$.ajax({
type : "POST",
url : "/<controller>/addfield/",
success : function(newElements) {
// Insert new element before the submit button
$("#productsNew-submit-element").before(newElements);
}
});
这样做是调用一个生成表单元素的动作并返回你可以添加的html
public function addfieldAction()
{
//use $ajaxContext = $this->_helper->getHelper('AjaxContext'); in the init to make it return html via ajax
$element = new Zend_Form_Element_Text("extraElement_1");
$element->setBelongsTo("yourForm");
$element->setLabel('myElementName');
/*
set other stuff like decorators or so
*/
//now create the html
$elements .= $element->__toString();
$this->view->fields = $elements;
}
之后,您将通过ajax
在表单中获得一个新元素现在,当您提交时,您必须再次执行此操作,然后进行预验证
public function saveAction()
{
function findFields($field) {
// return field names that include 'extraElement_'
if (strpos($field, 'extraElement_') !== false) {
return $field;
}
}
//set all stuff you need especially the form
if($this->getRequest()->isPost()) {
$postValues = $this->getRequest()->getPost();
//step 1
$extraFields = array_filter(array_keys(current($postValues)), 'findFields');
//add the element before validation
if(count($extraFields) !== 0) {
foreach(extraFields as $extraField) {
$this->addFields($postValues[$extraField]); <-- step 2 add the field(s)
}
}
//step 3 validate
if($this->_form->isValid($postValues)) {
//do post validation stuff
} else {
//show errors
}
}
}