Explain Drupal schema and drupal_write_record
1) Where is the best place to populate a new database table when you first enable the module? I need to go and get some data from an external source and do it transparently when the user installs / enables my custom module.
I create a schema in {mymodule} _schema (), do drupal_install_schema ({tablename}); in hook_install. Then I am trying to populate the table in hook_enable using drupal_write_record.
I have confirmed that the table has been created, I get no errors when doing hook_enable, but when I request a new table, I donβt return any rows - itβs empty.
Here's one variation of the code I tried:
/**
* Implementation of hook_schema()
*/
function ncbi_subsites_schema() {
// we know it MYSQL, so no need to check
$schema['ncbi_subsites_sites'] = array(
'description' => 'The base table for subsites',
'fields' => array(
'site_id' => array(
'description' => 'Primary id for site',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
), // end site_id
'title' => array(
'description' => 'The title of the subsite',
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '',
), //end title field
'url' => array(
'description' => 'The URL of the subsite in Production',
'type' => 'varchar',
'length' => 255,
'default' => '',
), //end url field
), //end fields
'unique keys' => array(
'site_id'=> array('site_id'),
'title' => array('title'),
), //end unique keys
'primary_key' => array('site_id'),
); // end schema
return $schema;
}
Here's hook_install:
function ncbi_subsites_install() {
drupal_install_schema('ncbi_subsites');
}
Here's hook_enable:
function ncbi_subsites_enable() {
drupal_get_schema('ncbi_subsites_site');
// my helper function to get data for table (not shown)
$subsites = ncbi_subsites_get_subsites();
foreach( $subsites as $name=>$attrs ) {
$record = new stdClass();
$record->title = $name;
$record->url = $attrs['homepage'];
drupal_write_record( 'ncbi_subsites_sites', $record );
}
}
Can someone tell me what I am missing?
a source to share
First of all (assuming Drupal 6) drupal_write_record()
you cannot call from hook_install () because Drupal will not find the database schema defined from the module, which will still be installed and enabled.
You need to use a function instead db_query()
. (The comments talk about a way to include data by default, guiding it hook_schema()
, but I haven't found any documentation on the matter.)
However, if you were using (development version) Drupal 7, you want to use db_insert()
.
a source to share