如何在View中访问实体

时间:2014-03-07 09:53:39

标签: php symfony symfony-forms

我有一个包含User实体项目的表单。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('user', 'entity', array(/* ... */));
}

我想在模板中访问实体的方法。例如,在用户列表中,管理员可以选择一些非管理员用户,并将其从数据库中删除:

{% block body %}
{% for user in form.user %}
    {% if user.isAdmin %}
        {# Disable the checkbox #}
    {% else %}
        {# Render normally #}
    {% endif %}
{% endfor %}
{% endblock %}

但是,当我运行我的应用程序时,Symfony告诉我对象isAdmin不存在此方法Symfony\Component\Form\FormView

我无法找到任何解决方案(尝试使用user.vars.value)。有没有办法做到这一点?

编辑:我正在使用Symfony 2.4.2。

3 个答案:

答案 0 :(得分:1)

您无需将用户传递到您的视图。 只需创建一个启用了多个选项的UsersType,并在提交时执行您想要执行的操作。 以下代码尚未经过测试。

class UsersType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('users', 'entity', array(
            'required'      => false,
            'class'         => 'MeMyBundle:UserEntity',
            'property'      => 'id',
            'property_path' => '[id]', # in square brackets!
            'multiple'      => true,
            'expanded'      => true
        ));
    }
}

创建控制器操作

/**
 * @Route("/my_users", name="_users")
 * @Template()
 */
public function usersAction()
{
    $request = $this->get('request');
    $users = $this->get('my_user_manager')->findAll() //get all users. Fit this line depending on your app.
    $form = $this->createForm(new UsersType(), $users); // I assume you have a UsersType here.

    $form->bind($request);
    if ($form->isValid()) {
        $data = $form->getData();
        foreach ($data['users'] as $user) {
            // Do what you want with $user, it contains one selected user
        }
        //you can redirect here
    }

    return array(
        'users' => $users,
        'form' => $form->createView(),
    );
}

现在,在您看来,您可以选择您的用户:

{% block body %}
{% if is_granted('ROLE_ADMIN') %}
    {{ form_start(form) }}
        {{ form_errors(form) }}
        ...
        <input type="submit" />
    {{ form_end(form) }}
{% else %}
        {# Render a list #}
        <ul>
        {% for user in users %}
            <li>{{user.username}}</li>
        {% endfor %}
        </ul>
{% endif %}
{% endblock %}

答案 1 :(得分:0)

我认为最好的方法是Custom Form Type。所以在你目前的形式中使用这个:

$builder->add('user', 'user', array(/* ... */));

并创建自己的UserType

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UserType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // ... implement your logic...
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
       // here you can set the isAdmin value
       // $view->vars['is_admin']
       // you can access your data via $form->getData()
    }

    public function getParent()
    {
        return 'choice';
    }

    public function getName()
    {
        return 'user';
    }
}

现在,您可以根据以下内容创建自己的模板:

{# src/Acme/DemoBundle/Resources/views/Form/fields.html.twig #}
{% block user_widget %}
    {# This will check a value when the user is admin: #}
    {% set is_selected is_admin %}
    {# let the original widget do the rest: #}
    {{ block('choice_widget') }}
{% endblock %}

另外,请务必将其添加到config.yml

twig:
    form:
        resources:
            - 'AcmeDemoBundle:Form:fields.html.twig'

答案 2 :(得分:0)

另一个答案(未经测试):

/**
 * @Route("/my_users", name="_users")
 * @Template()
 */
public function usersAction()
{
    $request = $this->get('request');
    $users = $this->get('my_user_manager')->findAll() //get all users. Fit this line depending on your app.

    if ("POST" === $request->getMethod()) {
        $data = $request->request->get('users');
        //Do what you want with submitted data
    }

    return array(
        'users' => $users,
    );
}

您的观点:

{% block body %}
<form action="{{ path("_users") }}" method="post">
    <table>
       <caption>Users</caption>
       <thead>
          <tr>
             {% if is_granted('ROLE_ADMIN') %}
             <th>Is admin?</th>
             {% endif %}
             <th>Username</th>
          </tr>
       </thead>
       <tbody>
          <tr>
             {% if is_granted('ROLE_ADMIN') %}
             <td>
                 <input class="{% if user.isAdmin() %}admin{% else %}notadmin{% endif %}" type="checkbox" id="user_{{user.getId()}}" name="users[]" value="{{user.getId()}}"{% if user.isAdmin() %} checked{% endif %} />
             </td>
             {% endif %}
             <td>{{user.getUsername()}}</td>
          </tr>
       </tbody>
    </table>
    <input type="submit" />
</form>
{% endblock %}