class WorkspaceForm in Workspace 8
Form controller for the workspace edit forms.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
- class \Drupal\Core\Entity\ContentEntityForm implements ContentEntityFormInterface
- class \Drupal\workspace\Entity\Form\WorkspaceForm
- class \Drupal\Core\Entity\ContentEntityForm implements ContentEntityFormInterface
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
Expanded class hierarchy of WorkspaceForm
1 file declares its use of WorkspaceForm
File
- src/
Entity/ Form/ WorkspaceForm.php, line 18
Namespace
Drupal\workspace\Entity\FormView source
class WorkspaceForm extends ContentEntityForm {
/**
* The injected service to track conflicts during replication.
*
* @var ConflictTrackerInterface
*/
protected $conflictTracker;
/**
* The workspace content entity.
*
* @var \Drupal\multiversion\Entity\WorkspaceInterface
*/
protected $entity;
/**
* Constructs a ContentEntityForm object.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* @param ConflictTrackerInterface $conflict_tracker
* The conflict tracking service.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
*
* @todo Add TimeInterface as parameter for constructor and use the value in
* parent constructor starting with Drupal 8.4.0.
*/
public function __construct(EntityManagerInterface $entity_manager, ConflictTrackerInterface $conflict_tracker, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL) {
parent::__construct($entity_manager, $entity_type_bundle_info);
$this->conflictTracker = $conflict_tracker;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container
->get('entity.manager'), $container
->get('workspace.conflict_tracker'), $container
->get('entity_type.bundle.info'));
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$workspace = $this->entity;
if ($this->operation == 'edit') {
// Allow the user to not abort on conflicts.
$this->conflictTracker
->useWorkspace($workspace);
$conflicts = $this->conflictTracker
->getAll();
if ($conflicts) {
$form['message'] = $this
->generateMessageRenderArray('error', $this
->t('There are <a href=":link">@count conflict(s) with the :target workspace</a>. Pushing changes to :target may result in unexpected behavior or data loss, and cannot be undone. Please proceed with caution.', [
'@count' => count($conflicts),
':link' => Url::fromRoute('entity.workspace.conflicts', [
'workspace' => $workspace
->id(),
])
->toString(),
':target' => $workspace
->get('upstream')->entity ? $workspace
->get('upstream')->entity
->label() : '',
]));
$form['is_aborted_on_conflict'] = [
'#type' => 'radios',
'#title' => $this
->t('Abort if there are conflicts?'),
'#default_value' => 'true',
'#options' => [
'true' => $this
->t('Yes, if conflicts are found do not replicate to upstream.'),
'false' => $this
->t('No, go ahead and push any conflicts to the upstream.'),
],
'#weight' => 0,
];
}
else {
$form['message'] = $this
->generateMessageRenderArray('status', 'There are no conflicts.');
}
// Set the form title based on workspace.
$form['#title'] = $this
->t('Edit workspace %label', [
'%label' => $workspace
->label(),
]);
}
$form['label'] = [
'#type' => 'textfield',
'#title' => $this
->t('Label'),
'#maxlength' => 128,
'#default_value' => $workspace
->label(),
'#description' => $this
->t("Label for the Workspace."),
'#required' => TRUE,
'#weight' => 1,
];
$form['machine_name'] = [
'#type' => 'machine_name',
'#required' => TRUE,
'#title' => $this
->t('Workspace Machine Name'),
'#maxlength' => 128,
'#default_value' => $workspace
->get('machine_name')->value,
'#machine_name' => [
'exists' => [
$this,
'exists',
],
],
];
return parent::form($form, $form_state, $workspace);
}
/**
* {@inheritdoc}
*/
protected function getEditedFieldNames(FormStateInterface $form_state) {
return array_merge([
'label',
'machine_name',
], parent::getEditedFieldNames($form_state));
}
/**
* {@inheritdoc}
*/
protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
// Manually flag violations of fields not handled by the form display. This
// is necessary as entity form displays only flag violations for fields
// contained in the display.
$field_names = [
'label',
'machine_name',
];
foreach ($violations
->getByFields($field_names) as $violation) {
list($field_name) = explode('.', $violation
->getPropertyPath(), 2);
$form_state
->setErrorByName($field_name, $violation
->getMessage());
}
parent::flagViolations($violations, $form, $form_state);
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
// Pass the abort flag to the ReplicationManager using runtime-only state,
// i.e. a static.
// @see \Drupal\workspace\ReplicatorManager
$is_aborted_on_conflict = !$form_state
->hasValue('is_aborted_on_conflict') || $form_state
->getValue('is_aborted_on_conflict') === 'true';
drupal_static('workspace_is_aborted_on_conflict', $is_aborted_on_conflict);
$workspace = $this->entity;
$is_new = $workspace
->isNew();
$workspace
->save();
$info = [
'%info' => $workspace
->label(),
];
$context = [
'@type' => $workspace
->bundle(),
'%info' => $workspace
->label(),
];
$logger = $this
->logger('workspace');
// If Workbench Moderation is enabled, a publish of the Workspace should
// trigger a replication. We pass back the status of that replication using
// a static variable. If replication happened, we want to handle the case
// of failed replication, as well as modify the wording of the saved
// message.
// @see \Drupal\workspace\EventSubscriber\WorkbenchModerationSubscriber
// @todo Avoid using statics.
$replication_status = drupal_static('publish_workspace_replication_status', NULL);
if ($replication_status !== NULL) {
$logger
->notice('@type: updated %info.', $context);
if ($replication_status == TRUE) {
// The replication succeeded, in addition to saving the workspace.
drupal_set_message($this
->t('Workspace :source has been updated and changes were pushed to :target.', [
':source' => $workspace
->label(),
':target' => $workspace
->get('upstream')->entity
->label(),
]), 'status');
$form_state
->setValue('id', $workspace
->id());
$form_state
->set('id', $workspace
->id());
$redirect = $this
->currentUser()
->hasPermission('administer workspaces') ? $workspace
->toUrl('collection') : $workspace
->toUrl('canonical');
$form_state
->setRedirectUrl($redirect);
}
else {
// The replication failed, even though the Workspace was updated.
$previous_workflow_state = drupal_static('publish_workspace_previous_state', NULL);
// This variable should always be set, else there is an issue with
// the trigger logic.
if ($previous_workflow_state === NULL) {
throw new \Exception('The publish_workspace_replication_status should be set.');
}
// Revert the workspace back to its previous moderation state.
$workspace->moderation_state->target_id = $previous_workflow_state;
$workspace
->save();
// Show the form again.
$form_state
->setRebuild();
}
}
else {
// Assume a replication did not happen OR that Workbench Moderation is not
// installed.
if ($is_new) {
$logger
->notice('@type: added %info.', $context);
drupal_set_message($this
->t('Workspace %info has been created.', $info));
}
else {
$logger
->notice('@type: updated %info.', $context);
drupal_set_message($this
->t('Workspace %info has been updated.', $info));
}
if ($workspace
->id()) {
$form_state
->setValue('id', $workspace
->id());
$form_state
->set('id', $workspace
->id());
$redirect = $this
->currentUser()
->hasPermission('administer workspaces') ? $workspace
->toUrl('collection') : $workspace
->toUrl('canonical');
$form_state
->setRedirectUrl($redirect);
}
else {
drupal_set_message($this
->t('The workspace could not be saved.'), 'error');
$form_state
->setRebuild();
}
}
}
/**
* Generate a message render array with the given text.
*
* @param string $type
* The type of message: status, warning, or error.
* @param string $message
* The message to create with.
*
* @return array
* The render array for a status message.
*
* @see \Drupal\Core\Render\Element\StatusMessages
*/
protected function generateMessageRenderArray($type, $message) {
return [
'#theme' => 'status_messages',
'#message_list' => [
$type => [
Markup::create($message),
],
],
];
}
/**
* Determines if a workspace with the specified machine name already exists.
*
* @param string $machine_name
*
* @return bool
* TRUE if the machine_name exists, FALSE otherwise.
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function exists($machine_name) {
return (bool) $this->entityTypeManager
->getStorage('workspace')
->getQuery()
->condition('machine_name', $machine_name)
->execute();
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
ContentEntityForm:: |
protected | property | The entity repository service. | |
ContentEntityForm:: |
protected | property | The entity type bundle info service. | |
ContentEntityForm:: |
protected | property | The time service. | |
ContentEntityForm:: |
protected | function | Add revision form fields if the entity enabled the UI. | |
ContentEntityForm:: |
public | function |
Builds an updated entity object based upon the submitted form values. Overrides EntityForm:: |
3 |
ContentEntityForm:: |
protected | function |
Copies top-level form values to entity properties Overrides EntityForm:: |
|
ContentEntityForm:: |
protected | function | Returns the bundle entity of the entity, or NULL if there is none. | |
ContentEntityForm:: |
public | function |
Gets the form display. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
public | function |
Gets the code identifying the active form language. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
protected | function | Should new revisions created on default. | |
ContentEntityForm:: |
protected | function |
Initializes the form state and the entity before the first form build. Overrides EntityForm:: |
1 |
ContentEntityForm:: |
protected | function | Initializes form language code values. | |
ContentEntityForm:: |
public | function |
Checks whether the current form language matches the entity one. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
protected | function |
Prepares the entity object before the form is built first. Overrides EntityForm:: |
1 |
ContentEntityForm:: |
public | function |
Sets the form display. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
protected | function | Checks whether the revision form fields should be added to the form. | |
ContentEntityForm:: |
public | function |
This is the default entity object builder function. It is called before any
other submit handler to build the new entity object to be used by the
following submit handlers. At this point of the form workflow the entity is
validated and the form state… Overrides EntityForm:: |
3 |
ContentEntityForm:: |
public | function | Updates the changed time of the entity. | |
ContentEntityForm:: |
public | function | Updates the form language to reflect any change to the entity language. | |
ContentEntityForm:: |
public | function |
Button-level validation handlers are highly discouraged for entity forms,
as they will prevent entity validation from running. If the entity is going
to be saved during the form submission, this method should be manually
invoked from the button-level… Overrides FormBase:: |
3 |
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 | |
EntityForm:: |
protected | property | The entity type manager. | 3 |
EntityForm:: |
protected | property | The module handler service. | |
EntityForm:: |
protected | property | The name of the current operation. | |
EntityForm:: |
private | property | The entity manager. | |
EntityForm:: |
protected | function | Returns an array of supported actions for the current entity form. | 29 |
EntityForm:: |
protected | function | Returns the action form element for the current entity form. | |
EntityForm:: |
public | function | Form element #after_build callback: Updates the entity with submitted data. | |
EntityForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
10 |
EntityForm:: |
public | function |
Returns a string identifying the base form. Overrides BaseFormIdInterface:: |
5 |
EntityForm:: |
public | function |
Gets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface:: |
1 |
EntityForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
10 |
EntityForm:: |
public | function |
Gets the operation identifying the form. Overrides EntityFormInterface:: |
|
EntityForm:: |
protected | function | Invokes the specified prepare hook variant. | |
EntityForm:: |
public | function | Process callback: assigns weights and hides extra fields. | |
EntityForm:: |
public | function |
Sets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity type manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the module handler for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the operation for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function | ||
EntityForm:: |
public | function | ||
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:: |
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. | |
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. | |
WorkspaceForm:: |
protected | property | The injected service to track conflicts during replication. | |
WorkspaceForm:: |
protected | property |
The workspace content entity. Overrides ContentEntityForm:: |
|
WorkspaceForm:: |
public static | function |
Instantiates a new instance of this class. Overrides ContentEntityForm:: |
|
WorkspaceForm:: |
public | function | Determines if a workspace with the specified machine name already exists. | |
WorkspaceForm:: |
protected | function |
Flags violations for the current form. Overrides ContentEntityForm:: |
|
WorkspaceForm:: |
public | function |
Gets the actual form array to be built. Overrides ContentEntityForm:: |
|
WorkspaceForm:: |
protected | function | Generate a message render array with the given text. | |
WorkspaceForm:: |
protected | function |
Gets the names of all fields edited in the form. Overrides ContentEntityForm:: |
|
WorkspaceForm:: |
public | function |
Form submission handler for the 'save' action. Overrides EntityForm:: |
|
WorkspaceForm:: |
public | function |
Constructs a ContentEntityForm object. Overrides ContentEntityForm:: |