HelperController.php 17 KB

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