我目前工作的用戶創建形式。Symfony的3 - 動態表單 - ChoiceType阿賈克斯
用戶都有一個配置文件屬性:
/**
* Many Users have One profile
* @ORM\ManyToOne(targetEntity="ProjectBundle\Entity\User\Profile", inversedBy="users")
* @ORM\JoinColumn(name="profile_id", referencedColumnName="id")
*/
private $profile;
這個圖譜是根據另一個選擇(變化行動的jQuery)選擇:
{% autoescape 'html'%}
{{ '<script id="tmpl_user_profile" type="text/x-jquery-tmpl">
<option value="${id}">${libelle}</option>
</script>'|raw }}
{% endautoescape %}
<script>
$('select#user_organisationMember').on('change',function(){
var value = this.value;
if (value == '') {
$('#user_profile').empty();
}
var urlAjax = "{{ path('admin_user_get_profile', { 'entity': "value" }) }}";
$.ajax({
url: urlAjax.replace("value",value),
method: "post"
}).done(function(msg){
$('#user_profile').empty();
$('#tmpl_user_profile').tmpl(JSON.parse(msg)).appendTo('#user_profile');
}) ;
});
</script>
在此之前一切運行正常! 根據其他選擇,選擇標籤中的不同配置文件會發生很好的變化。
在頁面上的到來,我想配置文件的列表是空的。
所以我使用的Symfony的FormEvent調整自己的狀態。
這是我第一次使用FormEvent,我可能犯了一個錯誤!
我FormType:
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('lastname')
->add('firstname')
->add('gender',null,array('required'=>true))
->add('organisationMember',null,array(
'required' => true,
'choices' => $options['organisation'],
'group_by' => 'type_organisation',
'placeholder' => 'Choisissez votre organisation'
))
->add('job')
->add('mobile')
->add('phone')
->add('alert_failure')
->add('alert_full')
->add('alert_other')
->add('plainPassword', TextType::class, array('required' => true))
->add('email')
->add('profile', null, array(
'required' => true,
));
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$entity = $event->getData();
$form = $event->getForm();
if (!$entity || null === $entity->getId()) {
$form->remove('profile');
$form->add('profile', ChoiceType::class);
}
});
}
默認情況下,我的數據庫的所有配置文件被加載在選擇不得到錯誤「這個值是不正確」。
但我不希望用戶看到所有的配置文件,所以我在事件中將其刪除,並將該字段返回爲空。
但我仍然收到錯誤「此值不正確」,因爲實際上,由於基本選擇是空的,表單沒有找到輸入的值。
我想有一個默認爲空的選擇,它填充在Ajax中,並且不會顯示錯誤「This value is incorrect」。
我怎麼能請你呢? 謝謝
是'profile'你的實體的成員與一個外鍵關係,或者是沒有連接到你的數據庫? –
有一個外鍵關係 –
你有沒有試過在你的''profile''表單選項中設置'data => null'? –