1

我正在尝试在一个简单的网站中实现这一点,以节省我的金钱开支。所以我希望能够在不刷新页面的情况下保存我的数据。

控制器:

namespace yz\BstBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use yz\BstBundle\Entity\Money;
use yz\BstBundle\Form\MoneyType;

/**
 * Money controller.
 *
 */
class MoneyController extends Controller
{
    /**
     * Lists all Money entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('yzBstBundle:Money')->findAll();

        return $this->render('yzBstBundle:Money:index.html.twig', array(
            'entities' => $entities,
        ));
    }

    /**
     * Creates a new Money entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity  = new Money();
        $form = $this->createForm(new MoneyType(), $entity);
        $form->bind($request);

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

            return $this->redirect($this->generateUrl('money_show', array('id' => $entity->getId())));
        }

        return $this->render('yzBstBundle:Money:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Displays a form to create a new Money entity.
     *
     */
    public function newAction()
    {
        $entity = new Money();
        $form   = $this->createForm(new MoneyType(), $entity);

        return $this->render('yzBstBundle:Money:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Money entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('yzBstBundle:Money')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Money entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('yzBstBundle:Money:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        ));
    }

    /**
     * Displays a form to edit an existing Money entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('yzBstBundle:Money')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Money entity.');
        }

        $editForm = $this->createForm(new MoneyType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

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

    /**
     * Edits an existing Money entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('yzBstBundle:Money')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Money entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new MoneyType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('money_edit', array('id' => $id)));
        }

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

    /**
     * Deletes a Money entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('yzBstBundle:Money')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Money entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('money'));
    }

    /**
     * Creates a form to delete a Money entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}

树枝模板:

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

    {% block body -%}
        <h1>Money creation</h1>

        <form action="{{ path('money_create') }}" method="post" {{ form_enctype(form) }}>
            {{ form_widget(form) }}
            <p>
                <button type="submit">Create</button>
            </p>
        </form>

            <ul class="record_actions">
        <li>
            <a href="{{ path('money') }}">
                Back to the list
            </a>
        </li>
    </ul>
    {% endblock %}

表单类型

namespace yz\BstBundle\Form;

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

class MoneyType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('created_at')
            ->add('type')
            ->add('price')
            ->add('comment')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'yz\BstBundle\Entity\Money'
        ));
    }

    public function getName()
    {
        return 'yz_bstbundle_moneytype';
    }
}
4

2 回答 2

4

要回答您的问题已更改,以下是您的案例的解决方案:

控制器:

/**
 * Creates a new Money entity.
 *
 */
public function createAction(Request $request)
{
    $entity  = new Money();
    $form = $this->createForm(new MoneyType(), $entity);
    $form->bind($request);

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

        if($request->isXmlHttpRequest()) {
             $response = new Response();
             $output = array('success' => true, 'type' => $entity->getType(), 'id' => $entity->getId(), 'comment' => $entity->getComment(), 'price' => $entity->getPrice());
             $response->headers->set('Content-Type', 'application/json');
             $response->setContent(json_encode($output));

             return $response;
        }

        return $this->redirect($this->generateUrl('money_show', array('id' => $entity->getId())));
    }

    return $this->render('yzBstBundle:Money:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}

模板

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

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

    <form action="{{ path('money_create') }}" method="post" {{ form_enctype(form) }}>
        {{ form_widget(form) }}
        <p>
            <button type="submit">Create</button>
        </p>
    </form>

        <ul class="record_actions">
    <li>
        <a href="{{ path('money') }}">
            Back to the list
        </a>
    </li>
</ul>
<div id="result"></div>
{% endblock %}

{% block javascripts %}
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script type="text/javascript">
     $().ready(function() {
         $("form").submit(function(e) {
             e.preventDefault();
             var $url = $(this).attr('action');
             var $data = $(this).serialize();
             $.ajax({
                type: "POST",
                url: $url,
                data: $data
             }).done(function( result ) {
                if(result.success) {
                    $('#result').html('<span>Monetary expense correctly saved!<br/> The data are:<br/>id: '+ result.id +'<br/>type: '+ result.type +'<br/>price: '+ result.price +'<br/>comment: '+ result.comment +'</span>');
                }
             });
         });
     });
     </script>
{% endblock %}

该解决方案功能齐全,随着时间的推移,您将学习许多替代方法来加快速度,例如使用 JsonResponse() 类或适合将对象序列化为 JMS Serializer Bundle 的出色包......

但我们不会把太多的肉放在火上!

我希望你能提供帮助!

编辑:

我打错$entity-getPrice()了,而不是$entity->getPrice().

ajax 调用中的类型必须是 POST。

如果您还没有这样做,请记住在控制器开头输入此行:

use Symfony\Component\HttpFoundation\Response;

现在它完美地工作了。

于 2013-07-31T00:30:55.373 回答
2

正如你所说@Pazi,问题很简单。

创建指向控制器的普通路由,控制器响应生成视图 json.twig 而不是视图 html.twig。

例如:

控制器:

/**
 * Add vote
 *
 * @Route("/{id}/add/", name="add", defaults={"_format"="json"})
 * @Template
 */
public function addAction(Vote $vote)
{
    //your logic...

    if (!$this->getRequest()->isXmlHttpRequest()) {
        return $this->redirect($this->generateUrl('homepage'));
    }

    return $vote;
}

模板(add.json.twig):

{%
  set data = {
    'id'        : vote.id,
    'total'     : vote.total,

    //your data..
  }
%}
{{ data|json_encode|raw }}

最后你的客户部分:

$.ajax({
      url: url //the url that points to the route /add (I recommend using FOSJsRoutingBundle to create routes dynamically)
}).done(function() { 
      //your response logic.. 
});

这是使用 Symfony2 处理 ajax 调用的方法之一。

我希望你对你有所帮助。

于 2013-07-28T23:45:54.663 回答