HIRSCHMANN Yann
HIRSCHMANN Yann

Reputation: 16

Symfony 4 : handelrequest not getting any submitted data

I try to submit data from a formular, they are send to the Post var, but not cached by the handlerequest() method. I tried to display potentials validator errors, but there are not any. Same for rebug:router and formular error catch.

AddArticleController

class AddArticleController extends AbstractController
{
    /**
     * @Route("/ajouter" , name="_add")
     * @param Environment $environment
     * @return Response
     * @throws \Twig_Error_Loader
     * @throws \Twig_Error_Runtime
     * @throws \Twig_Error_Syntax
     */
    public function index()
    {
        return $this->render('add_article/AddArticle.html.twig', [
            'controller_name' => 'AddArticleController',
        ]);
    }

    /**
     * @param Request $request
     * @return Response
     */
    public function addCompanie(ValidatorInterface $validator,Request $request){
        //On submit, data are in POST var, but not submited
        $companie = new Companies();
        $form = $this->createForm(AddCompanieType::class, $companie);
        $form->handleRequest($request);
        //displaying validator errors
        $errors = $validator->validate($companie);
        if (count($errors) > 0) {
            /*
             * Uses a __toString method on the $errors variable which is a
             * ConstraintViolationList object. This gives us a nice string
             * for debugging.
             */
            $errorsString = (string) $errors;

            return new Response($errorsString);
        }

        if($form->isSubmitted() && $form->isValid()){
            $companie = $form->getData();
            echo 'ok';

        }
        return $this->render('form/AddCompanie.html.twig', array(
            'formCompanie' => $form->createView(),
        ));
    }
}

AddCompanieType

class AddCompanieType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('companie_name',
                TextType::class, [
                    'label'=>'Nom de l\'Entreprise',
                    'attr'=>[
                        'pattern' => '[A-Za-z&]{1,}',
                        'class'=>'form-control'
                    ]
                ])
            ->add('Adress',
                TextType::class, [
                'label'=>'Adresse',
                'attr'=>[
                    'pattern' => '^\d{1,2}([- ]?[A-Za-z]){1,}([ ]?)$',
                    'class'=>'form-control'
                    ]
                ])
            ->add('postal_code',
                TextType::class, [
                    'label'=>'Code postal'
                    , 'attr'=>[
                        'pattern' => '\d{5}',
                        'class'=>'form-control'
                    ]
                ])
            ->add('City',
                TextType::class,  [
                    'label'=>'Ville',
                    'attr'=>[
                        'pattern' => '^[A-Z]([- ]?[A-Za-z]){1,}',
                        'class'=>'form-control'
                    ]
                ])
            ->add('phone_number',
                TelType::class, [
                    'label'=>'Téléphone Fixe',
                    'required'   => false,
                    'attr'=>[
                        'pattern' => '^0[1-68]([-. ]?\d{2}){4}$',
                        'class'=>'form-control'
                    ]
                ])
            ->add('turnover',
                IntegerType::class, [
                    'label'=>'Chiffre d\'Affaire',
                    'required'   => false,
                    'attr'=>[
                        'pattern' => '',
                        'class'=>'form-control'
                    ]
                ])
            ->add('social_reason',
                TextType::class, [
                    'label'=>'Raison Social',
                    'attr'=>[
                        'pattern' => '[A-Za-z&]{1,}',
                        'class'=>'form-control'
                    ]
                ]);
    }
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Companies::class,
        ]);
    }
}

Companies

/**
 * @ORM\Entity(repositoryClass="App\Repository\CompaniesRepository")
 */
class Companies
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Validator\Regex("/[A-Za-z&]{1,}/")
     */
    private $companie_name;

    /**
     * @ORM\Column(type="integer", nullable=true)
     */
    private $nb_projects;

    /**
     * @ORM\Column(type="string", length=255)
     *  @Validator\Regex("/^[A-Z]([- ]?[A-Za-z]){1,}/")
     */
    private $City;

    /**
     * @ORM\Column(type="string", length=255)
     * @Validator\Regex("/^\d{1,2}[A-Za-z]/")
     */
    private $Adress;

    /**
     * @ORM\Column(type="string", length=5)
     * @Validator\Length(
     *     min = 5,
     *     max = 5,
     *     minMessage = "Un numéro de téléphone doit être composé de {{ limit }} chiffres : trop court",
     *     maxMessage = "Un numéro de téléphone doit être composé de {{ limit }} chiffres : trop long"
     * )
     * @Validator\Regex("/\d{5}/")
     */
    private $postal_code;

    /**
     * @ORM\Column(type="string", length=10, nullable=true)
     * @Validator\Length(
     *     min = 10,
     *     max = 10,
     *     minMessage = "Un numéro de téléphone doit être composé de {{ limit }} chiffres : trop court",
     *     maxMessage = "Un numéro de téléphone doit être composé de {{ limit }} chiffres : trop long"
     * )
     * @Validator\Regex("/^0[1-68]([-. ]?\d{2}){4}$/")
     */
    private $phone_number;

    /**
     * @ORM\Column(type="integer", nullable=true)*
     * @Validator\Type(
     *     "integer",
     *     message="La valeur {{ value }} n'est pas un nombre)"
     * )
     */
    private $turnover;

    /**
     * @ORM\Column(type="string", length=255)
     * @Validator\Type("string")
     * @Validator\Regex("/[A-Za-z&]{1,}/")
     */
    private $social_reason;

    /**
     * @ORM\Column(type="integer", nullable=true)
     */
    private $effective;


    /**
     * @ORM\ManyToMany(targetEntity="Project", mappedBy="companies")²
     */
    private $projects;

    public function __construct()
    {
        $this->projects = new ArrayCollection();
    }

    public function __toString()
    {
        return '';
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getCompanieName(): ?string
    {
        return $this->companie_name;
    }

    public function setCompanieName(string $companie_name): self
    {
        $this->companie_name = $companie_name;

        return $this;
    }

    public function getNbProjects(): ?int
    {
        return $this->nb_projects;
    }

    public function setNbProjects(?int $nb_projects): self
    {
        $this->nb_projects = $nb_projects;

        return $this;
    }

    public function getCity(): ?string
    {
        return $this->City;
    }

    public function setCity(string $City): self
    {
        $this->City = $City;

        return $this;
    }

    public function getAdress(): ?string
    {
        return $this->Adress;
    }

    public function setAdress(string $Adress): self
    {
        $this->Adress = $Adress;

        return $this;
    }

    public function getPostalCode(): ?int
    {
        return $this->postal_code;
    }

    public function setPostalCode(int $postal_code): self
    {
        $this->postal_code = $postal_code;

        return $this;
    }

    public function getPhoneNumber(): ?int
    {
        return $this->phone_number;
    }

    public function setPhoneNumber(?int $phone_number): self
    {
        $this->phone_number = $phone_number;

        return $this;
    }

    public function getTurnover(): ?int
    {
        return $this->turnover;
    }

    public function setTurnover(?int $turnover): self
    {
        $this->turnover = $turnover;

        return $this;
    }

    public function getSocialReason(): ?string
    {
        return $this->social_reason;
    }

    public function setSocialReason(string $social_reason): self
    {
        $this->social_reason = $social_reason;

        return $this;
    }

    public function getEffective(): ?int
    {
        return $this->effective;
    }

    public function setEffective(?int $effective): self
    {
        $this->effective = $effective;

        return $this;
    }
}

AddCompanie (template)

{{ form_start(formCompanie) }}
    {{ form_widget(formCompanie) }}
    <input type="submit" class="btn btn-dark" value="Ajouter" />
{{ form_end(formCompanie) }}

I don't realy know where to search. I checked Symfony logs but nothing related to this formular.

EDIT

AddArticle (Template)

{% extends 'layout.html.twig' %}

{% block title %}
    {{ parent() }}Ajouter
{% endblock %}

{% block content %}
    {{ render(controller('App\\Controller\\AddArticleController::addCompanie')) }}
{% endblock %}

Solution

I dumped the whole $request variable and I noticed that the requested method was GET instead of POST. This was due the rendering of the form by calling the controller method in the AddArticle template. The cause was Symfony was calling the render function by GET method instead of the handlerequest by POST method.

Why getMethod() returns “GET” instead of “POST”?

Upvotes: 0

Views: 83

Answers (2)

Oleg Andreyev
Oleg Andreyev

Reputation: 657

Make sure that you've configured Form Method, handleRequest discards any requests if a method does not match

Upvotes: 0

Arnaud Strill
Arnaud Strill

Reputation: 76

Could you display the rendering of the form in the page, please? It could be impossible for the form to reach the correct function of the controller because of an invalid action value for example.

Upvotes: 0

Related Questions