3

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 '14 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 '14 at 0:38
  • What are you hard coding the length for? – rooby Mar 25 '14 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 '14 at 4:05
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 '17 at 13:34
  • @neha Answer updated to reflect that this function has a new name in D8. – Free Radical Jan 8 '17 at 14:58

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.