Symfony2: List Users with Option to Deactivate Each User

牧云@^-^@ 提交于 2019-12-25 12:42:55

问题


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.

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.

UPDATE

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

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

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>

回答1:


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(); 

}

On your view:

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

});


来源:https://stackoverflow.com/questions/33787647/symfony2-list-users-with-option-to-deactivate-each-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!