2

I've seen in a project that property-path can be used with square brackets like this:

foreach ($foo as $i => $object) {
    $builder->add("foo_{$i}", 'checkbox', array(
        'property_path' => "[$i].foo",
    ));
}

This seems to associate each field to the object's foo property with the given id, but I've not found out any documentation about it. Only this example. Any idea of what does it mean and where is it documented?

Community
  • 1
  • 1
Manolo
  • 24,020
  • 20
  • 85
  • 130

2 Answers2

3

This is what the Symfony UPGRADE from 2.0 to 2.1 says:

The mapping of property paths to arrays has changed.

Previously, a property path "street" mapped to both a field $street of a class (or its accessors getStreet() and setStreet()) and an index ['street'] of an array or an object implementing \ArrayAccess.

Now, the property path "street" only maps to a class field (or accessors), while the property path "[street]" only maps to indices.

Also take a look on Symfony's documentation about the PropertyAccess component.

The purpose of property_path is explained in the FormType Field page but I guess you already know what it is used for.

For the code you posted I guess (I used Symfony forms only once, just scratched its surface) that for each property bar of object $foo it creates an <input type="checkbox" name="foo_bar">.

When the form is submitted, the property_path tells the form to put the value of the checkbox named foo_bar into $data['bar']->foo where $data is the object returned by method getData() of the form.

axiac
  • 68,258
  • 9
  • 99
  • 134
  • Perfect! Indeed it also works with `'property_path' => "[foo]"`. The reason of `'property_path' => "[$i].foo"` is also working is explained here: https://symfony.com/doc/current/components/property_access/introduction.html#reading-from-arrays – Manolo Mar 01 '16 at 20:47
-1

It's a PHP thing. You can use variables within a string if you add squiggly brackets around it, instead of separating it out of the string.

$x = "world";
echo "Hello, {$x}";
// is equivalent to
echo "Hello, " . $x;

This is documented Here, just do a find for "curly".

Bango
  • 971
  • 6
  • 18