You are here

class BrightcoveVideoForm in Brightcove Video Connect 8

Same name and namespace in other branches
  1. 8.2 src/Form/BrightcoveVideoForm.php \Drupal\brightcove\Form\BrightcoveVideoForm
  2. 3.x src/Form/BrightcoveVideoForm.php \Drupal\brightcove\Form\BrightcoveVideoForm

Form controller for Brightcove Video edit forms.

Hierarchy

Expanded class hierarchy of BrightcoveVideoForm

File

src/Form/BrightcoveVideoForm.php, line 17

Namespace

Drupal\brightcove\Form
View source
class BrightcoveVideoForm extends BrightcoveVideoPlaylistForm {

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $form['#attached']['library'][] = 'brightcove/brightcove.video';

    /* @var $entity \Drupal\brightcove\Entity\BrightcoveVideo */
    $entity = $this->entity;

    // Get api client from the form settings.
    if (!empty($form_state
      ->getValue('api_client'))) {
      $api_client = $form_state
        ->getValue('api_client')[0]['target_id'];
    }
    else {
      $api_client = $form['api_client']['widget']['#default_value'];
    }

    // Remove _none value to make sure the first item is selected.
    if (isset($form['profile']['widget']['#options']['_none'])) {
      unset($form['profile']['widget']['#options']['_none']);
    }

    // Get the correct profiles' list for the selected api client.
    if ($entity
      ->isNew()) {

      // Class this class's update form method instead of the supper class's.
      $form['api_client']['widget']['#ajax']['callback'] = [
        self::class,
        'apiClientUpdateForm',
      ];

      // Add ajax wrapper for profile.
      $form['profile']['widget']['#ajax_id'] = 'ajax-profile-wrapper';
      $form['profile']['widget']['#prefix'] = '<div id="' . $form['profile']['widget']['#ajax_id'] . '">';
      $form['profile']['widget']['#suffix'] = '</div>';

      // Update allowed values for profile.
      $form['profile']['widget']['#options'] = BrightcoveVideo::getProfileAllowedValues($api_client);
    }

    // Set default profile.
    if (!$form['profile']['widget']['#default_value']) {
      $profile_keys = array_keys($form['profile']['widget']['#options']);
      $form['profile']['widget']['#default_value'] = reset($profile_keys);
    }

    // Add pseudo title for status field.
    $form['status']['pseudo_title'] = [
      '#markup' => $this
        ->t('Status'),
      '#prefix' => '<div id="status-pseudo-title">',
      '#suffix' => '</div>',
      '#weight' => -100,
    ];
    $upload_type = [
      '#type' => 'select',
      '#title' => $this
        ->t('Upload type'),
      '#options' => [
        'file' => $this
          ->t('File'),
        'url' => $this
          ->t('URL'),
      ],
      '#default_value' => !empty($form['video_url']['widget'][0]['value']['#default_value']) ? 'url' : 'file',
      '#weight' => -100,
    ];
    $form['video_file']['#states'] = [
      'visible' => [
        'select[name="upload_type"]' => [
          'value' => 'file',
        ],
      ],
    ];
    $form['video_url']['#states'] = [
      'visible' => [
        'select[name="upload_type"]' => [
          'value' => 'url',
        ],
      ],
    ];

    // Group video fields together.
    $form['video'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Video'),
      '#weight' => $form['economics']['#weight'] += 0.001,
      'upload_type' => &$upload_type,
      'video_file' => $form['video_file'],
      'video_url' => $form['video_url'],
      'profile' => $form['profile'],
    ];
    unset($form['video_file']);
    unset($form['video_url']);
    unset($form['profile']);

    // Group image fields together.
    $form['images'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Images'),
      '#weight' => $form['video']['#weight'] += 0.001,
      '#description' => $this
        ->t('For best results, use JPG or PNG format with a minimum width of 640px for video stills and 160px for thumbnails. Aspect ratios should match the video, generally 16:9 or 4:3. <a href=":link" target="_blank">Read More</a>', [
        ':link' => 'https://support.brightcove.com/en/video-cloud/docs/uploading-video-still-and-thumbnail-images',
      ]),
      'poster' => $form['poster'],
      'thumbnail' => $form['thumbnail'],
    ];
    unset($form['poster']);
    unset($form['thumbnail']);

    // Group scheduling fields together.
    $form['availability'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Availability'),
      '#weight' => $form['images']['#weight'] += 0.001,
      'schedule_starts_at' => $form['schedule_starts_at'],
      'schedule_ends_at' => $form['schedule_ends_at'],
    ];
    unset($form['schedule_starts_at']);
    unset($form['schedule_ends_at']);

    /** @var \Drupal\brightcove\Entity\BrightcoveCustomField[] $custom_fields */
    $custom_fields = BrightcoveCustomField::loadMultipleByApiClient($api_client);

    // Add ajax wrapper for custom fields.
    if ($entity
      ->isNew()) {
      $form['custom_fields']['#ajax_id'] = 'ajax-custom-fields-wrapper';
      $form['custom_fields']['#prefix'] = '<div id="' . $form['custom_fields']['#ajax_id'] . '">';
      $form['custom_fields']['#suffix'] = '</div>';
    }

    // Show custom fields.
    if (count($custom_fields) > 0) {
      $form['custom_fields']['#type'] = 'details';
      $form['custom_fields']['#title'] = $this
        ->t('Custom fields');
      $form['custom_fields']['#weight'] = $form['availability']['#weight'] += 0.001;
      $has_required = FALSE;
      $custom_field_values = $entity
        ->getCustomFieldValues();
      foreach ($custom_fields as $custom_field) {

        // Indicate whether that the custom fields has required field(s) or
        // not.
        if (!$has_required && $custom_field
          ->isRequired()) {
          $has_required = TRUE;
        }
        switch ($custom_field_type = $custom_field
          ->getType()) {
          case $custom_field::TYPE_STRING:
            $type = 'textfield';
            break;
          case $custom_field::TYPE_ENUM:
            $type = 'select';
            break;
          default:
            continue 2;
        }

        // Assemble form field for the custom field.
        $custom_field_id = $custom_field
          ->getCustomFieldId();
        $custom_field_name = "custom_field_{$custom_field_id}";
        $form['custom_fields'][$custom_field_name] = [
          '#type' => $type,
          '#title' => $custom_field
            ->getName(),
          '#description' => $custom_field
            ->getDescription(),
          '#required' => $custom_field
            ->isRequired(),
        ];

        // Set custom field value if it is set.
        if (isset($custom_field_values[$custom_field_id])) {
          $form['custom_fields'][$custom_field_name]['#default_value'] = $custom_field_values[$custom_field_id];
        }

        // Add options for enum types.
        if ($custom_field_type == $custom_field::TYPE_ENUM) {
          $options = [];

          // Add none option if the field is not required.
          if (!$form['custom_fields'][$custom_field_name]['#required']) {
            $options[''] = $this
              ->t('- None -');
          }
          foreach ($custom_field
            ->getEnumValues() as $enum) {
            $options[$enum['value']] = $enum['value'];
          }
          $form['custom_fields'][$custom_field_name]['#options'] = $options;
        }
      }

      // Show custom field group opened if it has at least one required field.
      if ($has_required) {
        $form['custom_fields']['#open'] = TRUE;
      }
    }
    $form['text_tracks']['widget']['actions']['ief_add']['#value'] = $this
      ->t('Add Text Track');
    return $form;
  }

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

    /* @var $entity \Drupal\brightcove\Entity\BrightcoveVideo */
    $entity = $this->entity;
    switch ($form_state
      ->getValue('upload_type')) {
      case 'file':
        if ($entity
          ->isNew() || !empty($form_state
          ->getValue('video_file')[0]['fids'])) {
          $form_state
            ->unsetValue('video_url');
          $entity
            ->setVideoUrl(NULL);
        }
        break;
      case 'url':
        if ($entity
          ->isNew()) {
          $form_state
            ->unsetValue('video_file');
        }
        elseif (!empty($form_state
          ->getValue('video_url')[0]['value'])) {
          $form_state
            ->unsetValue('video_file');
          $entity
            ->setVideoFile(NULL);
        }
        break;
    }
  }

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

    /* @var $entity \Drupal\brightcove\Entity\BrightcoveVideo */
    $entity = $this->entity;
    try {

      // Save custom field values.
      $custom_field_values = [];
      if (!empty($form['custom_fields'])) {
        foreach (Element::children($form['custom_fields']) as $field_name) {
          if (preg_match('/^custom_field_(.+)$/i', $field_name, $matches) === 1) {
            $custom_field_values[$matches[1]] = $form_state
              ->getValue($field_name);
          }
        }
        $entity
          ->setCustomFieldValues($custom_field_values);
      }
      $status = $entity
        ->save(TRUE);
      switch ($status) {
        case SAVED_NEW:
          drupal_set_message($this
            ->t('Created the %label Brightcove Video.', [
            '%label' => $entity
              ->label(),
          ]));
          break;
        default:
          drupal_set_message($this
            ->t('Saved the %label Brightcove Video.', [
            '%label' => $entity
              ->label(),
          ]));
      }
      $form_state
        ->setRedirect('entity.brightcove_video.canonical', [
        'brightcove_video' => $entity
          ->id(),
      ]);
    } catch (APIException $e) {
      drupal_set_message($e
        ->getMessage(), 'error');
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function apiClientUpdateForm(array $form, FormStateInterface $form_state) {
    $response = parent::apiClientUpdateForm($form, $form_state);

    // Update profile field.
    $response
      ->addCommand(new ReplaceCommand('#' . $form['profile']['widget']['#ajax_id'], $form['profile']));

    // Update custom fields.
    $response
      ->addCommand(new ReplaceCommand('#' . $form['custom_fields']['#ajax_id'], $form['custom_fields']));
    return $response;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BrightcoveVideoForm::apiClientUpdateForm public static function Ajax callback to update the player options list. Overrides BrightcoveVideoPlaylistForm::apiClientUpdateForm
BrightcoveVideoForm::buildForm public function Form constructor. Overrides BrightcoveVideoPlaylistForm::buildForm
BrightcoveVideoForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
BrightcoveVideoForm::validateForm public function Button-level validation handlers are highly discouraged for entity forms, as they will prevent entity validation from running. If the entity is going to be saved during the form submission, this method should be manually invoked from the button-level… Overrides ContentEntityForm::validateForm
BrightcoveVideoPlaylistForm::$defaultAPIClient protected property The default API Client.
BrightcoveVideoPlaylistForm::create public static function Instantiates a new instance of this class. Overrides ContentEntityForm::create
BrightcoveVideoPlaylistForm::getPlayerOptions protected static function Get the player options for the given api client.
BrightcoveVideoPlaylistForm::__construct public function Constructs a ContentEntityForm object. Overrides ContentEntityForm::__construct
ContentEntityForm::$entity protected property The entity being used by this form. Overrides EntityForm::$entity 9
ContentEntityForm::$entityRepository protected property The entity repository service.
ContentEntityForm::$entityTypeBundleInfo protected property The entity type bundle info service.
ContentEntityForm::$time protected property The time service.
ContentEntityForm::addRevisionableFormFields protected function Add revision form fields if the entity enabled the UI.
ContentEntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityForm::buildEntity 3
ContentEntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties Overrides EntityForm::copyFormValuesToEntity
ContentEntityForm::flagViolations protected function Flags violations for the current form. 4
ContentEntityForm::form public function Gets the actual form array to be built. Overrides EntityForm::form 13
ContentEntityForm::getBundleEntity protected function Returns the bundle entity of the entity, or NULL if there is none.
ContentEntityForm::getEditedFieldNames protected function Gets the names of all fields edited in the form. 4
ContentEntityForm::getFormDisplay public function Gets the form display. Overrides ContentEntityFormInterface::getFormDisplay
ContentEntityForm::getFormLangcode public function Gets the code identifying the active form language. Overrides ContentEntityFormInterface::getFormLangcode
ContentEntityForm::getNewRevisionDefault protected function Should new revisions created on default.
ContentEntityForm::init protected function Initializes the form state and the entity before the first form build. Overrides EntityForm::init 1
ContentEntityForm::initFormLangcodes protected function Initializes form language code values.
ContentEntityForm::isDefaultFormLangcode public function Checks whether the current form language matches the entity one. Overrides ContentEntityFormInterface::isDefaultFormLangcode
ContentEntityForm::prepareEntity protected function Prepares the entity object before the form is built first. Overrides EntityForm::prepareEntity 1
ContentEntityForm::setFormDisplay public function Sets the form display. Overrides ContentEntityFormInterface::setFormDisplay
ContentEntityForm::showRevisionUi protected function Checks whether the revision form fields should be added to the form.
ContentEntityForm::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 3
ContentEntityForm::updateChangedTime public function Updates the changed time of the entity.
ContentEntityForm::updateFormLangcode public function Updates the form language to reflect any change to the entity language.
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::$entityTypeManager protected property The entity type manager. 3
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::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::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.
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.