Nov 21, 2019 in Drupal 8, Snippets

It is a bit strange that the name field (which functions like the node's title field) can be only 50 characters long. The snippet I'd like to share with you, makes it 255 long.

First, make sure you increase the table size of the field (varchar)

I create my custom entity 'Question' in a custom module (files inside config/install). So after installation I would like to make sure my field gets longer accepted values in the database.

Inside my mymodule.install file I put the following:

use Drupal\Core\Database\Database;

/**
 * Implements hook_install().
 */
function mymodule_install() {
  
  // Change length of the name field.
  $schema = Database::getConnection()->schema();
  $schema->changeField('question', 'name', 'name', [
    'length' => '255',
    'not null' => TRUE,
    'type' => 'varchar',
  ]);

  // Change length of the name field in revisions.
  $schema = Database::getConnection()->schema();
  $schema->changeField('question_revision', 'name', 'name', [
    'default' => NULL,
    'length' => '255',
    'type' => 'varchar',
  ]);
}

We are not done yet. We also have to make changes in the entity add form. Place the following hook in your mymodule.module file:

/**
 * @param $fields
 * @param EntityTypeInterface $entity_type
 *
 * Makes sure the name field of a question entity can be 255 characters
 */
function mymodule_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'question' && !empty($fields['name'])) {
    $fields['name']->setSetting('max_length', 255);
  }
}

Done, now longer values get accepted!