【问题标题】:Symfony 4 Validator with AJAX带有 AJAX 的 Symfony 4 验证器
【发布时间】:2019-03-19 23:43:28
【问题描述】:

我想使用 Symfony 4 验证器组件来验证我通过 AJAX 发送到控制器的表单。

在Controller中使用这个方法渲染表单:

 /**
 * @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>

{% 端块 %}

现在我在使用 Symfony 验证器时遇到了一些问题:

Symfony 说我必须返回一些东西(它只在 $form->isSubmitted() 和/或 isValid() 时返回响应) 或者它说 handleRequest 方法需要一个字符串(但在我的例子中,它获取 NULL 作为 $request 的值)。

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

【问题讨论】:

    标签: php jquery ajax forms symfony


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      • 2019-01-12
      • 2011-06-27
      • 2019-01-06
      相关资源
      最近更新 更多