twigsymfony-2.8

$form->isSubmitted = false upon form post


Controller:

/**
 * @Route("/charity/add", name="charity_add")
 * @Method({"POST"})
 * @param Request $request
 */
public function addAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $charity = new Charity();
    $form = $this->createFormBuilder($charity)
        ->add('name')
        ->add('url')
        ->add('stripeApiKey')
        ->add('text')
        ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        echo "isSubmitted and isValid"; exit();
    }

    if (!$form->isSubmitted()) {
        echo "Not submitted"; exit();
    }

    if (!$form->isValid()) {
        echo "Not valid"; exit();
    }
}

Twig template:

<form name="new-charity-form" id="new-charity-form" method="post" action="{{ path('charity_add') }}">
        <label>Charity name <i class="fa fa-asterisk fa-1" aria-hidden="true"></i></label><br/>
        <input id="name" type="text" name="name" required="true"/><br/>

        <label>URL <i class="fa fa-asterisk fa-1" aria-hidden="true"></i></label><br/>
        <input id="url" type="text" name="url" required="true"/><br/>

        <label>Stripe API key <i class="fa fa-asterisk fa-1" aria-hidden="true"></i></label><br/>
        <input id="stripeApiKey" type="text" name="stripeApiKey" required="true"/><br/>

        <label>Coupon text <i class="fa fa-asterisk fa-1" aria-hidden="true"></i></label><br/>
        <textarea id="text" type="text" name="text" required="true"></textarea><br/>

        <div><b>!! Figure out image uploader/selector here !!</b></div><br/>


        <button type="button" onclick="window.location='{{ path('charities_list') }}'"><i class="fa fa-arrow-left"></i> Back</button>
        <button type="submit"><i class="fa fa-plus"></i> Create</button>
    </form>

Using the browser inspect tools I can see the POST request, with name, url, stripeApiKey and text all containing valid text data - name=a&url=b&stripeApiKey=c&text=d

But the browser outputs Not submitted on submit

I have simplified the Form above to remove any constraints, such as TextType for testing purposes but even with data validation, I get returned the same results


Solution

  • The issue was caused by getName() returning a value

    If I return an empty string from getName(), then the problem is solved

    Maybe somebody could add details as to why that is:

    Forms validates when using this:

    /**
     * @return string
     */
    public function getName()
    {
        return '';
    }