HelperController.php 16 KB

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