learnosity-1.0.x-dev/src/Form/LearnosityActivityPlayerForm.php
src/Form/LearnosityActivityPlayerForm.php
<?php
namespace Drupal\learnosity\Form;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Serialization\Yaml;
/**
* Class LearnosityActivityPlayerForm.
*
* The activity type form.
*
* @package Drupal\learnosity\Form
*/
class LearnosityActivityPlayerForm extends EntityForm {
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$learnosity_activity_player = $this->entity;
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#maxlength' => 255,
'#default_value' => $learnosity_activity_player->label(),
'#description' => $this->t("The human-readable name of this activity type. This text will be displayed as part of the list on the Add activity page. This name must be unique."),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $learnosity_activity_player->id(),
'#machine_name' => [
'exists' => '\Drupal\learnosity\Entity\LearnosityActivityPlayer::load',
],
'#disabled' => !$learnosity_activity_player->isNew(),
];
$form['description'] = [
'#type' => 'textarea',
'#title' => $this->t('Description'),
'#maxlength' => 255,
'#default_value' => $learnosity_activity_player->getDescription(),
];
$form['settings'] = [
'#type' => 'vertical_tabs',
'#title' => $this->t('Settings'),
];
$form['advanced'] = [
'#type' => 'details',
'#title' => $this->t('Advanced'),
'#open' => FALSE,
'#group' => 'settings',
];
$form['advanced']['config'] = [
'#type' => 'textarea',
'#title' => $this->t('Initialization Config'),
'#default_value' => $learnosity_activity_player->getConfig(),
'#rows' => 20,
'#description' => $this->t('The Learnosity Items API initialization settings. Leave blank to use Learnosity defaults. For more details see <a href = ":url">:url</a>.', [
':url' => 'https://reference.learnosity.com/items-api/initialization',
]),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
// Make sure that the Yaml is valid.
$config = $form_state->getValue('config');
try {
Yaml::decode($config);
}
catch (\Exception $exception) {
$form_state->setError($form['advanced']['config'], $exception->getMessage());
}
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$activity_type = $this->entity;
// Handle the mapping values.
$status = $activity_type->save();
switch ($status) {
case SAVED_NEW:
\Drupal::messenger()->addMessage($this->t('Created the %label Activity type.', [
'%label' => $activity_type->label(),
]));
break;
default:
\Drupal::messenger()->addMessage($this->t('Saved the %label Activity type.', [
'%label' => $activity_type->label(),
]));
}
$form_state->setRedirectUrl($activity_type->toUrl('collection'));
}
}
