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

Yesterday we talked about defining a datetime field for the table created by custom module.
Drupal 7 – Create a Datetime field in hook_schema() @ 1

As i have mentioned in the above post, the datetime field is no longer support by the Drupal Schema API. If you don’t want to use the datetime field, you can try to save the datetime in timestamp format and stored it in an int column.

<?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 timestamp.'),
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
    ),
    'primary key' => array('id'),
  );
  
  return $schema;
}

 

You can save the current timestamp as follow.

$id = db_insert('<table name>')
  ->fields(array(
    'created_at' => REQUEST_TIME
  )
)
->execute();

 

Done =)

Reference:

About these ads

2 thoughts on “Drupal 7 – Create a Datetime field in hook_schema() @ 2

  1. e

    In which function/hook should I put the call to db_insert? Sorry if it’s a stupid question, but I am a newbie when it comes to Drupal!

    Reply
    1. ykyuen Post author

      you can use it anywhere in your code which u want insert the database record. For example, if you want to insert the data during the module installation, you can use it in the hook_install().

      Reply

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s