You are here

class FilterForm in Feed Import 8

Hierarchy

Expanded class hierarchy of FilterForm

1 string reference to 'FilterForm'
feed_import.routing.yml in ./feed_import.routing.yml
feed_import.routing.yml

File

src/Form/FilterForm.php, line 15
Contains \Drupal\feed_import\Form\FilterForm

Namespace

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

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

  /**
   * The setting being changed.
   *
   * @var string of the setting name.
   */
  protected $setting;

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $fid = NULL, $setting = NULL) {
    $this->feed = FeedImport::loadFeed($fid);
    $this->setting = $setting;
    $fields = array_keys($this->feed->settings['fields']);
    if (is_null($form_state
      ->get('filter_fields'))) {

      // Save fields to be filtered.
      $form_state
        ->set('filter_fields', $fields);
    }
    $param_field = $this->feed->settings['filter']['options']['param'];
    $help = array();
    $help[0] = t('Filter name') . ': ' . t('A name given by you for this filter.');
    $help[1] = t('Filter function') . ': ' . t('Name of the php function to apply on field value.') . ' ';
    $help[1] .= t('You may also use a static function like this: ClassName::functionName.') . ' ';
    $help[1] .= t('Also check our provided filters in FeedImportFilter class.');
    $help[2] = t('Function params') . ': ' . t('Enter here params (one per line) for php function.') . ' ';
    $help[2] .= t('Enter "@param_field" (without quotes) were you want to be sent field value as parameter.', array(
      '@param_field' => $param_field,
    )) . ' ';
    $help[3] = t('Filtered value is the resulted string of all function calls from top to bottom.');
    $help = implode('<br />', $help);
    $form['help'] = array(
      '#markup' => &$help,
    );
    $v = $form_state
      ->getValues();
    if ($v) {
      foreach ($form_state
        ->get('filter_fields') as $field) {
        $filters = array(
          $field => array(),
        );
        $pos = 0;
        if (!empty($v['table_content'][$field])) {
          foreach ($v['table_content'][$field] as &$filter) {
            $vars = array(
              'name' => $filter['name'],
              'function' => $filter['function'],
              'params' => preg_split('/\\r?\\n/', $filter['params']),
            );
            $filters[$field][$filter['name'] . '-' . $pos] = $this
              ->addNewFilter($pos, $vars);
            $pos++;
          }
        }

        // Add new field.
        if ($form_state
          ->get('filter_action') == 'add' && $form_state
          ->get('action_field') == $field) {
          $vars = array(
            'name' => '',
            'function' => '',
            'params' => array(
              $param_field,
            ),
          );
          $filters[$field][$pos] = $this
            ->addNewFilter($pos, $vars);
        }
        $form['container_' . $field] = $this
          ->addContainer($field, $filters);
      }
    }
    else {
      foreach ($this->feed->settings['fields'] as $field => &$val) {
        $filters = array(
          $field => array(),
        );
        $pos = 0;
        foreach ($val[$this->setting] as $name => &$filter) {
          $vars = array(
            'name' => $name,
            'function' => $filter['function'],
            'params' => $filter['params'],
          );
          $filters[$field][$name] = $this
            ->addNewFilter($pos, $vars);
          $pos++;
        }
        $form['container_' . $field] = $this
          ->addContainer($field, $filters);
      }
    }
    if ($fields) {
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save filters'),
        '#prefix' => t('Your filters will be saved only after you press the button below.') . '<br />',
      );
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if ($form_state
      ->isSubmitted()) {
      return;
    }
    $action_field = NULL;
    $action = NULL;
    $trigger = $form_state
      ->getTriggeringElement();
    if ($trigger && isset($trigger['#action'])) {
      $action_field = $trigger['#field'];
      $action = $trigger['#action'];
    }
    foreach ($form_state
      ->get('filter_fields') as &$field) {
      $table_content = $form_state
        ->getValue('table_content');

      // Delete selected.
      if ($action == 'delete' && $field == $action_field) {
        foreach ($table_content[$field] as $key => &$filter) {
          if ($filter['selected']) {
            unset($table_content[$field][$key]);
          }
        }
      }
      if (!empty($table_content[$field])) {

        // Set filters order.
        usort($table_content[$field], array(
          'Drupal\\Component\\Utility\\SortArray',
          'sortByWeightElement',
        ));
      }
    }
    $form_state
      ->setValue('table_content', $table_content);
    $form_state
      ->set('action_field', $action_field);
    $form_state
      ->set('filter_action', $action);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    if (!$this->feed) {
      return;
    }
    foreach ($this->feed->settings['fields'] as $field => &$item) {
      $item[$this->setting] = array();
      if (!empty($values['table_content'][$field])) {
        usort($values['table_content'][$field], array(
          'Drupal\\Component\\Utility\\SortArray',
          'sortByWeightElement',
        ));
        foreach ($values['table_content'][$field] as &$filter) {
          if (!$filter['name'] || !$filter['function']) {
            continue;
          }
          if (!$filter['params']) {
            $filter['params'] = array();
          }
          else {
            $filter['params'] = preg_split('/\\r?\\n/', $filter['params']);
          }
          $item[$this->setting][$filter['name']] = array(
            'function' => trim($filter['function']),
            'params' => $filter['params'],
          );
          $filter = NULL;
        }
      }
    }

    // Save feed.
    if (FeedImport::saveFeed($this->feed)) {
      $vars = array(
        '@filter' => $this->setting == 'filters' ? t('Filters') : t('Pre-filters'),
        '@name' => $this->feed->name,
      );
      drupal_set_message(t('@filter saved for @name', $vars));
    }
  }

  /**
   * Return new filter elements
   *
   * @param int $pos
   *   Filter position
   * @param array $values
   *   Default filter values
   *
   *  @return array
   *    Array containing filter html forms
   */
  protected function addNewFilter($pos = 0, $values = NULL) {
    $values['params'] = isset($values['params']) ? $values['params'] : '';
    if (is_array($values['params'])) {
      $values['params'] = implode(PHP_EOL, $values['params']);
    }
    return array(
      '#attributes' => array(
        'class' => array(
          'draggable',
        ),
      ),
      '#weight' => $pos,
      'name' => array(
        '#type' => 'textfield',
        '#size' => 30,
        '#default_value' => isset($values['name']) ? $values['name'] : '',
      ),
      'function' => array(
        '#type' => 'textfield',
        '#size' => 30,
        '#default_value' => isset($values['function']) ? $values['function'] : '',
      ),
      'params' => array(
        '#type' => 'textarea',
        '#default_value' => $values['params'],
        '#rows' => 2,
        '#cols' => 30,
      ),
      'selected' => array(
        '#type' => 'checkbox',
        '#default_value' => 0,
      ),
      'weight' => array(
        '#type' => 'weight',
        '#title' => t('Weight for @title', array(
          '@title' => $values['name'],
        )),
        '#title_display' => 'invisible',
        '#default_value' => $pos,
        '#attributes' => array(
          'class' => array(
            'reorder-table-weight',
          ),
        ),
      ),
    );
  }

  /**
   * Add filter button actions: add new, remove all
   *
   * @param string $field
   *   Field name
   *
   * @return array
   *   Array with buttons
   */
  protected function addFilterActions($field) {
    return array(
      'add_new_filter_' . $field => array(
        '#type' => 'button',
        '#value' => t('Add new filter to @field', array(
          '@field' => Unicode::strtoupper($field),
        )),
        '#action' => 'add',
        '#field' => $field,
      ),
      'delete_selected_filters_' . $field => array(
        '#type' => 'button',
        '#value' => t('Remove selected from @field', array(
          '@field' => Unicode::strtoupper($field),
        )),
        '#action' => 'delete',
        '#field' => $field,
      ),
    );
  }

  /**
   * Add fieldset for a field's filters.
   *
   * @param string $field
   *   Field name
   * @param array $filters
   *   Filter options
   *
   * @return array
   *   Array containing a draggable set of filter fields
   */
  protected function addContainer($field, $filters) {
    return array(
      '#type' => 'fieldset',
      '#title' => Html::escape($field),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      'table_content' => array(
        '#tree' => TRUE,
        $field => array(
          '#type' => 'table',
          '#tree' => TRUE,
          '#header' => array(
            t('Filter name'),
            t('Filter function'),
            t('Function params (one per line)'),
            t('Select'),
            t('Weight'),
          ),
          '#empty' => t('No filters have been added'),
          '#tabledrag' => array(
            array(
              'action' => 'order',
              'relationship' => 'sibling',
              'group' => 'reorder-table-weight',
            ),
          ),
        ) + $filters[$field],
      ),
      'actions' => $this
        ->addFilterActions($field),
    );
  }

}

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
FilterForm::$feed protected property The feed being edited.
FilterForm::$setting protected property The setting being changed.
FilterForm::addContainer protected function Add fieldset for a field's filters.
FilterForm::addFilterActions protected function Add filter button actions: add new, remove all
FilterForm::addNewFilter protected function Return new filter elements
FilterForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
FilterForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
FilterForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
FilterForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
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.
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.
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.