我真的对我的表单过滤器感到困惑。
我的测试项目包含2个模型。
class Category extends AbstractEntity
{
use Nameable; // just property name and getter and setter
/**
* @var boolean
* @ORM\Column(name="issue", type="boolean")
*/
private $issue;
/**
* @var Collection|ArrayCollection|Entry[]
*
* @ORM\OneToMany(targetEntity="CashJournal\Model\Entry", mappedBy="category", fetch="EAGER", orphanRemoval=true, cascade={"persist", "remove"})
*/
private $entries;
}
条目
class Entry extends AbstractEntity
{
use Nameable;
/**
* @var null|float
*
* @ORM\Column(name="amount", type="decimal")
*/
private $amount;
/**
* @var null|Category
*
* @ORM\ManyToOne(targetEntity="CashJournal\Model\Category", inversedBy="entries", fetch="EAGER")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id", nullable=false)
*/
protected $category;
/**
* @var null|DateTime
*
* @ORM\Column(name="date_of_entry", type="datetime")
*/
private $dateOfEntry;
}
如果有人需要AbstractEntity
abstract class AbstractEntity implements EntityInterface
{
/**
* @var int
* @ORM\Id
* @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
}
每个类别可以有许多条目。我正在为此关系使用Doctrine
。而且效果很好。
我有一个基于此FieldSet的表单:
$this->add([
'name' => 'id',
'type' => Hidden::class
]);
$this->add([
'name' => 'name',
'type' => Text::class,
'options' => [
'label' => 'Name'
]
]);
$this->add([
'name' => 'amount',
'type' => Number::class,
'options' => [
'label' => 'Summe'
]
]);
$this->add([
'name' => 'date_of_entry',
'type' => Date::class,
'options' => [
'label' => 'Datum'
]
]);
$this->add([
'name' => 'category',
'type' => ObjectSelect::class,
'options' => [
'target_class' => Category::class,
]
]);
因此,我的表单显示一个带有我的类别的下拉列表。是的,很好。
要为我的输入实体加载类别,我使用过滤器。
$this->add([
'name' => 'category',
'required' => true,
'filters' => [
[
'name' => Callback::class,
'options' => [
'callback' => [$this, 'loadCategory']
]
]
]
]);
和回调:
public function loadCategory(string $categoryId)
{
return $this->mapper->find($categoryId);
}
映射器可以很好地加载类别。大。但是该表格无效,因为:
CashJournal \ Model \ Category类的对象无法转换为int
好,所以我要删除过滤器,但是现在它无法将属性设置为条目实体,因为设置器需要Category
。表单错误显示:
输入的步骤无效
在Symfony中,我可以创建一个ParamConverter
,它将category_id
转换为有效的Category
实体。
问题 我如何使用过滤器作为我的ParamConver?
更新 同样,当我将category_id转换为int时,也会从表单中得到错误。
更新2 我将FieldSet更改为:
class EntryFieldSet extends Fieldset implements ObjectManagerAwareInterface
{
use ObjectManagerTrait;
/**
* {@inheritDoc}
*/
public function init()
{
$this->add([
'name' => 'id',
'type' => Hidden::class
]);
$this->add([
'name' => 'name',
'type' => Text::class,
'options' => [
'label' => 'Name'
]
]);
$this->add([
'name' => 'amount',
'type' => Number::class,
'options' => [
'label' => 'Summe'
]
]);
$this->add([
'name' => 'date_of_entry',
'type' => Date::class,
'options' => [
'label' => 'Datum'
]
]);
$this->add([
'name' => 'category',
'required' => false,
'type' => ObjectSelect::class,
'options' => [
'target_class' => Category::class,
'object_manager' => $this->getObjectManager(),
'property' => 'id',
'display_empty_item' => true,
'empty_item_label' => '---',
'label_generator' => function ($targetEntity) {
return $targetEntity->getName();
},
]
]);
parent::init();
}
}
但是这将因错误消息而退出:
Entry :: setDateOfEntry()必须是DateTime的实例,已给出字符串
答案 0 :(得分:1)
您是否检查过ObjectSelect
的文档?您似乎缺少一些选择,即要使用哪个水化器(EntityManager)和标识属性(id)。 Have a look here。
示例:
$this->add([
'type' => ObjectSelect::class,
'name' => 'category', // Name of property, 'category' in your question
'options' => [
'object_manager' => $this->getObjectManager(), // Make sure you provided the EntityManager to this Fieldset/Form
'target_class' => Category::class, // Entity to target
'property' => 'id', // Identifying property
],
]);
要验证所选元素,请添加您的InputFilter:
$this->add([
'name' => 'category',
'required' => true,
]);
InputFilter不再需要。类别已经存在,因此已经经过验证。因此,您应该可以选择它。
仅在有特殊要求时才需要其他过滤器/验证器,例如:“类别只能在条目中使用一次”,因此,您需要使用NoObjectExists
验证器。但这似乎并非如此。
基于评论和过去的问题的更新
我认为您正在使要做的事情复杂化很多。似乎您只想在客户端加载表单之前先填充它即可。在收到来自客户端的POST后,您希望将收到的数据放入表单中,对其进行验证并存储。正确?
基于此,请找到我在一个项目中拥有的User的完整控制器。希望对您有所帮助。提供它是因为更新正偏离您的原始问题,这可能会对您有所帮助。
我已经删除了一些其他的检查和错误抛出,但是在其他方面却是完整的工作方式。
(请注意,我使用的是我自己的抽象控制器,请确保将其替换为您自己的和/或重新创建并匹配要求)
我还在此代码中附加了注释,以帮助您
<?php
namespace User\Controller\User;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\ORMException;
use Exception;
use Keet\Mvc\Controller\AbstractDoctrineActionController;
use User\Entity\User;
use User\Form\UserForm;
use Zend\Http\Request;
use Zend\Http\Response;
class EditController extends AbstractDoctrineActionController
{
/**
* @var UserForm
*/
protected $userEditForm; // Provide this
public function __construct(ObjectManager $objectManager, UserForm $userEditForm)
{
parent::__construct($objectManager); // Require this in this class or your own abstract class
$this->setUserEditForm($userEditForm);
}
/**
* @return array|Response
* @throws ORMException|Exception
*/
public function editAction()
{
$id = $this->params()->fromRoute('id', null);
// check if id set -> else error/redirect
/** @var User $entity */
$entity = $this->getObjectManager()->getRepository(User::class)->find($id);
// check if entity -> else error/redirect
/** @var UserForm $form */
$form = $this->getUserEditForm(); // GET THE FORM
$form->bind($entity); // Bind the Entity (object) on the Form
// Only go into the belof if() on POST, else return Form. Above the data is set on the Form, so good to go (pre-filled with existing data)
/** @var Request $request */
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost()); // Set received POST data on Form
if ($form->isValid()) { // Validates Form. This also updates the Entity (object) with the received POST data
/** @var User $user */
$user = $form->getObject(); // Gets updated Entity (User object)
$this->getObjectManager()->persist($user); // Persist it
try {
$this->getObjectManager()->flush(); // Store in DB
} catch (Exception $e) {
throw new Exception('Could not save. Error was thrown, details: ', $e->getMessage());
}
return $this->redirectToRoute('users/view', ['id' => $user->getId()]);
}
}
// Returns the Form with bound Entity (object).
// Print magically in view with `<?= $this->form($form) ?>` (prints whole Form!!!)
return [
'form' => $form,
];
}
/**
* @return UserForm
*/
public function getUserEditForm() : UserForm
{
return $this->userEditForm;
}
/**
* @param UserForm $userEditForm
*
* @return EditController
*/
public function setUserEditForm(UserForm $userEditForm) : EditController
{
$this->userEditForm = $userEditForm;
return $this;
}
}
希望有帮助...