我在Persons
时间Department
内有Period
个/**
* @ORM\Entity
*/
class Person {
/**
* @ORM\OneToMany(targetEntity="Job", mappedBy="person")
*/
private $jobs;
}
/**
* @ORM\Entity
*/
class Job {
/**
* @ORM\ManyToOne(targetEntity="Person", inversedBy="jobs")
*/
private $jobs;
/**
* @ORM\ManyToOne(targetEntity="Department")
*/
private $department;
/**
* @ORM\ManyToOne(targetEntity="Period")
*/
private $period;
}
的域模型:
period
如果没有Person
个字段,那就是一个简单的ManyToMany Department
< => Department
协会。
Symfony2允许您使用复选框将其很好地显示在表单中。你只需检查Period
s,魔法填充中间表。
现在,在我的应用中,管理员通过登录选择当前时段,Request
实例作为Job
的属性
我想用复选框显示完全相同的表单:
public function editJobsAction(Request $request, Person $person, Period $period) {
// departments are unmapped, so provide initial data
$form = $this->get('form.factory')->create('jobs_edit', [
'departments' => $person->getDepartmentsForYear($year),
]);
$form->handleRequest($request);
if($form->isValid()) {
/** @var ArrayCollection $departments */
$departments = $form->getData()['departments'];
// remove Job objects that was unchecked
// manually create and persist new Job objects
$this->om->flush();
return $this->redirect($this->generateUrl('person_jobs', ['id' => $person->getId()]));
}
return [
'form' => $form->createView(),
'person' => $person,
];
}
我目前的解决方案是使用未映射的表单并在控制器中完成所有工作:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('departments', 'entity', [
'property' => 'title',
'class' => 'MyBundle\Entity\Department',
'expanded' => true,
'multiple' => true,
'required' => false,
])
->add('edit', 'submit')
;
}
表单构建:
{{1}}
它按预期工作,但我仍然想知道是否有更清洁,更Symfony-ish的解决方案,以便'非常常规的任务。