从symfony2选择(实体)表单中动态删除选项

时间:2013-08-15 17:37:44

标签: symfony symfony-forms

我有一个实体类型表单,其中列出了当前用户的所有朋友。这是例如用于创建新组。现在我想使用相同的表单将人员添加到同一个组,因此Choice字段应该显示当前用户中尚未加入组的所有朋友。我以为我只是使用表单事件来删除组中已有的选项(用户)。

我的听众看起来像这样: class FriendSelectListener实现了EventSubscriberInterface {

public static function getSubscribedEvents() {
    // Tells the dispatcher that we want to listen on the form.pre_set_data
    // event and that the preSetData method should be called.
    return array(FormEvents::PRE_SET_DATA => 'preSetData');
}

public function preSetData(FormEvent $event) {
    $betRound = $event->getData();
    $form = $event->getForm();
    $groupForm = $form->get('userGroup');
    $usersForm = $groupForm->get('users');

    foreach($betRound->getUserGroup()->getUsers() as $user){
        if($usersForm->has($user->getId())){
            $usersForm->remove($user->getId());
        }
    }
}

}

但是我无法渲染它,因为在我的测试中我删除了id为2的用户,然后在渲染时收到以下错误消息:

  

对象(带有ArrayAccess)类型的键“2”   “Symfony \ Component \ Form \ FormView”中不存在   /var/lib/stickshift/1ed1210eec124c179c45aac4ad484afd/app-root/data/269891/src/Strego/UserBundle/Resources/views/Form/selectFriends.html.twig   在第5行

更新 这可能与我的观点有关:      {%代表id,选择选项%}

    {% set user = choice.data %}
    <label> 
    <div class="people-list people-choose unselected" style="width:270px;">
    <img src="{{ user.profilePic  | imagine_filter('profile_thumb') }}" class="img-polaroid" alt="{{ user.nickname }}">
    {#<img src="{{ asset('bundles/stregoapp/img/profile-thumb-90x90.png') }}" alt="Profilbild" class="img-polaroid">#}
    <p>{{ form_widget(form[id]) }}&nbsp;<span class="label">einladen</span></p>
    <h3>{{ user.nickname }}</h3>
    <h3><small>{{ user.firstName }} {{ user.lastName }}</small></h3>
    </div>
    </label>

{% endfor %}

对我而言,我似乎只删除了表单元素,但没有选择。

1 个答案:

答案 0 :(得分:0)

我发现了问题,这确实是我的看法。一旦我停止迭代选项但使用了我的表单元素的子元素,它就可以了:

{% for child in form %}

    {% set user = choices[child.vars.value].data %}

    <label> 
    <div class="people-list people-choose unselected" style="width:270px;">
    <img src="{{ user.profilePic  | imagine_filter('profile_thumb') }}" class="img-polaroid" alt="{{ user.nickname }}">

    <p>{{ form_widget(child) }}&nbsp;<span class="label">einladen</span></p>
    <h3>{{ user.nickname }}</h3>
    <h3><small>{{ user.firstName }} {{ user.lastName }}</small></h3>
    </div>
    </label>


{% endfor %}
相关问题