如上所述,您可以根据我使用的这段代码创建您的 onw 表单,以便在任何非管理员用户处呈现字段:
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Misd\PhoneNumberBundle\Form\Type\PhoneNumberType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Validator\Constraints\IsTrue as TrueConstraint;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
class RegistrationType extends AbstractType
{
/**
* @var AuthorizationChecker
*/
private $authorizationChecker=null;
public function __construct(AuthorizationChecker $authorizationChecker)
{
$this->authorizationChecker=$authorizationChecker;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name',TextType::class,["label"=>"register.name","required"=>true,'translation_domain' => 'FOSUserBundle'])
->add('surname',TextType::class,["label"=>"register.surname","required"=>true,'translation_domain' => 'FOSUserBundle']);
if(!$this->authorizationChecker->isGranted('ROLE_ADMIN'))
{
$builder->add('accept_terms',CheckboxType::class,["label"=>"register.acceptTerms","required"=>true,'translation_domain' => 'FOSUserBundle',
'mapped' => false,'constraints' => new TrueConstraint(array('message' => 'Your Confirmation Message','groups' => 'Registration'))]);
}
}
// Extra stuff ommited for convenience
}
如您所见,如果用户是管理员,我会通过 $this->authorizationChecker->isGranted('ROLE_ADMIN') 一段代码使用。
所以您只需将'@security.authorization_checker' 作为服务参数。