Symfony2:列出具有停用每个用户选项的用户 [英] Symfony2: List Users with Option to Deactivate Each User

查看:39
本文介绍了Symfony2:列出具有停用每个用户选项的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序的管理面板中,我显示了当前在数据库中标记为活动"的用户列表.

In my application's admin panel, I am showing a list of users who are currently marked as "Active" in the database.

       <ul class="list-group">
          {% for activeuser in activeusers %}
            <li class="list-group-item">
              {{ activeuser.username|e }}
              <input type="checkbox" name="my-checkbox" class="ckbx" checked>
            </li>
          {% endfor %}
        </ul>

如您所见,每个活动用户列表项现在都有一个占位符复选框,当用户处于活动状态时(您猜对了)会选中该复选框.

As you can see, each active user list item has a placeholder checkbox for now which is checked when the user is, you guessed it, active.

我希望能够简单地取消选中该复选框,然后运行 ​​AJAX 调用来更新数据库以将用户标记为非活动状态.我的第一直觉是为我的控制器中的每个用户对象创建一个表单,但这似乎会变得非常混乱.另外,我不能简单地传入一个

I would like to be able to simply uncheck the checkbox, and then run an AJAX call to update the database to mark the user as inactive. My first instinct was to create a form for each user object in my controller, but it seems like that would get incredibly messy. Also, I can't simply pass in a

'form' => $form->createView()

来自我的控制器,因为大概每个用户都必须有一个表单.我读过的关于这个主题的任何文档似乎都没有为这个特定问题提供任何帮助.

from my controller as there presumably has to be one form for each user. Any of the documentation I have read on the subject doesn't seem to provide any help for this particular problem.

更新

我在我的控制器中创建了一个函数来创建一个通用的用户更新表单:

I created a function within my controller to create a generic user update form:

   /**
     * Creates a form to create a User entity.
     *
     * @param User $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    public function createUserForm(User $entity){
      $form = $this->createForm(new UserType(), $entity, array(
          'action' => $this->generateUrl('user_update', array('id' => $entity->getId())),
          'method' => 'PUT',
      ));

      return $form;
    }

表单由 UserType 类生成

The form is generated by the UserType class

class UserType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('isActive', 'checkbox');
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\User'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'appbundle_user';
    }
}

现在在主要操作(称为dashboardAction)中,我得到一个用户列表,并为每个用户生成一个表单.不要忘记在每次生成表单时运行 createView()!

Now inside of the main action (called dashboardAction), I get a list of users and for each of user, generate a form for it. Don't forget to run createView() on each form generation!

public function dashboardAction()
    {
      $userService = new UserService($this->getDoctrine()->getManager());
      $activeUsers = $userService->listUsers('active');
      $inactiveUsers = $userService->listUsers('inactive');

      $formify_activeUsers = array();
      foreach($activeUsers as $activeUser){
        $formify_activeUsers[] = $this->createUserForm($activeUser)->createView();
      };
      return $this->render('AppBundle:Admin:dashboard.html.twig', 
          array('page_title' => 'Administration Panel', 
                'activeusers' => $formify_activeUsers,
          )
      );  
    }

然后树枝代码看起来像这样:

Then the twig code looks like this:

   <ul class="list-group">
      {% for activeuser in activeusers %}
        <li class="list-group-item">
          {{ form_start(activeuser) }}
          {{ form_widget(activeuser) }}
          {{ form_end(activeuser) }}

        </li>
      {% endfor %}
    </ul>

推荐答案

如果您真正想要的是激活/停用用户,为什么要将表单的开销置于这种情况下.

If what you really want is to activate/desactivate an user why put the overhead of the forms in this situation.

您可以简单地创建一个操作:

You could simply create an action:

/**
 * @Route("/admin/isactive", name="isactive")
 * @Method("POST")
 */
public function deactivateUserAction($id){

   $em = $this->getDoctrine();

   $user= $em 
        ->getRepository('AppBundle\Entity\User')
        ->find($id);

    if (!$user) {
        throw $this->createNotFoundException(
            'No userfound for id '.$id
        );
    }

    $user->setActive(false);

    $em->getManager()->flush($user);

    return new JsonResponse(); 

}

在您看来:

<ul class="list-group">
      {% for activeUser in activeusers %}
        <li class="list-group-item">

             <input class="user-status" type="checkbox" value="{{activeUser.id}}">{{activeUser.name}}

        </li>
      {% endfor %}
    </ul>

将点击事件附加到您的复选框中.

Attach a on click event into your checkboxs.

$('.user-status).on('click', function(e){

    $.post("{{ path('isactive') }}", {userId: $(this).val()})
      .done(function(data){
        alert("Data loaded: " + data);
      });

});

这篇关于Symfony2:列出具有停用每个用户选项的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆