Wednesday, 15 April 2015

How to create the table using Drupal module?

/* Implements hook_schema() */
function module_name_schema()
{
    $schema[‘module_name’] = array
    (
        ‘fields’ => array
            (
            ‘type’ => array(‘type’ => ‘varchar’, ‘length’ => 15, ‘not null’ => TRUE, ‘default’ => ‘node’),
            ‘id’ => array(‘type’ => ‘int’, ‘unsigned’ => TRUE, ‘not null’ => TRUE, ‘default’ => 0),
            ‘module_name’ => array(‘type’ => ‘varchar’, ‘length’ => 255, ‘not null’ => TRUE, ‘default’ => ”)
        ),
        ‘primary key’ => array(‘type’, ‘id’),
    );

    return $schema;
}

/* Implements hook_uninstall() */
function module_name_uninstall() {
    variable_del(‘module_name_default’);
}

/* Implements hook_update_n() */
function module_name_update_6200()
{
    $ret = array();
    if (db_column_exists(‘module_name’, ‘id’))
    {
        return $ret;
    }

    db_create_table($ret, ‘module_name_temp’, array(
                                                        ‘fields’ => array(
                                                        ‘type’ => array(‘type’ => ‘varchar’, ‘length’ => 15, ‘not null’ => TRUE, ‘default’ => ‘node’),
                                                        ‘id’ => array(‘type’ => ‘int’, ‘unsigned’ => TRUE, ‘not null’ => TRUE, ‘default’ => 0),
                                                        ‘module_name’ => array(‘type’ => ‘varchar’, ‘length’ => 255, ‘not null’ => TRUE, ‘default’ => ”)
                                                        ),
                                                        ‘primary key’ => array(‘type’, ‘id’),
                                                    )
    );

    $ret[] = update_sql(‘INSERT INTO {module_name_temp} (id, module_name) SELECT nid, module_name FROM {module_name}’);

    db_rename_table($ret, ‘module_name’, ‘module_name_old’);
    db_rename_table($ret, ‘module_name_temp’, ‘module_name’);

    $display_settings = variable_get(‘module_name_display’, array());
    foreach ($display_settings as $type)
    {
        if ($type)
        {
            variable_set(‘module_name_type_’ . $type . ‘_showfield’, 1);
        }
    }
    variable_del(‘module_name_display’);

    return $ret;
}

No comments:

Post a Comment