2012-08-04 12 views
7

フィクスチャから新しいユーザ管理を作成しようとしています。私はFOSUserBundleとSymfony2を使用しています。datafixturesとfosuserbundleを使用して管理者を作成する

$userManager = $this->container->get('fos_user.user_manager'); 

//$userAdmin = $userManager->createUser(); 

$userAdmin = new UserAdmin(); 
$userAdmin->setUsername('francis'); 
$userAdmin->setEmail('[email protected]'); 
$userAdmin->setEnabled(true); 
$userAdmin->setRoles(array('ROLE_ADMIN')); 

$userManager->updateUser($userAdmin, true); 

私はいつもこのエラーを取得しています:

[ErrorException]           
Notice: Undefined property:  
INCES\ComedorBundle\DataFixtures\ORM\LoadUserAdminData::$container in 
/public_html/Symfony/src/INCES/ComedorBundle/DataFixtures/ORM/LoadUserAdminData.php line 16 
+0

なぜfos:user:promoteを使用しないのですか? –

+0

プロダクションサーバーでアプリケーションを初めて実行するときに管理者ユーザーを作成したいと考えています。もし私がよく知っているのは、すでに作成されたユーザーの役割を変更するためのものですが、正確には私が望むものではありません。 –

答えて

25

これは、(iもFOSUserBundleを使用しています)私の仕事:

// Change the namespace! 
namespace Acme\DemoBundle\DataFixtures\ORM; 

use Doctrine\Common\DataFixtures\FixtureInterface; 
use Doctrine\Common\Persistence\ObjectManager; 
use Symfony\Component\DependencyInjection\ContainerAwareInterface; 
use Symfony\Component\DependencyInjection\ContainerInterface; 

class LoadUserData implements FixtureInterface, ContainerAwareInterface 
{ 
    //.. $container declaration & setter 

    public function load(ObjectManager $manager) 
    { 
     // Get our userManager, you must implement `ContainerAwareInterface` 
     $userManager = $this->container->get('fos_user.user_manager'); 

     // Create our user and set details 
     $user = $userManager->createUser(); 
     $user->setUsername('username'); 
     $user->setEmail('[email protected]'); 
     $user->setPlainPassword('password'); 
     //$user->setPassword('3NCRYPT3D-V3R51ON'); 
     $user->setEnabled(true); 
     $user->setRoles(array('ROLE_ADMIN')); 

     // Update the user 
     $userManager->updateUser($user, true); 
    } 
} 

が、これは誰かに役立ちます願っています! :)

+0

あまりにも私の仕事を冷やして:) Tnx。 https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/user_manager.md - 誰かが何か別のことをしたいのなら、これはuserManagerのドキュメントです:) – Petroff

+0

これはうまくいきます。共有してくれてありがとう。 +1 – BentCoder

3

は、ドキュメントのthisセクションに従ってください。

+0

ベストアンサー。ありがとうございました。 –

2

エラーは、$コンテナが現在未定義であるためです。これを修正するには、クラス定義にContainerAwareInterfaceを追加します。

UserManagerを使用せずにユーザーを作成するため、これで目的のものは完全には得られません。代わりに、コメントアウトした行を使用する必要があります。

UserAdminクラスは必要ありません。管理ユーザーは、所有している役割だけで区別されるユーザーのサブセットでなければなりません。

UserManagerを使用してUser(UserAdminではなく)Userを作成し、役割を設定する必要があります。 すべての管理者ユーザーのインデックスを保持する必要がある場合は、MySQL VIEWがこれを達成するか、独自のカスタム "キャッシュ"テーブルを作成し、Doctrine Listenersを使用して必要に応じて更新できます。

この質問はかなり古いので、私はあなたが答えを見つけたか、少なくとも回避策を見つけています。 お願いしますか?あなた自身の質問に答えても大丈夫です。

関連する問題