You are here

class ProjectListForm in Optimizely 8.0

Same name and namespace in other branches
  1. 8 src/ProjectListForm.php \Drupal\optimizely\ProjectListForm

Implements the form for the Projects Listing. The term "form" is used loosely here.

Hierarchy

Expanded class hierarchy of ProjectListForm

1 string reference to 'ProjectListForm'
optimizely.routing.yml in ./optimizely.routing.yml
optimizely.routing.yml

File

src/ProjectListForm.php, line 19
Contains \Drupal\optimizely\ProjectListForm

Namespace

Drupal\optimizely
View source
class ProjectListForm extends FormBase {
  use LookupPath;

  /**
   * {@inheritdoc}
   */
  public function getFormID() {
    return 'optimizely-project-listing';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = array();

    // Load css and js files specific to optimizely admin pages
    $form['#attached']['library'][] = 'optimizely/optimizely.forms';
    $form['#attached']['library'][] = 'optimizely/optimizely.enable';
    $prefix = '<ul class="admin-links"><li>';
    $prefix .= \Drupal::l(t('Add Project Entry'), new Url('optimizely.add_update'));
    $prefix .= '</li></ul>';
    $header = array(
      t('Enabled'),
      t('Project Title'),
      t('Update / Delete'),
      t('Paths'),
      t('Project Code'),
    );
    $form['projects'] = array(
      '#prefix' => $prefix . '<div id="optimizely-project-listing">',
      '#suffix' => '</div>',
      '#tree' => TRUE,
      '#theme' => 'table',
      '#header' => $header,
    );
    $rows_rend = array();

    // Lookup account ID setting to trigger "nag message".
    $account_id = AccountId::getId();

    // Begin building the query.
    $query = db_select('optimizely', 'o', array(
      'target' => 'slave',
    ))
      ->orderBy('oid')
      ->fields('o');
    $result = $query
      ->execute();

    // Build each row of the table
    foreach ($result as $project_count => $row) {

      // Listing of target paths for the project entry
      $paths = unserialize($row->path);

      // Modify the front page path, if present.
      $front_idx = array_search('<front>', $paths);
      if ($front_idx !== FALSE) {
        $config = \Drupal::config('system.site');
        $front_path = $config
          ->get('page.front');
        $front_path .= ' <-> ';
        $path_alias = $this
          ->lookupPathAlias($front_path);
        $front_path .= $path_alias ? $path_alias : '';
        $paths[$front_idx] = '<front>' . ' (' . $front_path . ')';
      }

      // Build form elements including enable checkbox and data columns
      $form['projects'][$project_count]['enable'] = array(
        '#type' => 'checkbox',
        '#attributes' => array(
          'id' => 'project-enable-' . $row->oid,
          'name' => 'project-' . $row->oid,
        ),
        '#default_value' => $row->enabled,
        '#extra_data' => array(
          'field_name' => 'project_enabled',
        ),
        '#suffix' => '<div class="status-container status-' . $row->oid . '"></div>',
      );
      if ($row->enabled) {
        $form['projects'][$project_count]['enable']['#attributes']['checked'] = 'checked';
      }

      // Build the Edit / Delete links
      // User may not delete the Default project.
      if ($row->oid == 1) {
        $render_links = array(
          '#type' => 'inline_template',
          '#template' => '<a href="{{ update_url }}">{{ update }}</a> / Default Entry',
          '#context' => array(
            'update' => t('Update'),
            'update_url' => \Drupal::url('optimizely.add_update.oid', array(
              'oid' => $row->oid,
            )),
          ),
        );
      }
      else {
        $render_links = array(
          '#type' => 'inline_template',
          '#template' => '<a href="{{ update_url }}">{{ update }}</a> / ' . '<a href="{{ delete_url }}">{{ delete }}</a>',
          '#context' => array(
            'update' => t('Update'),
            'delete' => t('Delete'),
            'update_url' => \Drupal::url('optimizely.add_update.oid', array(
              'oid' => $row->oid,
            )),
            'delete_url' => \Drupal::url('optimizely.delete.oid', array(
              'oid' => $row->oid,
            )),
          ),
        );
      }
      $render_paths = array(
        '#type' => 'inline_template',
        '#template' => '<ul>' . '{% for p in paths %}<li>{{ p }}</li>{% endfor %}' . '</ul>',
        '#context' => array(
          'paths' => $paths,
        ),
      );
      $form['projects'][$project_count]['#project_title'] = $row->project_title;
      $form['projects'][$project_count]['#admin_links'] = $render_links;
      $form['projects'][$project_count]['#paths'] = $render_paths;
      if ($account_id == 0 && $row->oid == 1) {

        // Calling the t() function will cause the embedded html
        // markup to be treated correctly as markup, not literal content.
        $project_code = t('Set Optimizely ID in <strong><a href="@url">@acct_info</a>' . '</strong> page to enable default project sitewide.', array(
          '@url' => \Drupal::url('optimizely.settings'),
          '@acct_info' => t('Account Info'),
        ));
      }
      else {
        $project_code = $row->project_code;
      }
      $form['projects'][$project_count]['#project_code'] = $project_code;
      $form['projects'][$project_count]['#oid'] = $row->oid;
      $rows_rend[] = $this
        ->_optimizely_project_row($form['projects'][$project_count]);
    }

    // Add all the rows to the render array.
    $form['projects']['#rows'] = $rows_rend;
    return $form;
  }

  /**
   * Build render array for one row of the table of projects.
   */
  private function _optimizely_project_row($proj) {
    $enabled = array_key_exists('checked', $proj['enable']['#attributes']) ? TRUE : FALSE;
    $render = array(
      'class' => array(
        'project-row-' . $proj['#project_code'],
      ),
      'id' => array(
        'project-' . $proj['#oid'],
      ),
      'data' => array(
        array(
          'class' => $enabled ? 'enable-column enabled' : 'enable-column disabled',
          'data' => $proj['enable'],
        ),
        array(
          'class' => $enabled ? 'project-title-column enabled' : 'project-title-column disabled',
          // 'data' => render($proj['#project_title']),
          'data' => $proj['#project_title'],
        ),
        array(
          'class' => $enabled ? 'admin-links-column enabled' : 'admin-links-column disabled',
          'data' => $proj['#admin_links'],
        ),
        array(
          'class' => $enabled ? 'paths-column enabled' : 'paths-column disabled',
          'data' => $proj['#paths'],
        ),
        array(
          'class' => $enabled ? 'project-code-column enabled' : 'project-code-column disabled',
          'data' => $proj['#project_code'],
        ),
      ),
    );
    return $render;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // Not used.
    return;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Not used.
    return;
  }

}

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.
FormInterface::getFormId public function Returns a unique string identifying the form. 236
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.
LookupPath::checkPath static function Ensure that $path starts with a forward slash because the alias_manager requires it.
LookupPath::lookupPathAlias static function Helper function to lookup a path alias, given a path. This function acts as an adapter and passes back a return value like those of drupal_lookup_path(), which has been removed as of Drupal 8.
LookupPath::lookupSystemPath static function Helper function to lookup a system path, given a path alias. This function acts as an adapter and passes back a return value like those of drupal_lookup_path(), which has been removed as of Drupal 8.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
ProjectListForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ProjectListForm::getFormID public function
ProjectListForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ProjectListForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ProjectListForm::_optimizely_project_row private function Build render array for one row of the table of projects.
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.