Repository URL to install this package:
|
Version:
1.3.0 ▾
|
<?php
namespace Drupal\custom_forms\Entity;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Database\StatementInterface;
use Drupal\Core\Entity\EntityPublishedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\RevisionLogEntityTrait;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\RevisionableContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\custom_forms\CustomFormItem;
use Drupal\custom_forms\CustomFormInterface;
use Drupal\user\EntityOwnerTrait;
/**
* Defines the custom form entity class.
*
* @ContentEntityType(
* id = "custom_form",
* label = @Translation("Custom Form"),
* label_collection = @Translation("Custom Forms"),
* label_singular = @Translation("Custom Form"),
* label_plural = @Translation("Custom Forms"),
* label_count = @PluralTranslation(
* singular = "@count custom form",
* plural = "@count custom forms"
* ),
* bundle_label = @Translation("Custom Form type"),
* handlers = {
* "storage" = "Drupal\Core\Entity\Sql\SqlContentEntityStorage",
* "view_builder" = "Drupal\custom_forms\CustomFormViewBuilder",
* "list_builder" = "Drupal\custom_forms\CustomFormListBuilder",
* "views_data" = "Drupal\views\EntityViewsData",
* "access" = "Drupal\custom_forms\CustomFormAccessControlHandler",
* "translation" = "Drupal\content_translation\ContentTranslationHandler",
* "form" = {
* "add" = "Drupal\custom_forms\Form\CustomFormForm",
* "edit" = "Drupal\custom_forms\Form\CustomFormForm",
* "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm"
* },
* "route_provider" = {
* "html" = "Drupal\custom_forms\Routing\CustomFormHtmlRouteProvider",
* },
* },
* fieldable = TRUE,
* admin_permission = "administer custom forms",
* base_table = "custom_forms",
* data_table = "custom_forms_data",
* revision_table = "custom_forms_revision",
* revision_data_table = "custom_forms_data_revision",
* show_revision_ui = TRUE,
* translatable = TRUE,
* entity_keys = {
* "id" = "id",
* "revision" = "vid",
* "bundle" = "type",
* "label" = "title",
* "langcode" = "langcode",
* "uuid" = "uuid",
* "status" = "status",
* "published" = "status",
* "uid" = "uid",
* "owner" = "uid"
* },
* revision_metadata_keys = {
* "revision_user" = "revision_user",
* "revision_created" = "revision_timestamp",
* "revision_log_message" = "revision_log"
* },
* bundle_entity_type = "custom_form_type",
* field_ui_base_route = "entity.custom_form_type.edit_form",
* common_reference_target = TRUE,
* permission_granularity = "bundle",
* links = {
* "add-form" = "/admin/custom_forms/add/{custom_form_type}",
* "add-page" = "/admin/custom_forms/add",
* "canonical" = "/admin/custom_forms/{custom_form}",
* "edit-form" = "/admin/custom_forms/{custom_form}/settings",
* "delete-form" = "/admin/custom_forms/{custom_form}/delete",
* "collection" = "/admin/custom_forms",
* "version-history" = "/admin/custom_forms/{custom_form}/revisions",
* "revision" =
* "/admin/custom_forms/{custom_form}/revisions/{custom_form_revision}/view",
* }
* )
*/
class CustomForm extends RevisionableContentEntityBase implements CustomFormInterface {
use EntityOwnerTrait;
use EntityChangedTrait;
use EntityPublishedTrait;
use RevisionLogEntityTrait;
use StringTranslationTrait;
/**
* The factory in charge of CRUD operations on custom form items.
*
* @var \Drupal\custom_forms\CustomFormItemFactory $itemFactory
*/
protected $itemFactory;
/**
* {@inheritdoc}
*/
public function __construct(array $values, $entity_type, $bundle = FALSE, $translations = []) {
parent::__construct($values, $entity_type, $bundle, $translations);
$this->itemFactory = \Drupal::service('custom_forms.factory.item');
}
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
// Add the revision metadata fields.
$fields += static::revisionLogBaseFieldDefinitions($entity_type);
// Add the published field.
$fields += static::publishedBaseFieldDefinitions($entity_type);
// Add the owner field
$fields += static::ownerBaseFieldDefinitions($entity_type);
$fields['uid']
->setLabel(t('Authored by'))
->setDescription(t('The user ID of author of the custom form.'))
->setRevisionable(TRUE)
->setSetting('target_type', 'user')
->setSetting('handler', 'default')
->setTranslatable(TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'author',
'weight' => 0,
])
->setDisplayOptions('form', [
'type' => 'entity_reference_autocomplete',
'weight' => 5,
'settings' => [
'match_operator' => 'CONTAINS',
'size' => '60',
'autocomplete_type' => 'tags',
'placeholder' => '',
],
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['title'] = BaseFieldDefinition::create('string')
->setTranslatable(TRUE)
->setRevisionable(TRUE)
->setLabel(t('Title'))
->setDescription(t('The title of the custom form.'))
->setRequired(TRUE)
->setSetting('max_length', 255)
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => -5,
])
->setDisplayConfigurable('form', TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'string',
'weight' => -5,
])
->setDisplayConfigurable('view', TRUE);
$fields['receipt_page'] = BaseFieldDefinition::create('entity_reference')
->setTranslatable(TRUE)
->setRevisionable(TRUE)
->setLabel(t('Receipt page'))
->setDescription(t('The page to use for the receipt.'))
->setRequired(FALSE)
->setSettings([
'target_type' => 'node',
'default_value' => NULL,
])
->setDisplayOptions('form', [
'type' => 'entity_reference_autocomplete',
'weight' => 5,
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['use_ajax'] = BaseFieldDefinition::create('boolean')
->setLabel(t('Use ajax'))
->setRevisionable(TRUE)
->setDefaultValue(TRUE)
->setDisplayConfigurable('form', TRUE);
$fields['status']
->setDisplayOptions('form', [
'type' => 'boolean_checkbox',
'weight' => -3,
]);
$fields['created'] = BaseFieldDefinition::create('created')
->setLabel(t('Created'))
->setDescription(t('The time that the custom form was created.'));
$fields['changed'] = BaseFieldDefinition::create('changed')
->setLabel(t('Changed'))
->setDescription(t('The time that the custom form was last edited.'));
return $fields;
}
/**
* {@inheritdoc}
*/
public function preSave(EntityStorageInterface $storage) {
parent::preSave($storage);
foreach (array_keys($this->getTranslationLanguages()) as $langcode) {
$translation = $this->getTranslation($langcode);
// If no owner has been set explicitly, make the anonymous user the owner.
if (!$translation->getOwner()) {
$translation->setOwnerId(0);
}
}
// If no revision author has been set explicitly, make the custom form owner the
// revision author.
if (!$this->getRevisionUser()) {
$this->setRevisionUserId($this->getOwnerId());
}
}
/**
* {@inheritdoc}
*/
public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
parent::preSaveRevision($storage, $record);
if ($this->isNewTranslation() && isset($this->original)) {
// If this is a new translation, clone all original fields to it.
/** @var CustomFormInterface $source */
$source = $this->getTranslation($this->defaultLangcode);
$source_fields = $this->itemFactory->getFormItems($source);
foreach ($source_fields as $source_field) {
// Add fields to translation.
$field = clone $source_field;
$field->setLangcode($this->language()->getId());
$field->setFormId($this->id());
$field->setFormRevisionId($this->getLoadedRevisionId());
try {
$field->save(FALSE);
} catch (\Exception $e) {
$error_message = $this->t('Failed saving cloned field to translation. Message = %message', [
'%message' => $e->getMessage()
]);
\Drupal::logger('Custom Forms')->error($error_message);
$this->messenger()->addError($this->t('Failed saving cloned field to translation. If it continues please contact an administrator.'));
}
// Update field revision for source fields.
$source_field->setFormRevisionId($this->getLoadedRevisionId());
try {
$source_field->save();
} catch (\Exception $e) {
$error_message = $this->t('Failed saving source field revision. Message = %message', [
'%message' => $e->getMessage()
]);
\Drupal::logger('Custom Forms')->error($error_message);
$this->messenger()->addError($this->t('Failed saving source field revision. If it continues please contact an administrator.'));
}
}
}
if (!$this->isNewRevision() && isset($this->original)
&& (!isset($record->revision_log) || $record->revision_log === '')
) {
// If we are updating an existing custom form without adding a new revision, we
// need to make sure $entity->revision_log is reset whenever it is empty.
// Therefore, this code allows us to avoid clobbering an existing log
// entry with an empty one.
$record->revision_log = $this->original->revision_log->value;
}
}
/**
* @inheritDoc
*/
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);
// Update the current fields if the revision has been updated.
if ($this->isDefaultRevision() && $this->getRevisionId() !== null) {
// Run through all languages to update their fields.
$languages = $this->getTranslationLanguages();
/** @var \Drupal\Core\Language\LanguageInterface $language */
foreach ($languages as $language) {
/** @var \Drupal\custom_forms\Entity\CustomForm $translated_form */
$translated_form = $this->getTranslation($language->getId());
// Load all fields associated with the previous revision
$items = $this->itemFactory->getFormItemsAsTree($translated_form, FALSE, TRUE);
// Create new copies of each field for the new revision
foreach ($items as $item) {
$new_item = clone $item;
$new_item->setFormRevisionId($translated_form->getRevisionId());
try {
$new_item->save();
// Remember to clone children, used for nested groups with fields, etc.
if (count($new_item->getChildren()) > 0) {
$this->itemFactory->cloneItemChildren($item, $new_item);
}
} catch (\Exception $e) {
$error_message = t('Failed during cloning of items. Message = %message', [
'%message' => $e->getMessage(),
]);
\Drupal::logger('Custom Forms')->error($error_message);
\Drupal::messenger()->addError(t('Failed during cloning of items. Please contact an administrator.'));
}
}
}
}
}
/**
* {@inheritdoc}
*/
public function delete() {
$this->itemFactory->deleteFormItems($this);
parent::delete();
}
/**
* {@inheritdoc}
*/
public function removeTranslation($langcode) {
$this->itemFactory->deleteFormItems($this, $langcode);
parent::removeTranslation($langcode);
}
}