HelperController.php 17 KB

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