/**
  * @param FormStateInterface $form_state
  * @return object | bool
  */
 public static function get_form_entity($form_state)
 {
     if (!is_null($form_state->getFormObject()) && method_exists($form_state->getFormObject(), 'getEntity')) {
         $entity = $form_state->getFormObject()->getEntity();
         return $entity;
     }
     return FALSE;
 }
 /**
  * {@inheritdoc}
  */
 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
 {
     /* @var $instance \Drupal\mailchimp_lists\Plugin\Field\FieldType\MailchimpListsSubscription */
     $instance = $items[0];
     $subscribe_default = $instance->getSubscribe();
     $email = NULL;
     if (!empty($instance->getEntity())) {
         $email = mailchimp_lists_load_email($instance, $instance->getEntity(), FALSE);
         if ($email) {
             $subscribe_default = mailchimp_is_subscribed($instance->getFieldDefinition()->getSetting('mc_list_id'), $email);
         }
     }
     $element += array('#title' => SafeMarkup::checkPlain($element['#title']), '#type' => 'fieldset');
     $element['subscribe'] = array('#title' => t('Subscribe'), '#type' => 'checkbox', '#default_value' => $subscribe_default ? TRUE : $this->fieldDefinition->isRequired(), '#required' => $this->fieldDefinition->isRequired(), '#disabled' => $this->fieldDefinition->isRequired());
     $form_id = $form_state->getFormObject()->getFormId();
     if ($this->fieldDefinition->getSetting('show_interest_groups') || $form_id == 'field_ui_field_edit_form') {
         $mc_list = mailchimp_get_list($instance->getFieldDefinition()->getSetting('mc_list_id'));
         $element['interest_groups'] = array('#type' => 'fieldset', '#title' => SafeMarkup::checkPlain($instance->getFieldDefinition()->getSetting('interest_groups_title')), '#weight' => 100, '#states' => array('invisible' => array(':input[name="' . $instance->getFieldDefinition()->getName() . '[0][value][subscribe]"]' => array('checked' => FALSE))));
         if ($form_id == 'field_ui_field_edit_form') {
             $element['interest_groups']['#states']['invisible'] = array(':input[name="field[settings][show_interest_groups]"]' => array('checked' => FALSE));
         }
         $groups_default = $instance->getInterestGroups();
         if ($groups_default == NULL) {
             $groups_default = array();
         }
         if ($mc_list['stats']['group_count']) {
             $element['interest_groups'] += mailchimp_interest_groups_form_elements($mc_list, $groups_default, $email);
         }
     }
     return array('value' => $element);
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function buildConfigurationForm(array $form, FormStateInterface $form_state)
 {
     $form_object = $form_state->getFormObject();
     $form['animal_type'] = ['#type' => 'select', '#title' => $this->t('Animal type'), '#options' => ['vertebrates' => $this->t('Vertebrates (with backbone)'), 'invertebrates' => $this->t('Invertebrates (without backbone)')], '#default_value' => $this->getConfigurationValue('animal_type'), '#required' => TRUE, '#ajax' => ['callback' => [$form_object, 'updateTypeSettings'], 'effect' => 'fade']];
     if ($this->getConfigurationValue('animal_type') === 'vertebrates') {
         $form['allowed_vertebrates'] = ['#type' => 'checkboxes', '#title' => $this->t('Limit allowed vertebrates'), '#options' => ['amphibians' => $this->t('Amphibians'), 'birds' => $this->t('Birds'), 'fish' => $this->t('Fish'), 'mammals' => $this->t('Mammals'), 'reptiles' => $this->t('Reptiles')], '#default_value' => $this->getConfigurationValue('allowed_vertebrates', [])];
     }
     return $form;
 }
Example #4
0
 /**
  * Submit handler for feedback options.
  */
 public static function addFeedbackOptionsSubmit(&$form, FormStateInterface &$form_state)
 {
     $forms = FormController::getProtectedForms();
     $mollom_form = Form::load($forms['delete'][$form_state->getFormObject()->getFormId()])->initialize();
     $entity_type = $mollom_form['entity'];
     if (!empty($entity_type)) {
         $id = $form_state->getFormObject()->getEntity()->id();
     } else {
         $id = $form_state->getValue($mollom_form['mapping']['post_id']);
     }
     $feedback = $form_state->getValue(array('mollom', 'feedback'));
     if (!empty($feedback)) {
         if (self::sendFeedback($entity_type, $id, $feedback, 'moderate', 'mollom_data_delete_form_submit')) {
             drupal_set_message(t('The content was successfully reported as inappropriate.'));
         }
     }
     // Remove Mollom session data.
     ResponseDataStorage::delete($entity_type, $id);
 }
 /**
  * {@inheritdoc}
  */
 public function enforceRevisionsBundleFormAlter(array &$form, FormStateInterface $form_state, $form_id)
 {
     /* @var \Drupal\node\Entity\NodeType $entity */
     $entity = $form_state->getFormObject()->getEntity();
     if ($entity->getThirdPartySetting('content_moderation', 'enabled', FALSE)) {
         // Force the revision checkbox on.
         $form['workflow']['options']['#default_value']['revision'] = 'revision';
         $form['workflow']['options']['revision']['#disabled'] = TRUE;
     }
 }
 /**
  * {@inheritdoc}
  *
  * @todo Change this because $component could be component type or component id
  *       Would make sense to make our own ParamConverterInterface's so component is loaded at this point?
  */
 public function buildForm(array $form, FormStateInterface $form_state, Node $node = NULL, $component = NULL)
 {
     // Load the component plugin.
     $form_state->getFormObject();
     if (empty($form['#component'])) {
         $component = $this->prepareComponent($node, $component);
     } else {
         $component = $form['#component'];
     }
     // Get the form from the component plugin.
     $form = $component->buildForm($form, $form_state, $node);
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function entityFormEntityBuild($entity_type, EntityInterface $entity, array $form, FormStateInterface $form_state)
 {
     if ($form_state->hasValue('content_translation')) {
         $form_object = $form_state->getFormObject();
         $translation =& $form_state->getValue('content_translation');
         $translation['status'] = $form_object->getEntity()->isPublished();
         // $form['content_translation']['name'] is the equivalent field
         // for translation author uid.
         $account = $entity->uid->entity;
         $translation['name'] = $account ? $account->getUsername() : '';
         $translation['created'] = format_date($entity->created->value, 'custom', 'Y-m-d H:i:s O');
     }
     parent::entityFormEntityBuild($entity_type, $entity, $form, $form_state);
 }
Example #8
0
  /**
   * Saves Schema.org mappings in \Drupal\node\NodeTypeForm.
   */
  public static function submitForm(array &$form, FormStateInterface $form_state) {
    if ($form_state->hasValue('types')) {
      $entity_type = $form_state->getFormObject()->getEntity();
      $mapping = rdf_get_mapping('node', $entity_type->id());
      if ($entity_type->isNew()) {
        $mapping = rdf_get_mapping('node', $form_state->getValue('types'));
      }

      if ($form_state->hasValue('types')) {
        $mapping->setBundleMapping(array('types' => array($form_state->getValue('types'))))
          ->save();
      }
    }
  }
 /**
  * {@inheritdoc}
  */
 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
 {
     // Determine if this is an existing or a new entity.
     /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
     $form_object = $form_state->getFormObject();
     /** @var \Drupal\Core\Entity\EntityInterface $entity */
     $entity = $form_object->getEntity();
     $is_new = empty($entity->id());
     $behaviour = $this->getSetting('behaviour');
     if ($behaviour == 'create' && $is_new || $behaviour == 'modified') {
         $element['set_date'] = ['#type' => 'item', '#value' => TRUE];
     }
     return $element;
 }
 /**
  * {@inheritdoc}
  */
 public function buildConfigurationForm(array $form, FormStateInterface $form_state)
 {
     $options = [];
     foreach ($this->entityFieldManager->getFieldDefinitions('media', $form_state->getFormObject()->getEntity()->id()) as $field_name => $field) {
         if ($field->getType() == 'video_embed_field') {
             $options[$field_name] = $field->getLabel();
         }
     }
     if (empty($options)) {
         $form['summary']['#markup'] = $this->t('A video embed field will be created on this media bundle when you save this form. You can return to this configuration screen to alter the video field used for this bundle, or you can use the one provided.');
     }
     if (!empty($options)) {
         $form['source_field'] = ['#type' => 'select', '#required' => TRUE, '#title' => t('Source Video Field'), '#description' => t('The field on the media entity that contains the video URL.'), '#default_value' => empty($this->configuration['source_field']) ? VideoEmbedField::VIDEO_EMBED_FIELD_DEFAULT_NAME : $this->configuration['source_field'], '#options' => $options];
     }
     return $form;
 }
Example #11
0
 /**
  * Form element validation handler; Invokes selection plugin's validation.
  *
  * @param array $form
  *   The form where the settings form is being included in.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The form state of the (entire) configuration form.
  */
 public static function fieldSettingsFormValidate(array $form, FormStateInterface $form_state)
 {
     $field = $form_state->getFormObject()->getEntity();
     $handler = \Drupal::service('plugin.manager.entity_reference_selection')->getSelectionHandler($field);
     $handler->validateConfigurationForm($form, $form_state);
 }
Example #12
0
 /**
  * Ajax callback for the job item review form.
  */
 function ajaxReviewForm(array $form, FormStateInterface $form_state)
 {
     $key = array_slice($form_state->getTriggeringElement()['#array_parents'], 0, 2);
     $render_data = NestedArray::getValue($form, $key);
     tmgmt_write_request_messages($form_state->getFormObject()->getEntity()->getJob());
     return $render_data;
 }
 /**
  * {@inheritdoc}
  */
 public function retrieveForm($form_id, FormStateInterface &$form_state)
 {
     // Record the $form_id.
     $form_state->addBuildInfo('form_id', $form_id);
     // We save two copies of the incoming arguments: one for modules to use
     // when mapping form ids to constructor functions, and another to pass to
     // the constructor function itself.
     $build_info = $form_state->getBuildInfo();
     $args = $build_info['args'];
     $callback = [$form_state->getFormObject(), 'buildForm'];
     $form = array();
     // Assign a default CSS class name based on $form_id.
     // This happens here and not in self::prepareForm() in order to allow the
     // form constructor function to override or remove the default class.
     $form['#attributes']['class'][] = Html::getClass($form_id);
     // Same for the base form ID, if any.
     if (isset($build_info['base_form_id'])) {
         $form['#attributes']['class'][] = Html::getClass($build_info['base_form_id']);
     }
     // We need to pass $form_state by reference in order for forms to modify it,
     // since call_user_func_array() requires that referenced variables are
     // passed explicitly.
     $args = array_merge(array($form, &$form_state), $args);
     $form = call_user_func_array($callback, $args);
     // If the form returns some kind of response, deliver it.
     if ($form instanceof Response) {
         $this->sendResponse($form);
         exit;
     }
     $form['#form_id'] = $form_id;
     return $form;
 }
 /**
  * Process callback to alter action buttons.
  */
 public static function processActions($element, FormStateInterface $form_state, array &$form)
 {
     // We'll steal most of the button configuration from the default submit
     // button. However, NodeForm also hides that button for admins (as it adds
     // its own, too), so we have to restore it.
     $default_button = $form['actions']['submit'];
     $default_button['#access'] = TRUE;
     // Add a custom button for each transition we're allowing. The #dropbutton
     // property tells FAPI to cluster them all together into a single widget.
     $options = $element['#options'];
     $entity = $form_state->getFormObject()->getEntity();
     $translatable = !$entity->isNew() && $entity->isTranslatable();
     foreach ($options as $id => $label) {
         $button = ['#dropbutton' => 'save', '#moderation_state' => $id, '#weight' => -10];
         $button['#value'] = $translatable ? t('Save and @transition (this translation)', ['@transition' => $label]) : t('Save and @transition', ['@transition' => $label]);
         $form['actions']['moderation_state_' . $id] = $button + $default_button;
     }
     // Hide the default buttons, including the specialty ones added by
     // NodeForm.
     foreach (['publish', 'unpublish', 'submit'] as $key) {
         $form['actions'][$key]['#access'] = FALSE;
         unset($form['actions'][$key]['#dropbutton']);
     }
     // Setup a callback to translate the button selection back into field
     // widget, so that it will get saved properly.
     $form['#entity_builders']['update_moderation_state'] = [get_called_class(), 'updateStatus'];
     return $element;
 }
 /**
  * Form submission handler for ContentTranslationHandler::entityFormAlter().
  *
  * Takes care of content translation deletion.
  */
 function entityFormDeleteTranslation($form, FormStateInterface $form_state)
 {
     $form_object = $form_state->getFormObject();
     $entity = $form_object->getEntity();
     $entity_type_id = $entity->getEntityTypeId();
     $form_state->setRedirect('content_translation.translation_delete_' . $entity_type_id, array($entity_type_id => $entity->id(), 'language' => $form_object->getFormLangcode($form_state)));
 }
Example #16
0
 /**
  * Provide a standard set of Apply/Cancel/OK buttons for the forms. Also provide
  * a hidden op operator because the forms plugin doesn't seem to properly
  * provide which button was clicked.
  *
  * TODO: Is the hidden op operator still here somewhere, or is that part of the
  * docblock outdated?
  */
 public function getStandardButtons(&$form, FormStateInterface $form_state, $form_id, $name = NULL)
 {
     $form['actions'] = array('#type' => 'actions');
     if (empty($name)) {
         $name = t('Apply');
         if (!empty($this->stack) && count($this->stack) > 1) {
             $name = t('Apply and continue');
         }
         $names = array(t('Apply'), t('Apply and continue'));
     }
     // Views provides its own custom handling of AJAX form submissions. Usually
     // this happens at the same path, but custom paths may be specified in
     // $form_state.
     $form_url = $form_state->get('url') ?: Url::fromRouteMatch(\Drupal::routeMatch());
     // Forms that are purely informational set an ok_button flag, so we know not
     // to create an "Apply" button for them.
     if (!$form_state->get('ok_button')) {
         $form['actions']['submit'] = array('#type' => 'submit', '#value' => $name, '#id' => 'edit-submit-' . Html::getUniqueId($form_id), '#submit' => array(array($this, 'standardSubmit')), '#button_type' => 'primary', '#ajax' => array('url' => $form_url));
         // Form API button click detection requires the button's #value to be the
         // same between the form build of the initial page request, and the
         // initial form build of the request processing the form submission.
         // Ideally, the button's #value shouldn't change until the form rebuild
         // step. However, \Drupal\views_ui\Form\Ajax\ViewsFormBase::getForm()
         // implements a different multistep form workflow than the Form API does,
         // and adjusts $view->stack prior to form processing, so we compensate by
         // extending button click detection code to support any of the possible
         // button labels.
         if (isset($names)) {
             $form['actions']['submit']['#values'] = $names;
             $form['actions']['submit']['#process'] = array_merge(array('views_ui_form_button_was_clicked'), \Drupal::service('element_info')->getInfoProperty($form['actions']['submit']['#type'], '#process', array()));
         }
         // If a validation handler exists for the form, assign it to this button.
         $form['actions']['submit']['#validate'][] = [$form_state->getFormObject(), 'validateForm'];
     }
     // Create a "Cancel" button. For purely informational forms, label it "OK".
     $cancel_submit = function_exists($form_id . '_cancel') ? $form_id . '_cancel' : array($this, 'standardCancel');
     $form['actions']['cancel'] = array('#type' => 'submit', '#value' => !$form_state->get('ok_button') ? t('Cancel') : t('Ok'), '#submit' => array($cancel_submit), '#validate' => array(), '#ajax' => array('path' => $form_url), '#limit_validation_errors' => array());
     // Compatibility, to be removed later: // TODO: When is "later"?
     // We used to set these items on the form, but now we want them on the $form_state:
     if (isset($form['#title'])) {
         $form_state->set('title', $form['#title']);
     }
     if (isset($form['#section'])) {
         $form_state->set('#section', $form['#section']);
     }
     // Finally, we never want these cached -- our object cache does that for us.
     $form['#no_cache'] = TRUE;
 }
 /**
  * Form submission handler.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $sitemap = \Drupal::service('custom_sitemap.sitemap');
     $custom_links = $sitemap->get_custom_links();
     $form_state->cleanValues();
     $custom_links[$form_state->getValue('name')] = array('path' => $form_state->getValue('path'), 'index' => (bool) $form_state->getValue('index'), 'priority' => (double) $form_state->getValue('priority'));
     $sitemap->save_custom_links($custom_links);
     $sitemap->generate_all_sitemaps();
     if ($form_state->getFormObject()->getFormId() == 'custom_sitemap_add_link_form') {
         drupal_set_message($this->t('The custom link has been added to the sitemap.'));
     } else {
         drupal_set_message($this->t('The custom link has been saved.'));
     }
     $form_state->setRedirect('custom_sitemap.overview');
 }
Example #18
0
 /**
  * {@inheritdoc}
  */
 public function retrieveForm($form_id, FormStateInterface &$form_state)
 {
     // Record the $form_id.
     $form_state->addBuildInfo('form_id', $form_id);
     // We save two copies of the incoming arguments: one for modules to use
     // when mapping form ids to constructor functions, and another to pass to
     // the constructor function itself.
     $build_info = $form_state->getBuildInfo();
     $args = $build_info['args'];
     $callback = [$form_state->getFormObject(), 'buildForm'];
     $form = array();
     // Assign a default CSS class name based on $form_id.
     // This happens here and not in self::prepareForm() in order to allow the
     // form constructor function to override or remove the default class.
     $form['#attributes']['class'][] = Html::getClass($form_id);
     // Same for the base form ID, if any.
     if (isset($build_info['base_form_id'])) {
         $form['#attributes']['class'][] = Html::getClass($build_info['base_form_id']);
     }
     // We need to pass $form_state by reference in order for forms to modify it,
     // since call_user_func_array() requires that referenced variables are
     // passed explicitly.
     $args = array_merge(array($form, &$form_state), $args);
     $form = call_user_func_array($callback, $args);
     // If the form returns a response, skip subsequent page construction by
     // throwing an exception.
     // @see Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber
     //
     // @todo Exceptions should not be used for code flow control. However, the
     //   Form API currently allows any form builder functions to return a
     //   response.
     //   @see https://www.drupal.org/node/2363189
     if ($form instanceof Response) {
         throw new EnforcedResponseException($form);
     }
     $form['#form_id'] = $form_id;
     return $form;
 }
Example #19
0
 /**
  * {@inheritdoc}
  */
 public function getFormObject()
 {
     return $this->mainFormState->getFormObject();
 }
Example #20
0
  /**
   * Submit callback for the 'reverse', 'shuffle' and 'clear' actions.
   */
  public static function submitAction(array &$form, FormStateInterface $form_state) {
    $trigger = $form_state->getTriggeringElement();
    $op = $trigger['#op'];

    // Check if we have a form element for the 'items' field.
    $path = array_merge($form['#parents'], ['items']);
    $key_exists = NULL;
    NestedArray::getValue($form_state->getValues(), $path, $key_exists);

    if ($key_exists) {
      // Remove any user input for the 'items' element in order to allow the
      // values set below to be applied.
      $user_input = $form_state->getUserInput();
      NestedArray::setValue($user_input, $path, NULL);
      $form_state->setUserInput($user_input);

      $entity = $form_state->getFormObject()->getEntity();
      $items_widget = $form_state->getFormObject()->getFormDisplay($form_state)->getRenderer('items');

      $subqueue_items = $entity->get('items');
      $items_widget->extractFormValues($subqueue_items, $form, $form_state);
      $items_values = $subqueue_items->getValue();

      switch ($op) {
        case 'reverse':
          $subqueue_items->setValue(array_reverse($items_values));
          break;

        case 'shuffle':
          shuffle($items_values);
          $subqueue_items->setValue($items_values);
          break;

        case 'clear':
          $subqueue_items->setValue(NULL);
          break;
      }

      $form_state->getFormObject()->setEntity($entity);

      $form_state->setRebuild();
    }
  }
Example #21
0
 /**
  * {@inheritdoc}
  */
 public function buildConfigurationForm(array $form, FormStateInterface $form_state)
 {
     /** @var MediaBundleInterface $bundle */
     $bundle = $form_state->getFormObject()->getEntity();
     $options = [];
     $allowed_field_types = ['file', 'image'];
     foreach ($this->entityFieldManager->getFieldDefinitions('media', $bundle->id()) as $field_name => $field) {
         if (in_array($field->getType(), $allowed_field_types) && !$field->getFieldStorageDefinition()->isBaseField()) {
             $options[$field_name] = $field->getLabel();
         }
     }
     $form['source_field'] = ['#type' => 'select', '#title' => t('Field with source information'), '#description' => t('Field on media entity that stores Image file. You can create a bundle without selecting a value for this dropdown initially. This dropdown can be populated after adding fields to the bundle.'), '#default_value' => empty($this->configuration['source_field']) ? NULL : $this->configuration['source_field'], '#options' => $options];
     $form['gather_exif'] = ['#type' => 'select', '#title' => t('Whether to gather exif data.'), '#description' => t('Gather exif data using exif_read_data().'), '#default_value' => empty($this->configuration['gather_exif']) || !function_exists('exif_read_data') ? 0 : $this->configuration['gather_exif'], '#options' => [0 => t('No'), 1 => t('Yes')], '#disabled' => function_exists('exif_read_data') ? FALSE : TRUE];
     return $form;
 }
Example #22
0
 /**
  * Redirect content entity edit forms on save, if there is a forward revision.
  *
  * When saving their changes, editors should see those changes displayed on
  * the next page.
  *
  * @param array $form
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  */
 public static function bundleFormRedirect(array &$form, FormStateInterface $form_state)
 {
     /* @var ContentEntityInterface $entity */
     $entity = $form_state->getFormObject()->getEntity();
     $moderation_info = \Drupal::getContainer()->get('workbench_moderation.moderation_information');
     if ($moderation_info->hasForwardRevision($entity)) {
         $entity_type_id = $entity->getEntityTypeId();
         $form_state->setRedirect("entity.{$entity_type_id}.latest_version", [$entity_type_id => $entity->id()]);
     }
 }
Example #23
0
 /**
  * {@inheritdoc}
  */
 public function buildConfigurationForm(array $form, FormStateInterface $form_state)
 {
     $embed_button = $form_state->getTemporaryValue('embed_button');
     $entity_type_id = $this->getConfigurationValue('entity_type');
     $form['entity_type'] = array('#type' => 'select', '#title' => $this->t('Entity type'), '#options' => $this->getEntityTypeOptions(), '#default_value' => $entity_type_id, '#description' => $this->t("Entity type for which this button is to enabled."), '#required' => TRUE, '#ajax' => array('callback' => array($form_state->getFormObject(), 'updateTypeSettings'), 'effect' => 'fade'), '#disabled' => !$embed_button->isNew());
     if ($entity_type_id) {
         $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
         $form['bundles'] = array('#type' => 'checkboxes', '#title' => $entity_type->getBundleLabel() ?: $this->t('Bundles'), '#options' => $this->getEntityBundleOptions($entity_type), '#default_value' => $this->getConfigurationValue('bundles'), '#description' => $this->t('If none are selected, all are allowed.'));
         $form['bundles']['#access'] = !empty($form['bundles']['#options']);
         // Allow option to limit Entity Embed Display plugins.
         $form['display_plugins'] = array('#type' => 'checkboxes', '#title' => $this->t('Allowed Entity Embed Display plugins'), '#options' => $this->displayPluginManager->getDefinitionOptionsForEntityType($entity_type_id), '#default_value' => $this->getConfigurationValue('display_plugins'), '#description' => $this->t('If none are selected, all are allowed. Note that these are the plugins which are allowed for this entity type, all of these might not be available for the selected entity.'));
         $form['display_plugins']['#access'] = !empty($form['display_plugins']['#options']);
         /** @var \Drupal\entity_browser\EntityBrowserInterface[] $browsers */
         if ($this->entityTypeManager->hasDefinition('entity_browser') && ($browsers = $this->entityTypeManager->getStorage('entity_browser')->loadMultiple())) {
             $ids = array_keys($browsers);
             $labels = array_map(function ($item) {
                 /** @var \Drupal\entity_browser\EntityBrowserInterface $item */
                 return $item->label();
             }, $browsers);
             $options = ['_none' => $this->t('None (autocomplete)')] + array_combine($ids, $labels);
             $form['entity_browser'] = ['#type' => 'select', '#title' => $this->t('Entity browser'), '#description' => $this->t('Entity browser to be used to select entities to be embedded.'), '#options' => $options, '#default_value' => $this->getConfigurationValue('entity_browser')];
             $form['entity_browser_settings'] = ['#type' => 'details', '#title' => $this->t('Entity browser settings'), '#open' => TRUE, '#states' => ['invisible' => [':input[name="type_settings[entity_browser]"]' => ['value' => '_none']]]];
             $form['entity_browser_settings']['display_review'] = ['#type' => 'checkbox', '#title' => 'Display the entity after selection', '#default_value' => $this->getConfigurationValue('entity_browser_settings')['display_review']];
         } else {
             $form['entity_browser'] = ['#type' => 'value', '#value' => ''];
         }
     }
     return $form;
 }
 /**
  * {@inheritdoc}
  *
  * Implements workflow_transition() -> WorkflowDefaultWidget::submit().
  *
  * Overrides submit(array $form, array &$form_state).
  * Contains 2 extra parameters for D7
  *
  * @param array $form
  * @param array $form_state
  * @param array $items
  *   The value of the field.
  * @param bool $force
  *   TRUE if all access must be overridden, e.g., for Rules.
  *
  * @return int
  *   If update succeeded, the new State Id. Else, the old Id is returned.
  *
  * This is called from function _workflowfield_form_submit($form, &$form_state)
  * It is a replacement of function workflow_transition($entity, $to_sid, $force, $field)
  * It performs the following actions;
  * - save a scheduled action
  * - update history
  * - restore the normal $items for the field.
  * @todo: remove update of {node_form} table. (separate task, because it has features, too)
  */
 public function massageFormValues(array $values, array $form, FormStateInterface $form_state)
 {
     $user = workflow_current_user();
     // @todo #2287057: verify if submit() really is only used for UI. If not, $user must be passed.
     // Set the new value.
     // Beware: We presume cardinality = 1 !!
     // The widget form element type has transformed the value to a
     // WorkflowTransition object at this point. We need to convert it
     // back to the regular 'value' string format.
     foreach ($values as &$item) {
         if (!empty($item)) {
             // } && $item['value'] instanceof DrupalDateTime) {
             // The following can NOT be retrieved from the WorkflowTransition.
             /* @var $entity EntityInterface */
             $entity = $form_state->getFormObject()->getEntity();
             /* @var $transition \Drupal\workflow\Entity\WorkflowTransitionInterface */
             $transition = $item['workflow_transition'];
             $field_name = $transition->getFieldName();
             // N.B. Use a proprietary version of copyFormValuesToEntity,
             // where $entity/$transition is passed by reference.
             // $this->copyFormValuesToEntity($entity, $form, $form_state);
             /* @var $transition \Drupal\workflow\Entity\WorkflowTransitionInterface */
             $transition = WorkflowTransitionElement::copyFormItemValuesToEntity($transition, $form, $item);
             // Try to execute the transition. Return $from_sid when error.
             if (!$transition) {
                 // This should not be possible (perhaps when testing/developing).
                 drupal_set_message(t('Error: the transition from %from_sid to %to_sid could not be generated.'), 'error');
                 // The current value is still the previous state.
                 $to_sid = $from_sid;
             } else {
                 // The transition may be scheduled or not. Save the result, and
                 // rely upon hook workflow_entity_insert/update($entity) in
                 // file workflow.module to save/execute the transition.
                 // - validate option; add hook to let other modules change comment.
                 // - add to history; add to watchdog
                 // Return the new State ID. (Execution may fail and return the old Sid.)
                 // Get the new value from an action button if set in the workflow settings.
                 $action_info = _workflow_transition_form_get_triggering_button($form_state);
                 if ($field_name == $action_info['field_name']) {
                     $transition->to_sid->value = $action_info['to_sid'];
                 }
                 $force = FALSE;
                 // @TODO D8-port: add to form for usage in VBO.
                 // Now, save/execute the transition.
                 $from_sid = $transition->getFromSid();
                 $force = $force || $transition->isForced();
                 if (!$transition->isAllowed($user, $force)) {
                     // Transition is not allowed.
                     $to_sid = $from_sid;
                 } elseif (!$entity || !$entity->id()) {
                     // Entity is inserted. The Id is not yet known.
                     // So we can't yet save the transition right now, but must rely on
                     // function/hook workflow_entity_insert($entity) in file workflow.module.
                     // $to_sid = $transition->execute($force);
                     $to_sid = $transition->getToSid();
                 } else {
                     // Entity is updated. To stay in sync with insert, we rely on
                     // function/hook workflow_entity_update($entity) in file workflow.module.
                     // $to_sid = $transition->execute($force);
                     $to_sid = $transition->getToSid();
                 }
             }
             // Now the data is captured in the Transition, and before calling the
             // Execution, restore the default values for Workflow Field.
             // For instance, workflow_rules evaluates this.
             //
             // Set the transition back, to be used in hook_entity_update().
             $item['workflow_transition'] = $transition;
             //
             // Set the value at the proper location.
             $item['value'] = $to_sid;
         }
     }
     return $values;
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // If moderation is enabled, revisions MUST be enabled as well.
     // Otherwise we can't have forward revisions.
     if ($form_state->getValue('enable_moderation_state')) {
         /* @var ConfigEntityTypeInterface $bundle */
         $bundle = $form_state->getFormObject()->getEntity();
         $this->entityTypeManager->getHandler($bundle->getEntityType()->getBundleOf(), 'moderation')->onBundleModerationConfigurationFormSubmit($bundle);
     }
     parent::submitForm($form, $form_state);
     drupal_set_message($this->t('Your settings have been saved.'));
 }
 /**
  * Redirect content entity edit forms on save, if there is a forward revision.
  *
  * When saving their changes, editors should see those changes displayed on
  * the next page.
  *
  * @param array $form
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  */
 public function bundleFormRedirect(array &$form, FormStateInterface $form_state)
 {
     /* @var ContentEntityInterface $entity */
     $entity = $form_state->getFormObject()->getEntity();
     if ($this->moderationInfo->hasForwardRevision($entity)) {
         $entity_type_id = $entity->getEntityTypeId();
         $form_state->setRedirect("entity.{$entity_type_id}.latest_version", [$entity_type_id => $entity->id()]);
     }
 }
 /**
  * Form submission handler for ContentTranslationHandler::entityFormAlter().
  *
  * Takes care of content translation deletion.
  */
 function entityFormDeleteTranslation($form, FormStateInterface $form_state)
 {
     /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
     $form_object = $form_state->getFormObject();
     /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
     $entity = $form_object->getEntity();
     $entity_type_id = $entity->getEntityTypeId();
     if ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form')) {
         $form_state->setRedirectUrl($entity->urlInfo('delete-form'));
     } else {
         $form_state->setRedirect('content_translation.translation_delete_' . $entity_type_id, [$entity_type_id => $entity->id(), 'language' => $form_object->getFormLangcode($form_state)]);
     }
 }
Example #28
0
 /**
  * Determines if the entity already exists.
  *
  * @param string|int $entity_id
  *   The entity ID.
  * @param array $element
  *   The form element.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  *
  * @return bool
  *   TRUE if the entity exists, FALSE otherwise.
  */
 public function exists($entity_id, array $element, FormStateInterface $form_state)
 {
     /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $entity */
     $entity = $form_state->getFormObject()->getEntity();
     return (bool) $this->entityQuery->get($entity->getEntityTypeId())->condition($entity->getEntityType()->getKey('id'), $entity_id)->execute();
 }
 /**
  * Process callback: assigns weights and hides extra fields.
  *
  * @see \Drupal\Core\Entity\EntityForm::form()
  */
 public function processForm($element, FormStateInterface $form_state, $form)
 {
     // If the form is cached, process callbacks may not have a valid reference
     // to the entity object, hence we must restore it.
     $this->entity = $form_state->getFormObject()->getEntity();
     return $element;
 }
 /**
  * {@inheritdoc}
  */
 public function getFormObject()
 {
     return $this->decoratedFormState->getFormObject();
 }