我正在尝试获得我选择表格的结果。
表格是这样的:
$user_picked =
$em->getRepository('UserBundle:User')->
findBy(array('usFirstname' => $form->getForm()->get('users')->getData()));
然后我想让用户选中,我尝试了几件事,但没有任何效果...... 它应该是这样的:
NAME
1. AHMET
2. MEHMET
3. VELİ
4. TEMEL
点击“提交”按钮后,如何让用户选中?
答案 0 :(得分:0)
表单构建器的神奇之处在于此功能
如果转储数据dump($form->get('users')->getData())
,它将是表单中选择的用户实例。无需进行额外查询。
此外,choice_label只会过滤select选项文本中的内容,而不是值。
实施例
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\User,
AppBundle\Form\MyFormType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route,
Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\Request,
Symfony\Bundle\FrameworkBundle\Controller\Controller;
class MyController extends Controller
{
public function addAction(Request $request)
{
$form = $this->createForm(new MyFormType(), null, []);
$form->add('submit', 'submit', [
'label' => 'Create',
'attr' => ['class' => 'btn btn-success pull-right']
]
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
dump($form->get('users')->getData());
exit(0);
}
return $this->render('AppBundle:user:form.html.twig', [
'form' => $form->createView()
]
);
}
}
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType,
Symfony\Component\Form\FormBuilderInterface,
Symfony\Component\OptionsResolver\OptionsResolver,
Symfony\Component\Validator\Constraints as Assert;
class MyFormType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('users', 'entity', [
'required' => false,
'class' => 'AppBundle:User',
'choice_label' => 'usFirstname',
'expanded' => false,
'multiple' => false,
]);
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => null,
));
}
/**
* @return string
*/
public function getName()
{
return 'my_form';
}
}