FlaggingCollectionForm.php in Flag Lists 4.0.x
File
src/Form/FlaggingCollectionForm.php
View source
<?php
namespace Drupal\flag_lists\Form;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityFormInterface;
class FlaggingCollectionForm extends ContentEntityForm {
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
$flaglistService = \Drupal::service('flaglists');
$account = \Drupal::currentUser();
$entity = $this->entity;
$existing_flaglists = $flaglistService
->getAllFlagForList(NULL, NULL);
$options = [];
foreach ($existing_flaglists as $flaglist) {
if ($flaglist
->hasBaseFlag()) {
$options[$flaglist
->get('id')] = $flaglist
->label();
}
}
$current_value = empty($entity
->getBaseFlag()) ? FALSE : $entity
->getBaseFlag()
->id();
$form['templateflag'] = [
'#type' => 'select',
'#title' => $this
->t('Template flag'),
'#required' => TRUE,
'#options' => $options,
'#default_value' => $current_value,
];
return $form;
}
public function save(array $form, FormStateInterface $form_state) {
$entity =& $this->entity;
if (!$form_state
->isValueEmpty('new_revision') && $form_state
->getValue('new_revision') != FALSE) {
$entity
->setNewRevision();
$entity
->setRevisionCreationTime(\Drupal::time()
->getRequestTime());
$entity
->setRevisionUserId(\Drupal::currentUser()
->id());
}
else {
$entity
->setNewRevision(FALSE);
}
$status = parent::save($form, $form_state);
switch ($status) {
case SAVED_NEW:
$this
->messenger()
->addMessage($this
->t('Created the %label Flagging collection.', [
'%label' => $entity
->label(),
]));
break;
default:
$this
->messenger()
->addMessage($this
->t('Saved the %label Flagging collection.', [
'%label' => $entity
->label(),
]));
}
$form_state
->setRedirect('entity.flagging_collection.canonical', [
'flagging_collection' => $entity
->id(),
]);
}
public function validateForm(array &$form, FormStateInterface $form_state) {
if (strlen($form_state
->getValue('name')[0]['value']) == 0) {
$form_state
->setErrorByName('name', $this
->t('Please provide a name.'));
}
if ($form_state
->getFormObject() instanceof EntityFormInterface) {
$entity_new = $form_state
->getFormObject()
->getEntity()
->isNew();
}
if (strlen($form_state
->getValue('name')[0]['value']) > 32) {
$form_state
->setErrorByName('name', $this
->t('Please provide a name that is maximum 32 characters long.'));
}
$flagService = \Drupal::service('flag');
$machineId = strtolower($form_state
->getValue('name')[0]['value'] . '_' . $this->entity
->getOwnerId());
$machineId = preg_replace("/[^a-z0-9_]/", "_", $machineId);
$exists = $flagService
->getFlagById($machineId);
if (!empty($exists) && $entity_new) {
$form_state
->setErrorByName('name', $this
->t('The Name is already in use. Please provide a unique name.'));
}
parent::validateForm($form, $form_state);
}
}