I would like to retrieve the maximum length of a field programmatically, for instance the $node->title field .

I am writing a module that sets title and I don't really want to hard-code '255'. I am using Drupal 7.

  • By title do you mean node title?
    – Clive
    Mar 24, 2014 at 23:49
  • If you are talking about $node->title, its field in the database schema is set to 255 characters long and is enforced in the node form via #maxlength of the same.
    – Jimajamma
    Mar 25, 2014 at 0:38
  • What are you hard coding the length for?
    – rooby
    Mar 25, 2014 at 3:24
  • My question here was how to get the 255 number without hard coding it so that I can truncate the title - $node->title. I call field_info_instances('node') & there is no title, let alone #maxlength. I call node_save and get a PDO exception. I call drupal_form_submit and get errors I can parse. Reactionary and doesn't help. More generally I want a way to retrieve field constraints.
    – Interlated
    Mar 25, 2014 at 4:05

2 Answers 2


The Drupal schema API has a function named drupal_get_schema (D7) or drupal_get_module_schema (D8) that lets you inspect a schema programatically and retrieve field constraints.

For instance, to get the maxlength of the title field in the {node} table, you can use the following in D7:

$schema = drupal_get_schema('node');
$maxlength = $schema['fields']['title']['length'];

You can also inspect the max length of any field used by Drupal simply by looking at the database schema that defines that field. This will also tell you the names you need to use in the above PHP to get the right value in cases where you're unfamiliar with the schema.

For instance, if you are talking about the title field in the {node} table, you can see when looking at a scheme in a database inspection tool such phpMyAdmin that it is a varchar with a maximum length of 255 characters.

Screen-shot from phpMyAdmin.

  • How to do exactly same thing in drupal 8 i.e get length of an entity field ?Since there is no drupal_get_schema.
    – neha
    Jan 8, 2017 at 13:34
  • @neha Answer updated to reflect that this function has a new name in D8. Jan 8, 2017 at 14:58
 * Implements hook_form_alter().
function custom_module_form_alter(&$form, FormStateInterface $form_state, 
$form_id): void {
  if ($form['#form_id'] == 'node_event_form') {
    // Limit charset for the Event content type and add the description.
    $form['title']['widget'][0]['value']['#maxlength'] = 100;
    $form['title']['widget'][0]['value']['#description'] = t('The title is limited to 100 characters maximum.');
  • That code will not work, if the new length is higher than the length allowed from the database table.
    – apaderno
    Oct 27, 2023 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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