For the PHP solution you have to provide an EntityReferenceSelection Plugin. I give you an example from my "proreos" project:
namespace Drupal\proreos\Plugin\EntityReferenceSelection;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection
...
/**
* Plugin implementation of the 'selection' entity_reference.
*
* @EntityReferenceSelection(
* id = "default:proreos",
* label = @Translation("proreos selection"),
* entity_types = {"address_entity", "anwalt_entity", "library_entity"},
* group = "default",
* weight = 1
* )
*/
class OwnEntitiesSelection extends DefaultSelection {
protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
$query = parent::buildEntityQuery($match, $match_operator);
... your code here to modify the query ...
... (I do $query->condition('user_id', $currentUid);) ...
return $query;
}}
You may also need to override validateReferenceableNewEntities().
Look for more examples in the core modules.