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.
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityThe 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.
$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.