我定义了自己的名为“Tab”的字段,并在出现新选项卡时添加它。
<?php
//\src\Alden\xyzBundle\Form\Type\TabsType.php
namespace Alden\BonBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\CallbackValidator;
use Symfony\Component\Form\FormValidatorInterface;
use Symfony\Component\Form\Form;
class TabsType extends AbstractType {
public function buildForm(FormBuilder $builder, array $options)
{
$builder->setAttribute('starting', $options['starting']);
$builder->setAttribute('ending', $options['ending']);
$builder->setAttribute('header', $options['header']);
}
public function buildView(FormView $view, FormInterface $form)
{
$parent = $form->getParent();
if (is_null($parent->getParent()))
{
$tabs = $this->findTabs($parent);
}
else
{
$tabs = array();
}
$view->set('starting', $form->getAttribute('starting'));
$view->set('ending', $form->getAttribute('ending'));
$view->set('header', $form->getAttribute('header'));
$view->set('tabs', $tabs);
}
public function getDefaultOptions(array $options)
{
return array(
'property_path' => false,
'starting' => true,
'ending' => true,
'header' => false,
);
}
public function getName()
{
return 'tabs';
}
public function getParent(array $options)
{
return 'field';
}
private function findTabs(Form $form)
{
$prefix = $form->getName();
$tabs = array();
foreach ($form->getChildren() as $child)
{
foreach ($child->getTypes() as $type)
/* @var $child \Symfony\Component\Form\Form */
{
if (get_class($type) == __NAMESPACE__ . '\TabsType')
{
if ($child->getAttribute('starting'))
{
$tabs[$prefix . '_' . $child->getName()] = $child->getAttribute('label');
}
}
}
}
return $tabs;
}
}
?>
和树枝
{# \src\Alden\xyzBundle\Resources\views\Form\fields.html.twig #}
{% block tabs_row %}
{% if header %}
<ul>
{% for tid, t in tabs %}
<li>
<a href="#{{ tid }}">{{ t }}</a>
</li>
{% endfor %}
</ul>
{% endif %}
{% if ending %}
</div>
{% endif %}
{% if starting %}
<div id="{{ id }}">
{% endif %}
{% endblock %}
和表单生成器中的用法:
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('tabs_head', new TabsType(), array(
'ending' => false,
'starting' => false,
'header' => true
))
->add('tab_1', new TabsType(), array(
'ending' => false,
'label' => 'Podstawowe'
))
->add('firstName', null, array(
'label' => 'Imię'
))
->add('lastName', null, array(
'label' => 'Nazwisko'
))
->add('tab_contact', new TabsType(), array(
'label' => 'Kontakt'
))
->add('address', new AddressType(), array(
'label' => 'Adres zameldowania'
))
->add('tabs_end', new TabsType(), array(
'starting' => false
))
;
}