Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony - Form item as plain text

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.

like image 436
p3tch Avatar asked Nov 16 '25 11:11

p3tch


1 Answers

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.

like image 88
yceruto Avatar answered Nov 19 '25 01:11

yceruto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!