如何在服务器响应后在Symfony2中显示警报或信息消息而不重新加载页面

时间:2014-09-02 16:55:46

标签: javascript php jquery ajax symfony

我正在使用Symfony2构建配镜师的管理应用程序。当管理员将新客户添加到数据库时,我的控制器会检查客户名称是否重复。我想显示一个弹出对话框,询问用户是否要添加新客户。我该如何实现呢?我应该使用Ajax吗?以下是我在这种情况下使用的控制器的示例代码:

public function nouveauAction(Request $request)
{
    $form = $this->createFormBuilder()
        ->add('nom','text')
        ->add('tel','text', array('label' => 'Nº de téléphone', 'data' => '06'))
        ->add('email','email', array('label' => 'E-mail', 'required' => false))
        ->add('date','date', array('label' => 'Date d\'ajout', 'data' => new \DateTime()))
        ->add('ajouter','submit')
        ->getForm()
    ;

    $form->handleRequest($request);

    if ($form->isValid()){

        $client = new Client();
        $client->setNomClient($form["nom"]->getData());
        $client->setTelClient($form["tel"]->getData());
        $client->setEmailClient($form["email"]->getData());
        $client->setDateEditionClient($form["date"]->getData());
        //just for now (Later we'll retrieve the username from the session)
        $em = $this->getDoctrine()->getEntityManager();
        $user = (new Utilisateur)->rechercherParPseudo($em, 'admin');
        $client->setIdUtilisateur($user);

        $em = $this->getDoctrine()->getEntityManager();

        if($client->existe($em))
        {
            //I need a popup message here : The customer you are trying to add already exists""
        }

        else
        {
            $request = $this->container->get('request');
            if($client->existeNomDouble($em)) //If the customer name is duplicate
            {
                //I need a popup message here with Yes/No buttons...
            }
            else
            {
                //Writing to the database:
                $em = $this->getDoctrine()->getEntityManager();
                $client->ajouterClient($em);

                //A notification to fade in here : "Customer successfully added"
            }


        }

    }

    return $this->render('ClientBundle:Client:nouveau.html.twig', array(
        'formAjouter' => $form->createView(),
    ));
}

2 个答案:

答案 0 :(得分:8)

试试这个:

控制器端:

 $this->get('session')->getFlashBag()->add(
        'notice',
        'Customer Added!'
    );

查看侧面(Twig):

{% for flashMessage in app.session.flashbag.get('notice') %}

<div class="alert alert-success">
    {{ flashMessage }}
</div>

{% endfor %}

答案 1 :(得分:0)

您是否在点击按钮后询问是否应该使用ajax来显示弹出窗口?如果是这样,我建议使用ajax。这是我之前在symfony中使用过的一个Bootstrap库,它应该派上用场:http://vitalets.github.io/x-editable/