symfony3没有重定向到ajax调用

时间:2017-10-01 21:58:11

标签: php ajax symfony redirect

我试图通过ajax在Symfony3上提交表单,但我遇到了问题,因为有时它不会重定向到" ShowView"保存数据后。

如果输入的数据在第一个ajax调用中有效,则会保存数据,但不会重定向。

如果输入的数据在第一次ajax调用中无效,则会正确刷新表单,然后我更正数据并再次提交,这次保存数据并重定向正确。

我不知道为什么有时它会重定向正确而有些则不重定向。 somebady可以帮助我,plaese。

这是我的实体:

<?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;
    }
}

控制器:

<?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的:

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

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

这是一个简单的Symfony3代码,感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

感谢各位帮助,

我发现我的代码是完全错误的,在第一次AJAX调用时,我正在用另一种形式(表单形式)替换表单内容,当发生第二次AJAX调用失败时,因为它发送了一个空表单。

我更改了我的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>

我也改变了我的控制器:

//...
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()]));