class EditUpdateForm in Scheduled Publish 8.3
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\scheduled_publish\Form\EditUpdateForm
Expanded class hierarchy of EditUpdateForm
1 string reference to 'EditUpdateForm'
File
- src/
Form/ EditUpdateForm.php, line 18 - Contains \Drupal\scheduled_publish\Form\EditUpdateForm.
Namespace
Drupal\scheduled_publish\FormView source
class EditUpdateForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'scheduled_publish_edit_update_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $entity = NULL, $field_delta = NULL) {
if (!isset($entity) || !isset($field_delta)) {
$form['message'] = [
'#theme_wrappers' => [
'container',
],
'#markup' => $this
->t('A valid entity and field delta must be provided.'),
];
return $form;
}
$fields = $this
->getScheduledFields($entity
->getEntityTypeId(), $entity
->bundle());
$field = reset($fields);
$states = $entity
->get($field)
->getValue();
if (!isset($states[$field_delta])) {
$form['message'] = [
'#theme_wrappers' => [
'container',
],
'#markup' => $this
->t('This status update does not exist.'),
];
return $form;
}
// Save data into form_state.
$form_state
->set([
'scheduled_publish',
'entity',
], $entity);
$form_state
->set([
'scheduled_publish',
'field',
], $field);
$form_state
->set([
'scheduled_publish',
'field_delta',
], $field_delta);
$entity_info = $entity
->label() . ' (' . $entity
->id() . ')';
$form['#title'] = $this
->t('Edit status update for the "@node" node', [
'@node' => $entity_info,
]);
$form['message'] = [
'#theme_wrappers' => [
'container',
],
'#markup' => $this
->t('If this state change invalidates any existing transitions those will be deleted.'),
];
$prev_state = $states[$field_delta - 1] ?? FALSE;
if ($prev_state) {
$orig_status = $entity->moderation_state->value;
$entity->moderation_state->value = $prev_state['moderation_state'];
}
$m_options = $this
->getModerationOptions($entity);
if ($prev_state) {
$entity->moderation_state->value = $orig_status;
}
$form['moderation_state'] = [
'#type' => 'select',
'#title' => $this
->t('Moderation state change'),
'#options' => $m_options,
'#default_value' => isset($m_options[$states[$field_delta]['moderation_state']]) ? $states[$field_delta]['moderation_state'] : NULL,
'#required' => TRUE,
];
$form['value'] = [
'#type' => 'datetime',
'#title' => $this
->t('Scheduled date'),
'#description' => $this
->t('Date & time of the scheduled state change'),
'#date_increment' => 1,
'#date_timezone' => date_default_timezone_get(),
'#default_value' => new DrupalDateTime($states[$field_delta]['value'], ScheduledPublish::STORAGE_TIMEZONE),
'#required' => TRUE,
];
$form['actions'] = [
'#type' => 'container',
'#weight' => 10,
];
$form['actions']['save'] = [
'#type' => 'submit',
'#value' => $this
->t('Save'),
'#attributes' => [
'class' => [
'button',
'button--primary',
],
],
];
$query = \Drupal::service('request_stack')
->getCurrentRequest()->query;
$url = Url::fromRoute('view.scheduled_publish.page_1');
if ($query
->has('destination')) {
$options = UrlHelper::parse($query
->get('destination'));
try {
$url = Url::fromUserInput('/' . ltrim($options['path'], '/'), $options);
} catch (\InvalidArgumentException $e) {
// Suppress the exception.
}
}
if ($url) {
$form['actions']['cancel'] = [
'#type' => 'link',
'#title' => $this
->t('Cancel'),
'#attributes' => [
'class' => [
'button',
],
],
'#url' => $url,
];
}
return $form;
}
/**
* Returns scheduled publish fields
*
* @param string $entityTypeName
* @param string $bundleName
*
* @return array
*/
protected function getScheduledFields(string $entityTypeName, string $bundleName) : array {
$scheduledFields = [];
$fields = \Drupal::service('entity_field.manager')
->getFieldDefinitions($entityTypeName, $bundleName);
foreach ($fields as $fieldName => $field) {
/** @var FieldConfig $field */
if (strpos($fieldName, 'field_') !== FALSE) {
if ($field
->getType() === 'scheduled_publish') {
$scheduledFields[] = $fieldName;
}
}
}
return $scheduledFields;
}
/**
* Get moderation options.
*/
protected function getModerationOptions($entity) {
$states = [];
/** @var \Drupal\content_moderation\ModerationInformation $moderationInformationService */
$moderationInformationService = \Drupal::service('content_moderation.moderation_information');
if ($moderationInformationService
->isModeratedEntity($entity)) {
/** @var \Drupal\content_moderation\StateTransitionValidation $transitionValidationService */
$transitionValidationService = \Drupal::service('content_moderation.state_transition_validation');
$transitions = $transitionValidationService
->getValidTransitions($entity, \Drupal::currentUser());
foreach ($transitions as $key => $value) {
$states[$transitions[$key]
->to()
->id()] = $transitions[$key]
->label();
}
}
return $states;
}
/**
* Handles state values, clean-up and ordering.
*/
public function handleStates(FormStateInterface $form_state, &$states) {
$entity = $form_state
->get([
'scheduled_publish',
'entity',
]);
$orig_status = $entity->moderation_state->value;
$m_options = $this
->getModerationOptions($entity);
// Make sure states are ordered correctly.
$this
->handleStateOrdering($states);
foreach ($states as $key => $state) {
if (isset($m_options[$state['moderation_state']])) {
$entity->moderation_state->value = $state['moderation_state'];
$m_options = $this
->getModerationOptions($entity);
}
else {
// Delete invalid state changes.
unset($states[$key]);
}
}
$entity->moderation_state->value = $orig_status;
// Adjust ordering in case any invalid entries got removed.
$this
->handleStateOrdering($states);
}
/**
* Re-orders states and adds/changes their delta values based on date.
*/
public static function handleStateOrdering(&$states) {
usort($states, function ($a, $b) {
$a_timestamp = strtotime($a['value']);
$b_timestamp = strtotime($b['value']);
if ($a_timestamp == $b_timestamp) {
return 0;
}
return $a_timestamp < $b_timestamp ? -1 : 1;
});
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$state = $form_state
->getValue('moderation_state');
$date = $form_state
->getValue('value');
$date
->setTimezone(new \DateTimezone(ScheduledPublish::STORAGE_TIMEZONE));
$value = $date
->format(ScheduledPublish::DATETIME_STORAGE_FORMAT);
$entity = $form_state
->get([
'scheduled_publish',
'entity',
]);
$field = $form_state
->get([
'scheduled_publish',
'field',
]);
$delta = $form_state
->get([
'scheduled_publish',
'field_delta',
]);
$states = $entity
->get($field)
->getValue();
$states[$delta]['moderation_state'] = $state;
$states[$delta]['value'] = $value;
$this
->handleStates($form_state, $states);
// Reload entity to be sure it's not old.
$entity = \Drupal::entityTypeManager()
->getStorage($entity
->getEntityTypeId())
->load($entity
->id());
$entity
->set($field, $states);
$entity
->save();
$this
->messenger()
->addStatus($this
->t('Status update changed.'));
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
EditUpdateForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
|
EditUpdateForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
|
EditUpdateForm:: |
protected | function | Get moderation options. | |
EditUpdateForm:: |
protected | function | Returns scheduled publish fields | |
EditUpdateForm:: |
public static | function | Re-orders states and adds/changes their delta values based on date. | |
EditUpdateForm:: |
public | function | Handles state values, clean-up and ordering. | |
EditUpdateForm:: |
public | function |
Form submission handler. Overrides FormInterface:: |
|
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
public static | function |
Instantiates a new instance of this class. Overrides ContainerInjectionInterface:: |
87 |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
FormBase:: |
public | function |
Form validation handler. Overrides FormInterface:: |
62 |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |