0
我正在嘗試使用annotatnions來構建和驗證zend表單。 但當前我recive錯誤,當我打開showformAction:Zend表單和批註驗證
「致命錯誤:未捕獲異常'Zend \ Form \ Exception \ InvalidElementException'消息'沒有元素的名稱[用戶名]在窗體中找到'... 「
下面是我的代碼。我做錯了什麼?
實體\ user.php的
namespace Application\Model;
use Zend\Form\Annotation;
/**
* @Annotation\Hydrator("Zend\Stdlib\Hydrator\ObjectProperty")
* @Annotation\Name("user")
*/
class User
{
/**
* @Annotation\Attributes({"type":"text" })
* @Annotation\Validator({"type":"Regex","options":{"regex":"/^[a-zA-Z][a-zA-Z0-9_-]{1,19}/"}})
* @Annotation\Options({"label":"Username:"})
*/
public $username;
}
控制器\ ProductsController.php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Json\Json;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;
use Zend\Debug\Debug;
use Application\Entity\Products;
use Application\Entity\Category;
use Application\Form\ProductsForm;
use Doctrine\ORM\EntityManager;
use Application\Model\User;
use Zend\Form\Annotation\AnnotationBuilder;
class ProductsController extends AbstractActionController {
protected $albumTable;
protected $em;
protected $form;
public function savetodb($data) {
//code save to db ....
}
protected function getForm() {
$entity = new User();
$builder = new AnnotationBuilder();
$this->form = $builder->createForm($entity);
return $this->form;
}
public function showformAction() {
$viewmodel = new ViewModel();
$form = $this->getForm();
$request = $this->getRequest();
//disable layout if request by Ajax
$viewmodel->setTerminal($request->isXmlHttpRequest());
$is_xmlhttprequest = 1;
if (!$request->isXmlHttpRequest()) {
//if NOT using Ajax
$is_xmlhttprequest = 0;
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
//save to db <span class="wp-smiley emoji emoji-wink" title=";)">;)</span>
$this->savetodb($form->getData());
}
}
}
$viewmodel->setVariables(array(
'form' => $form,
// is_xmlhttprequest is needed for check this form is in modal dialog or not
// in view
'is_xmlhttprequest' => $is_xmlhttprequest
));
return $viewmodel;
}
public function validatepostajaxAction() {
$form = $this->getForm();
$request = $this->getRequest();
$response = $this->getResponse();
$messages = array();
if ($request->isPost()) {
$form->setData($request->getPost());
if (!$form->isValid()) {
$errors = $form->getMessages();
foreach ($errors as $key => $row) {
if (!empty($row) && $key != 'submit') {
foreach ($row as $keyer => $rower) {
//save error(s) per-element that
//needed by Javascript
$messages[$key][] = $rower;
}
}
}
}
if (!empty($messages)) {
$response->setContent(\Zend\Json\Json::encode($messages));
} else {
//save to db <span class="wp-smiley emoji emoji-wink" title=";)">;)</span>
$this->savetodb($form->getData());
$response->setContent(\Zend\Json\Json::encode(array('success' => 1)));
}
}
return $response;
}
}
嘗試添加@annotation \型號(「Zend的\表格\元素\ -whatever-「) – cptnk
是的,我剛剛添加,但仍然得到同樣的問題:( – jasne