Symfony 4 Validator with AJAX

#1
I would like to use the Symfony 4 Validator Component to validate my forms which I send via AJAX to my Controller.

The Form is rendered with this method in the Controller:
Mã:
 /**
 * @Route("/profile", name="profile")
 */
public function profile(Request $request){

    $user = $this->getUser();

    $form = $this->createFormBuilder($user)
        ->add('email', EmailType::class)
        ->add('name', TextType::class)
        ->getForm();

    return $this->render('user/user-profile.html.twig', [
        #'user' => $user,
        'form' => $form->createView(),
    ]);
}
Then I have another method for handling the post request sent via AJAX:
Mã:
 /**
 * Update user profile data
 *
 * @Route("/api/users/updateprofile")
 * @Security("is_granted('USERS_LIST')")
 */

public function apiProfileUpdate()
{
    $request = Request::createFromGlobals();

    $user = $this->getUser();
    /** @var User $user */

    // Is this needed?
    $form = $this->createFormBuilder($user)
        ->add('email', EmailType::class)
        ->add('name', TextType::class)
        ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted()) {
        if($form->isValid()) {
            $user->setName($request->request->get('name'));
            $user->setEmail($request->request->get('email'));

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();
            return new Response('valid');
        } else {
            return new Response('not valid');
        }
    }
}
The JavaScript:
Mã:
$.post('/api/users/' + method, formdata, function (response) {
        $('#updateProfileAlertTitle').text("Success!");
        $('#updateProfileAlertMessage').text(response);
        $('#updateProfileAlert').removeClass('hidden');
        $('#updateProfileAlert').removeClass('alert-danger');
        $('#updateProfileAlert').addClass('alert-success');
        $('.btn-save').button('reset');
        $('.btn-cancel').prop('disabled', false);
    });
The Twig:
Mã:
{% block body %}
<section id="sectionProfile">
    <div class="box">
        <div class="box-body">
            <div id="updateProfileAlert" class="alert alert-success alert-dismissible hidden">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                <h4 id="updateProfileAlertTitle"><i class="icon fa fa-check"></i> Success!</h4>
                <p id="updateProfileAlertMessage">Success!</p>
            </div>
            {{ form_start(form, {attr: {class: 'form-horizontal', id: 'formEditProfile', autocomplete: 'disabled'}}) }}
            <div class="form-group">
                {{ form_label(form.email, 'E-Mail', {label_attr: {class: 'col-sm-2 control-label'}}) }}
                <div class="col-sm-10 col-lg-6">
                    {{ form_widget(form.email, {id: 'email', full_name: 'email', attr: {class: 'form-control', autocomplete: 'disabled'}}) }}
                </div>
            </div>
            <div class="form-group">
                {{ form_label(form.name, 'Name', {label_attr: {class: 'col-sm-2 control-label'}}) }}
                <div class="col-sm-10 col-lg-6">
                    {{ form_widget(form.name, {id: 'name',full_name: 'name', attr: {class: 'form-control', autocomplete: 'disabled'}}) }}
                </div>
            </div>
            <div class="module-buttons">
                <button type="button" id="updateUserProfile" class="btn btn-primary btn-save" data-loading-text="<i class='fa fa-spinner fa-spin '></i> Saving">Save</button>
            </div>
            {{ form_end(form) }}
        </div>
    </div>
</section>
{% endblock %}

Now I have some problems when using the Symfony Validator:

Either Symfony says I must return something (it only returns a response if $form->isSubmitted() and/or isValid() ) or it says that the handleRequest method expects a string (but in my case it gets NULL as value for $request).

Do I have to use the handleRequest method in order to use the Symfony Validator and its Validation methods isValid and isSubmitted? Or what is the way to go? Thank you in advance and sorry for my bad english
 

Admin

Administrator
Thành viên BQT
#2
Symfony controller actions always need to return something, put
Mã:
return new Response('not submitted');
at the end of the action.

The request object needs to be given to the action properly. Try this:

Mã:
use Symfony\Component\HttpFoundation\Request;

public function apiProfileUpdate(Request $request)
{
    // delete this: $request = Request::createFromGlobals();
To validate an entity you don't necessarily need to use a form, you can use the validator directly. Using a form is the standard way because usually when creating or editing an entity a form is used anyway. https://symfony.com/doc/current/validation.html
 
Top