首页 文章

使用AJAX的Symfony 4 Validator

提问于
浏览
1

我想使用Symfony 4 Validator Component来验证我通过AJAX发送到Controller的表单 .

Form中使用此方法呈现Form:

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

然后我有另一种方法来处理通过AJAX发送的post请求:

/**
 * 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');
        }
    }
}

JavaScript:

$.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);
    });

树枝:

{% 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%}

现在我在使用Symfony Validator时遇到了一些问题:

Symfony说我必须返回一些内容(它只返回一个响应,如果$ form-> isSubmitted()和/或isValid())或者它说handleRequest方法需要一个字符串(但在我的情况下,它获取NULL作为$的值)请求) .

我是否必须使用handleRequest方法才能使用Symfony Validator及其验证方法isValid和isSubmitted?或者走的路是什么?提前谢谢你,抱歉我的英语不好

1 回答

  • 1

    Symfony控制器动作总是需要返回一些东西

    return new Response('not submitted');
    

    在行动结束时 .

    需要将请求对象正确地赋予操作 . 试试这个:

    use Symfony\Component\HttpFoundation\Request;
    
    public function apiProfileUpdate(Request $request)
    {
        // delete this: $request = Request::createFromGlobals();
    

    要验证实体,您不一定需要使用表单,可以直接使用验证器 . 使用表单是标准方式,因为通常在创建或编辑实体时,无论如何都要使用表单 . https://symfony.com/doc/current/validation.html

相关问题