Symfony - Form item as plain text

别来无恙 提交于 2019-12-24 07:06:09

问题


I have a form that contains a collection of forms (a Vote with many VoteChoice). The VoteChoiceType is as follows

class VoteChoiceType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('answer', null, array('disabled' => true))
            ->add('priority', null);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'PollBundle\Entity\VoteChoice',
        ));
    }
}

Now in my Controller I create and populate many VoteChoices, setting the answer according to the available choices for the current poll (derived from the URL)

$vote = new Vote();
$vote->setPoll($poll);
foreach ($vote->getPoll()->getPollOptions() as $op) {
    $vc = New VoteChoice();
    $vote->addVoteChoice($vc->setAnswer($op));
}

So when the Form loads, I want all the options to display only - not to be an actual choice, and then the user can set the priority they want. However, the answer is of every single answer I have in my poll_options table (each Poll has many PollOption, similar to how each Vote has many VoteChoice)

Current twig template

<ul class="voteChoices" data-prototype="{{ form_widget(form.voteChoices.vars.prototype)|e('html_attr')  }}">
    {% for voteChoice in form.voteChoices %}
            <li>{{ form_row(voteChoice.answer) }} {{ form_row(voteChoice.priority) }}</li>
    {% endfor %}
</ul>
</div>
<p><button type="submit" class="btn btn-success">Go!</button></p>
{{ form_end(form) }}

I want the voteChoice.answer as a plain text (so it's not part of a dropdown - I know I can disable it in the FormBuilder, but I don't want it to appear as part of a drop-down menu, I just want it as plain text)

If I use voteChoice.answer I get the following symfony error

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Symfony\Component\Form\FormView could not be converted to string") in poll\vote.html.twig at line 9.

I have a __toString function in my VoteChoice class.


回答1:


I want the voteChoice.answer as a plain text (so it's not part of a dropdown - I know I can disable it in the FormBuilder, but I don't want it to appear as part of a drop-down menu, I just want it as plain text)

You can access the current data of your form via form.vars.value (Reference):

{{ voteChoice.vars.value.answer }}

This means that voteChoice.vars.value is an instance of PollBundle\Entity\VoteChoice so you can remove the answer field from your form safely if this is not required by edit.



来源:https://stackoverflow.com/questions/40227349/symfony-form-item-as-plain-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!