Browse Source

Merge pull request #2677 from claudusd/closure-associated_property

Add closure possibility on the options associated_property
Andrej Hudec 10 years ago
parent
commit
26ee9fc4a5

+ 1 - 1
Resources/doc/reference/action_list.rst

@@ -96,7 +96,7 @@ Options
 - ``link_parameters`` (o): add link parameter to the related Admin class when the ``Admin::generateUrl`` is called
 - ``code`` (o): the method name to retrieve the related value
 - ``associated_tostring`` (o): (deprecated, use associated_property option) the method to retrieve the "string" representation of the collection element.
-- ``associated_property`` (o): property path to retrieve the "string" representation of the collection element.
+- ``associated_property`` (o): property path to retrieve the "string" representation of the collection element, or a closure with the element as argument and return a string.
 - ``identifier`` (o): if set to true a link appears on the value to edit the element
 
 Available types and associated options

+ 19 - 0
Tests/Twig/Extension/SonataAdminExtensionTest.php

@@ -789,6 +789,25 @@ class SonataAdminExtensionTest extends \PHPUnit_Framework_TestCase
 
     }
 
+    public function testRenderRelationElementWithClosure()
+    {
+        $this->fieldDescription->expects($this->exactly(1))
+            ->method('getOption')
+
+            ->will($this->returnCallback(function ($value, $default = null) {
+                if ($value == 'associated_property') {
+                    return function($element) {
+                        return 'closure '.$element->foo;
+                    };
+                }
+            }));
+
+        $element = new \stdClass();
+        $element->foo = "bar";
+
+        $this->assertEquals('closure bar', $this->twigExtension->renderRelationElement($element, $this->fieldDescription));
+    }
+
     public function testGetUrlsafeIdentifier()
     {
         $entity = new \stdClass();

+ 4 - 0
Twig/Extension/SonataAdminExtension.php

@@ -293,6 +293,10 @@ class SonataAdminExtension extends \Twig_Extension
             return call_user_func(array($element, $method));
         }
 
+        if (is_callable($propertyPath)) {
+            return $propertyPath($element);
+        }
+
         return PropertyAccess::createPropertyAccessor()->getValue($element, $propertyPath);
     }