View source
<?php
namespace Drupal\course\Form;
use Drupal;
use Drupal\Core\Entity\BundleEntityFormBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormStateInterface;
class CourseTypeForm extends BundleEntityFormBase {
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$course_type = $this->entity;
if ($this->operation == 'add') {
$fields = \Drupal::service('entity_field.manager')
->getBaseFieldDefinitions('course');
$course = \Drupal::entityTypeManager()
->getStorage('course')
->create([
'type' => $course_type
->uuid(),
]);
}
else {
$fields = \Drupal::service('entity_field.manager')
->getFieldDefinitions('node', $course_type
->id());
$course = \Drupal::entityTypeManager()
->getStorage('course')
->create([
'type' => $course_type
->id(),
]);
}
$form['label'] = [
'#title' => t('Label'),
'#type' => 'textfield',
'#default_value' => $course_type
->label(),
'#description' => t('The admin-facing name.'),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#required' => TRUE,
'#default_value' => $course_type
->id(),
'#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
'#machine_name' => [
'exists' => '\\Drupal\\course\\Entity\\CourseType::load',
'source' => [
'label',
],
],
];
$outlines = array_column(Drupal::service('plugin.manager.course.outline')
->getDefinitions(), 'label', 'id');
$form['outline'] = [
'#title' => t('Default outline'),
'#description' => t('The default outline to use when creating courses of this type.'),
'#type' => 'select',
'#default_value' => $course
->get('outline')->value,
'#options' => $outlines,
'#required' => TRUE,
];
$form['status'] = [
'#title' => t('Published by default'),
'#description' => t('The default published state.'),
'#type' => 'checkbox',
'#default_value' => $course
->get('status')->value,
];
$form['new_revision'] = [
'#title' => t('Revision by default'),
'#description' => t('Create a new revision by default.'),
'#type' => 'checkbox',
'#default_value' => $course_type
->get('new_revision'),
];
return $form;
}
public function save(array $form, FormStateInterface $form_state) {
$type = $this->entity;
$status = parent::save($form, $form_state);
$t_args = [
'%name' => $type
->label(),
];
if ($status == SAVED_UPDATED) {
$this
->messenger()
->addStatus($this
->t('The course type %name has been updated.', $t_args));
}
elseif ($status == SAVED_NEW) {
$this
->messenger()
->addStatus($this
->t('The course type %name has been added.', $t_args));
}
$form_state
->setRedirectUrl($type
->toUrl('collection'));
return $status;
}
}