How to hide single labels on a symfony form?
I am creating a very custom form on a symfony project and currently I have something like this:
foreach ($foo as $c) {
$fields['crit_v_'.$c->开发者_Go百科;getId()]=new sfWidgetFormInput(array('label'=>''));
$fields['crit_m_'.$c->getId()]=new sfWidgetFormTextarea(array('label'=>__($c->getName(),array(),'messages')));
}
As you can see I have 2 inputs foreach element, but I only want to have a label for the second one. Setting the label for the first one to null
or to ''
does not make symfony to not render this label and displays the default text for this label. (This means the for input is labeled crit_v_xx
.)
If you set the label to false then symfony will not render the <label>
tags at all. False behaves differently then null or ''
$your_form->widgetSchema->setLabel('the_field_id', false);
I ended up with the following:
I make a seperate template file called _form.php
which looked like this:
<form action="<?php echo url_for('evaluation_submit')?>" method="post">
<?php echo $form['id']?>
<div> <!-- with label -->
<?php echo $form['foo']->renderLabel() ?>
<?php echo $form['foo']->renderError() ?>
<?php echo $form['foo'] ?>
</div>
<div> <!-- without label -->
<?php echo $form['bar']->renderError() ?>
<?php echo $form['bar'] ?>
</div>
In the main template for this action I included the form like this:
<?php include_partial('form', array('form' => $form)) ?>
You could just disable it in the generator.yml
filter:
fields:
name: { label: false }
You can create a custom row format that defines how the fields will be rendered (if you are not using a custom template anyway). I found it in this forum thread.
A good solution might be overriding the formatRow
method:
public function formatRow($label, $field, $errors = array(), $help = '', $hiddenFields = null)
{
if(strip_tags($label) == '__UNSET__')
{
return strtr($this->getRowFormat(), array(
'%label%' => null,
'%field%' => $field,
'%error%' => $this->formatErrorsForRow($errors),
'%help%' => $this->formatHelp($help),
'%hidden_fields%' => is_null($hiddenFields) ? '%hidden_fields%' : $hiddenFields,
));
}
else
{
return strtr($this->getRowFormat(), array(
'%label%' => $label,
'%field%' => $field,
'%error%' => $this->formatErrorsForRow($errors),
'%help%' => $this->formatHelp($help),
'%hidden_fields%' => is_null($hiddenFields) ? '%hidden_fields%' : $hiddenFields,
));
}
}
Then you set __UNSET__
as label for those fields that should not have their label rendered.
Or you even use a custom row format depending on the label name to prevent outputting the enclosing tag of the label.
A row format would look like this <div >%field%%help%%error%%hidden_fields%</div>
and would pass this instead of $this->getRowFormat()
.
To set the label of a single field in a symfony form as blank:
$your_form->widgetSchema->setLabel('the_field_id', ' ');
It will render the <label>
tags, but with a blank space inside, so they won't output anything on the browser
精彩评论