Symfony 2:动态表单事件仅在编辑时返回 InvalidArgumentException [英] Symfony 2: Dynamic Form Event returns InvalidArgumentException only when editing
问题描述
我有一个名为Activity"的实体,它定义了另外两个实体Service"和Location"之间的关系.
I got an entity called 'Activity', that defines a relation between 2 more entities, 'Service' and 'Location'.
服务"和位置"都使用另一个名为分配"的实体来定义可以在具体位置使用哪些服务.
Both 'Service' and 'Location', use another entity called 'Allocation', to define what services can be used in a concrete location.
当我创建一个新活动时,在选择一项服务后,我希望位置选择字段更新为分配定义的值.
When I create a new Activity, after selecting a service I want the location choice field update with the values defined by allocation.
我已经按照 symfony 文档在表单中创建了这个位置"相关选择字段.
I have followed symfony documentation to create this 'location' dependent choice field in the form.
在创建/新表单上一切正常,但是当我尝试在已创建的活动中编辑服务字段值时,位置字段不会更新,symfony 分析器向我显示以下消息:
All works great on create/new form, but when i try to edit service field value in an already created Activity, location field does not update and the symfony profiler shows me the following message:
未捕获的 PHP 异常 Symfony\Component\PropertyAccess\Exception\InvalidArgumentException:在 F:\xampp\htdocs\gcd\vendor\symfony 处给出了AppBundle\Entity\Location"类型的预期参数,给出了NULL"\symfony\src\Symfony\Component\PropertyAccess\PropertyAccessor.php line 253 上下文:{异常":对象(Symfony\Component\PropertyAccess\Exception\InvalidArgumentException)"}
这是我的活动实体的一部分
This is a section of my Activity Entity
/**
* Activity
*
* @ORM\Table(name="activity")
* @ORM\Entity(repositoryClass="AppBundle\Repository\ActivityRepository")
*/
class Activity
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var Service
*
* @ORM\ManyToOne(targetEntity="Service", fetch="EAGER")
* @ORM\JoinColumn(name="service_id", referencedColumnName="id", nullable=false)
*/
private $service;
/**
* @var Location
*
* @ORM\ManyToOne(targetEntity="Location", fetch="EAGER")
* @ORM\JoinColumn(name="location_id", referencedColumnName="id", nullable=false)
*/
private $location;
我的控制器.
/**
* Creates a new Activity entity.
*
* @Route("/new", name="core_admin_activity_new")
* @Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$activity = new Activity();
$form = $this->createForm('AppBundle\Form\ActivityType', $activity);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$locationAvailable = $this->isLocationAvailable($activity);
$activityOverlap = $this->hasOverlap($activity);
if($locationAvailable && !$activityOverlap){
$em = $this->getDoctrine()->getManager();
$em->persist($activity);
$em->flush();
return $this->redirectToRoute('core_admin_activity_show', array('id' => $activity->getId()));
}
}
return $this->render('activity/new.html.twig', array(
'activity' => $activity,
'form' => $form->createView(),
));
}
/**
* Displays a form to edit an existing Activity entity.
*
* @Route("/{id}/edit", name="core_admin_activity_edit")
* @Method({"GET", "POST"})
*/
public function editAction(Request $request, Activity $activity)
{
$deleteForm = $this->createDeleteForm($activity);
$editForm = $this->createForm('AppBundle\Form\ActivityType', $activity);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$locationAvailable = $this->isLocationAvailable($activity);
$activityOverlap = $this->hasOverlap($activity);
if($locationAvailable && !$activityOverlap){
$em = $this->getDoctrine()->getManager();
$em->persist($activity);
$em->flush();
return $this->redirectToRoute('core_admin_activity_show', array('id' => $activity->getId()));
}
}
return $this->render('activity/edit.html.twig', array(
'activity' => $activity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
我的表单类型
class ActivityType extends AbstractType
{
private $em;
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('service', EntityType::class, array(
'class' => 'AppBundle:Service',
'placeholder' => 'elige servicio',
))
->add('location', EntityType::class, array(
'class' => 'AppBundle:Location',
'choices' => array(),
))
->add('name')
->add('virtual')
->add('customerSeats')
->add('customerVacants')
->add('employeeSeats')
->add('firstDate', 'date')
->add('lastDate', 'date')
->add('weekday')
->add('beginTime', 'time')
->add('endTime', 'time')
->add('admissionType')
->add('status');
$formModifier = function (FormInterface $form, Service $service = null) {
$locations = null === $service ? array() : $this->em->getRepository('AppBundle:Allocation')->findLocationsByService($service);
$form->add('location', EntityType::class, array(
'class' => 'AppBundle:Location',
'choices' => $locations,
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$data = $event->getData();
$formModifier($event->getForm(), $data->getService());
}
);
$builder->get('service')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$service = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $service);
}
);
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Activity'
));
}
}
javaScript 函数
javaScript function
<script>
var $service = $('#activity_service');
// When sport gets selected ...
$service.change(function() {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected service value.
var data = {};
data[$service.attr('name')] = $service.val();
// Submit data via AJAX to the form's action path.
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
// Replace current position field ...
$('#activity_location').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#activity_location')
);
}
});
});
</script>
任何帮助都会很棒,谢谢.
Any help will be great, thanks.
推荐答案
我遇到了类似的问题,我找到了解决方案:Symfony - 动态下拉列表仅在编辑时不起作用
I had a similar problem, I found a solution : Symfony - dynamic drop down lists not working only when editing
这篇关于Symfony 2:动态表单事件仅在编辑时返回 InvalidArgumentException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!