所以我创建了一个表单,我想在我的项目中使用它。我使用 Zend Framework 2 和 Doctrine Orm。提交表单时出现问题:我什么都没有,这意味着表单未提交。有关更多详细信息,我将编写我的代码。因此,如果有人有任何解决方案,我将不胜感激。
这是我的实体:
class Article implements InputFilterAwareInterface
{
protected $inputFilter;
/**
* @ORMColumn(name="publication", type="boolean")
*/
protected $publication;
public function __construct()
{
$this->date = new Datetime();
}
/**
* @var integer
*
* @ORMColumn(name="id", type="integer")
* @ORMId
* @ORMGeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
*
* @ORMColumn(name="title", type="string", length=255)
*/
protected $title;
// ....
/**
* Populate from an array.
*
* @param array $data
*/
// here maybe the data can't pass from my form to the entity !!
public function populate($data = array())
{
$this->content = $data['content'];
$this->title = $data['title'];
$this->date = $data['date'];
$this->publication = $data['publication'];
$this->image = $data['image'];
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'content',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 60,
),
),
),
)));
// ....
}
}
然后我的操作:
$form = new ArticleForm();
$form->get('submit')->setAttribute('label', 'Add');
$request = $this->getRequest();
if ($this->zfcUserAuthentication()->hasIdentity()) {
if ($request->isPost())
{
$article = new Article();
$form->setInputFilter($article->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$article->populate($form->getData());// here i think i have a problem
$this->getObjectManager()->flush();
$newId = $article->getId();
return $this->redirect()->toRoute('blog');
}
}
}
而不是 : $article->populate($form->getData());
尝试: $article->populate($request->getPost()->toArray());//bad idea
或 : $article->populate($form->getData()->toArray());//good idea
向上: $form->getData()
将返回实体,因此您必须实现toArray()
函数;
public function toArray()
{
return array(
'title' => $this->title,
//...
);
}