Skip to content

Commit

Permalink
[Form] CSRF fields are not included in the children of a FormView any…
Browse files Browse the repository at this point in the history
…more if the view is not the root
  • Loading branch information
webmozart committed May 4, 2011
1 parent 173beeb commit 74cca63
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 29 deletions.

This file was deleted.

Expand Up @@ -74,13 +74,6 @@
{{ block('field_widget') }}
{% endblock hidden_widget %}

{% block csrf_widget %}
{% if not form.hasParent or not form.getParent.hasParent %}
{% set type = type|default('hidden') %}
{{ block('field_widget') }}
{% endif %}
{% endblock csrf_widget %}

{% block hidden_row %}
{{ form_widget(form) }}
{% endblock hidden_row %}
Expand Down
Expand Up @@ -13,6 +13,8 @@

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;

class FormTypeCsrfExtension extends AbstractTypeExtension
{
Expand All @@ -34,7 +36,19 @@ public function buildForm(FormBuilder $builder, array $options)
$csrfOptions['csrf_provider'] = $options['csrf_provider'];
}

$builder->add($options['csrf_field_name'], 'csrf', $csrfOptions);
$builder->add($options['csrf_field_name'], 'csrf', $csrfOptions)
->setAttribute('csrf_field_name', $options['csrf_field_name']);
}
}

public function buildViewBottomUp(FormView $view, FormInterface $form)
{
if ($view->hasParent() && $form->hasAttribute('csrf_field_name')) {
$name = $form->getAttribute('csrf_field_name');

if (isset($view[$name])) {
unset($view[$name]);
}
}
}

Expand Down
13 changes: 0 additions & 13 deletions tests/Symfony/Tests/Component/Form/AbstractLayoutTest.php
Expand Up @@ -480,19 +480,6 @@ public function testCsrf()
);
}

public function testCsrfWithNonRootParent()
{
$form = $this->factory->createNamed('csrf', 'na&me', null, array(
'property_path' => 'name',
));
$form->setParent($this->factory->create('form'));
$form->getParent()->setParent($this->factory->create('form'));

$html = $this->renderWidget($form->createView());

$this->assertEquals('', trim($html));
}

public function testDateTime()
{
$form = $this->factory->createNamed('datetime', 'na&me', '2011-02-03 04:05:06', array(
Expand Down
Expand Up @@ -30,4 +30,24 @@ public function testCsrfProtectionCanBeDisabled()

$this->assertEquals(0, count($form));
}

public function testCsrfTokenIsOnlyIncludedInRootView()
{
$view =
$this->factory->createBuilder('form', null, array(
'csrf_field_name' => 'csrf',
))
->add('notCsrf', 'text')
->add(
$this->factory->createNamedBuilder('form', 'child', null, array(
'csrf_field_name' => 'csrf',
))
->add('notCsrf', 'text')
)
->getForm()
->createView();

$this->assertEquals(array('csrf', 'notCsrf', 'child'), array_keys(iterator_to_array($view)));
$this->assertEquals(array('notCsrf'), array_keys(iterator_to_array($view['child'])));
}
}

0 comments on commit 74cca63

Please sign in to comment.