我有一个学说实体,一个表格和两个字段集。 当我用值填充实体时,值会按预期水合成形式。 当我尝试从表单数据创建实体时,它保持空白..
我必须忘记一些事情,但却无法找到它,我还有其他几种没有字段集的形式,它们按预期工作。
任何想法?
将我的代码发布在
下面实体:
class User
{
/**
* @var int
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
* @ORM\Column(type="string", length=255, unique=true, nullable=true)
*/
protected $username;
..
}
表格:
class CreateUserForm extends Form
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('create-user');
$this->setAttribute('method', 'post');
// The form will hydrate an object
$this->setHydrator(new DoctrineHydrator($objectManager));
$userFieldset = new UserFieldset($objectManager);
$this->add($userFieldset);
// … add CSRF and submit elements …
$baseFieldset = new BaseFieldset($objectManager);
$baseFieldset->setUseAsBaseFieldset(true);
$this->add($baseFieldset);
}
}
UserFIeldset:
class UserFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct($objectManager)
{
parent::__construct($name = 'user');
$this->setHydrator(
new DoctrineHydrator($objectManager, 'YrmUser\Entity\User')
)->setObject(new User());
$this->add(
array(
'name' => 'username',
'attributes' => array(
'type' => 'text',
'placeholder' =>'Username',
),
'options' => array(
'label' => 'Username',
),
)
);
...
}
}
BaseFieldset:
class BaseFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct($objectManager)
{
parent::__construct('base');
$this->setHydrator(new DoctrineHydrator($objectManager));
$this->add(
array(
'name' => 'security',
'type' => 'Zend\Form\Element\Csrf',
'options' => array(
'csrf_options' => array(
'timeout' => 600
)
)
)
);
$this->add(
array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Save',
'class' => 'btn btn-success btn-lg confirm',
),
)
);
}
}
控制器动作:
public function createAction()
{
$form = new CreateUserForm($this->getObjectManager());
$entity = new User();
$form->bind($entity);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getObjectManager()->persist($entity);
$this->getObjectManager()->flush();
return $this->redirect()->toRoute($this->redirect);
}
}
return array(
'form' => $form
);
}
答案 0 :(得分:1)
你可以在$form->getData()
之后找到$form->isValid()
吗?
或者,您可以尝试使用$form->isValid($request->getPost())
代替setData()
。