You are here

StaticFieldsForm.php in Feed Import 8

File

src/Form/StaticFieldsForm.php
View source
<?php

/**
 * @file
 * Contains \Drupal\feed_import\Form\StaticFieldsForm
 */
namespace Drupal\feed_import\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\feed_import_base\FeedImport;
use Drupal\Component\Utility\Html;
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;
  }

}

Classes

Namesort descending Description
StaticFieldsForm