Skip to content

Instantly share code, notes, and snippets.

@rn0
Forked from spcmky/ExampleType.php
Last active August 29, 2015 14:07
Show Gist options
  • Save rn0/0303d47505dd28d7121f to your computer and use it in GitHub Desktop.
Save rn0/0303d47505dd28d7121f to your computer and use it in GitHub Desktop.
# app/config/config.yml
twig:
form:
resources:
- 'AcmeDemoBundle:Form:fields.html.twig'
<?php
// src/Acme/DemoBundle/Form/ExampleType.php
namespace Acme\DemoBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Acme\DemoBundle\Form\Type\FieldsetType;
class ExampleType extends AbstractType {
protected $options;
public function __construct ( $options = array() ) {
$this->options = $options;
}
public function buildForm ( FormBuilderInterface $builder, array $options ) {
$builder
->add('firstname')
->add('lastname')
->add('email','email');
$builder->add('credentials',new FieldsetType(),array(
'label' => false,
'required' => false,
'mapped' => false,
'title' => 'Credentials',
'subforms' => array(
array(
'name'=>'username',
'type'=>'text',
'attr'=> array(
'required' => true
)
),
array(
'name'=>'password',
'type'=>'password',
'attr'=> array(
'required' => true
)
)
)
)
);
}
public function getName() {
return 'acme_mainbundle_exampletype';
}
}
{# src/Acme/DemoBundle/Resources/views/Form/fields.html.twig #}
{% block fieldset_widget %}
{% spaceless %}
<fieldset {{ block('widget_container_attributes') }}>
{% if title is defined %}<legend>{{ title }}</legend>{% endif %}
{{ form_widget(form) }}
</fieldset>
{% endspaceless %}
{% endblock %}
<?php
// src/Acme/DemoBundle/Form/Type/FieldsetType.php
namespace Acme\DemoBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class FieldsetType extends AbstractType {
public function setDefaultOptions ( OptionsResolverInterface $resolver ) {
$resolver->setDefaults(array(
'title' => false,
'subforms' => array(),
'options' => array()
));
}
public function buildForm ( FormBuilderInterface $builder, array $options ) {
if ( !empty($options['subforms']) ) {
foreach ( $options['subforms'] as $f ) {
$builder->add($f['name'],$f['type'],$f['attr']);
}
}
}
public function buildView ( FormView $view, FormInterface $form, array $options ) {
if ( isset($options['title']) || $options['title'] !== false ) {
$view->vars['title'] = $options['title'];
}
}
public function getName() {
return 'fieldset';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment