weixin_33721427 2018-10-15 14:04 采纳率: 0%
浏览 28

使用AJAX的Symfony 4验证器

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:

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

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

$.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:

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

  • 写回答

1条回答 默认 最新

  • perhaps? 2018-10-15 15:41
    关注

    Symfony controller actions always need to return something, put

    return new Response('not submitted');
    

    at the end of the action.

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

    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

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效