2016-10-29 29 views
1

我有一個帳戶(如公司帳戶)實體,其中有accountOwner的用戶關聯。在Symfony 3中有條件顯示錶單字段

帳戶所有者和擁有ROLE_ADMIN的用戶都可以編輯帳戶,但只有擁有ROLE_ADMIN的用戶才能設置帳戶所有者。

我需要2種表單類型嗎?或者我可以根據用戶角色有條件地在同一表單上顯示accountOwner字段?

回答

1

您可以有條件地提供accountOwner關聯。 當您想要動態修改表單時,通常需要使用form events

然而,因爲你的表單字段不依賴於綁定的形式實際數據,但在安全性方面,你可以注入授權檢驗到你的表單類型,並檢查是否要添加所需的字段:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder->add('always_present_field'); 
    $builder->add('another_always_present_field'); 

    if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) { 
     $builder->add('conditional_field_if_current_user_is_admin'); 
    } 
} 
+0

確認。後一種方法效果很好,謝謝。 – Coder1

相關問題