You can create a controller in its simplest form.
In my_module.routing.yml :
my_module.profile_controller_profile:
path: '/user/{user}/my-profile'
defaults:
_controller: '\Drupal\my_module\Controller\ProfileController::profile'
_title: 'Profile'
requirements:
_permission: 'edit profile'
user: \d+
In ProfileController.php :
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\my_module\Entity\Profile;
use Drupal\user\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Class ProfileController.
*/
class ProfileController extends ControllerBase {
/**
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new ProfileController object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* @param \Drupal\Core\Entity\EntityFormBuilderInterface $entity_form_builder
*/
public function __construct(
EntityTypeManagerInterface $entity_type_manager,
EntityFormBuilderInterface $entity_form_builder
) {
$this->entityTypeManager = $entity_type_manager;
$this->entityFormBuilder = $entity_form_builder;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('entity.form_builder')
);
}
/**
* @param \Drupal\user\Entity\User $user
*
* @return array
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function profile(User $user) {
$profiles = $this->entityTypeManager->getStorage('profile')->loadByProperties(
['user_id' => $user->id()]
);
if ($profiles) {
$profile = array_pop($profiles);
$action = 'edit';
} else {
$profile = Profile::create([
'user_id' => $user->id(),
]);
$action = 'add';
}
return $this->entityFormBuilder->getForm($profile, $action);
}
}
You can choose to redirect after submitting the form, etc.