How to handle (create table, alter ...) database schemas on drupal 8 ?
Get Database Schema
$schema = \Drupal\Core\Database\Database::getConnection()->schema();
Create a table.
$spec = array(
'description' => 'New table description',
'fields' => array(
'id' => array(
'type' => 'serial',
'not null' => TRUE,
),
'name' => array(
'type' => 'varchar',
'length' => 64,
'not null' => TRUE,
'default' => '',
),
'value' => array(
'type' => 'varchar',
'length' => 64,
'not null' => TRUE,
'default' => '',
),
),
'primary key' => array('id'),
);
$schema->createTable('the_table_name', $spec);
Drop / Delete a field.
$schema = Database::getConnection()->schema();
$schema->dropField('the_table_name', 'field_to_drop');
Add a field to a table.
$spec = array(
'type' => 'varchar',
'length' => '255',
'not null' => TRUE,
'default' => '0',
);
$schema->addField('the_table_name', 'field_to_add', $spec);
Examples
Delete a table field from hook_update_N()
/**
* Update 8001, Delete Field 'field_to_delete' from table 'the_test_table'.
*/
function mymodule_update_8001(&$sandbox) {
$schema = \Drupal\Core\Database\Database::getConnection()->schema();
$schema->dropField('the_test_table', 'field_to_delete');
return ('The field field_to_delete has been dropped from the_test_table');
}
More :
https://api.drupal.org/api/drupal/includes!database!schema.inc/group/schemaapi/7.x
Comments
how to Fetch database table using date field and button control
public function buildForm(array $form, FormStateInterface $form_state) {
$form['set_start_date'] = [
'#title' => $this->t('START DATE '),
'#type' => 'date',
'#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
'#date_date_format' => 'd/m/Y',
'#required' => TRUE,
];
$form['set_end_date'] = [
'#title' => $this->t('END DATE'),
'#type' => 'date',
'#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
'#date_date_format' => 'd/m/Y',
'#required' => TRUE,
];
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Fetch'),
'#button_type' => 'primary',
);
return $form;
}
public function buildForm…
public function buildForm(array $form, FormStateInterface $form_state) {
$form['set_start_date'] = [
'#title' => $this->t('START DATE '),
'#type' => 'date',
'#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
'#date_date_format' => 'd/m/Y',
'#required' => TRUE,
];
$form['set_end_date'] = [
'#title' => $this->t('END DATE'),
'#type' => 'date',
'#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
'#date_date_format' => 'd/m/Y',
'#required' => TRUE,
];
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Fetch'),
'#button_type' => 'primary',
);
return $form;
}
Add new comment