permanaj

Untitled

May 20th, 2021
1,028
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.04 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' => 'item-category-field-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']['#prefix'] = '<div id="item-category-field-wrapper">';
  97.     $form['item_category']['widget']['#suffix'] = '</div>';
  98.     $form['item_category']['#attributes']['id'] = 'edit-item-category-abc';
  99.     $form['item_category']['widget']['#attributes']['id'] = 'edit-item-category';
  100.     $form['item_category']['widget']['#options'] = $item_category_options;
  101.     $form['item_category']['widget']['#default_value'] = !empty($form_state->getValue('item_category')) ? $form_state->getValue('item_category') : '';
  102.  
  103.     return $form;
  104.   }
  105.  
  106.   protected function getMapVocabulary(int $map_id): string {
  107.     if (!is_int($map_id)) {
  108.       return '';
  109.     }
  110.  
  111.     $map = $this->interactiveMapEntityStorage->load($map_id);
  112.     $map_vocab_id = NULL;
  113.     if (!$map->get('field_map_vocabulary')->isEmpty()) {
  114.       $field_map_vocabulary = $map->get('field_map_vocabulary')->getValue();
  115.       if (isset($field_map_vocabulary[0]['target_id'])) {
  116.         $map_vocab_id = $field_map_vocabulary[0]['target_id'];
  117.       }
  118.     }
  119.     return $map_vocab_id;
  120.   }
  121.  
  122.   protected function getTermData($vocabulary): array {
  123.     $terms = NULL;
  124.     try {
  125.       // get terms of the vocabulary
  126.       $terms = \Drupal::entityTypeManager()
  127.         ->getStorage('taxonomy_term')
  128.         ->loadTree($vocabulary);
  129.  
  130.     } catch (\Exception $e) {
  131.       // log exception
  132.       \Drupal::logger('og_sydneymetrod9')
  133.         ->warning(t('Exception when getting list of terms in vocabulary @vocabulary. Message: @message', [
  134.           '@vocabulary' => $vocabulary,
  135.           '@message' => $e->getMessage(),
  136.         ]));
  137.     }
  138.  
  139.     $terms_array = [];
  140.     foreach ($terms as $term) {
  141.       $terms_array[$term->tid] = $term->name;
  142.     }
  143.     return $terms_array;
  144.   }
  145.  
  146.   /**
  147.    * Callback function to fetch list of terms based on Map's vocabulary.
  148.    *
  149.    * @param array $form
  150.    * @param \Drupal\Core\Form\FormStateInterface $form_state
  151.    *
  152.    * @return mixed
  153.    */
  154.   public static function getItemCategoryCallback(array $form, FormStateInterface $form_state) {
  155.     return $form['item_category'];
  156.   }
  157.  
  158.   /**
  159.    * {@inheritdoc}
  160.    */
  161.   public function save(array $form, FormStateInterface $form_state) {
  162.     $entity = $this->entity;
  163.  
  164.     // Save as a new revision if requested to do so.
  165.     if (!$form_state->isValueEmpty('new_revision') && $form_state->getValue('new_revision') != FALSE) {
  166.       $entity->setNewRevision();
  167.  
  168.       // If a new revision is created, save the current user as revision author.
  169.       $entity->setRevisionCreationTime($this->time->getRequestTime());
  170.       $entity->setRevisionUserId($this->account->id());
  171.     }
  172.     else {
  173.       $entity->setNewRevision(FALSE);
  174.     }
  175.  
  176.     $status = parent::save($form, $form_state);
  177.  
  178.     switch ($status) {
  179.       case SAVED_NEW:
  180.         $this->messenger()->addMessage($this->t('Created the %label Interactive Map Item.', [
  181.           '%label' => $entity->label(),
  182.         ]));
  183.         break;
  184.  
  185.       default:
  186.         $this->messenger()->addMessage($this->t('Saved the %label Interactive Map Item.', [
  187.           '%label' => $entity->label(),
  188.         ]));
  189.     }
  190.     $form_state->setRedirect('entity.interactive_map_item.canonical', ['interactive_map_item' => $entity->id()]);
  191.   }
  192.  
  193. }
  194.  
Advertisement
Add Comment
Please, Sign In to add comment