简体   繁体   English

symfony3不在ajax调用上重定向

[英]symfony3 not redirecting on ajax call

I'm trying to submit a form via ajax on Symfony3, but I have a problem because sometimes it does not redirect to "ShowView" after saving the data. 我正在尝试通过Symfony3上的Ajax提交表单,但是有一个问题,因为有时在保存数据后它不会重定向到“ ShowView”。

If the entered data is valid in the first ajax call it saves the data, but it does not redirect. 如果在第一个ajax调用中输入的数据有效,它将保存数据,但不会重定向。

If the entered data is invalid in the first ajax call it refresh the form correctly then I correct the data and submit it again, this time it saves the data and it redirects correctly. 如果在第一个ajax调用中输入的数据无效,它将正确刷新表单,然后我更正数据并再次提交,这一次它将保存数据并正确地重定向。

I do not know why sometimes it redirects correcty and others it does not. 我不知道为什么有时它会重定向正确性,而其他人却不这样做。 Can somebady help me, plaese. 拜拜,能不能帮我一下。

This is my entity: 这是我的实体:

<?php

namespace PruebaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;


/**
 * Prueba
 *
 * @ORM\Table(name="prueba")
 * @ORM\Entity(repositoryClass="PruebaBundle\Repository\PruebaRepository")
 */
class Prueba
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     * @Assert\NotBlank(message="Ingresar un valor")
     * @Assert\Length(
     *      min = 2,
     *      max = 10,
     *      minMessage = "La descripcion debe tener un minimo de {{ limit }} caracteres de longitud",
     *      maxMessage = "La descripcion debe tener un maximo de {{ limit }} caracteres de longitud"
     * )
     * @ORM\Column(name="descripcion", type="string", length=100)
     *
     */
    private $descripcion;


    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set descripcion
     *
     * @param string $descripcion
     *
     * @return Prueba
     */
    public function setDescripcion($descripcion)
    {
        $this->descripcion = $descripcion;

        return $this;
    }

    /**
     * Get descripcion
     *
     * @return string
     */
    public function getDescripcion()
    {
        return $this->descripcion;
    }
}

Controller: 控制器:

<?php

namespace PruebaBundle\Controller;

use PruebaBundle\Entity\Prueba;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

/**
 * Prueba controller.
 *
 * @Route("prueba")
 */
class PruebaController extends Controller {

    /**
     * Lists all prueba entities.
     *
     * @Route("/", name="prueba_index")
     * @Method("GET")
     */
    public function indexAction() {
        $em = $this->getDoctrine()->getManager();

        $pruebas = $em->getRepository('PruebaBundle:Prueba')->findAll();

        return $this->render('PruebaBundle:Prueba:index.html.twig', array(
                    'pruebas' => $pruebas,
        ));
    }

    /**
     * Creates a new prueba entity.
     *
     * @Route("/new", name="prueba_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request) {
        $prueba = new Prueba();
        $form = $this->createForm('PruebaBundle\Form\PruebaType', $prueba);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($prueba);
            $em->flush();

            return $this->redirectToRoute('prueba_show', array('id' => $prueba->getId()));

        }

        return $this->render('PruebaBundle:Prueba:new.html.twig', array(
                    'prueba' => $prueba,
                    'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a prueba entity.
     *
     * @Route("/{id}", name="prueba_show")
     * @Method("GET")
     */
    public function showAction(Prueba $prueba) {
        $deleteForm = $this->createDeleteForm($prueba);

        return $this->render('PruebaBundle:Prueba:show.html.twig', array(
                    'prueba' => $prueba,
                    'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing prueba entity.
     *
     * @Route("/{id}/edit", name="prueba_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, Prueba $prueba) {
        $deleteForm = $this->createDeleteForm($prueba);
        $editForm = $this->createForm('PruebaBundle\Form\PruebaType', $prueba);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('prueba_edit', array('id' => $prueba->getId()));
        }

        return $this->render('PruebaBundle:Prueba:edit.html.twig', array(
                    'prueba' => $prueba,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a prueba entity.
     *
     * @Route("/{id}", name="prueba_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, Prueba $prueba) {
        $form = $this->createDeleteForm($prueba);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($prueba);
            $em->flush();
        }

        return $this->redirectToRoute('prueba_index');
    }

    /**
     * Creates a form to delete a prueba entity.
     *
     * @param Prueba $prueba The prueba entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(Prueba $prueba) {
        return $this->createFormBuilder()
                        ->setAction($this->generateUrl('prueba_delete', array('id' => $prueba->getId())))
                        ->setMethod('DELETE')
                        ->getForm()
        ;
    }

}

FormType: 表格类型:

<?php

namespace PruebaBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PruebaType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('descripcion');
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'PruebaBundle\Entity\Prueba',
            'attr' => array('id' => 'prueba_form',
                            'novalidate' => 'novalidate'
                           )
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'pruebabundle_prueba';
    }


}

NewView: NewView:

{% extends 'base.html.twig' %}

{% block body %}
    <h1>Prueba creation</h1>

    {{ form_start(form) }}
    {{ form_errors(form) }}

    <div>
        {{ form_label(form.descripcion) }}
        {{ form_widget(form.descripcion) }} {{ form_errors(form.descripcion) }}
    </div>
    <input type="submit" value="Create" />
    {{ form_end(form) }}

    <ul>
        <li>
            <a href="{{ path('prueba_index') }}">Back to the list</a>
        </li>
    </ul>


{% endblock %}

{% block javascripts %}            
    <script>

        $(document).ready(function () {
            var $form = $('#prueba_form');
            $form.submit(function (e) {
                e.preventDefault();

                $.ajax({
                    url: $form.attr('action'),
                    type: $form.attr('method'),
                    data: $form.serialize(),

                    success: function (html) {
                        $form.html($(html).filter('#prueba_form'));
                    },
                    error: function (data) {
                        alert("error" + data);
                    }
                });

            });
        });
    </script>
{% endblock %}

ShowView: ShowView:

{% extends 'base.html.twig' %}

{% block body %}
    <h1>Prueba</h1>

    <table>
        <tbody>
            <tr>
                <th>Id</th>
                <td>{{ prueba.id }}</td>
            </tr>
            <tr>
                <th>Descripcion</th>
                <td>{{ prueba.descripcion }}</td>
            </tr>
        </tbody>
    </table>

    <ul>
        <li>
            <a href="{{ path('prueba_index') }}">Back to the list</a>
        </li>
        <li>
            <a href="{{ path('prueba_edit', { 'id': prueba.id }) }}">Edit</a>
        </li>
        <li>
            {{ form_start(delete_form) }}
                <input type="submit" value="Delete">
            {{ form_end(delete_form) }}
        </li>
    </ul>
{% endblock %}

It is a simple Symfony3 code, thanks for your help. 这是一个简单的Symfony3代码,感谢您的帮助。

Thanks Guys for your help, 谢谢大家帮助,

I found that my code was completely wrong, at the first AJAX call I was replacing the form content whith another form (form into form), when that happend the second AJAX call failed because it was sending an empty form. 我发现我的代码是完全错误的,在第一次AJAX调用中,我正在替换表单内容,而在另一种表单中(表单转换为表单),第二次AJAX调用因发送空表单而失败。

I changeg my View Javascript: 我更改了View Javascript:

//...
<script>

    $(document).ready(function () {
        observForm();
    });

    function observForm() {
        var $inputSubmit = $('#prueba_form :submit');
        $inputSubmit.on('click', function () {
            setClick();
            return false;
        });
    }

    function setClick() {
        var $form = $('#prueba_form');

        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),

            success: function (html) {
                if (html.startsWith('route::')) {
                    route = html.replace('route::', '');
                    location.href = route;
                } else {
                    $form.html($(html).filter('#prueba_form').html());
                    observForm();
                }

            },
            error: function (data) {
                alert("error" + data);
            }
        });
    }
</script>

And I also changed my controller: 我还更改了控制器:

//...
use Symfony\Component\HttpFoundation\JsonResponse;
//...
            //return $this->redirectToRoute('prueba_show', array('id' => $prueba->getId()));
            return new JsonResponse('route::'.$this->get('router')->generate('prueba_show', ['id' => $prueba->getId()])); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM