I am trying to create a simple time tracking app and for this purpose, I need an entity reference field with some additional filtering of referenced entities (only active projects can be selected).
I read some guides and it seems that what I need is to
1. create entity reference field
This is done in the buildForm()
function of the src/Form/TimesheetForm.php
class like this:
$form['project'] = [
'#type' => 'entity_autocomplete',
'#title' => $this->t('Project'),
'#weight' => '0',
'#target_type' => 'project_entity',
'#selection_handler' => 'default:active_projects',
'#selection_settings' => [
],
'#tags' => FALSE,
];
2. create custom plugin
This is done in src/Plugin/ActiveProjectsSelection.php
like this:
<?php
namespace Drupal\timesheet\Plugin\EntityReferenceSelection;
use Drupal\node\Plugin\EntityReferenceSelection\NodeSelection;
/**
* Provides specific access control for the node entity type.
*
* @EntityReferenceSelection(
* id = "active_projects",
* label = @Translation("Active projects selection"),
* entity_types = {"project_entity"},
* group = "default",
* weight = 3
* )
*/
class ActiveProjectsSelection extends NodeSelection {
/**
* @param null $match
* @param string $match_operator
*
* @return \Drupal\Core\Entity\Query\QueryInterface
*/
protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
\Drupal::logger('timesheet')->debug('buildEntityQuery');
$query = parent::buildEntityQuery($match, $match_operator);
//$query->condition('project_start_date', time(), '<');
//$query->condition('project_end_date', time(), '>');
return $query;
}
}
However, even when I commented out all the logic, the autocomplete does not work. When I type in the field, no autocomplete popup appears. Not even the debug message is logged when I try to trigger the autocomplete.
I have also tried to extend DefaultSelection
instead of the NodeSelection
as I am using a custom entity which is not a node
, but the result was the same.
It looks like my plugin is not even reached, but I do not know why.
I cleared the cache, my local site is in dev mode.
EntityReferenceSelection
and clear the cache again, should be picked up – Clive♦ Dec 10 '18 at 0:00