HelperController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. <?php
  2. /*
  3. * This file is part of the Sonata package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Controller;
  11. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  12. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\HttpFoundation\JsonResponse;
  15. use Symfony\Component\PropertyAccess\PropertyAccess;
  16. use Symfony\Component\PropertyAccess\PropertyPath;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\Validator\ValidatorInterface;
  19. use Sonata\AdminBundle\Admin\Pool;
  20. use Sonata\AdminBundle\Admin\AdminHelper;
  21. use Sonata\AdminBundle\Admin\AdminInterface;
  22. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  23. use Sonata\AdminBundle\Filter\FilterInterface;
  24. class HelperController
  25. {
  26. /**
  27. * @var \Twig_Environment
  28. */
  29. protected $twig;
  30. /**
  31. * @var \Sonata\AdminBundle\Admin\AdminHelper
  32. */
  33. protected $helper;
  34. /**
  35. * @var \Sonata\AdminBundle\Admin\Pool
  36. */
  37. protected $pool;
  38. /**
  39. * @var \Symfony\Component\Validator\ValidatorInterface
  40. */
  41. protected $validator;
  42. /**
  43. * @param \Twig_Environment $twig
  44. * @param \Sonata\AdminBundle\Admin\Pool $pool
  45. * @param \Sonata\AdminBundle\Admin\AdminHelper $helper
  46. * @param \Symfony\Component\Validator\ValidatorInterface $validator
  47. */
  48. public function __construct(\Twig_Environment $twig, Pool $pool, AdminHelper $helper, ValidatorInterface $validator)
  49. {
  50. $this->twig = $twig;
  51. $this->pool = $pool;
  52. $this->helper = $helper;
  53. $this->validator = $validator;
  54. }
  55. /**
  56. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  57. *
  58. * @param \Symfony\Component\HttpFoundation\Request $request
  59. *
  60. * @return \Symfony\Component\HttpFoundation\Response
  61. */
  62. public function appendFormFieldElementAction(Request $request)
  63. {
  64. $code = $request->get('code');
  65. $elementId = $request->get('elementId');
  66. $objectId = $request->get('objectId');
  67. $uniqid = $request->get('uniqid');
  68. $admin = $this->pool->getInstance($code);
  69. $admin->setRequest($request);
  70. if ($uniqid) {
  71. $admin->setUniqid($uniqid);
  72. }
  73. $subject = $admin->getModelManager()->find($admin->getClass(), $objectId);
  74. if ($objectId && !$subject) {
  75. throw new NotFoundHttpException;
  76. }
  77. if (!$subject) {
  78. $subject = $admin->getNewInstance();
  79. }
  80. $admin->setSubject($subject);
  81. list($fieldDescription, $form) = $this->helper->appendFormFieldElement($admin, $subject, $elementId);
  82. /** @var $form \Symfony\Component\Form\Form */
  83. $view = $this->helper->getChildFormView($form->createView(), $elementId);
  84. // render the widget
  85. // todo : fix this, the twig environment variable is not set inside the extension ...
  86. $extension = $this->twig->getExtension('form');
  87. $extension->initRuntime($this->twig);
  88. $extension->renderer->setTheme($view, $admin->getFormTheme());
  89. return new Response($extension->renderer->searchAndRenderBlock($view, 'widget'));
  90. }
  91. /**
  92. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  93. *
  94. * @param \Symfony\Component\HttpFoundation\Request $request
  95. *
  96. * @return \Symfony\Component\HttpFoundation\Response
  97. */
  98. public function retrieveFormFieldElementAction(Request $request)
  99. {
  100. $code = $request->get('code');
  101. $elementId = $request->get('elementId');
  102. $objectId = $request->get('objectId');
  103. $uniqid = $request->get('uniqid');
  104. $admin = $this->pool->getInstance($code);
  105. $admin->setRequest($request);
  106. if ($uniqid) {
  107. $admin->setUniqid($uniqid);
  108. }
  109. if ($objectId) {
  110. $subject = $admin->getModelManager()->find($admin->getClass(), $objectId);
  111. if (!$subject) {
  112. throw new NotFoundHttpException(sprintf('Unable to find the object id: %s, class: %s', $objectId, $admin->getClass()));
  113. }
  114. } else {
  115. $subject = $admin->getNewInstance();
  116. }
  117. $admin->setSubject($subject);
  118. $formBuilder = $admin->getFormBuilder($subject);
  119. $form = $formBuilder->getForm();
  120. $form->submit($request);
  121. $view = $this->helper->getChildFormView($form->createView(), $elementId);
  122. // render the widget
  123. // todo : fix this, the twig environment variable is not set inside the extension ...
  124. $extension = $this->twig->getExtension('form');
  125. $extension->initRuntime($this->twig);
  126. $extension->renderer->setTheme($view, $admin->getFormTheme());
  127. return new Response($extension->renderer->searchAndRenderBlock($view, 'widget'));
  128. }
  129. /**
  130. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\RuntimeException
  131. *
  132. * @param \Symfony\Component\HttpFoundation\Request $request
  133. *
  134. * @return \Symfony\Component\HttpFoundation\Response
  135. */
  136. public function getShortObjectDescriptionAction(Request $request)
  137. {
  138. $code = $request->get('code');
  139. $objectId = $request->get('objectId');
  140. $uniqid = $request->get('uniqid');
  141. $linkParameters = $request->get('linkParameters', array());
  142. $admin = $this->pool->getInstance($code);
  143. if (!$admin) {
  144. throw new NotFoundHttpException();
  145. }
  146. $admin->setRequest($request);
  147. if ($uniqid) {
  148. $admin->setUniqid($uniqid);
  149. }
  150. if (!$objectId){
  151. $objectId = null;
  152. }
  153. $object = $admin->getObject($objectId);
  154. if (!$object && 'html' == $request->get('_format')) {
  155. return new Response();
  156. }
  157. if ('json' == $request->get('_format')) {
  158. return new JsonResponse(array('result' => array(
  159. 'id' => $admin->id($object),
  160. 'label' => $admin->toString($object)
  161. )));
  162. } elseif ('html' == $request->get('_format')) {
  163. return new Response($this->twig->render($admin->getTemplate('short_object_description'), array(
  164. 'admin' => $admin,
  165. 'description' => $admin->toString($object),
  166. 'object' => $object,
  167. 'link_parameters' => $linkParameters
  168. )));
  169. } else {
  170. throw new \RuntimeException('Invalid format');
  171. }
  172. }
  173. /**
  174. * @param \Symfony\Component\HttpFoundation\Request $request
  175. *
  176. * @return \Symfony\Component\HttpFoundation\Response
  177. */
  178. public function setObjectFieldValueAction(Request $request)
  179. {
  180. $field = $request->get('field');
  181. $code = $request->get('code');
  182. $objectId = $request->get('objectId');
  183. $value = $request->get('value');
  184. $context = $request->get('context');
  185. $admin = $this->pool->getInstance($code);
  186. $admin->setRequest($request);
  187. // alter should be done by using a post method
  188. if (!$request->isXmlHttpRequest()) {
  189. return new JsonResponse(array('status' => 'KO', 'message' => 'Expected a XmlHttpRequest request header'));
  190. }
  191. if ($request->getMethod() != 'POST') {
  192. return new JsonResponse(array('status' => 'KO', 'message' => 'Expected a POST Request'));
  193. }
  194. $rootObject = $object = $admin->getObject($objectId);
  195. if (!$object) {
  196. return new JsonResponse(array('status' => 'KO', 'message' => 'Object does not exist'));
  197. }
  198. // check user permission
  199. if (false === $admin->isGranted('EDIT', $object)) {
  200. return new JsonResponse(array('status' => 'KO', 'message' => 'Invalid permissions'));
  201. }
  202. if ($context == 'list') {
  203. $fieldDescription = $admin->getListFieldDescription($field);
  204. } else {
  205. return new JsonResponse(array('status' => 'KO', 'message' => 'Invalid context'));
  206. }
  207. if (!$fieldDescription) {
  208. return new JsonResponse(array('status' => 'KO', 'message' => 'The field does not exist'));
  209. }
  210. if (!$fieldDescription->getOption('editable')) {
  211. return new JsonResponse(array('status' => 'KO', 'message' => 'The field cannot be edit, editable option must be set to true'));
  212. }
  213. $propertyAccessor = PropertyAccess::createPropertyAccessor();
  214. $propertyPath = new PropertyPath($field);
  215. // If property path has more than 1 element, take the last object in order to validate it
  216. if ($propertyPath->getLength() > 1) {
  217. $object = $propertyAccessor->getValue($object, $propertyPath->getParent());
  218. $elements = $propertyPath->getElements();
  219. $field = end($elements);
  220. $propertyPath = new PropertyPath($field);
  221. }
  222. $propertyAccessor->setValue($object, $propertyPath, '' !== $value ? $value : null);
  223. $violations = $this->validator->validateProperty($object, $field);
  224. if (count($violations)) {
  225. $messages = array();
  226. foreach ($violations as $violation) {
  227. $messages[] = $violation->getMessage();
  228. }
  229. return new JsonResponse(array('status' => 'KO', 'message' => implode("\n", $messages)));
  230. }
  231. $admin->update($object);
  232. // render the widget
  233. // todo : fix this, the twig environment variable is not set inside the extension ...
  234. $extension = $this->twig->getExtension('sonata_admin');
  235. $extension->initRuntime($this->twig);
  236. $content = $extension->renderListElement($rootObject, $fieldDescription);
  237. return new JsonResponse(array('status' => 'OK', 'content' => $content));
  238. }
  239. /**
  240. * Retrieve list of items for autocomplete form field
  241. *
  242. * @param Request $request
  243. *
  244. * @return JsonResponse
  245. *
  246. * @throws \RuntimeException
  247. * @throws AccessDeniedException
  248. */
  249. public function retrieveAutocompleteItemsAction(Request $request)
  250. {
  251. $admin = $this->pool->getInstance($request->get('code'));
  252. $admin->setRequest($request);
  253. // check user permission
  254. if (false === $admin->isGranted('LIST')) {
  255. throw new AccessDeniedException();
  256. }
  257. // subject will be empty to avoid unnecessary database requests and keep autocomplete function fast
  258. $admin->setSubject($admin->getNewInstance());
  259. $fieldDescription = $this->retrieveFieldDescription($admin, $request->get('field'));
  260. $formAutocomplete = $admin->getForm()->get($fieldDescription->getName());
  261. if ($formAutocomplete->getConfig()->getAttribute('disabled')) {
  262. throw new AccessDeniedException('Autocomplete list can`t be retrieved because the form element is disabled or read_only.');
  263. }
  264. $property = $formAutocomplete->getConfig()->getAttribute('property');
  265. $callback = $formAutocomplete->getConfig()->getAttribute('callback');
  266. $minimumInputLength = $formAutocomplete->getConfig()->getAttribute('minimum_input_length');
  267. $itemsPerPage = $formAutocomplete->getConfig()->getAttribute('items_per_page');
  268. $reqParamPageNumber = $formAutocomplete->getConfig()->getAttribute('req_param_name_page_number');
  269. $toStringCallback = $formAutocomplete->getConfig()->getAttribute('to_string_callback');
  270. $searchText = $request->get('q');
  271. if (mb_strlen($searchText, 'UTF-8') < $minimumInputLength) {
  272. return new JsonResponse(array('status' => 'KO', 'message' => 'Too short search string.', 403));
  273. }
  274. $targetAdmin = $fieldDescription->getAssociationAdmin();
  275. $datagrid = $targetAdmin->getDatagrid();
  276. if ($callback !== null) {
  277. if (!is_callable($callback)) {
  278. throw new \RuntimeException('Callback doesn`t contain callable function.');
  279. }
  280. call_user_func($callback, $datagrid, $property, $searchText);
  281. } else {
  282. if (is_array($property)) {
  283. // multiple properties
  284. foreach ($property as $prop) {
  285. if (!$datagrid->hasFilter($prop)) {
  286. throw new \RuntimeException(sprintf('To retrieve autocomplete items, you should add filter "%s" to "%s" in configureDatagridFilters() method.', $prop, get_class($targetAdmin)));
  287. }
  288. $filter = $datagrid->getFilter($prop);
  289. $filter->setCondition(FilterInterface::CONDITION_OR);
  290. $datagrid->setValue($prop, null, $searchText);
  291. }
  292. } else {
  293. if (!$datagrid->hasFilter($property)) {
  294. throw new \RuntimeException(sprintf('To retrieve autocomplete items, you should add filter "%s" to "%s" in configureDatagridFilters() method.', $prop, get_class($targetAdmin)));
  295. }
  296. $datagrid->setValue($property, null, $searchText);
  297. }
  298. }
  299. $datagrid->setValue('_per_page', null, $itemsPerPage);
  300. $datagrid->setValue('_page', null, $request->query->get($reqParamPageNumber, 1));
  301. $datagrid->buildPager();
  302. $pager = $datagrid->getPager();
  303. $items = array();
  304. $results = $pager->getResults();
  305. foreach ($results as $entity) {
  306. if ($toStringCallback !== null) {
  307. if (!is_callable($toStringCallback)) {
  308. throw new \RuntimeException('Option "to_string_callback" doesn`t contain callable function.');
  309. }
  310. $label = call_user_func($toStringCallback, $entity, $property);
  311. } else {
  312. $resultMetadata = $targetAdmin->getObjectMetadata($entity);
  313. $label = $resultMetadata->getTitle();
  314. }
  315. $items[] = array(
  316. 'id' => $admin->id($entity),
  317. 'label' => $label,
  318. );
  319. }
  320. return new JsonResponse(array(
  321. 'status' => 'OK',
  322. 'more' => !$pager->isLastPage(),
  323. 'items' => $items
  324. ));
  325. }
  326. /**
  327. * Retrieve the field description given by field name.
  328. *
  329. * @param AdminInterface $admin
  330. * @param string $field
  331. *
  332. * @return \Symfony\Component\Form\FormInterface
  333. *
  334. * @throws \RuntimeException
  335. */
  336. private function retrieveFieldDescription(AdminInterface $admin, $field)
  337. {
  338. $admin->getFormFieldDescriptions();
  339. $fieldDescription = $admin->getFormFieldDescription($field);
  340. if (!$fieldDescription) {
  341. throw new \RuntimeException(sprintf('The field "%s" does not exist.', $field));
  342. }
  343. if ($fieldDescription->getType() !== 'sonata_type_model_autocomplete') {
  344. throw new \RuntimeException(sprintf('Unsupported form type "%s" for field "%s".', $fieldDescription->getType(), $field));
  345. }
  346. if (null === $fieldDescription->getTargetEntity()) {
  347. throw new \RuntimeException(sprintf('No associated entity with field "%s".', $field));
  348. }
  349. return $fieldDescription;
  350. }
  351. }