我有一个FormType可以重复用于编辑&创建记录。此表单有一个实体字段,根据记录ID呈现为填充的选择,因此我需要在创建新记录时跳过此字段。我读了http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html,在改变了一些根源之后,在我遇到这个错误时,我试图编辑现有记录之前似乎一切正常:
ContextErrorException:注意:未定义的变量:/ Users / a77 / Documents / DEV / UVox Com / src / Acme / DemoBundle / EventListener / VenueFieldSubscriber.php第32行中的选项
Mi VenuesFormType是:
namespace Acme\DemoBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Acme\DemoBundle\EventListener\VenueFieldSubscriber;
class VenuesType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('name', 'text')
->add('password', 'text')
->add('save', 'submit', array('label' => 'Save', 'attr' => array('data-loading-text' => 'loading', 'class' => "btn btn-primary")))
->addEventSubscriber(new VenueFieldSubscriber());
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Entity\Venues'
));
}
/**
* @return string
*/
public function getName() {
return 'acme_demobundle_venues';
}
}
我的VenueFieldSubscriber是:
namespace Acme\DemoBundle\EventListener;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;
class VenueFieldSubscriber implements EventSubscriberInterface {
public static function getSubscribedEvents() {
// Tells the dispatcher that you want to listen on the form.pre_set_data
// event and that the preSetData method should be called.
return array(FormEvents::PRE_SET_DATA => 'preSetData');
}
public function preSetData(FormEvent $event) {
$product = $event->getData();
$form = $event->getForm();
if (!$product || null === $product->getId()) {
// no action for new record
} else {
$form->add('user', 'entity', array(
'class' => 'AcmeDemoBundle:Users',
'property' => 'username',
'query_builder' => function(EntityRepository $er) use ($options) {
return $er->createQueryBuilder('u')
->Where('u.venue=?1')
->andWhere('u.usertype >1')
->orderBy('u.username', 'ASC')
->setParameter(1, $options['attr']['venueid']);
}
));
}
}
任何想法,我错过了什么? $ options [' attr'] [' venueid']应该为我提供我正在编辑的记录的ID ...谢谢;)
答案 0 :(得分:1)
我认为在
之后$product = $event->getData();
$product
是Acme\DemoBundle\Entity\Venues
类的对象。
然后代替
->setParameter(1, $options['attr']['venueid'])
尝试
->setParameter(1, $product->getId())