BrightcoveVideoPlaylistForm.php in Brightcove Video Connect 3.x
File
src/Form/BrightcoveVideoPlaylistForm.php
View source
<?php
namespace Drupal\brightcove\Form;
use Drupal\brightcove\BrightcoveUtil;
use Drupal\brightcove\Entity\BrightcovePlayer;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class BrightcoveVideoPlaylistForm extends ContentEntityForm {
protected $defaultAPIClient;
public function __construct(EntityManagerInterface $entity_manager, $defaultAPIClient) {
parent::__construct($entity_manager);
$this->defaultAPIClient = $defaultAPIClient;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity.manager'), $container
->get('config.factory')
->get('brightcove.settings')
->get('defaultAPIClient'));
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
$entity = $this->entity;
$triggering_element = $form_state
->getTriggeringElement();
if ($entity
->id() && empty($triggering_element)) {
BrightcoveUtil::checkUpdatedVersion($entity);
}
if ($entity
->isNew()) {
if (!$form['api_client']['widget']['#default_value']) {
$form['api_client']['widget']['#default_value'] = $this->defaultAPIClient;
}
$form['api_client']['widget']['#ajax'] = [
'callback' => [
self::class,
'apiClientUpdateForm',
],
'event' => 'change',
'wrapper' => 'player-ajax-wrapper',
];
$form['player']['widget']['#prefix'] = '<div id="' . $form['api_client']['widget']['#ajax']['wrapper'] . '">';
$form['suffix']['widget']['#suffix'] = '</div>';
}
else {
$form['api_client']['widget']['#disabled'] = TRUE;
}
$form['player']['widget']['#options'] = self::getPlayerOptions($form, $form_state);
return $form;
}
protected static function getPlayerOptions(array $form, FormStateInterface $form_state) {
if (empty($form_state
->getValue('api_client'))) {
$api_client = $form['api_client']['widget']['#default_value'];
}
else {
$api_client = $form_state
->getValue('api_client')[0]['target_id'];
}
return [
'_none' => t("Use API Client's default player"),
] + BrightcovePlayer::getList($api_client, TRUE);
}
public static function apiClientUpdateForm(array $form, FormStateInterface $form_state) {
$form['player']['widget']['#options'] = self::getPlayerOptions($form, $form_state);
$response = new AjaxResponse();
$response
->addCommand(new ReplaceCommand('#' . $form['api_client']['widget']['#ajax']['wrapper'], $form['player']));
return $response;
}
}