What is the best way to submit a form using Vue Axios in combination with Symfony 4

Need help! I am struggling with sending data from my Vue app to Symfony using axios. Even though I try to send the data, the Symfony request doesn't seem to receive it.

Check out my controller code below:

$form = $this->createForm(TeacherType::class);
$form->submit($request->request->all());
$form->handleRequest($request);

if($form->isSubmitted() && !$form->isValid()) {
    return new JsonResponse([
        'code' => "400",
        'data' => $this->getErrorMessages($form),
    ]);
}

return new JsonResponse(array(
    'code' => 200,
));

This is how I am using axios:

sent() {
axios.post('http://localhost:8000/valid', {
     firstname: this.firstname
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
}

Here's a snippet of my form:

<form @submit.prevent="sent" id="form" name="teacher" method="POST" action="#">
    <input type="text" name="teacher[firstname]" v-model="firstname">
    <button type="submit">OK</button>
</form>

I always get a response of {'code': 400} and an alert that the firstname should not be blank (I have set assert NotBlank for firstname in the form).

Any suggestions on what I might be doing wrong?

Answer №1

Don't forget to omit

$form->handleRequest($request);
, it doesn't work with API calls.

Update:

Here is a simple example for validating an entity:

Entity:

use Symfony\Component\Validator\Constraints as Assert;

class SomeClass
{
    /**
     * @Assert\NotBlank
     */
    private $content;
}

FormType:

class SomeType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('content', TextType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => SomeClass::class,
        ]);
    }
}

FormHandler:

class FormHandler
{
    private $formFactory;

    public function __construct(FormFactoryInterface $formFactory)
    {
        $this->formFactory = $formFactory;
    }

    public function handleWithSubmit(
        array $data,
        string $type,
        $entity,
        array $options = []
    ) {
        $form = $this->formFactory->create($type, $entity, $options);
        $form->submit($data);

        return $this->processSubmitted($form, $entity);
    }

    private function processSubmitted(FormInterface $form, $entity)
    {
        if (!$form->isValid()) {
            return $form->getErrors();
        }

        if (!is_object($entity)) {
            $entity = $form->getData();
        }

        return $entity;
    }
}

Inject FormHandler into the controller and make a call like this:

$handled = $this->formHandler->handleWithSubmit($request->request->all(), SomeType::class, new SomeClass());
if (!$handled instanceof SomeClass) {
    // return errors
}

Answer №2

The reason for this issue is that the naming of your fields in the HTML document is incorrect.

Currently, it looks like this:

teacher[firstname]

However, it should actually be more like this:

teacher_teacher[firstname]

To resolve this, utilize a FormFactoryInterface to create a named form instead:

public function yourAction(Request $request, FormFactoryInterface $forms)
{
    $form = $this->forms->createNamed('', TeacherType::class);
    $form->handleRequest($request);

    if ($form->isSubmitted() && !$form->isValid()) {
        return new JsonResponse([
            'code' => '400',
            'data' => $this->getErrorMessages($form),
        ]);
    }

    return new JsonResponse(['code' => 200]);
}

When you create a form without a specified name (e.g.,

$this->createForm(TeacherType::class)
), a name will be automatically generated for you based on the form's class name without the words Form and Type, hence the necessity for the teacher_ prefix before the field names.

Answer №3

To set up the FOS Rest bundle, ensure that you have a serializer installed. The Symfony Serializer is recommended for this task.

https://symfony.com/doc/master/bundles/FOSRestBundle/1-setting_up_the_bundle.html

The main purpose of the FOS Rest bundle is to decode the HTTP request body and Accept headers, which are essential for processing the

$form->handleRequest($request)
function in order to display the submitted form.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting an array of strings into an Entity using Symfony

I have received a payload that has the following structure: { "date": "2019-03-14 14:48:26 +0000", "events": [ "E09FDE82-4CAA-4641-87AF-6C092D6E71C1", "AE12A6BC-DA37-4C37-BF49-DD0CE096AE00" ], "location": null } The main object is ...

Exploring ways to expand a field in Laravel Nova

Recently, I have been working with Laravel Nova and am trying to develop a custom field inspired by BelongsToMany. The plan is to start with the existing code for this field and then incorporate my modifications. I attempted to create a custom field and e ...

Refresh the component following a successful POST request in Vue.js

Having issues with reloading components in my VueJS app using NUXTJS. The page in my app calls a component called “CustomerCard.” When I use fetch to communicate with my API and retrieve all customers, everything works perfectly upon arriving on the p ...

[Vue Alert]: Render Error - "TypeError: Unable to retrieve the 'getters' property of an undefined object"

Here is the code snippet from my app.js file. Can someone please review it and confirm if I have defined the items correctly according to the Vuex documentation? import store from "./store"; require('./bootstrap'); window.Vue = require( ...

Having trouble utilizing Vue3 methods while utilizing the `<script setup lang="ts">` syntax

Looking to incorporate Vue into a non-Vue Class using the Composition API for a Chrome Extension project where having the entire thing as a Vue App doesn't make sense. The Vue Instance is being instantiated in the usual manner and then injected into ...

The useSlots property in VueJs encounters an error when used in conjunction with the array.map

Recently, I developed a reusable component for tabs in vuejs. It works perfectly when using the Tab component like this in App.vue: <Tabs> <Tab title="Tab 1"></Tab> </Tabs> However, when attempting to loop the Tab comp ...

How can Vue.js pass an array from a child component to its parent component?

I'm currently developing a contact book app and I have created a modal within a child component that contains a form with several input fields. My goal is to utilize the values entered in the form and add them to the parent component. I have successfu ...

Encountering difficulties when attempting to test Vue CSS styling

Encountering difficulties in my unit tests while attempting to test a method that alters the CSS style "display" to "none". The test fails with this message: Expected: "display: none" Received: undefined Within my component, there is a method: closeCook ...

Exploring Vuetify: Navigating Through Sub-Menus on a Drawer

My goal is to create a navigation drawer with expandable sub-menus for specific options. For example, the main menu option "User Profile" may have sub-menus like "Update Contact Details" and "Review Registration". I've experimented with different app ...

Creating a route-guard in a Vue.js/Firebase authentication system for secure navigation

I have created a Vue.js/Firebase authentication interface following a tutorial. The app is mostly functioning properly, but I am experiencing issues with the route guard. Upon signing in and redirecting from "http://localhost:8080/home" to "http://localh ...

Webpage video stalling due to buffering

Currently, I am developing personalized video controls and have integrated a @progress event to monitor the video buffering progress and adjust the width of a progress bar div: <video @progress="videoBuffer($event)"> videoBuffer(e) { if ...

Guide to integrating Google Maps into your Vue application using vue2-google-maps

I have been trying to integrate vue2-google-maps into my app, but unfortunately, the map is not displaying as expected. Despite carefully following the documentation on how to use it, all I get is a blank white page instead of the Google Maps interface. St ...

Is your NativeScript dynamic array causing elements to disappear at the bottom of the screen?

I'm encountering a frustrating problem with NativeScript styled using Vue. My issue is related to a dynamic array that captures user input from a modal. Check out the code snippet below: <StackLayout v-show="model.length > 0" class=&q ...

Is Apollo & GraphQL caching a better alternative to using Vuex?

I've been diving into Apollo & GraphQL recently. I've come across the idea of leveraging the cache instead of relying on Vuex - but I'm struggling to understand how to do this without creating some sort of anti-pattern by mixing the two toge ...

Bypass React Query execution when the parameter is null

I am facing an issue with a react query problem. I have a separate file containing all the queries: const useFetchApTableQuery = (date: string): UseQueryResult => { const axiosClient = axios.create() const fetchApTableQuery = async (): Promise<A ...

Exploring Vue3: Implementing Highlight.js for Solidity code highlighting

Currently working on developing a webpage using Vue3. The goal is to display Solidity code in a visually pleasing and highlighted manner. After some research, I came across the Highlight.js library (link). Additionally, I found specific rules for highlight ...

Exploring Symfony 4: Implementing leftJoin on tables using doctrine annotations

When attempting to combine the tables categories and news, everything was running smoothly. However, when I intentionally changed a foreign key from 2 to 911 on the news table, the jointure broke as expected. As a result, Symfony threw an error related to ...

Developing modular applications with Vue.js and leveraging locally installed NPM packages

I am currently working on developing a modular application using Vue through the vue-cli-service. The main application and its modules are located in separate folders, with a structure that looks something like this: -- app/package.json /src/** -- mo ...

Vue cannot compile Window.resize

Could someone please assist me in identifying the issue with this code snippet? I copied some pure HTML from a specific website. The window resize function is showing up as incorrect syntax marked in red, but I'm not sure why. Any guidance on fixing t ...

What could be causing anime.js to malfunction when clicked in Vue.js?

After implementing the mounted() function, the animation now successfully plays when the page is updated. However, there seems to be an issue as the animation does not trigger when clicked. Even though console.log registers a click event, the animation fa ...