Drupal Quick Code

Action Code
CREATE NEW NODE
(Basic)
$node_title = 'Article One';
$content_type = 'article';

$node = new stdClass();
$node->type = $content_type;
$node->language = LANGUAGE_NONE;

// Set default attributes like uid, status, created time etc.
node_object_prepare($node);

$node->title = $node_title;
node_save($node);

// Above $node will now be the complete node object.
$new_node_id = $node->nid;
CREATE NEW NODE
(Associating references)
$node_title = 'Article One';
$content_type = 'article';
$entity_reference_type = 'node';
$entity_reference_id = 4; // Say, node ID 4.
$term_reference_id = 4; // Say, term ID 4.

$node = new stdClass();
$node->type = $content_type;
$node->language = LANGUAGE_NONE;

// Set default attributes like uid, status, created time etc.
node_object_prepare($node);

$node->title = $node_title;

//Entity reference field
$node->field_my_entity_reference[$node->language][0]['target_id'] = $entity_reference_id;
$node->field_my_entity_reference[$node->language][0]['target_type'] = $entity_reference_type;

//Term reference field
$node->field_my_term_reference[$node->language][0]['tid'] = $term_reference_id;

node_save($node);

// Above $node will now be the complete node object.
$new_node_id = $node->nid;
NODE DELETE
(Returns NULL in both the case valid or invalid node ID)
$nid = 4; // Say, node ID 4.
node_delete($nid);
DEFINE CONSTANT
const MY_CONSTANT_NAME = 'Drupal Drug';
const MY_SECOND_CONSTANT = 7;

Also, check Drupal Constants
GET VARIABLE
(Returns variable value OR NULL in case not set)
variable_get('my_module_my_variable');

// Use $default_value if the variable has never been set
// Note: $default_value is for current scope it does not set value for future use
variable_get('my_module_my_variable', $default_value);
SET VARIABLE
(Returns NULL)
variable_set('my_module_my_variable', $value);
DELETE VARIABLE
(Returns NULL)
variable_del('my_module_my_variable');
CREATE WEBFORM COMPONENTS
Required Module: webform
(Returns component ID on each iteration)
$webform_node = node_load($webform_nid);

$components = array(
  array(
    'name' => 'Name',
    'form_key' => 'name',
    'type' => 'textfield',
    'required' => 1,
    'weight' => 0,
    'pid' => 0,
  ),
  array(
    'name' => 'Age',
    'form_key' => 'age',
    'type' => 'number',
    'required' => 0,
    'weight' => 2,
    'pid' => 0,
  ),
);

foreach($components as $component) {
  $component['nid'] = $webform_node->nid;
  $component['extra']['title_display'] = 'inline';
  $webform_node->webform['components'][] = $component;
  $component_id = webform_component_insert($component);
}
SUBMIT WEBFORM
Required Module: webform
(Returns submission ID)
global $user;
$uid = $user->uid;

$webform_node = node_load($webform_nid);

// Input values to be submitted.
$data[$form_key] = $input;
$data[$form_key2] = $input2;

// Include supporting files.
module_load_include('inc', 'webform', 'webform.module');
module_load_include('inc', 'webform', 'includes/webform.submissions');

// Arrange $data in the way Webform expects it.
$data = _webform_client_form_submit_flatten($webform_node, $data);
$data = webform_submission_data($webform_node, $data);

$submission = (object) array(
  'nid' => $webform_node->nid,
  'uid' => $uid,
  'submitted' => REQUEST_TIME,
  'remote_addr' => ip_address(),
  'is_draft' => FALSE,
  'data' => $data,
);

$submission_id = webform_submission_insert($webform_node, $submission);

Comments

  1. /**
    * Unpublishes a node.
    */
    function _node_unpublish($nid = NULL) {
    // Check if NID an integer
    $node = precheck_node($nid);
    $msg = 'Node could not be unpublished.';

    // Unpublish if node exists.
    if ($node) {
    $node->status = 0;
    node_save($node);
    $msg = 'Node unpublished successfully.';
    }

    drupal_set_message(t($msg));
    }

    /**
    * Delete a node.
    */
    function _node_delete($nid = NULL) {
    // Check if NID an integer
    $node = precheck_node($nid);
    $msg = 'Node could not be deleted.';

    // Unpublish if node exists.
    if ($node) {
    node_delete($nid);
    $msg = 'Node deleted successfully.';
    }

    drupal_set_message(t($msg));
    }


    /*
    * Returns node object for valid node id.
    */
    function precheck_node ($nid) {
    if (preg_match('/^[0-9]+$/', $nid)) {
    return node_load($nid);
    }
    }

    ReplyDelete
  2. TIP: Find latest drupal version here 'https://www.drupal.org/download-latest/tar.gz'

    ReplyDelete
  3. global $base_url;
    $file = file_load($fid);
    $file_uri = $file->uri;

    $zipfile = substr(file_create_url($file_uri), strlen($base_url) + 1);
    $extract_path = 'sites/default/files/template_html/html_' . $node->nid;


    $zipfile = 'sites/all/file.zip';
    $path = 'sites/all/extracted'

    // Unzips a file.
    function _unzip_html_files($zipfile, $path, $id = '') {
    $zip = new ZipArchive;
    $open = $zip->open($zipfile);

    if ($open === TRUE) {
    $extract = $zip->extractTo($path);
    if ($extract === TRUE) {
    $zip->close();
    }
    else{
    watchdog('template-html', 'We cannot unzip the file:' . $id);
    }
    }
    else{
    watchdog('template-html', 'Could not open uploaded zip archive: ' . $id);
    }

    }

    ReplyDelete
  4. Drupal code search in all contributed modules.
    Example search, node_insert
    http://grep.xnddx.ru/

    ReplyDelete

Post a Comment

Drupal Contribution
Git Commands
RESTful Services
Lando Commands
Docker Commands
MySQL
Database Quick Code
Drush Commands
Drupal Console
PHP Quick Code
Drupal Quick Code
Composer Commands
Linux Commands
Linux Shell Scripting
Drupal Hooks
Twig Tricks
PHPUnit Test
PhpMyAdmin
Drupal Constants
CSS Clues
BLT Commands
Vagrant Commands
Localhost
127.0.0.1
Drupal Interview
Drupal Certifications
Concept & Definitions
Mac Tips
Windows Tips
Browser Tips

Best Practice

Use 'elseif' instead of 'else if'
#CodingTips

As of PHP 5.4 you can also use the short array syntax, which replaces array() with []
#CodingTips

Functions in general shall be named using snake_case(say, my_function()), and using camelCase(say, myFunction()) when declared within a plugin class
#CodingTips

Variables in general shall be named using snake_case(say, $my_variable), and using camelCase(say, $myVariable) when declared within a plugin class
#CodingTips

Manage automatically assigning of new permissions whenever a module is enabled here- admin/config/people/accounts
#ConfigurationTips

Manage source of Main-menu and User-menu links here- admin/structure/menu/settings
#ConfigurationTips

Helper function(s) shall be named prefixing an underscore(say, _my_helper_function()), which can prevent hooks from being called
#CodingTips

Ideally, configuring of 'Private file system path' at admin/config/media/file-system should be located outside of your Drupal root folder(say, ../my_private_files)
#ConfigurationTips

You should be aware that uploading files as 'Private file' will slow down the process of loading the files as Drupal has to be bootstrapped for every file that needs to be downloaded
#ConfigurationTips #BeAware

Code should always be pushed up(dev -> staging -> production) and databases should only be pushed down(production -> staging -> dev)
#DevelopmentTips

Get Raw SQL Query of drupal dynamic queries before executing it using $query->__toString();
#DebugTips

In VI-Editor, Press ESC key to come in command mode and for undo type :U and for redo type :Ctrl+R
#LinuxTips

Insert queries must always use a query builder object(layer of abstraction), allowing individual database drivers special handling for column values (if applicable), example case for LOB and BLOB fields.
#DatabaseQueryTips

Drupal uses the .inc extension to prevent files from being executed directly.
#DevelopmentTips

Popular Posts