You are here

class StaticFieldsForm in Feed Import 8

Hierarchy

Expanded class hierarchy of StaticFieldsForm

File

src/Form/StaticFieldsForm.php, line 14
Contains \Drupal\feed_import\Form\StaticFieldsForm

Namespace

Drupal\feed_import\Form
View source
class StaticFieldsForm extends FormBase {

  /**
   * The feed being edited.
   *
   * @var object containing feed settings.
   */
  protected $feed;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'feed_import_static_fields';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $fid = NULL) {
    $this->feed = FeedImport::loadFeed($fid);
    $el = $this
      ->getFieldOptions(FeedImport::getEntityInfo($this->feed->entity));
    $form['fields'] = array(
      '#type' => 'tableselect',
      '#header' => array(
        'field_name' => t('Field'),
        'field_value' => t('Value'),
      ),
      '#empty' => t('No static fields'),
    );
    foreach ($this->feed->settings['static_fields'] as $f => &$val) {
      if (is_scalar($val)) {
        $form['fields']['#options'][$f] = $this
          ->getStaticField($val, $f);
        unset($el['#'][$f]);
      }
      else {
        foreach ($val as $col => &$v) {
          unset($el[$f][$col]);
          $col = $f . ':' . $col;
          $form['fields']['#options'][$col] = $this
            ->getStaticField($v, $col);
        }
      }
    }

    // Get optgroups.
    $opt = $this
      ->getOptionsGroup($el);
    unset($el);
    $form['field_add_method'] = array(
      '#type' => 'checkbox',
      '#title' => t('Use entity fields'),
      '#default_value' => TRUE,
    );
    $form['entity_field'] = array(
      '#type' => 'select',
      '#title' => t('Select field'),
      '#options' => $opt,
      '#states' => array(
        'visible' => array(
          ':input[name=field_add_method]' => array(
            'checked' => TRUE,
          ),
        ),
      ),
    );
    $form['manual_field'] = array(
      '#type' => 'textfield',
      '#title' => t('Enter field name'),
      '#description' => t('You can use filed_name:column format.'),
      '#states' => array(
        'visible' => array(
          ':input[name=field_add_method]' => array(
            'checked' => FALSE,
          ),
        ),
      ),
    );
    $form['add'] = array(
      '#type' => 'submit',
      '#value' => t('Add field'),
      '#name' => 'add',
    );
    $form['remove'] = array(
      '#type' => 'submit',
      '#value' => t('Remove selected fields'),
      '#name' => 'remove',
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save fields'),
      '#name' => 'save',
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $v = $form_state
      ->getValues();
    if (!$this->feed) {
      return;
    }
    $trigger = $form_state
      ->getTriggeringElement();
    switch ($trigger['#name']) {
      case 'add':
        $field = $v['field_add_method'] ? $v['entity_field'] : $v['manual_field'];
        $field = trim($field);
        $column = NULL;
        if (strpos($field, ':') !== FALSE) {
          list($field, $column) = array_map('trim', explode(':', $field, 2));
        }
        if (!$field) {
          return;
        }
        if ($column) {
          $this->feed->settings['static_fields'][$field][$column] = '';
        }
        else {
          $this->feed->settings['static_fields'][$field] = '';
        }
        break;
      case 'save':
        $fields = array();
        $input = $form_state
          ->getUserInput();
        foreach ($v['fields'] as $f => &$val) {
          $val = isset($input["field|{$f}"]) ? $input["field|{$f}"] : NULL;
          if (strpos($f, ':') === FALSE) {
            $fields[$f] = $val;
          }
          else {
            $f = explode(':', $f, 2);
            $fields[$f[0]][$f[1]] = $val;
          }
        }
        $this->feed->settings['static_fields'] = $fields;
        break;
      case 'remove':
        if (!($fields = array_filter($v['fields']))) {
          return;
        }
        $s =& $this->feed->settings['static_fields'];
        foreach ($fields as $f) {
          if (strpos($f, ':') === FALSE) {
            unset($s[$f]);
          }
          else {
            $f = explode(':', $f, 2);
            unset($s[$f[0]][$f[1]]);
          }
        }
        break;
      default:
        return;
    }

    // Save static fields in feed.
    if (FeedImport::saveFeed($this->feed)) {
      drupal_set_message(t('Feed saved'));
    }
  }

  /**
   * Gets an array containing entity fields
   *
   * @param object $e
   *    Entity info
   *
   * @return array
   *    Array with groupped fields
   */
  protected function getFieldOptions($e) {
    $el = array();

    // Handle properties.
    if ($el = array_combine($e->properties, $e->properties)) {
      $el = array(
        '#' => $el,
      );
    }

    // Handle fields.
    foreach ($e->fields as $f => $val) {
      foreach ($val['columns'] as $col) {
        $el[$f][$col] = $f . ':' . $col;
      }
    }
    return $el;
  }

  /**
   * Returns a row for static fields table.
   *
   * @param string $val
   *    Default field value
   * @param string $name
   *    Field name
   *
   * @return array
   *    A row for table
   */
  protected function getStaticField($val = NULL, $name = NULL) {
    return array(
      'field_name' => Html::escape($name),
      'field_value' => array(
        'data' => array(
          '#type' => 'textfield',
          '#maxlength' => 2048,
          '#value' => $val,
          '#name' => 'field|' . $name,
        ),
      ),
    );
  }

  /**
   * Returns an array for select options group
   *
   * @param array $el
   *    An array of available fields
   *
   * @return array
   *    An array of optgroups.
   *
   * @see getFieldOptions()
   */
  protected function getOptionsGroup(array $el) {
    $opt = array();

    // Handle properties.
    if (isset($el['#'])) {
      $opt[t('Properties')
        ->render()] = $el['#'];
      unset($el['#']);
    }

    // Handle fields.
    foreach ($el as $f => &$val) {
      if ($val) {
        $p = t('Field @name', array(
          '@name' => $f,
        ));
        $opt[$p
          ->render()] = array_flip($val);
      }
    }
    return $opt;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StaticFieldsForm::$feed protected property The feed being edited.
StaticFieldsForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
StaticFieldsForm::getFieldOptions protected function Gets an array containing entity fields
StaticFieldsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
StaticFieldsForm::getOptionsGroup protected function Returns an array for select options group
StaticFieldsForm::getStaticField protected function Returns a row for static fields table.
StaticFieldsForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.