user3491057
user3491057

Reputation:

Symfony FormBuilder GetData

i'm using symfony 3 with formbuilder.

i create an EditAction to Edit a service:

 /**
 * @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(),
    ]);
}

now the form will be create with:

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,
            ]);
        }
    }

now i'm trying to get the current Value of each input.

And i"m using it also to Add a Service.

This how i use with the twig:

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

I try different ways, but no success. Thanks

Upvotes: 1

Views: 1262

Answers (3)

user3491057
user3491057

Reputation:

It was simple i just do:

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

Upvotes: 0

Rafal Kozlowski
Rafal Kozlowski

Reputation: 770

$form->getData() is a method You are looking for http://symfony.com/doc/current/forms.html

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

or as @pavlovich suggested

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

Upvotes: 0

pavlovich
pavlovich

Reputation: 1942

There are few different ways to get input value of a form:

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

Upvotes: 1

Related Questions