permanaj

interactive-map

May 20th, 2021
983
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.58 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Drupal\og_sydneymetrod9\Form;
  4.  
  5. use Drupal\Core\Ajax\AjaxResponse;
  6. use Drupal\Core\Ajax\HtmlCommand;
  7. use Drupal\Core\Entity\ContentEntityForm;
  8. use Drupal\Core\Entity\EntityStorageInterface;
  9. use Drupal\Core\Form\FormStateInterface;
  10. use Symfony\Component\DependencyInjection\ContainerInterface;
  11.  
  12. /**
  13.  * Form controller for Interactive Map Item edit forms.
  14.  *
  15.  * @ingroup og_sydneymetrod9
  16.  */
  17. class InteractiveMapItemEntityForm extends ContentEntityForm {
  18.  
  19.   /**
  20.    * The current user account.
  21.    *
  22.    * @var \Drupal\Core\Session\AccountProxyInterface
  23.    */
  24.   protected $account;
  25.  
  26.   /**
  27.    * The Interactive Map storage.
  28.    *
  29.    * @var \Drupal\Core\Entity\EntityStorageInterface
  30.    */
  31.   protected EntityStorageInterface $interactiveMapEntityStorage;
  32.  
  33.   /**
  34.    * {@inheritdoc}
  35.    */
  36.   public static function create(ContainerInterface $container) {
  37.     // Instantiates this form class.
  38.     $instance = parent::create($container);
  39.     $instance->account = $container->get('current_user');
  40.     $instance->interactiveMapEntityStorage = $container->get('entity_type.manager')->getStorage('interactive_map');
  41.     return $instance;
  42.   }
  43.  
  44.   /**
  45.    * {@inheritdoc}
  46.    */
  47.   public function buildForm(array $form, FormStateInterface $form_state) {
  48.     $form = parent::buildForm($form, $form_state);
  49.  
  50.     if (!$this->entity->isNew()) {
  51.       $form['new_revision'] = [
  52.         '#type' => 'checkbox',
  53.         '#title' => $this->t('Create new revision'),
  54.         '#default_value' => FALSE,
  55.         '#weight' => 10,
  56.       ];
  57.     }
  58.  
  59.     $form['map']['widget']['#ajax'] = [
  60.       'event' => 'change',
  61.       'callback' => '::getItemCategoryCallback',
  62.       'wrapper' => 'edit-item-category-wrapper',
  63.     ];
  64.  
  65.     $form_state->setCached(FALSE);
  66.     $user_input = $form_state->getUserInput();
  67.     $map_id = NULL;
  68.     $item_category_options['_none'] = t('- None -');
  69.  
  70.     // If map is selected
  71.     if (isset($user_input['_triggering_element_name'])) {
  72.       if ($user_input['_triggering_element_name'] === 'map') {
  73.         $field_map_id = $form_state->getValue('map');
  74.         if (isset($field_map_id[0]['target_id'])) {
  75.           $map_id = $field_map_id[0]['target_id'];
  76.         }
  77.       }
  78.     }
  79.     elseif (!empty($form['map']['widget']['#default_value'][0])) {
  80.       // When map already there, meaning in edit mode
  81.       $map_id = $form['map']['widget']['#default_value'][0];
  82.     }
  83.     elseif ($form_state->hasValue('map')) {
  84.       $field_map_id = $form_state->getValue('map');
  85.       if (isset($field_map_id[0]['target_id'])) {
  86.         $map_id = $field_map_id[0]['target_id'];
  87.       }
  88.     }
  89.  
  90.     if ($map_id) {
  91.       $map_vocab_id = $this->getMapVocabulary($map_id);
  92.       $terms = $this->getTermData($map_vocab_id);
  93.       $item_category_options = $item_category_options + $terms;
  94.     }
  95.  
  96.     $form['item_category']['widget']['#options'] = $item_category_options;
  97.  
  98.     return $form;
  99.   }
  100.  
  101.   protected function getMapVocabulary(int $map_id): string {
  102.     if (!is_int($map_id)) {
  103.       return '';
  104.     }
  105.  
  106.     $map = $this->interactiveMapEntityStorage->load($map_id);
  107.     $map_vocab_id = NULL;
  108.     if (!$map->get('field_map_vocabulary')->isEmpty()) {
  109.       $field_map_vocabulary = $map->get('field_map_vocabulary')->getValue();
  110.       if (isset($field_map_vocabulary[0]['target_id'])) {
  111.         $map_vocab_id = $field_map_vocabulary[0]['target_id'];
  112.       }
  113.     }
  114.     return $map_vocab_id;
  115.   }
  116.  
  117.   protected function getTermData($vocabulary): array {
  118.     $terms = NULL;
  119.     try {
  120.       // get terms of the vocabulary
  121.       $terms = \Drupal::entityTypeManager()
  122.         ->getStorage('taxonomy_term')
  123.         ->loadTree($vocabulary);
  124.  
  125.     } catch (\Exception $e) {
  126.       // log exception
  127.       \Drupal::logger('og_sydneymetrod9')
  128.         ->warning(t('Exception when getting list of terms in vocabulary @vocabulary. Message: @message', [
  129.           '@vocabulary' => $vocabulary,
  130.           '@message' => $e->getMessage(),
  131.         ]));
  132.     }
  133.  
  134.     $terms_array = [];
  135.     foreach ($terms as $term) {
  136.       $terms_array[$term->tid] = $term->name;
  137.     }
  138.     return $terms_array;
  139.   }
  140.  
  141.   /**
  142.    * Callback function to fetch list of terms based on Map's vocabulary.
  143.    *
  144.    * @param array $form
  145.    * @param \Drupal\Core\Form\FormStateInterface $form_state
  146.    *
  147.    * @return mixed
  148.    */
  149.   public static function getItemCategoryCallback(array $form, FormStateInterface $form_state) {
  150.     return $form['item_category'];
  151.   }
  152.  
  153.   /**
  154.    * {@inheritdoc}
  155.    */
  156.   public function save(array $form, FormStateInterface $form_state) {
  157.     $entity = $this->entity;
  158.  
  159.     // Save as a new revision if requested to do so.
  160.     if (!$form_state->isValueEmpty('new_revision') && $form_state->getValue('new_revision') != FALSE) {
  161.       $entity->setNewRevision();
  162.  
  163.       // If a new revision is created, save the current user as revision author.
  164.       $entity->setRevisionCreationTime($this->time->getRequestTime());
  165.       $entity->setRevisionUserId($this->account->id());
  166.     }
  167.     else {
  168.       $entity->setNewRevision(FALSE);
  169.     }
  170.  
  171.     $status = parent::save($form, $form_state);
  172.  
  173.     switch ($status) {
  174.       case SAVED_NEW:
  175.         $this->messenger()->addMessage($this->t('Created the %label Interactive Map Item.', [
  176.           '%label' => $entity->label(),
  177.         ]));
  178.         break;
  179.  
  180.       default:
  181.         $this->messenger()->addMessage($this->t('Saved the %label Interactive Map Item.', [
  182.           '%label' => $entity->label(),
  183.         ]));
  184.     }
  185.     $form_state->setRedirect('entity.interactive_map_item.canonical', ['interactive_map_item' => $entity->id()]);
  186.   }
  187.  
  188. }
  189.  
Advertisement
Add Comment
Please, Sign In to add comment