Drupal 7 – Create a Datetime field in hook_schema() @ 1

Next: Drupal 7 – Create a Datetime field in hook_schema() @ 1

If your custom module requires an additional table in the Drupal database, you have to create the .install file and define the schema inside it. In Drupal 7, the datetime field is no longer support by the Drupal Schema API. If you want to create a datetime field, you have to use the mysql_type or pgsql_type. Here is an example.

<?php

function <module>_schema() {
  $schema = array();
  
  $schema['<table name>'] = array(
    'description' => t('<table description>'),
    'fields' => array(
      'id' => array(
        'description' => t('The primary identifier.'),
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
      'created_at' => array(
        'description' => t('The creation date.'),
        'mysql_type' => 'DATETIME',
        'not null' => TRUE
      ),
    ),
    'primary key' => array('id'),
  );
  
  return $schema;
}

 

In the above case, you can save the value of the created_at value by

$id = db_insert('<table name>')
  ->fields(array(
    'created_at' => format_date(time(), 'custom', 'Y-m-d H:i:s')
  )
)
->execute();

 

Done =)

Reference:

Advertisements

3 thoughts on “Drupal 7 – Create a Datetime field in hook_schema() @ 1”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.