【问题标题】:Dynamically remove Options from symfony2 choice (entity) form从 symfony2 选择(实体)表单中动态删除选项
【发布时间】:2013-08-15 17:37:43
【问题描述】:

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

我的听众是这样的: 类 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 行

更新: 这可能与我的观点有关: {% for 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 %}

对我来说,我似乎只删除了表单元素,但没有删除选项。

【问题讨论】:

  • 我认为最好的办法是在两种表单上都挂一个监听器,然后添加实际的 userGroup 元素,而不是尝试修改现有的元素。 Form 组件以神秘的方式工作。
  • 我觉得我只删除了表单元素而不是“选择”本身。这可能与我的观点有关。我会更新我的问题

标签: symfony symfony-forms


【解决方案1】:

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

{% 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 %}

【讨论】:

    猜你喜欢
    • 2013-12-07
    • 2013-08-14
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    相关资源
    最近更新 更多