You are here

FlagForListForm.php in Flag Lists 8

Same filename and directory in other branches
  1. 4.0.x src/Form/FlagForListForm.php

File

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

namespace Drupal\flag_lists\Form;

use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;

/**
 * Class FlagForListForm.
 */
class FlagForListForm extends EntityForm {

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

    /* You will need additional form elements for your custom properties. */
    $form = parent::form($form, $form_state);
    $flagService = \Drupal::service('flaglists');
    $account = \Drupal::currentUser();
    $entity = $this->entity;
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Template name'),
      '#maxlength' => 255,
      '#default_value' => $entity
        ->label(),
      '#description' => $this
        ->t("Template name for the Flag for list."),
      '#required' => TRUE,
      '#weight' => -3,
    ];
    $existing_flags = $flagService
      ->getAllFlagForList(NULL, NULL);
    $options = [];
    foreach ($existing_flags as $flag) {
      if ($flag
        ->hasBaseFlag()) {
        $options[$flag
          ->get('id')] = $flag
          ->label();
      }
    }
    $form['base_flag'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Template flag'),
      '#required' => TRUE,
      '#default_value' => $entity
        ->getBaseFlag(),
      '#options' => $options,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $flag_for_list = $this->entity;
    $is_new = !$flag_for_list
      ->getOriginalId();
    $flag_for_list
      ->setOwner();
    if ($is_new) {

      // Configuration entities need an ID manually set.
      $machine_name = \Drupal::transliteration()
        ->transliterate($flag_for_list
        ->label(), LanguageInterface::LANGCODE_DEFAULT, '_');
      $flag_for_list
        ->set('id', mb_strtolower($machine_name));
      $flag_for_list
        ->set('weight', '0');
      $this
        ->messenger()
        ->addMessage(t('The %label flag list has been created.', [
        '%label' => $flag_for_list
          ->label(),
      ]));
    }
    else {
      $this
        ->messenger()
        ->addMessage(t('Updated the %label flag list.', [
        '%label' => $flag_for_list
          ->label(),
      ]));
    }
    $flag_for_list
      ->save();

    // Redirect to edit form so we can populated colors.
    $form_state
      ->setRedirectUrl($flag_for_list
      ->toUrl('collection'));
  }

}

Classes

Namesort descending Description
FlagForListForm Class FlagForListForm.