learnosity-1.0.x-dev/src/Form/LearnosityNodeTypeForm.php
src/Form/LearnosityNodeTypeForm.php
<?php
namespace Drupal\learnosity\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Provides a form to alter the node type form.
*/
class LearnosityNodeTypeForm {
use StringTranslationTrait;
/**
* The allowed field types.
*
* Should be restricted to appropriate field lengths. For example, we don't
* want to allow users to map to textarea or boolean fields.
*
* @return array
* Array of allowed field types.
*/
protected function allowedFieldTypes() {
return [
'string',
'integer',
'uuid',
'email',
];
}
/**
* {@inheritdoc}
*/
public function formAlter(array &$form, FormStateInterface $form_state) {
// @todo: Add reasonable defaults. Perhaps during module installation?
$entityFieldManager = \Drupal::service('entity_field.manager');
$entity = $form_state->getFormObject()->getEntity();
$mappingsHandler = \Drupal::service('learnosity.mappings_handler');
// @todo Add support for other entity types.
$entity_type = 'node';
$bundle = $entity->id();
$fields = [];
$field_definitions = $entityFieldManager->getFieldDefinitions($entity_type, $bundle);
foreach ($field_definitions as $field) {
if (in_array($field->getType(), $this->allowedFieldTypes())) {
$fields[$field->getName()] = $field->getLabel();
}
}
$form['learnosity'] = [
'#type' => 'details',
'#title' => t('Learnosity settings'),
'#access' => \Drupal::currentUser()->hasPermission('administer site configuration'),
'#group' => 'additional_settings',
'#tree' => TRUE,
];
$form['learnosity']['mappings'] = [
'#type' => 'fieldset',
'#title' => $this->t('Mappings'),
];
$form['learnosity']['mappings']['activity_id'] = [
'#type' => 'select',
'#title' => $this->t('Activity ID'),
'#options' => $fields,
'#description' => $this->t("The ID that will be used in Learnosity's Reports API and Data API. Limit 36 characters. UUID recommended."),
'#default_value' => $mappingsHandler->getMapping($entity_type, $bundle, 'activity_id'),
];
$form['learnosity']['mappings']['name'] = [
'#type' => 'select',
'#title' => $this->t('Name'),
'#options' => $fields,
'#description' => $this->t("The name that will be displayed in Learnosity's Reports API and Data API"),
'#default_value' => $mappingsHandler->getMapping($entity_type, $bundle, 'name'),
];
$form['actions']['submit']['#submit'][] = [LearnosityNodeTypeForm::class, 'submitForm'];
}
/**
* {@inheritdoc}
*/
public static function submitForm(array &$form, FormStateInterface $form_state) {
$entity = $form_state->getFormObject()->getEntity();
$mappings = $form_state->getValue(['learnosity', 'mappings']);
$mappingsHandler = \Drupal::service('learnosity.mappings_handler');
$mappingsHandler->setMappings('node', $entity->id(), $mappings);
$mappingsHandler->save();
}
}
