18

ユーザー作成用のフォームを作成しています。ユーザーを作成するときに、1つまたは複数の役割をユーザーに付与したいと思います。

で定義されているロールのリストを取得するにはどうすればよいsecurity.ymlですか?

現時点での私のフォームビルダーは次のとおりです。

public function buildForm(FormBuilder $builder, array $options)
{
    parent::buildForm($builder, $options);

    // add your custom fields
    $user = new User();
    $builder->add('regionUser');
    $builder->add('roles' ,'choice' ,array('choices' => $user->getRolesNames(),
            'required'  => true,
    ));

}

およびUser.php

public function getRolesNames(){
    return array(
        "ADMIN" => "Administrateur",
        "ANIMATOR" => "Animateur",
        "USER" => "Utilisateur",        
    );
}

もちろん、このソリューションは機能しません。これrolesは、データベースでビットマップとして定義されているため、choicesリストを作成できないためです。

前もって感謝します。

4

10 に答える 10

23

security.role_hierarchy.rolesコンテナパラメータは、役割階層を配列として保持します。これを一般化して、定義されたロールのリストを取得できます。

于 2012-06-28T17:18:32.553 に答える
14

このメソッドから到達可能なロールのリストを取得できます。

Symfony\Component\Security\Core\Role\RoleHierarchy::getReachableRoles(array $roles)

$roles配列パラメータのロールから到達可能なすべてのロールを返すようです。これはSymfonyの内部サービスであり、そのIDはsecurity.role_hierarchyパブリックであり、パブリックではありません(明示的にパラメーターとして渡す必要があり、サービスコンテナーからはアクセスできません)。

于 2012-06-28T15:27:56.347 に答える
9

このためのサービスを作成し、「security.role_hierarchy.roles」パラメーターを挿入できます。

サービス定義:

acme.user.roles:
   class: Acme\DemoBundle\Model\RolesHelper
   arguments: ['%security.role_hierarchy.roles%']

サービスクラス:

class RolesHelper
{
    private $rolesHierarchy;

    private $roles;

    public function __construct($rolesHierarchy)
    {
        $this->rolesHierarchy = $rolesHierarchy;
    }

    public function getRoles()
    {
        if($this->roles) {
            return $this->roles;
        }

        $roles = array();
        array_walk_recursive($this->rolesHierarchy, function($val) use (&$roles) {
            $roles[] = $val;
        });

        return $this->roles = array_unique($roles);
    }
}

次のように、コントローラーでロールを取得できます。

$roles = $this->get('acme.user.roles')->getRoles();
于 2014-07-24T06:05:39.190 に答える
9

自分の役割を正しく表現するには、再帰が必要です。ロールは他のロールを拡張できます。

例として、security.ymlの次の役割を使用します。

ROLE_SUPER_ADMIN: ROLE_ADMIN
ROLE_ADMIN:       ROLE_USER
ROLE_TEST:        ROLE_USER

この役割は次の方法で取得できます。

$originalRoles = $this->getParameter('security.role_hierarchy.roles');

再帰の例:

private function getRoles($originalRoles)
{
    $roles = array();

    /**
     * Get all unique roles
     */
    foreach ($originalRoles as $originalRole => $inheritedRoles) {
        foreach ($inheritedRoles as $inheritedRole) {
            $roles[$inheritedRole] = array();
        }

        $roles[$originalRole] = array();
    }

    /**
     * Get all inherited roles from the unique roles
     */
    foreach ($roles as $key => $role) {
        $roles[$key] = $this->getInheritedRoles($key, $originalRoles);
    }

    return $roles;
}

private function getInheritedRoles($role, $originalRoles, $roles = array())
{
    /**
     * If the role is not in the originalRoles array,
     * the role inherit no other roles.
     */
    if (!array_key_exists($role, $originalRoles)) {
        return $roles;
    }

    /**
     * Add all inherited roles to the roles array
     */
    foreach ($originalRoles[$role] as $inheritedRole) {
        $roles[$inheritedRole] = $inheritedRole;
    }

    /**
     * Check for each inhered role for other inherited roles
     */
    foreach ($originalRoles[$role] as $inheritedRole) {
        return $this->getInheritedRoles($inheritedRole, $originalRoles, $roles);
    }
}

出力:

array (
  'ROLE_USER' => array(),
  'ROLE_TEST' => array(
                        'ROLE_USER' => 'ROLE_USER',
  ),
  'ROLE_ADMIN' => array(
                        'ROLE_USER' => 'ROLE_USER',
  ),
  'ROLE_SUPER_ADMIN' => array(
                        'ROLE_ADMIN' => 'ROLE_ADMIN',
                        'ROLE_USER' => 'ROLE_USER',
  ),
)
于 2016-04-27T21:01:08.917 に答える
4

Symfony 3.3では、次のようにRolesType.phpを作成できます。

<?php

namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;

/**
 * @author Echarbeto
 */
class RolesType extends AbstractType {

  private $roles = [];

  public function __construct(RoleHierarchyInterface $rolehierarchy) {
    $roles = array();
    array_walk_recursive($rolehierarchy, function($val) use (&$roles) {
      $roles[$val] = $val;
    });
    ksort($roles);
    $this->roles = array_unique($roles);
  }

  public function configureOptions(OptionsResolver $resolver) {
    $resolver->setDefaults(array(
        'choices' => $this->roles,
        'attr' => array(
            'class' => 'form-control',
            'aria-hidden' => 'true',
            'ref' => 'input',
            'multiple' => '',
            'tabindex' => '-1'
        ),
        'required' => true,
        'multiple' => true,
        'empty_data' => null,
        'label_attr' => array(
            'class' => 'control-label'
        )
    ));
  }

  public function getParent() {
    return ChoiceType::class;
  }

}

次に、次のようにフォームに追加します。

$builder->add('roles', RolesType::class,array(
          'label' => 'Roles'
      ));

重要なのは、各役割も含まれている必要があることです。次に例を示します。ROLE_ADMIN:[ROLE_ADMIN、ROLE_USER]

于 2017-10-25T00:17:52.863 に答える
3

特定の役割のすべての継承された役割を取得する必要がある場合:

use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchy;

private function getRoles($role)
{
    $hierarchy = $this->container->getParameter('security.role_hierarchy.roles');
    $roleHierarchy = new RoleHierarchy($hierarchy);
    $roles = $roleHierarchy->getReachableRoles([new Role($role)]);
    return array_map(function(Role $role) { return $role->getRole(); }, $roles);
}

次に、この関数を呼び出します。$this->getRoles('ROLE_ADMIN');

于 2016-12-21T10:24:12.760 に答える
1

これは正確にはあなたが望むものではありませんが、それはあなたの例を機能させます:

use Vendor\myBundle\Entity\User;

public function buildForm(FormBuilder $builder, array $options)
{
    parent::buildForm($builder, $options);

    // add your custom fields
    $user = new User();
    $builder->add('regionUser');
    $builder->add('roles' ,'choice' ,array('choices' => User::getRolesNames(),
            'required'  => true,
    ));
}

ただし、エンティティからロールを取得することに関しては、エンティティリポジトリのものを使用してデータベースにクエリを実行できる場合があります。

これは、 queryBuilderを使用してエンティティリポジトリに必要なものを取得するための良い例です。

public function buildForm(FormBuilder $builder, array $options)
{
    parent::buildForm($builder, $options);

    // add your custom fields
    $user = new User();
    $builder->add('regionUser');
    $builder->add('roles' ,'entity' array(
                 'class'=>'Vendor\MyBundle\Entity\User',
                 'property'=>'roles',
                 'query_builder' => function (\Vendor\MyBundle\Entity\UserRepository $repository)
                 {
                     return $repository->createQueryBuilder('s')
                            ->add('orderBy', 's.sort_order ASC');
                 }
                )
          );
}

http://inchoo.net/tools-frameworks/symfony2-entity-field-type/

于 2012-06-28T14:42:44.407 に答える
1

Symfony 2.7では、コントローラーで$ this-> getParameters()を使用してロールを取得する必要があります。

$roles = array();
foreach ($this->getParameter('security.role_hierarchy.roles') as $key => $value) {
    $roles[] = $key;

    foreach ($value as $value2) {
        $roles[] = $value2;
    }
}
$roles = array_unique($roles);
于 2015-11-20T11:01:05.517 に答える
-2

これが私がしたことです:

FormType:

use FTW\GuildBundle\Entity\User;

class UserType extends AbstractType
{

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('username')
        ->add('email')
        ->add('enabled', null, array('required' => false))
        ->add('roles', 'choice', array(
        'choices' => User::getRoleNames(),
        'required' => false,'label'=>'Roles','multiple'=>true
    ))
        ->add('disableNotificationEmails', null, array('required' => false));
}

エンティティ内:

use Symfony\Component\Yaml\Parser; ...

static function getRoleNames()
{
    $pathToSecurity = __DIR__ . '/../../../..' . '/app/config/security.yml';
    $yaml = new Parser();
    $rolesArray = $yaml->parse(file_get_contents($pathToSecurity));
    $arrayKeys = array();
    foreach ($rolesArray['security']['role_hierarchy'] as $key => $value)
    {
        //never allow assigning super admin
        if ($key != 'ROLE_SUPER_ADMIN')
            $arrayKeys[$key] = User::convertRoleToLabel($key);
        //skip values that are arrays --- roles with multiple sub-roles
        if (!is_array($value))
            if ($value != 'ROLE_SUPER_ADMIN')
                $arrayKeys[$value] = User::convertRoleToLabel($value);
    }
    //sort for display purposes
    asort($arrayKeys);
    return $arrayKeys;
}

static private function convertRoleToLabel($role)
{
    $roleDisplay = str_replace('ROLE_', '', $role);
    $roleDisplay = str_replace('_', ' ', $roleDisplay);
    return ucwords(strtolower($roleDisplay));
}

フィードバックを提供してください...私は他の回答からいくつかの提案を使用しましたが、それでもこれは最善の解決策ではないと感じています!

于 2013-01-22T01:23:42.257 に答える
-3
//FormType
use Symfony\Component\Yaml\Parser;

function getRolesNames(){
        $pathToSecurity = /var/mydirectory/app/config/security.yml
        $yaml = new Parser();
        $rolesArray = $yaml->parse(file_get_contents($pathToSecurity ));

        return $rolesArray['security']['role_hierarchy']['ROLE_USER'];
}

これは、これまでのところ、構成ファイルから必要なものを取得または設定するための最良の方法です。

ボン勇気

于 2012-06-28T15:22:07.407 に答える