My EntityForm has a field where

  '#machine_name' => array(
    'exists' => array($this, 'load'),

To check the validation of this, I wanted to know about writing the function load() in my EntityListBuilder to check its validation.

A way around would be to use ctools:

$result = ctools_export_load_object('module_entityname', 'names', array($field_id));

However, I wanted to avoid using ctools. Are there any Drupal 8 APIs available to check the validation of #machine_name?

  • 1
    machine_name elements are already validated by form_validate_machine_name ()...have I missed what you're trying to do? Or are you looking for a generic entity_exists type callback you can use in place of your own exists function? – Clive Jul 6 '14 at 21:14
  • @Clive: So that means, it should just be '#machine_name' => array('exists' => array($this)? I'm unable to find any relevant docs about the second parameter passed in the array. – xan Jul 6 '14 at 21:19
  • 1
    Sorry if I'm still misunderstanding, but if I'm not then you don't need to implement a new method for this, you can use your entity controller's load method. So it would be 'exists' => '\Drupal\mymodule\Entity\MyEntity::load' – Clive Jul 6 '14 at 21:38
  • @Clive: that was my basic doubt. I'm unable to code the load function. The Entity examples given on Drupal.org are without any implementation of load functions. – xan Jul 6 '14 at 21:46
  • No need to implement anything unless you need to change the default behaviour of loading by ID, load() is inherited from Entity::load() so it's already available – Clive Jul 6 '14 at 21:50

The exists key wants a callback that it can test for boolean true/false. The machine name to test will be passed as the first (and only) argument to that callback.

Since your entity class (not the list builder class) already has a load method, inherited from Entity::load(), which accepts an ID and returns either an entity object or a null/false value, you can (and probably should) use that.

So, assuming your entity is defined as \Drupal\mymodule\Entity\MyEntity, you would use the following:

'#machine_name' => array(
  'exists' => '\Drupal\mymodule\Entity\MyEntity::load',

Exactly the same method is used in the CommentTypeForm, and probably others:

$form['id'] = array(
  '#type' => 'machine_name',
  '#default_value' => $comment_type->id(),
  '#machine_name' => array(
    'exists' => '\Drupal\comment\Entity\CommentType::load',
  '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
  '#disabled' => !$comment_type->isNew(),
  • @xan is that content entity or config entity? I trying this for content entity and it is not working. I'm trying to port PET module. – Sharique Mar 3 '16 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.