从表单输入中调用特定控制器的操作

时间:2014-09-08 20:50:51

标签: forms symfony twig

在我看来,你可以看到其他用户'个人资料,我想添加一个只对管理员和版主可见的小表单,他们可以选择他们想要给显示的用户的角色。

我创建了一个控制器,其中包含针对每种促销类型的操作(对于每种促销类型,要求不同(例如:只有管理员可以提升某人管理员角色)并且可以更改)。

现在我不确定我是否应该:

*在我的Twig视图中创建一个并以某种方式(请帮助我),根据输入重定向到操作(可能这样)

{% if is_granted("ROLE_MODERATEUR") %}
                        Rendre ce membre : 
                                <form name="form" >
                                <select>
                                    <option >Sélectionner un rôle</option>
                                    {% if is_granted("ROLE_ADMIN") %}
                                    <option value="{{ path('annuaire_admin_admin', {id:membre.id}) }}" >Administrateur</option>
                                    {% endif %}
                                    <option value="{{ path('annuaire_admin_moderateur', {id:membre.id})}}" >Modérateur</option>
                                    <option value="{{ path('annuaire_admin_actif', {id:membre.id})}}" >Utilisateur actif</option>
                                    <option value="{{ path('annuaire_admin_passif', {id:membre.id}) }}" >Utilisateur passif</option>
                                </select>
                                <input type="submit" value="Confirmer">
                                </form>
                    {% endif %}

*创建更多内容&#34; symfony like&#34;像FormType或类来处理这个功能。

这是我的控制器:

namespace Cua\AnnuaireBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class AdminController extends Controller
{

    public function adminAction($id)
    {   
        if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedException();
        }elseif (isset($id)){

            $membre =$this->getDoctrine()
            ->getManager()
            ->getRepository('CuaUserBundle:Membre')
            ->find($id);

        // Ou nul si aucun membre  n'a été trouvé avec l'id $id
            if($membre === null)
            {
            throw $this->createNotFoundException('Membre[id='.$id.'] inexistant.');

            }
            $membre->setRole("ROLE_ADMIN");
        }
    }

    public function moderateurAction($id)
    {
        if (false === $this->get('security.context')->isGranted('ROLE_MODERATEUR')) {
            throw new AccessDeniedException();
        }elseif (isset($id)){

            $membre =$this->getDoctrine()
            ->getManager()
            ->getRepository('CuaUserBundle:Membre')
            ->find($id);

            // Ou nul si aucun membre  n'a été trouvé avec l'id $id
            if($membre === null)
            {
                throw $this->createNotFoundException('Membre[id='.$id.'] inexistant.');

            }
            if (!$membre->hasRole("ROLE_ADMIN") or $this->get('security.context')->isGranted('ROLE_ADMIN')){
                $membre->setRole("ROLE_MODERATEUR");
            }
        }
    }

    public function actifAction($id)
    {
        if (false === $this->get('security.context')->isGranted('ROLE_MODERATEUR')) {
            throw new AccessDeniedException();
        }elseif (isset($id)){

            $membre =$this->getDoctrine()
            ->getManager()
            ->getRepository('CuaUserBundle:Membre')
            ->find($id);

            // Ou nul si aucun membre  n'a été trouvé avec l'id $id
            if($membre === null)
            {
                throw $this->createNotFoundException('Membre[id='.$id.'] inexistant.');

            }
            if (!$membre->hasRole("ROLE_ADMIN") or $this->get('security.context')->isGranted('ROLE_ADMIN')){
                $membre->setRole("ROLE_UTILISATEUR_ACTIF");
            }
        }
    }

    public function passifAction($id)
    {
        if (false === $this->get('security.context')->isGranted('ROLE_MODERATEUR')) {
            throw new AccessDeniedException();
        }elseif (isset($id)){

            $membre =$this->getDoctrine()
            ->getManager()
            ->getRepository('CuaUserBundle:Membre')
            ->find($id);

            // Ou nul si aucun membre  n'a été trouvé avec l'id $id
            if($membre === null)
            {
                throw $this->createNotFoundException('Membre[id='.$id.'] inexistant.');

            }
            if (!$membre->hasRole("ROLE_ADMIN") or $this->get('security.context')->isGranted('ROLE_ADMIN')){
                $membre->setRole("ROLE_UTILISATEUR_PASSIF");
            }
        }
    }
}

感谢您的建议!

3 个答案:

答案 0 :(得分:1)

你有两个独立的问题。

Symfony Forms

基本表单结构

为了创建表单,我同意Haig的说法,制作FormType可能是最好的:它非常好地打包所有内容,并且很容易。你的表格非常简单(一个领域),所以这取决于你。无论哪种方式,我都会使用Symfony的Form基础结构(生成HTML,处理提交和处理HTTP数据到对象),这非常方便。

多项操作

至于表单提交如何根据下拉列表导致不同的活动,在您的示例中,您的下拉列表中有多个角色作为选项,并且您希望每个选项都能达到不同的Symfony Action。这是可能的 - 您可以使用Javascript根据所选的选项更改表单操作 - 但不整洁。更好,更适合Symfony Forms,将他们全部转到一个Action(例如roleAction),然后在该Action中检查role字段并执行另一个方法来执行所需的任务(这些方法与您现有的操作类似)。

e.g。

<强> FormType

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

class RoleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('role', 'choice', ['choices' => ['admin'=>'Administrateur', 'actif'=>'Actif']]) //etc etc
            ->add('save', 'submit');
    }

    public function getName()
    {
        return 'role';
    }
}

<强>控制器

public function roleAction(Request $request, $id)
{   
    //We could create an object representing the data behind the form here,
    //but we don't have to.  If we don't, we get a simple array back
    //http://symfony.com/doc/current/book/forms.html#using-a-form-without-a-class
    $form = $this->createForm(new RoleType() ); //Object representing form itself

    $form->handleRequest($request);

    if ($form->isValid() )
    {
         //Get the data from the form, in the form of an array
         $data = $form->getData();

         //Get role chosen from form data (key is fieldname) and choose appropriate method to make change
         switch($data['role'] ) 
             case "moderateur":
                 $this->donneModerateur($id);
                 break;
             case "actif":
                 $this->donneActif($id);
                 break;
             //etc etc
    }
}

private function donneModerateur($id)
{
    //Similar to previous Action
}

您需要将表单设置为提交到包含用户ID的网址,例如->setAction($this->generateUrl('annuaire_admin_', ['id'=>$user->getId()]))

答案 1 :(得分:0)

我倾向于使用Symfony表单类型类而不是直接将表单嵌入到视图中。这是因为表单类型类是非常可重用的,表单处理和验证是为您完成的(导致更精简的控制器和模型),并且如果您需要添加更多字段,它很容易扩展。

我当然建议走那条路。根据我的经验,一旦您了解了如何创建和使用Symfony表单模型和类型,它就会感觉非常笨拙和低效,可以追溯到硬编码形式。如何做到这一点有很好的记录:

Creating Forms from Classes

答案 2 :(得分:0)

我不确定,如果它在这里我应该发布,但评论部分太短。 所以这是我的MainController(ProfilController):

<?php

namespace Cua\AnnuaireBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Cua\AnnuaireBundle\Form\Type\RoleType;
class ProfilController extends Controller
{

    public function voirAction($id)
    {   
        $request=$this->get('request');
        if ($request->getMethod() == 'POST') {
            $admin=$this->get('admin');
            $admin->roleAction($request, $id);
        }
        if (isset($id))
        {   

            $membre =$this->getDoctrine()
            ->getManager()
            ->getRepository('CuaUserBundle:Membre')
            ->find($id);

        // Ou nul si aucun membre  n'a été trouvé avec l'id $id
            if($membre === null)
            {
            throw $this->createNotFoundException('Membre[id='.$id.'] inexistant.');

            }
        }else{
            $membre=$this->getUser();
        }
        $form=$this->CreateForm(new RoleType());
        $postes=$this->getDoctrine()->getManager()->getRepository('CuaAnnuaireBundle:Poste')->listerPostes($membre);
        $cheerups=$this->getDoctrine()->getManager()->getRepository('CuaAnnuaireBundle:Cheerup')->listerCheerups($membre);
        return $this->render('CuaAnnuaireBundle:Profil:voir.html.twig', array('membre' => $membre, 'postes'=>$postes, 'form'=>$form->CreateView(), 'cheerups' =>$cheerups
        ));
    }
}

这是我修改过的AdminController:

<?php

namespace Cua\AnnuaireBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Cua\AnnuaireBundle\Form\Type\RoleType;
class AdminController extends Controller
{

    public function roleAction($donnees, $id)
    {
        //We could create an object representing the data behind the form here,
        //but we don't have to.  If we don't, we get a simple array back
        $form2 = $this->createForm(new RoleType() ); //Object representing form itself

        $form2->handleRequest($donnees);

            if ($form2->isValid() )
            {
                 //Get the data from the form, in the form of an array
                 $data = $form2->getData();

                 //Get role chosen from form data (key is fieldname) and choose appropriate method to make change
                 switch($data['role'] ) { 
                     case "admin":
                         $this->donneAdmin($id);
                         break;//etc

我使用了RoleType Frumious建议。 当我提交表单时,我得到了这个例子:“FatalErrorException:Error:在C:\ wamp \ www \ CuaProject \ vendor \ symfony \ symfony \ src \ Symfony \ Bundle中的非对象上调用成员函数get() \ FrameworkBundle \ Controller \ Controller.php第163行

我不确定我使用命名空间:

**我打电话给AdminController传递“$ donnees”可能会改变“$ request”的类型。也许这是不必要的,因为我仍然可以访问我的管理员中的“$ request”:roleAction知道命名空间是一样的吗?

*我在AdminController“form2”中命名了表单,因为命名空间是相同的,我想避免冲突(是否有必要?)

相关问题