external_entity-1.0.x-dev/src/Form/ExternalEntityTypeAwareEntityForm.php
src/Form/ExternalEntityTypeAwareEntityForm.php
<?php
declare(strict_types=1);
namespace Drupal\external_entity\Form;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Define the external entity type aware entity form.
*
* Extend this class if you form needs to be aware of the external entity type.
*/
abstract class ExternalEntityTypeAwareEntityForm extends EntityForm {
/**
* {@inheritDoc}
*/
public function getEntityFromRouteMatch(RouteMatchInterface $route_match, $entity_type_id) {
/** @var \Drupal\external_entity\Entity\ExternalEntityResourceAlter $entity */
$entity = parent::getEntityFromRouteMatch($route_match, $entity_type_id);
$this->setRequiredRouteParameters(
$entity,
$route_match
);
return $entity;
}
/**
* Define the required route parameter information.
*
* @return array
* An array of route parameters.
*/
protected function requiredRouteParameterInfo(): array {
return [
'external_entity_type' => [
'method' => 'setExternalEntityTypeId',
],
];
}
/**
* Set required route parameters.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity instance to set parameters on.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match service.
*/
protected function setRequiredRouteParameters(
EntityInterface $entity,
RouteMatchInterface $route_match,
): void {
foreach ($this->requiredRouteParameterInfo() as $name => $info) {
if (!isset($info['method']) || !method_exists($entity, $info['method'])) {
continue;
}
$method = $info['method'];
if ($value = $route_match->getRawParameter($name)) {
$entity->{$method}($value);
}
}
}
}
