123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344 |
- <?php
- namespace Drupal\edlp_ajax\Controller;
- use Drupal\Core\Controller\ControllerBase;
- use Symfony\Component\HttpFoundation\Request;
- use Drupal\Core\Url;
- use Drupal\Core\Language\LanguageInterface;
- use Drupal\menu_link_content\Entity\MenuLinkContent;
- use Drupal\Core\Datetime\DrupalDateTime;
- // use Symfony\Component\HttpFoundation\JsonResponse;
- use \Drupal\block\Entity\Block;
- use Drupal\Core\Cache\CacheableJsonResponse;
- use Drupal\Core\Cache\CacheableMetadata;
- use Drupal\core\render\RenderContext;
- class EdlpAjaxController extends ControllerBase {
- private function query() {
- $this->langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
- $entity = entity_load($this->entity_type, $this->id);
- if ($entity->hasTranslation($this->langcode)){
- $this->entity = $entity->getTranslation($this->langcode);
- }else{
- $this->entity = $entity;
- }
- if($this->entity){
- switch($this->entity_type){
- case 'node':
- $this->bundle = $this->entity->getType();
- $this->title = $this->entity->getTitle();
- break;
- case 'taxonomy_term':
- $this->bundle = $this->entity->bundle();
- $this->title = $this->entity->getName();
- break;
- default:
- $this->bundle = NULL;
- $this->title = '';
- }
- }
- }
- private function getProductionDatesAside(){
- $now = new DrupalDateTime('now');
- $now->setTimezone(new \DateTimeZone(DATETIME_STORAGE_TIMEZONE));
- $future_dates_query = \Drupal::entityQuery('node')
- ->condition('status', 1)
- ->condition('type', 'evenement')
- ->condition('field_page_liee.target_id', $this->entity->id(), 'IN')
- ->condition('field_date', $now->format(DATETIME_DATETIME_STORAGE_FORMAT), '>=')
- ->sort('field_date');
- $future_nids = $future_dates_query->execute();
- $past_dates_query = \Drupal::entityQuery('node')
- ->condition('status', 1)
- ->condition('type', 'evenement')
- ->condition('field_page_liee.target_id', $this->entity->id(), 'IN')
- ->condition('field_date', $now->format(DATETIME_DATETIME_STORAGE_FORMAT), '<')
- ->sort('field_date', 'DESC');
- $past_nids = $past_dates_query->execute();
- if(count($future_nids) || count($past_nids)){
- $aside = array(
- '#type'=>'container',
- "#attributes"=>array(
- "class"=>['agenda']
- )
- );
- $node_view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
- if(count($future_nids)){
- $future_nodes = entity_load_multiple('node', $future_nids);
- $future_list = array (
- '#theme' => 'item_list',
- '#items' => [],
- );
- foreach($future_nodes as $node){
- $future_list['#items'][] = $node_view_builder->view($node, 'aside');
- }
- $aside['future_events'] = array(
- "#type"=>"container",
- "#attributes"=>array(
- "class"=>['future-events']
- ),
- "#markup"=>"<h3>" . t("Upcoming events") . "</h3>",
- "future_events"=>$future_list
- );
- }
- if(count($past_nids)){
- $past_nodes = entity_load_multiple('node', $past_nids);
- $past_list = array (
- '#theme' => 'item_list',
- '#items' => [],
- );
- foreach($past_nodes as $node){
- $past_list['#items'][] = $node_view_builder->view($node, 'aside');
- }
- $aside['past_events'] = array(
- "#type"=>"container",
- "#attributes"=>array(
- "class"=>['past-events']
- ),
- "#markup"=>"<h3>" . t("Past events") . "</h3>",
- "past_events"=>$past_list
- );
- }
- }else{
- $aside = null;
- }
- return $aside;
- }
- /**
- *
- * return a renderable array
- */
- private function getAside() {
- if($this->bundle == 'page'){
- $aside = $this->getProductionDatesAside();
- }else{
- $aside = null;
- }
- return $aside;
- }
- private function toRenderable(){
- $this->query();
- if($this->entity){
- return array(
- "#theme"=>'edlp_ajax',
- "#entity_type" => $this->entity_type,
- '#entity' => $this->entity,
- '#view_mode' => $this->viewmode,
- '#aside' => $this->getAside(),
- '#bundle' => $this->bundle,
- );
- }else{
- return array(
- '#markup'=>'404! '.$this->entity_type.' '.$this->id." not found!"
- );
- }
- }
- /**
- * Get entity as json through ajax.
- *
- * @return json
- */
- public function entityjson($entity_type, $id, $viewmode) {
- $this->entity_type = $entity_type;
- $this->id = $id;
- $this->viewmode = $viewmode;
- $renderable = $this->toRenderable();
- // $rendered = render($renderable);
- // We can't render directly the entity as it throw an exception with cachable data
- // see http://blog.dcycle.com/blog/2018-01-24/caching-drupal-8-rest-resource/#the-dreaded-leaked-metadata-error
- $rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($renderable) {
- return render($renderable);
- });
- $title = $this->title;
- $title .= $this->viewmode != '' && $this->viewmode != 'default' ? ' | ' . $this->viewmode : '';
- $data = [
- 'date' => time(),
- 'id' => $this->id,
- 'title' => $title,
- 'view_mode' => $this->viewmode,
- 'bundle' => $this->bundle,
- 'entity_type' => $this->entity_type,
- 'rendered'=> $rendered,
- 'language' => $this->langcode
- ];
- // if content type page (productions) :
- // -- get the menu items and linked dates
- // -- get the linked documents for corpus map
- if($this->bundle == "page"){
- $menuLinkManager = \Drupal::service('plugin.manager.menu.link');
- $links = $menuLinkManager->loadLinksByRoute('entity.node.canonical', array('node' => $this->id), 'productions');
- // dpm($links, 'links');
- $menu_parents = array();
- foreach ($links as $link) {
- $parents = $menuLinkManager->getParentIds($link->getPluginId());
- // dpm($parents, 'parents');
- foreach ($parents as $parent_id) {
- $parent = $menuLinkManager->getInstance(array('id'=>$parent_id));
- // dpm($parent, 'parent');
- $url = $parent->getUrlObject();
- $sys_path = $url->getInternalPath();
- // dpm($sys_path);
- $menu_parents[] = $sys_path;
- }
- }
- $data['menu_parents'] = $menu_parents;
- // Documents liés
- $documents_lies = $this->entity->get('field_documents_lies')->getValue();
- if(count($documents_lies)){
- foreach ($documents_lies as $key => $field) {
- $data['documents_lies'][] = $field['target_id'];
- }
- }
- }
- // translations links
- $links = \Drupal::languageManager()->getLanguageSwitchLinks(LanguageInterface::TYPE_URL, $this->entity->toUrl());
- if (isset($links->links)) {
- $translations_build = [
- '#theme' => 'links__language_block',
- '#links' => $links->links,
- '#attributes' => ['class' => ["language-switcher-{$links->method_id}"]],
- '#set_active_class' => TRUE,
- ];
- $translations_rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($translations_build) {return render($translations_build);});
- // dpm($links);
- $data['translations_links'] = $translations_rendered;
- }
- $data['#cache'] = [
- 'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
- 'tags' => [
- 'edlp-ajax-cache',
- // $this->entity_type.':'.$this->id // not necessary as we add $renderable as CacheableMetadata to the response
- ],
- 'contexts' => [
- 'languages:language_content',
- 'user'
- ]
- ];
- // $response = new JsonResponse();
- // $response->setData($data);
- $response = new CacheableJsonResponse($data);
- $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
- $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
- return $response;
- // dpm($response);
- // return array(
- // '#markup'=>'hello'
- // );
- }
- /**
- * Get all visisble blocks from edlptheme as json through ajax.
- *
- * @return json
- */
- // NOT USED (YET)
- public function blocksjson($blockid) {
- $block_viewbuilder = \Drupal::entityTypeManager()->getViewBuilder('block');
- //
- $blocksids = [];
- if(!$blockid){
- // TODO: get all blocks definition from edlptheme
- $block_storage = \Drupal::entityTypeManager()->getStorage('block');
- // dpm($block_storage, '$block_storage');
- $allblocks = $block_storage->loadMultiple();
- // dpm($blocks, 'blocks');
- foreach ($allblocks as $block) {
- // dpm($block->id(), 'block');
- // dpm($block->getTheme(), 'theme');
- // $visibility = $block->getVisibility();
- if($block->getTheme() == "edlptheme"){
- // dpm($block, $block->id());
- $blocksids[] = $block->id();
- }
- }
- // $block_listbuilder = \Drupal::entityTypeManager()->getListBuilder('block');
- // dpm($block_listbuilder, '$block_listbuilder');
- // // foreach ($blocks as $key => $value) {
- // // $block = \Drupal\block\Entity\Block::load('productions');
- // // }
- }
- else{
- $blocksids[] = $blockid;
- }
- // dpm($blocksids, 'blockids');
- //
- $blocks = [];
- foreach ($blocksids as $id) {
- $block = Block::load($id);
- $block_render = $block_viewbuilder->view($block);
- $rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($block_render) {
- return render($block_render);
- });
- $blocks[$id] = array(
- 'rendered'=> $rendered,
- 'region'=> str_replace('_', '-', $block->getRegion()),
- 'id'=> preg_replace('/^[^:]+:(.+)$/', 'block-$1', $block->getPluginId())
- );
- }
- // dpm($blocks, 'blocks');
- //
- $data = [
- 'blockid'=>$blockid,
- 'blocks' => $blocks,
- '#cache' => [
- 'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
- 'tags' => [
- 'edlp-ajax-blocks-cache',
- // $this->entity_type.':'.$this->id // not necessary as we add $renderable as CacheableMetadata to the response
- ],
- 'contexts' => [
- 'languages:language_content',
- 'user'
- ]
- ]
- ];
- // dpm($data);
- //
- $response = new CacheableJsonResponse($data);
- // $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
- $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
- //
- return $response;
- // dpm($response);
- //
- return array(
- '#markup'=>'hello'
- );
- }
- }
|