You are here

class HeartbeatTypeForm in Heartbeat 8

Class HeartbeatTypeForm.

@property \Drupal\Component\Render\MarkupInterface|string tokenTree @package Drupal\heartbeat\Form

Hierarchy

Expanded class hierarchy of HeartbeatTypeForm

File

src/Form/HeartbeatTypeForm.php, line 22

Namespace

Drupal\heartbeat\Form
View source
class HeartbeatTypeForm extends EntityForm {
  protected $treeBuilder;
  protected $renderer;
  private $tokenTree;
  protected $entityTypeManager;
  protected $entityTypes;
  private $treeAdded = false;
  private $messageMap = array();

  /**
   * {@inheritdoc}
   * @throws \Exception
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('token.tree_builder'), $container
      ->get('renderer'), $container
      ->get('entity_type.manager'));
  }

  /**
   * PHP 5 allows developers to declare constructor methods for classes.
   * Classes which have a constructor method call this method on each newly-created object,
   * so it is suitable for any initialization that the object may need before it is used.
   *
   * Note: Parent constructors are not called implicitly if the child class defines a constructor.
   * In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.
   *
   * param [ mixed $args [, $... ]]
   * @param TreeBuilder $tree_builder
   * @param Renderer $renderer
   * @throws \Exception
   */
  public function __construct(TreeBuilder $tree_builder, Renderer $renderer, EntityTypeManager $entityTypeManager) {
    $this->treeBuilder = $tree_builder;
    $this->renderer = $renderer;
    $this->entityTypeManager = $entityTypeManager;
    $this->tokenTree = $this->renderer
      ->render($this->treeBuilder
      ->buildAllRenderable([
      'click_insert' => TRUE,
      'show_restricted' => TRUE,
      'show_nested' => FALSE,
    ]));
  }
  public function buildForm(array $form, FormStateInterface $form_state) {
    $this->entityTypes = Entity\Heartbeat::getEntityNames($this->entityTypeManager
      ->getDefinitions());
    $doStuff = 'stuff';
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form_state
      ->setCached(FALSE);
    $heartbeat_type = $this->entity;
    $form['#tree'] = TRUE;
    $form['#attached']['library'] = 'heartbeat/treeTable';
    $form['label'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#maxlength' => 255,
      '#default_value' => $heartbeat_type
        ->label(),
      '#description' => $this
        ->t("Label for the Heartbeat Type."),
      '#required' => TRUE,
    );
    $form['description'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('description'),
      '#maxlength' => 255,
      '#default_value' => $heartbeat_type
        ->getDescription(),
      '#description' => $this
        ->t("Description of the Heartbeat Type"),
      '#required' => TRUE,
    );

    //TODO Select is nested, thus any returned value seems to be read as "true", which results in the first item within the nest being chosen as the value populating the form's field. This will need to be fixed to prevent wrongly changing one's values without thinking about it.
    $form['entity_type'] = array(
      '#type' => 'select',
      '#title' => $this
        ->t('Entity Type'),
      //      '#default_value' => $heartbeat_type->getMainEntity(),
      '#description' => $this
        ->t("Primary Entity Type for this Heartbeat Type"),
      '#options' => array(
        $this->entityTypes,
      ),
      '#required' => TRUE,
    );
    $bundles = $form_state
      ->get('entity_bundles');
    $form['entity_bundles'] = array(
      '#type' => 'container',
      '#prefix' => '<div id="entity-bundles">',
      '#suffix' => '</div>',
    );
    $form['entity_bundles']['getBundles'] = [
      '#type' => 'submit',
      '#value' => t('Getting bundles'),
      '#submit' => array(
        '::getBundlesForEntity',
      ),
      '#ajax' => [
        'callback' => '::getBundlesForEntity',
        'wrapper' => 'entity-bundles',
        'progress' => array(
          'type' => 'throbber',
          'message' => t('Getting bundles'),
        ),
      ],
    ];
    $form['entity_bundles']['list'] = array(
      '#type' => 'select',
      '#title' => $this
        ->t('Entity Bundles'),
      '#default_value' => $heartbeat_type
        ->getBundle(),
      '#description' => $this
        ->t("Any bundles available to the specified entity"),
      '#options' => $bundles,
    );
    $form['message'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('message'),
      '#maxlength' => 255,
      '#default_value' => $heartbeat_type
        ->getMessage(),
      '#description' => $this
        ->t("The structure for messages of this type. Use !exclamation marks before fields and entities"),
      '#required' => TRUE,
    );

    //    $form['message_concat'] = array(
    //      '#type' => 'textfield',
    //      '#title' => $this->t('Message structure in concatenated form'),
    //      '#maxlength' => 255,
    //      '#default_value' => $heartbeat_type->getMessageConcat(),
    //      '#description' => $this->t("The structure for messages of this type. Use !exclamation marks before fields and entities"),
    //      '#required' => FALSE,
    //    );
    $form['perms'] = array(
      '#type' => 'select',
      '#title' => $this
        ->t('Permissions'),
      '#default_value' => $heartbeat_type
        ->getPerms(),
      '#description' => $this
        ->t("Default permissions to view Heartbeats of this type"),
      '#options' => array(
        Entity\HEARTBEAT_NONE => 'None',
        Entity\HEARTBEAT_PRIVATE => 'Private',
        Entity\HEARTBEAT_PUBLIC_TO_ADDRESSEE => 'Public to Addressee',
        Entity\HEARTBEAT_PUBLIC_TO_CONNECTED => 'Public to Connected',
        Entity\HEARTBEAT_PUBLIC_TO_ALL => 'Public to All',
      ),
      '#required' => TRUE,
    );
    $form['group_type'] = array(
      '#type' => 'select',
      '#title' => $this
        ->t('Group Type'),
      '#default_value' => 0,
      '#description' => $this
        ->t("Type of group associated with Heartbeats of this type"),
      '#options' => array(
        Entity\HEARTBEAT_GROUP_NONE => 'None',
        Entity\HEARTBEAT_GROUP_SINGLE => 'Single',
        Entity\HEARTBEAT_GROUP_SUMMARY => 'Group',
      ),
      '#required' => TRUE,
    );
    $form['variables'] = array(
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Variables to map'),
      '#prefix' => '<div id="Variables-fieldset-wrapper">',
      '#suffix' => '</div>',
    );
    $messageArguments = $form_state
      ->get('data_hidden');
    if ($messageArguments === NULL) {
      $messageArguments = $this
        ->extractMessageArguments($heartbeat_type
        ->getMessage());
    }
    $argNum = count($messageArguments);
    for ($i = 0; $i < $argNum; $i++) {
      if (is_array($messageArguments) && $messageArguments[$i] != null) {
        $variableValue = isset($heartbeat_type
          ->getVariables()[$i]) && !empty($heartbeat_type
          ->getVariables()[$i]) ? $heartbeat_type
          ->getVariables()[$i] : '';
        $form['variables'][$i] = array(
          '#type' => 'textfield',
          '#title' => t($messageArguments[$i]),
          '#description' => t('Map value to this variable'),
          '#default_value' => $variableValue,
        );
      }
    }
    $form['variables']['rebuildArgs'] = [
      '#type' => 'submit',
      '#value' => t('Rebuild Arguments'),
      '#submit' => array(
        '::rebuildMessageArguments',
      ),
      '#ajax' => [
        'callback' => '::rebuildMessageArguments',
        'wrapper' => 'Variables-fieldset-wrapper',
      ],
    ];
    $form['tokens'] = array(
      '#prefix' => '<div id="token-tree"></div>',
      '#markup' => $this->tokenTree,
    );
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $heartbeat_type
        ->id(),
      '#machine_name' => [
        'exists' => '\\Drupal\\heartbeat\\Entity\\HeartbeatType::load',
      ],
      '#disabled' => !$heartbeat_type
        ->isNew(),
    ];
    $form_state
      ->setCached(FALSE);
    return parent::form($form, $form_state, $heartbeat_type);
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $heartbeat_type = $this->entity;
    $heartbeat_type
      ->set('description', $form_state
      ->getValue('description'));
    $heartbeat_type
      ->set('message', $form_state
      ->getValue('message'));
    $heartbeat_type
      ->set('perms', $form_state
      ->getValue('perms'));
    $heartbeat_type
      ->set('variables', $form_state
      ->getValue('variables'));
    $heartbeat_type
      ->set('arguments', json_encode($form_state
      ->get('messageMap')));
    $heartbeat_type
      ->set('mainentity', $this->entityTypes[$form_state
      ->getValue('entity_type')]);
    $heartbeat_type
      ->set('bundle', $form_state
      ->get('entity_bundles')[$form_state
      ->getValue('entity_bundles')['list']]);
    $status = $heartbeat_type
      ->save();
    switch ($status) {
      case SAVED_NEW:
        drupal_set_message($this
          ->t('Created the %label Heartbeat type.', [
          '%label' => $heartbeat_type
            ->label(),
        ]));
        break;
      default:
        drupal_set_message($this
          ->t('Saved the %label Heartbeat type.', [
          '%label' => $heartbeat_type
            ->label(),
        ]));
    }
    $form_state
      ->setRedirectUrl($heartbeat_type
      ->toUrl('collection'));
  }

  /**
   * Custom form validation to rebuild
   * Form field for mapping Message Arguments
   */
  public function rebuildMessageArguments(array &$form, FormStateInterface $form_state) {
    $messageArgString = $form_state
      ->getValue('message');
    if ($form_state != NULL) {
      $argsArray = $this
        ->extractMessageArguments($messageArgString, $form_state);
      foreach ($argsArray as $key => $arg) {
        $this->messageMap[$key] = '!' . $arg;
      }
      $form_state
        ->set('messageMapKey', $this->messageMap);
      $form_state
        ->set('data_hidden', $argsArray);
      $form_state
        ->setRebuild();
      return $form['variables'];
    }
    else {
      return NULL;
    }
  }
  public function prepareVariables(&$form, FormStateInterface $form_state) {
    return $form['variables'];
  }
  private function extractMessageArguments($message) {

    //TODO find solution for trailing exclamation marks being wrongly interpreted

    //ie parse each word in string and reconstruct string prior to exploding it on

    //exclamation marks again
    $messageArguments = array_slice(explode('!', $message), 1);
    $argsArray = array();
    foreach ($messageArguments as $argument) {
      if (strlen($argument) > 0) {
        $cleanArgument = strpos($argument, ' ') ? substr($argument, 0, strpos($argument, ' ')) : $argument;
        $argsArray[] = $cleanArgument;
        $this->messageMap[] = '!' . $cleanArgument;
      }
    }
    return $argsArray;
  }
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $messageMapKeysget = $form_state
      ->get('messageMapKey');
    if ($variables = $form_state
      ->getValue('variables')) {
      $num = count($variables);
      for ($i = 0; $i < $num; $i++) {
        if (!is_string($variables[$i])) {
          continue;
        }
        $this->messageMap[$messageMapKeysget[$i]] = $variables[$i];
      }
      $form_state
        ->set('messageMap', $this->messageMap);
      parent::submitForm($form, $form_state);
    }
  }

  /**
   * Custom form validation to rebuild
   * Form field for mapping Message Arguments
   */
  public function getBundlesForEntity(array &$form, FormStateInterface $form_state) {
    $entityType = $this->entityTypes[$form_state
      ->getValue('entity_type')];
    $entity = $this->entityTypeManager
      ->getStorage($entityType);
    $bundleTypeName = $entity
      ->getEntityType()
      ->getBundleEntityType();
    $bundles = $this->entityTypeManager
      ->getStorage($bundleTypeName)
      ->loadMultiple();
    $bundleNames = array();
    foreach ($bundles as $bundle) {
      $bundleNames[] = $bundle
        ->id();
    }
    $form_state
      ->set('entity_bundles', $bundleNames);

    //    $form['entity_bundles']['#options'] = array($bundleNames);
    $form_state
      ->setRebuild();
    return $form['entity_bundles'];
  }
  public function tokenSelectDialog(array &$form, FormStateInterface $form_state) {

    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();

    // Add a command to execute on form, jQuery .html() replaces content between tags.
    // In this case, we replace the description with whether the username was found or not.
    //    $ajax_response->addCommand(new HtmlCommand('#token-tree', $output));
    // CssCommand did not work.

    //$ajax_response->addCommand(new CssCommand('#edit-user-name--description', array('color', $color)));

    //    $color = 'pink';
    // Add a command, InvokeCommand, which allows for custom jQuery commands.
    // In this case, we alter the color of the description.
    $ajax_response
      ->addCommand(new InvokeCommand('.token-tree', 'css', array(
      'display',
      'block',
    )));
    $this->treeAdded = TRUE;

    // Return the AjaxResponse Object.
    return $ajax_response;
  }
  public function getBundlesAlternate(array &$form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();
    $AddChartForm = \Drupal::formBuilder()
      ->getForm('Drupal\\heartbeat\\Form\\HeartbeatTypeForm');
    $ajax_response
      ->addCommand(new HtmlCommand('#formarea', $AddChartForm));
  }

}

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
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
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::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
HeartbeatTypeForm::$entityTypeManager protected property The entity type manager. Overrides EntityForm::$entityTypeManager
HeartbeatTypeForm::$entityTypes protected property
HeartbeatTypeForm::$messageMap private property
HeartbeatTypeForm::$renderer protected property
HeartbeatTypeForm::$tokenTree private property
HeartbeatTypeForm::$treeAdded private property
HeartbeatTypeForm::$treeBuilder protected property
HeartbeatTypeForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
HeartbeatTypeForm::create public static function Overrides FormBase::create
HeartbeatTypeForm::extractMessageArguments private function
HeartbeatTypeForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
HeartbeatTypeForm::getBundlesAlternate public function
HeartbeatTypeForm::getBundlesForEntity public function Custom form validation to rebuild Form field for mapping Message Arguments
HeartbeatTypeForm::prepareVariables public function
HeartbeatTypeForm::rebuildMessageArguments public function Custom form validation to rebuild Form field for mapping Message Arguments
HeartbeatTypeForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
HeartbeatTypeForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm
HeartbeatTypeForm::tokenSelectDialog public function
HeartbeatTypeForm::__construct public function PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
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.