php - 使用 AJAX 的 Symfony 4 验证器

标签 php jquery ajax forms symfony

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

在 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);
    });

Twig :

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

{% 结束 block %}

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

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

我是否必须使用handleRequest方法才能使用Symfony验证器及其验证方法isValid和isSubscribed? 或者说要走什么路?预先感谢您,抱歉我的英语不好

最佳答案

Symfony Controller Action 总是需要返回一些东西,把

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

关于php - 使用 AJAX 的 Symfony 4 验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52818549/

相关文章:

javascript - AJAX 和 JavaScript 对象中的问题

php - 如何将(美国/芝加哥)时间更改为印度(亚洲/加尔各答)时间

javascript - Google 可视化 API google.charts.Bar(chartDiv) 返回未定义

jquery - 如何按类查找元素并获取值?

javascript - 如何将自定义 jQuery 插件应用于多个元素?

php - 在每 6 秒加载一个页面的同一个 div 中使用 jQuery/Ajax 加载页面?

从 AJAX 请求中剥离 POST 的 PHP 配置?

php比较包含&的字符串

php - jQGrid - 从 Grid1 中选择行以填充 Grid2(MySQL、jQuery、PHP)

php - 迁移 blob 字段 mysqli