Skip to content

Instantly share code, notes, and snippets.

@itmyprofession
Forked from laradevitt/d8module.install
Last active March 16, 2017 15:40
Show Gist options
  • Save itmyprofession/e7b51dea2db13495ad514ada4ed99fc5 to your computer and use it in GitHub Desktop.
Save itmyprofession/e7b51dea2db13495ad514ada4ed99fc5 to your computer and use it in GitHub Desktop.
Drupal 8
<?php
# Reading configuration
$config = \Drupal::config('system.maintenance');
$message = $config->get('message');
?>
<?php
// Writing in Configuration
$config = \Drupal::service('config.factory')->getEditable('system.performance');
// Set a scalar value.
$config->set('cache.page.enabled', 1);
// Set an array of values.
$page_cache_data = array('enabled' => 1, 'max_age' => 5);
$config->set('cache.page', $page_cache_data);
// Save your data to the file system.
$config->save();
?>
<?php
// Removing Configuration
$config = \Drupal::service('config.factory')->getEditable('system.performance');
$config->clear('cache.page.max_age')->save();
?>
<?php
// Best Practive
$config = \Drupal::service('config.factory')->getEditable('foo.bar');
$config
->set('foo', 'foo')
->set('bar', 'bar')
->save();
?>
Help
----
https://www.drupal.org/docs/8/api/configuration-api/simple-configuration-api
Before:
$form_state['rebuild'] = TRUE;
$form_builder->buildForm('Drupal\my_module\Form\MyForm', $form_state);
After:
use Drupal\Core\Form\FormState;
$form_state = new FormState();
$form_state->setRebuild();
$form_builder->buildForm('Drupal\my_module\Form\MyForm', $form_state);
In order to do things like setting errors, you no longer need the whole form builder:
Before:
form_set_error($element, $form_state, $message);
form_set_error('element_name', $form_state, $message);
After:
$form_state->setError($element, $message);
$form_state->setErrorByName($element, $message);
In addition to the functions that were replaced by methods, all array-based usage of $form_state is now replaced by methods:
Before:
$complete_form = &$form_state['complete_form'];
$form_state['complete_form'] = &$complete_form;
After:
$complete_form = &$form_state->getCompleteForm();
$form_state->setCompleteForm($complete_form);
Before:
$response = $form_state['response'];
$form_state['response'] = $response;
After:
$response = $form_state->getResponse();
$form_state->setResponse($response);
Before:
$form_state['redirect'] = new Url('route_name', array('route' => 'parameters'));
$form_state['redirect'] = array('route_name', array('route' => 'parameters'));
$redirect = $form_state['redirect'];
$form_state['no_redirect'] = TRUE;
if (!empty($form_state['no_redirect'])) {
}
After:
$form_state->setRedirectUrl(new Url('route_name', ['route' => 'parameters']));
$form_state->setRedirect('route_name', ['route' => 'parameters']);
$redirect = $form_state->getRedirect();
$form_state->disableRedirect();
if ($form_state->isRedirectDisabled()) {
}
Before:
$storage = &$form_state['storage'];
$form_state['storage'] = &$storage;
After:
$storage = &$form_state->getStorage();
$form_state->setStorage($storage);
Before:
$temporary = $form_state['temporary'];
$form_state['temporary'] = $temporary;
After:
$temporary = $form_state->getTemporary();
$form_state->setTemporary($temporary);
Before:
$arbitrary_value = $form_state['arbitrary_key'];
$form_state['arbitrary_key'] = $arbitrary_value;
$nested_arbitrary_value = $form_state['nested']['arbitrary_key'];
$form_state['nested']['arbitrary_key'] = $nested_arbitrary_value;
After:
$arbitrary_value = $form_state->get('arbitrary_key');
$form_state->set('arbitrary_key', $arbitrary_value);
$nested_arbitrary_value = $form_state->get(['nested', 'arbitrary_key']);
$form_state->set(['nested', 'arbitrary_key'], $nested_arbitrary_value);
Before:
$build_info = $form_state['build_info'];
$form_state['build_info'] = $build_info;
$form_state['build_info']['args'] = $args;
$args = $form_state['build_info']['args'];
After:
$build_info = $form_state->getBuildInfo();
$form_state->setBuildInfo($build_info);
$form_state->addBuildInfo('args', $args);
$args = $form_state->getBuildInfo()['args'];
Before:
$input = &$form_state['input'];
$form_state['input'] = $input;
After:
$input = &$form_state->getUserInput();
$form_state->setUserInput($input);
Before:
$foo = $form_state['values']['foo']; // This will return an array. print_r($foo)
$foobar = $form_state['values']['foo']['bar'];
$values = $form_state['values'];
$form_state['values']['foo'] = 'bar';
$form_state['values']['bar']['baz'] = 'foo';
if (isset($form_state['values']['foo'])) {
}
if (isset($form_state['values']['foo']['bar'])) {
}
if (empty($form_state['values']['foo'])) {
}
if (empty($form_state['values']['foo']['bar'])) {
}
After:
$foo = $form_state->getValue('foo');
$foobar = $form_state->getValue(['foo', 'bar']);
$values = $form_state->getValues();
$form_state->setValue('foo', array('bar'));
$form_state->setValue(['bar', 'baz'], 'foo');
if ($form_state->hasValue('foo')) {
}
if ($form_state->hasValue(['foo', 'bar'])) {
}
if ($form_state->isValueEmpty('foo')) {
}
if ($form_state->isValueEmpty(['foo', 'bar'])) {
}
Before:
$form_state['rebuild'] = TRUE;
$form_state['rebuild'] = FALSE;
if (!empty($form_state['rebuild'])) {
}
After:
$form_state->setRebuild();
$form_state->setRebuild(FALSE);
if ($form_state->isRebuilding()) {
}
Before:
$form_state['build_info']['callback_object'] = $callback;
$callback = $form_state['build_info']['callback_object'];
After:
$form_state->setFormObject($callback);
$callback = $form_state->getFormObject();
Before:
$form_state['always_process'] = TRUE;
$form_state['always_process'] = FALSE;
if (!empty($form_state['always_process'])) {
}
After:
$form_state->setAlwaysProcess();
$form_state->setAlwaysProcess(FALSE);
if ($form_state->getAlwaysProcess()) {
}
Before:
$buttons = $form_state['buttons'];
$form_state['buttons'] = $buttons;
After:
$buttons = $form_state->getButtons();
$form_state->setButtons($buttons);
Before:
$form_state['cache'] = TRUE;
$form_state['cache'] = FALSE;
$form_state['no_cache'] = TRUE;
if (!empty($form_state['cache']) && empty($form_state['no_cache'])) {
}
After:
$form_state->setCached();
$form_state->setCached(FALSE);
$form_state->disableCache();
if ($form_state->isCached()) {
}
Before:
$form_state['executed'] = TRUE;
if (!empty($form_state['executed'])) {
}
After:
$form_state->setExecuted();
if ($form_state->isExecuted()) {
}
Before:
$groups = &$form_state['groups'];
$form_state['groups'] = $groups;
After:
$groups = &$form_state->getGroups();
$form_state->setGroups($groups);
Before:
$form_state['has_file_element'] = TRUE;
$form_state['has_file_element'] = FALSE;
if (!empty($form_state['has_file_element'])) {
}
After:
$form_state->setHasFileElement();
$form_state->setHasFileElement(FALSE);
if ($form_state->hasFileElement()) {
}
Before:
$limit_validation_errors = $form_state['limit_validation_errors'];
$form_state['limit_validation_errors'] = $limit_validation_errors;
After:
$limit_validation_errors = $form_state->getLimitValidationErrors();
$form_state->setLimitValidationErrors($limit_validation_errors);
Before:
$form_state['method'] = 'get';
if ($form_state['method'] == 'get') {
}
After:
$form_state->setMethod('get');
if ($form_state->isMethodType('get')) {
}
Before:
$form_state['must_validate'] = TRUE;
$form_state['must_validate'] = FALSE;
if (!empty($form_state['must_validate'])) {
}
After:
$form_state->setValidationEnforced();
$form_state->setValidationEnforced(FALSE);
if ($form_state->isValidationEnforced()) {
}
Before:
$form_state['process_input'] = TRUE;
$form_state['process_input'] = FALSE;
if (!empty($form_state['process_input'])) {
}
After:
$form_state->setProcessInput();
$form_state->setProcessInput(FALSE);
if ($form_state->isProcessingInput()) {
}
Before:
$form_state['programmed'] = TRUE;
$form_state['programmed'] = FALSE;
if (!empty($form_state['programmed'])) {
}
After:
$form_state->setProgrammed();
$form_state->setProgrammed(FALSE);
if ($form_state->isProgrammed()) {
}
Before:
$form_state['programmed_bypass_access_check'] = TRUE;
$form_state['programmed_bypass_access_check'] = FALSE;
if (!empty($form_state['programmed_bypass_access_check'])) {
}
After:
$form_state->setProgrammedBypassAccessCheck();
$form_state->setProgrammedBypassAccessCheck(FALSE);
if ($form_state->isBypassingProgrammedAccessChecks()) {
}
Before:
$form_state['submitted'] = TRUE;
if (!empty($form_state['submitted'])) {
}
After:
$form_state->setSubmitted();
if ($form_state->isSubmitted()) {
}
Before:
$form_state['validation_complete'] = TRUE;
$form_state['validation_complete'] = FALSE;
if (!empty($form_state['validation_complete'])) {
}
After:
$form_state->setValidationComplete();
$form_state->setValidationComplete(FALSE);
if ($form_state->isValidationComplete()) {
}
Before:
$build_info = $form_state['rebuild_info'];
$form_state['rebuild_info'] = $build_info;
$form_state['rebuild_info']['copy'] = $info;
$info = $form_state['rebuild_info']['copy'];
After:
$build_info = $form_state->getRebuildInfo();
$form_state->setRebuildInfo($build_info);
$form_state->addRebuildInfo('copy', $info);
$info = $form_state->getRebuildInfo()['copy'];
Before:
$submit_handlers = $form_state['submit_handlers'];
$form_state['submit_handlers'] = $submit_handlers;
After:
$submit_handlers = $form_state->getSubmitHandlers();
$form_state->setSubmitHandlers($submit_handlers);
Before:
$validate_handlers = $form_state['validate_handlers'];
$form_state['validate_handlers'] = $validate_handlers;
After:
$validate_handlers = $form_state->getValidateHandlers();
$form_state->setValidateHandlers($validate_handlers);
Before:
$triggering_element = &$form_state['triggering_element'];
$form_state['triggering_element'] = $triggering_element;
After:
$triggering_element = &$form_state->getTriggeringElement();
$form_state->setTriggeringElement($triggering_element);
http://w3shaman.com/article/drupal-8-sortable-table-pager
<?php
/**
* @file
* Install, update and uninstall functions for the d8module module.
*/
function d8module_schema_otherdb() {
$schema['mytable'] = array(
'description' => 'My table description',
'fields' => array(
'myfield' => array(
'description' => 'My field description',
'type' => 'serial',
'size' => 'medium',
'not null' => TRUE,
'unsigned' => TRUE,
),
),
'primary key' => array('myfield'),
);
return $schema;
}
/**
* Implements hook_install().
*/
function d8module_install() {
\Drupal\Core\Database\Database::setActiveConnection('otherdb');
$connection = \Drupal\Core\Database\Database::getConnection();
$schema = d8module_schema_shared();
foreach ($schema as $name => $table) {
$connection->schema()->createTable($name, $table);
}
\Drupal\Core\Database\Database::setActiveConnection();
}
/**
* Implements hook_uninstall().
*/
function d8module_uninstall() {
\Drupal\Core\Database\Database::setActiveConnection('otherdb');
$connection = \Drupal\Core\Database\Database::getConnection();
$schema = d8module_schema_shared();
foreach ($schema as $name => $table) {
$connection->schema()->dropTable($name);
}
\Drupal\Core\Database\Database::setActiveConnection();
}
//////////////////////////////////////////////////////////////////////////
use Drupal\Core\Database\Database;
use Drupal\Core\Database\Schema;
/**
* Implements hook_schema()
*/
function ussa_fis_schema()
{
$schema = array();
$schema['fis_tables'] = create_fis_tables();
$schema['fis_syncs'] = create_fis_syncs();
$schema['fis_table_syncs'] = create_fis_table_syncs();
$schema['fis_scheduled_tables'] = create_fis_scheduled_tables();
return $schema;
}
/**
* Implements hook_install().
*/
function ussa_fis_install()
{
}
/**
* Create fis_tables table
*/
function create_fis_tables()
{
return array(
'fields' => array(
'id' => array(
'type' => 'serial',
'not null' => TRUE,
),
'name' => array(
'type' => 'varchar',
'length' => 64,
'not null' => TRUE,
),
'frequency' => array(
'type' => 'varchar',
'length' => 16,
'not null' => TRUE,
'default' => 'None'
),
'status' => array(
'type' => 'varchar',
'length' => 16,
'null' => TRUE,
),
'created_at' => array(
'type' => 'varchar',
'mysql_type' => 'timestamp DEFAULT CURRENT_TIMESTAMP',
'not null' => TRUE,
),
'updated_at' => array(
'type' => 'varchar',
'mysql_type' => 'timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
'not null' => TRUE,
),
),
'primary key' => array('id'),
);
}
/**
* Create fis_syncs table
*/
function create_fis_syncs()
{
return array(
'fields' => array(
'id' => array(
'type' => 'serial',
'not null' => TRUE,
),
'started_at' => array(
'type' => 'int',
'size' => 'normal',
'null' => TRUE,
),
'finished_at' => array(
'type' => 'int',
'size' => 'normal',
'null' => TRUE,
),
'status' => array(
'type' => 'varchar',
'length' => 16,
'null' => TRUE,
),
'log_file' => array(
'type' => 'varchar',
'description' => "Log File",
'length' => 64,
'not null' => FALSE,
),
'dump_file' => array(
'type' => 'varchar',
'description' => "Sync File",
'length' => 64,
'not null' => FALSE,
),
'created_at' => array(
'type' => 'varchar',
'mysql_type' => 'timestamp DEFAULT CURRENT_TIMESTAMP',
'not null' => TRUE,
),
'updated_at' => array(
'type' => 'varchar',
'mysql_type' => 'timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
'not null' => TRUE,
),
),
'primary key' => array('id'),
);
}
/**
* Create fis_table_syncs table
*/
function create_fis_table_syncs()
{
return array(
'fields' => array(
'table_id' => array(
'type' => 'int',
'size' => 'normal',
'not null' => TRUE,
),
'sync_id' => array(
'type' => 'int',
'size' => 'normal',
'not null' => TRUE,
),
'created_at' => array(
'type' => 'varchar',
'mysql_type' => 'timestamp DEFAULT CURRENT_TIMESTAMP',
'not null' => TRUE,
),
'updated_at' => array(
'type' => 'varchar',
'mysql_type' => 'timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
'not null' => TRUE,
),
),
'primary key' => array('table_id', 'sync_id')
);
}
function create_fis_scheduled_tables()
{
return array(
'fields' => array(
'id' => array(
'type' => 'serial',
'not null' => TRUE,
),
'table_id' => array(
'type' => 'int',
'size' => 'normal',
'not null' => TRUE,
),
'sync_id' => array(
'type' => 'int',
'size' => 'normal',
'not null' => FALSE,
),
'created_at' => array(
'type' => 'varchar',
'mysql_type' => 'timestamp DEFAULT CURRENT_TIMESTAMP',
'not null' => TRUE,
),
'updated_at' => array(
'type' => 'varchar',
'mysql_type' => 'timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
'not null' => TRUE,
),
),
'primary key' => array('id')
);
}
<?php
$database_schema = $this->connection->schema();
if (!$database_schema->tableExists(static::TABLE_NAME)) {
$schema_definition = $this->schemaDefinition();
$database_schema->createTable(static::TABLE_NAME, $schema_definition);
return TRUE;
}
// http://www.eilyin.name/note/database-queries-drupal-8-7
// Get Single Value
$query = \Drupal::database()->select('node_field_data', 'nfd');
$query->addField('nfd', 'nid');
$query->condition('nfd.title', 'Potato');
$query->range(0, 1);
$nid = $query->execute()->fetchField();
// Get Single row
$query = \Drupal::database()->select('node_field_data', 'nfd');
$query->fields('nfd', ['nid', 'title']);
$query->condition('nfd.type', 'vegetable');
$query->range(0, 1);
$vegetable = $query->execute()->fetchAssoc();
// Using db like:
$query = \Drupal::database()->select('node_field_data', 'nfd');
$query->fields('nfd', ['nid', 'title']);
$query->condition('nfd.type', 'vegetable');
$query->condition('nfd.title', $query->escapeLike('ca') . '%', 'LIKE');
$vegetable = $query->execute()->fetchAllKeyed();
// Get several rows with JOIN:
$query = \Drupal::database()->select('node_field_data', 'nfd');
$query->fields('nfd', ['nid', 'title']);
$query->addField('ufd', 'name');
$query->join('users_field_data', 'ufd', 'ufd.uid = nfd.uid');
$query->condition('nfd.type', 'vegetable');
$vegetable = $query->execute()->fetchAllAssoc('nid');
//Insert
$query = \Drupal::database()->insert('flood');
$query->fields([
'event',
'identifier'
]);
$query->values([
'My event',
'My indentifier'
]);
$query->execute();
// Update
$query = \Drupal::database()->update('flood');
$query->fields([
'identifier' => 'My new identifier'
]);
$query->condition('event', 'My event');
$query->execute();
//Upsert
$query = \Drupal::database()->upsert('flood');
$query->fields([
'fid',
'identifier',
]);
$query->values([
1,
'My indentifier for upsert'
]);
$query->key('fid');
$query->execute();
// Delete
$query = \Drupal::database()->delete('flood');
$query->condition('event', 'My event');
$query->execute();
'LastUpdated' => array(
'description' => 'Last Updated Timestamp',
'type' => 'varchar',
'mysql_type' => 'timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
'not null' => TRUE,
),
http://www.timtoon.com/2009/01/08/fix-to-drupal-to-allow-now-and-current_timestamp-in-new-tables/
https://www.drupal.org/node/1464354
https://www.drupal.org/docs/7/api/schema-api/data-types
https://www.drupal.org/docs/7/api/schema-api/updating-tables-hook_update_n-functions
https://www.interworks.com/blog/jkhalaj/2012/04/12/drupal-7-usage-foreign-keys-schema-api-and-current-default-fk-erd
<?php
$form['fis_syncs'][$i]['operations'] = array(
'#type' => 'link',
'#title' => $this->t('View Tables'),
'#url' => Url::fromRoute('ussa_fis.admin_management.history.table', ['id' => $result->id]),
'#attributes' => [
'class' => ['button', 'use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 700,
'height' => 400,
]),
],
);
<?php
$queue = \Drupal::queue('database');
// create item
$queue->createItem(['test'=>'teest']);
// number of itmes in queue
$queue->numberOfItems()
// get queue item
$item = $queue->claimItem();
// delete itme
$queue->deleteItem($item);
/** Help **/
https://knackforge.com/blog/vamsi/how-create-queue-woker-drupal-8
http://drupal.stackexchange.com/questions/206838/documentation-or-tutorial-on-using-batch-or-queue-services-api-programmatically
https://www.sitepoint.com/drupal-8-queue-api-powerful-manual-and-cron-queueing/
https://knackforge.com/blog/vamsi/how-create-queue-woker-drupal-8
<?php
function __backup_mysql_database($params)
{
$mtables = array(); $contents = "-- Database: `".$params['db_to_backup']."` --\n";
$mysqli = new mysqli($params['db_host'], $params['db_uname'], $params['db_password'], $params['db_to_backup']);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$results = $mysqli->query("SHOW TABLES");
while($row = $results->fetch_array()){
if (!in_array($row[0], $params['db_exclude_tables'])){
$mtables[] = $row[0];
}
}
foreach($mtables as $table){
$contents .= "-- Table `".$table."` --\n";
$results = $mysqli->query("SHOW CREATE TABLE ".$table);
while($row = $results->fetch_array()){
$contents .= $row[1].";\n\n";
}
$results = $mysqli->query("SELECT * FROM ".$table);
$row_count = $results->num_rows;
$fields = $results->fetch_fields();
$fields_count = count($fields);
$insert_head = "INSERT INTO `".$table."` (";
for($i=0; $i < $fields_count; $i++){
$insert_head .= "`".$fields[$i]->name."`";
if($i < $fields_count-1){
$insert_head .= ', ';
}
}
$insert_head .= ")";
$insert_head .= " VALUES\n";
if($row_count>0){
$r = 0;
while($row = $results->fetch_array()){
if(($r % 400) == 0){
$contents .= $insert_head;
}
$contents .= "(";
for($i=0; $i < $fields_count; $i++){
$row_content = str_replace("\n","\\n",$mysqli->real_escape_string($row[$i]));
switch($fields[$i]->type){
case 8: case 3:
$contents .= $row_content;
break;
default:
$contents .= "'". $row_content ."'";
}
if($i < $fields_count-1){
$contents .= ', ';
}
}
if(($r+1) == $row_count || ($r % 400) == 399){
$contents .= ");\n\n";
}else{
$contents .= "),\n";
}
$r++;
}
}
}
if (!is_dir ( $params['db_backup_path'] )) {
mkdir ( $params['db_backup_path'], 0777, true );
}
$backup_file_name = "sql-backup-".date( "d-m-Y--h-i-s").".sql";
$fp = fopen($backup_file_name ,'w+');
if (($result = fwrite($fp, $contents))) {
echo "Backup file created '--$backup_file_name' ($result)";
}
fclose($fp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment