Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Drupal\og_sydneymetrod9\Form;
- use Drupal\Core\Ajax\AjaxResponse;
- use Drupal\Core\Ajax\HtmlCommand;
- use Drupal\Core\Entity\ContentEntityForm;
- use Drupal\Core\Entity\EntityStorageInterface;
- use Drupal\Core\Form\FormStateInterface;
- use Symfony\Component\DependencyInjection\ContainerInterface;
- /**
- * Form controller for Interactive Map Item edit forms.
- *
- * @ingroup og_sydneymetrod9
- */
- class InteractiveMapItemEntityForm extends ContentEntityForm {
- /**
- * The current user account.
- *
- * @var \Drupal\Core\Session\AccountProxyInterface
- */
- protected $account;
- /**
- * The Interactive Map storage.
- *
- * @var \Drupal\Core\Entity\EntityStorageInterface
- */
- protected EntityStorageInterface $interactiveMapEntityStorage;
- /**
- * {@inheritdoc}
- */
- public static function create(ContainerInterface $container) {
- // Instantiates this form class.
- $instance = parent::create($container);
- $instance->account = $container->get('current_user');
- $instance->interactiveMapEntityStorage = $container->get('entity_type.manager')->getStorage('interactive_map');
- return $instance;
- }
- /**
- * {@inheritdoc}
- */
- public function buildForm(array $form, FormStateInterface $form_state) {
- $form = parent::buildForm($form, $form_state);
- if (!$this->entity->isNew()) {
- $form['new_revision'] = [
- '#type' => 'checkbox',
- '#title' => $this->t('Create new revision'),
- '#default_value' => FALSE,
- '#weight' => 10,
- ];
- }
- $form['map']['widget']['#ajax'] = [
- 'event' => 'change',
- 'callback' => '::getItemCategoryCallback',
- 'wrapper' => 'edit-item-category-wrapper',
- ];
- $form_state->setCached(FALSE);
- $user_input = $form_state->getUserInput();
- $map_id = NULL;
- $item_category_options['_none'] = t('- None -');
- // If map is selected
- if (isset($user_input['_triggering_element_name'])) {
- if ($user_input['_triggering_element_name'] === 'map') {
- $field_map_id = $form_state->getValue('map');
- if (isset($field_map_id[0]['target_id'])) {
- $map_id = $field_map_id[0]['target_id'];
- }
- }
- }
- elseif (!empty($form['map']['widget']['#default_value'][0])) {
- // When map already there, meaning in edit mode
- $map_id = $form['map']['widget']['#default_value'][0];
- }
- elseif ($form_state->hasValue('map')) {
- $field_map_id = $form_state->getValue('map');
- if (isset($field_map_id[0]['target_id'])) {
- $map_id = $field_map_id[0]['target_id'];
- }
- }
- if ($map_id) {
- $map_vocab_id = $this->getMapVocabulary($map_id);
- $terms = $this->getTermData($map_vocab_id);
- $item_category_options = $item_category_options + $terms;
- }
- $form['item_category']['widget']['#options'] = $item_category_options;
- return $form;
- }
- protected function getMapVocabulary(int $map_id): string {
- if (!is_int($map_id)) {
- return '';
- }
- $map = $this->interactiveMapEntityStorage->load($map_id);
- $map_vocab_id = NULL;
- if (!$map->get('field_map_vocabulary')->isEmpty()) {
- $field_map_vocabulary = $map->get('field_map_vocabulary')->getValue();
- if (isset($field_map_vocabulary[0]['target_id'])) {
- $map_vocab_id = $field_map_vocabulary[0]['target_id'];
- }
- }
- return $map_vocab_id;
- }
- protected function getTermData($vocabulary): array {
- $terms = NULL;
- try {
- // get terms of the vocabulary
- $terms = \Drupal::entityTypeManager()
- ->getStorage('taxonomy_term')
- ->loadTree($vocabulary);
- } catch (\Exception $e) {
- // log exception
- \Drupal::logger('og_sydneymetrod9')
- ->warning(t('Exception when getting list of terms in vocabulary @vocabulary. Message: @message', [
- '@vocabulary' => $vocabulary,
- '@message' => $e->getMessage(),
- ]));
- }
- $terms_array = [];
- foreach ($terms as $term) {
- $terms_array[$term->tid] = $term->name;
- }
- return $terms_array;
- }
- /**
- * Callback function to fetch list of terms based on Map's vocabulary.
- *
- * @param array $form
- * @param \Drupal\Core\Form\FormStateInterface $form_state
- *
- * @return mixed
- */
- public static function getItemCategoryCallback(array $form, FormStateInterface $form_state) {
- return $form['item_category'];
- }
- /**
- * {@inheritdoc}
- */
- public function save(array $form, FormStateInterface $form_state) {
- $entity = $this->entity;
- // Save as a new revision if requested to do so.
- if (!$form_state->isValueEmpty('new_revision') && $form_state->getValue('new_revision') != FALSE) {
- $entity->setNewRevision();
- // If a new revision is created, save the current user as revision author.
- $entity->setRevisionCreationTime($this->time->getRequestTime());
- $entity->setRevisionUserId($this->account->id());
- }
- else {
- $entity->setNewRevision(FALSE);
- }
- $status = parent::save($form, $form_state);
- switch ($status) {
- case SAVED_NEW:
- $this->messenger()->addMessage($this->t('Created the %label Interactive Map Item.', [
- '%label' => $entity->label(),
- ]));
- break;
- default:
- $this->messenger()->addMessage($this->t('Saved the %label Interactive Map Item.', [
- '%label' => $entity->label(),
- ]));
- }
- $form_state->setRedirect('entity.interactive_map_item.canonical', ['interactive_map_item' => $entity->id()]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment