Symfony FormBuilder GetData

时间:2016-08-18 14:10:04

标签: symfony symfony-forms

我正在使用symfony 3和formbuilder。

我创建一个EditAction来编辑服务:

 /**
 * @Route("/admin/service/edit/{id}", requirements={"id": "\d+"}, name="edit_service")
 */
public function EditAction($id , Request $request){
    $service = $this->getDoctrine()
        ->getRepository('AppBundle:Services')
        ->findOneById($id);
    $form = $this->get('form.factory')->createNamedBuilder('edit_service', ServiceType::class)->getForm();
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()){
        die("OK"):
    }
    return $this->render('AppBundle:Admin:EditService.html.twig', [
        'service'        => $service,
        'form'   => $form->createView(),
    ]);
}

现在表单将使用:

创建
class ServiceType extends AbstractType{
        /**
         * {@inheritdoc}
         */
        public function buildForm(FormBuilderInterface $builder, array $options){
            $builder
                ->add('title', TextType::class, [
                    'attr' => ['autofocus' => true],
                    'label' => 'service.title',
                ])
                ->add('text', TextareaType::class, [
                    'attr' => [ 'pattern' => '.{10,}' , 'rows' => '10'],
                    'label' => 'service.text',
                ])
                ->add('submit', SubmitType::class, [
                    'attr' => ['class' => 'btn btn-lg btn-primary'],
                    'label' => 'submit',
                ])
            ;
        }
        /**
         * {@inheritdoc}
         */
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults([
                'data_class' => Services::class,
            ]);
        }
    }

现在我正在尝试获取每个输入的当前值。

我也用它来添加服务。

这是我如何使用树枝:

{{ form_start(form) }}{{ form_end(form) }}

我尝试不同的方式, 但没有成功。 感谢

3 个答案:

答案 0 :(得分:1)

$form->getData()是您正在寻找的方法 http://symfony.com/doc/current/forms.html

if ($form->isSubmitted() && $form->isValid()){
    $formData = $form->getData();
    die($formData['field_name']);
}

或@pavlovich建议

if ($form->isSubmitted() && $form->isValid()){
    die($form->get('field_name');
}

答案 1 :(得分:1)

获取表单输入值的方法很少:

  • $form->getData()['your_field_name']
  • $form->get('your_field_name');

答案 2 :(得分:0)

很简单 我只是这样做:

$service = $this->getDoctrine()
    ->getRepository('AppBundle:Services')
    ->findOneById($id);
$form = $this->get('form.factory')->createNamedBuilder('edit_service', ServiceType::class , $service)->getForm();