经过一些研究后,我经常找到解决问题的答案,但今天情况并非如此。
假设我有2个实体,"任务"和" TaskCategory",每个任务都有一个类别。 我想让我的用户不仅将现有类别归因于他们的任务,还要创建新的类别。
这是我到目前为止的代码:
<?php
// TaskCategoryType.php
class TaskCategoryType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
;
}
// Some stuff...
和
<?php
// TaskType.php
// Some stuff...
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// Add some fields there
->add(
'category',
TransformableEntityType::class,
['class' => 'AppBundle:TaskCategory']
)
->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$task = $event->getData();
$form = $event->getForm();
if (empty($task['category']['id']) && !empty($task['category']['name'])) {
$task['category']['id'] = null;
$event->setData($task);
$form->remove('category');
$form->add('category', TaskCategoryType::class);
}
})
;
}
// Some stuff...
它适用于创建任务,但是当我编辑现有任务时,它会编辑关联的TaskCategory而不是创建新任务。 我试图强制创建一个新的TaskCategory:$ task [&#39; category&#39;] [&#39; id&#39;] = null;但它不起作用。
感谢您的帮助,我真的陷入了困境:(
编辑:我忘了提到我仅将此表单用作API,这就是为什么我只有一个类别&#39;字段,否则我会使用另一个&#39; category_new&#39;字段。
答案 0 :(得分:0)
<?php
class TaskType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// Some fields...
->add(
'category',
TransformableEntityType::class,
['class' => 'AppBundle:TaskCategory']
)
->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$task = $event->getData();
$form = $event->getForm();
if (empty($task['category']['id']) && !empty($task['category']['name'])) {
// If there is no category id but there is a category
// name it means it is a new category. so replace
// the custom entity field with this simple field
$form->remove('category');
$form->add('category', TaskCategoryType::class, ['allow_extra_fields' => true]);
}
})
->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
$catForm = $event->getForm()->get('category');
if ($catForm->has('name') && $catForm->get('name')->getData() !== "") {
// If there is a category name it means
// it is a new category.
$category = new TaskCategory(); // Create new category
$category->setName($catForm->get('name')->getData());
$task = $event->getData()->setCategory($category);
$event->setData($task);
}
})
;
}
答案 1 :(得分:0)
考虑到您已为cascade-persist
到Task
的关联启用了TaskCategory
。我想最好的解决办法就是使用autocompleter
作为基于标记的工作。
如果Transformer
可用,TaskCategory
应该检查数据库,否则创建一个新的。{/ p>