0

In this situation, I have a simple form, not generated by Zend:

<form id='com-prefs'>
  <input type='checkbox' name='accept-sms' />
  <input type='checkbox' name='accept-phone' />
  <input type='checkbox' name='accept-email' />
  <!-- etc -->
</form>

The form is longer than this, but it's essentially just more inputs. Zend_Form's form creation seems bloated, and since I'll be working on this project with others, I don't feel like complicating things with Zend form creation. However, Zend_Form's validation seems much more useful, and I'd like to use it through Ajax.

My question is, how do I grab the above form with jQuery (or just regular JS), and convert it into something that I can make into a Zend_Form easily to use the below:

$form->isValid();

Is serializeArray() the route I want to go?

EDIT: Using ZF1

4

2 回答 2

0

我正在寻找的确实是serializeArray()。Zend_Form 验证器接受一个 'name'=> 'value'=> = 等数组。

.serializeArray() 创建一个多维数组,表示表单中所有元素的值已设置(或者在复选框和单选按钮的情况下,具有值“已选中”)。

于 2013-06-14T19:19:32.967 回答
0

我做了一些可能对你有用的东西。
IndexController.php我添加了这个动作:

public function checkformAction(){
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);

    if($this->getRequest()->isPost()){
        $data = $this->getRequest()->getPost();
        $form = new $data["zend_form"]();
        unset($data["zend_form"]);
        echo $form->processAjax($this->getRequest()->getPost());
    }else{
        echo false;
    }
}

在全局 Javascript 文件中,我添加了这个函数:

function validate(form,zend_form){
  $.ajax({
    url: '/index/checkform/',
    data:  $(form).serialize()+'&zend_form='+zend_form,
    type: 'post',
    success: function(response) {
        response = $.parseJSON(response);
        if(response == true){
            $(form).removeAttr("onsubmit");
            $("#submit").click();
        }
        $("ul.errors").remove();
        $.each(response,function(key,value){
            var errorlist = '<ul class="errors">';
            $.each(value,function(key,value){
                errorlist += '<li>'+value+'</li>';
            });
            errorlist += '</ul>';
            $("#"+key).after(errorlist);
        });
    }
  });   
  return false;
}

最后在 init() 函数的每个表单类中,我添加了onsubmit属性:

class Frontend_Form_Doc extends Zend_Form
{
   public function init()
   {
      $this->setMethod('post');
      $this->setAttrib("onsubmit","return validate(this,'Frontend_Form_Doc')");

      .....

   }
}
于 2016-04-05T10:30:56.703 回答