أكواد دروبال سريعة

كتابات: 
Drupal code snippets you can use it when you doing custom code. Some of these codes is just for testing purposes since it may affect your website performance.
http://maps.google.com/maps?&z=14&q=24.789072,46.635504&ll=24.789072,46.635504
https://www.google.com/maps/place/24.827073,46.613617/@24.827073,46.613617,17z
https://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
/* maintenance-page styling */
body.maintenance-page #page{width:480px;background:#f7f7f7;margin:27px auto;padding:12px;text-align:center;
  border:1px solid #e7e7e7;border-radius:12px;}
body.maintenance-page #page a{text-decoration:none;font-weight:bold;}
body.maintenance-page #logo img{max-width:300px}
// CSS LTR numbers in Arabic pages.
unicode-bidi: embed; direction: ltr;

// Language switcher invoke.
$block = module_invoke('locale', 'block_view', 'language');
$block = module_invoke('search', 'block_view', 'search');
print $block['content'];
print render($block['content']);

// Invoke custom block.
$my_block_name = module_invoke('custom', 'block_view', 'my_block_name');
print render($my_block_name['content']);
// Print view in templates.
print views_embed_view('users', 'block_1');
            // Set default value for MVF field.
            $form['field_price']['und'][0]['#items'][0]['value'] = 122;
            $form['field_price']['und'][0]['#items'][0]['target_id'] = 157;
// Page tpl for specific node type.
function THEME_preprocess_page(&$variables) {
  if (isset($variables['node']->type)) {
    $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
  }
}
// Discard unsaved view.
Clear cache won't help. Just signout then signin again.

// FieldQuery to get order by custom field.
  $query = new EntityFieldQuery;
  $query->entityCondition('entity_type', 'uc_order', '=')
    ->fieldCondition('field_contract_reference', 'target_id', '160', '=')
    ->range(0, 1);

  // Load user data by custom field using Field Query.
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'user')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_mobile_number', 'value', '050505', '=');
  $result = $query->execute();

        // Generate thumb style image automatically to prepare it for first request.
        image_style_create_derivative(image_style_load('100x100'), $fileData->uri, image_style_path('100x100', $fileData->uri));

  // Upload and save file from $_FILES.
  if(isset($_FILES['file']['tmp_name'])){
    // Rebuild FILES to suite file_save_upload() needs.
    $_FILES['files']['tmp_name']['file'] = $_FILES['file']['tmp_name'];
    $_FILES['files']['name']['file'] = $_FILES['file']['name'];
    $_FILES['files']['size']['file'] = $_FILES['file']['size'];
    $_FILES['files']['error']['file'] = $_FILES['file']['error'];

    // Handle file uploads.
    $validators = array('file_validate_is_image' => array());

    // Check for a new uploaded logo.
    $fileData = file_save_upload('file', $validators, 'public://', FILE_EXISTS_RENAME);
    if (isset($fileData)) {
      // Move the file, into the Drupal file system
      if ($fileData = file_move($fileData, 'public://', FILE_EXISTS_RENAME)) {
        // Generate thumb style image.
        image_style_create_derivative(image_style_load('100x100'), $fileData->uri, image_style_path('100x100', $fileData->uri));

        // Add thumb size.
        $fileData->thumb = image_style_url('100x100', $fileData->uri);
        return $fileData;
      }else{
        return 'ERROR';
      }
    }else{
      return 'ERROR';
    }

  }else{
    return NULL;
  }

// Changing a field type from Integer to Decimal
// Source: http://drupal.stackexchange.com/a/151367/24113

// Change this to your field name, obvs.
$field = 'field_myfieldname';

// Update the storage tables
$tables = array('field_data', 'field_revision');
foreach ($tables as $table) {
  $tablename = $table .'_'. $field;
  $fieldname = $field .'_value';
  db_change_field($tablename, $fieldname, $fieldname, array(
    'type' => 'numeric',
    'precision' => 10,
    'scale' => 2,
    'not null' => FALSE,
  ));
}

// Fetch the current field configuration
$field_config = db_query("SELECT data FROM {field_config} WHERE field_name = :field_name", array(
    ':field_name' => $field,
  ))
  ->fetchObject();
$data = unserialize($field_config->data);

// Update the settings entry
$data['settings'] = array(
  'precision' => 10,
  'scale' => 2,
  'decimal_separator' => '.',
);

// Store the new field config, update the field type at the same time
db_update('field_config')
  ->fields(array(
    'data' => serialize($data),
    'type' => 'number_decimal',
  ))
  ->condition('field_name', $field)
  ->execute();    

// If you are confident about what bundles have instances of this field you can
// go straight to the db_query with a hardcoded entity_type / bundle.
$instances = field_info_field_map();
foreach ($instances[$field]['bundles'] as $entity_type => $bundles) {
  foreach ($bundles as $bundle) {

    // Fetch the field instance data
    $field_config_instance = db_query("SELECT data FROM {field_config_instance}
                                       WHERE field_name = :field_name
                                       AND entity_type = :entity_type
                                       AND bundle = :bundle", array(
        ':field_name' => $field,
        ':entity_type' => $entity_type,
        ':bundle' => $bundle,
      ))
      ->fetchObject();
    $data = unserialize($field_config_instance->data);

    // Update it with the new display type
    $data['display']['default']['type'] = 'number_decimal';

    // Store it back to the database
    db_update('field_config_instance')
      ->fields(array('data' => serialize($data)))
      ->condition('field_name', $field)
      ->condition('entity_type', $entity_type)
      ->condition('bundle', $bundle)
      ->execute();

  }
}

 20161223
// Redirect user after register
function custom_user_register_form($form, &$form_state) {
  $form_state['redirect'] = 'user/intro';
}

// Use custom page.tpl for specific content type.
// And the new template will be page--type-page.tpl.php
function CUSTOM_preprocess_page(&$vars) {
  if($vars['node']->type == 'page'){
    $vars['theme_hook_suggestions'][] = 'page__type_'.$vars['node']->type.'';
  }
}

// Add classes to submit button of sepcific form.
// Source: http://drupal.stackexchange.com/questions/4008/how-do-i-alter-the-submission-button-class
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id = 'my_form') {
    $form['actions']['submit']['#attributes']['class'][] = 'form-submitone';
  }
}

// Render node.
// Source: http://stackoverflow.com/questions/8564265/render-a-drupal-node
$nid = 739;
$nodeview = node_view(node_load($nid));
print drupal_render($nodeview);

  // Drupal enable service resource programmatically for existing endpoint.
  $endpoint = services_endpoint_load('ENDPOINT_NAME');
  $endpoint->resources['RESOURCE_NAME']['operations']['index']['enabled'] = 1;
  services_endpoint_save($endpoint);

/**
 * Alter views output.
 */
function HOOK_services_views_execute_view_alter(&$output, $view) {
  if ($view->name == 'test') {
    $paged_output = array(
      'results' => $output,
      'total_rows' => $view->total_rows,
    );
    $output = $paged_output;
  }
}

    // Drupal ubercart Save address extra field programmatically using module 
    // Extra Fields Checkout Pane ( uc_extra_fields_pane ) 
    // Since hook_ucxf_field is not work very well when $op = insert or update .. 
    // so you can handle that using this code:
    // $address_fields = UCXF_FieldList::getAllAddressFields();
    $order = uc_order_load(385);
    $fields = UCXF_FieldList::getFieldsFromPane('extra_delivery');
    uc_extra_fields_pane_value_save(
      array(
        'element_id' => $order->order_id,
        'element_type' => UCXF_Value::UCXF_VALUE_ORDER_BILLING,
        'field_id' => $fields['ucxf_FIELDNAME']->field_id,
        'value' => 'VALUE_HERE',
      )
    );

// Alter and override field value before display.
// Altering displayed value using Drupal hook.
/**
 * Implements hook_field_attach_view_alter().
 */
function HOOK_field_attach_view_alter(&$output, $context) {
  if ($context['entity_type'] == 'profile2') {
	if( isset($output['field_NAME']) ){
	  $output['field_NAME'][0]['#title'] = 'NEW_VALUE';
	}
  }

  if (isset($context['entity_type']) && ($context['entity_type'] == 'node') && isset($context['entity']) && isset($context['entity']->type) && ($context['entity']->type == 'CONTENT_TYPE') ) {
    if( isset($context['entity']->field_NAME['und']) ){
      // $context['entity']->field_NAME['und'][0]['value'] = 'NEW_VALUE1';
      // $output['field_NAME']['#object']->field_NAME['und'][0]['value'] = 'NEW_VALUE2';
      // $output['field_NAME']['#items'][0]['value'] = 'NEW_VALUE3';
      $output['field_NAME'][0]['#markup'] = 'NEW_VALUE';
    }
  }
}

  // Save new value in field collection.
  $MY_COLLECTION = array();
  $MY_COLLECTION['field_name'] = 'field_SUB_COLLECTION';
  $MY_COLLECTION['field_twitter_username'][LANGUAGE_NONE][0]['value'] = '';
  $MY_entity = entity_create('field_collection_item', $MY_COLLECTION);
  $MY_entity->setHostEntity('node', $node); // If node use this line.
  $MY_entity->setHostEntity('user', $user); // If user use this line.
  $MY_entity->save(); 

  // -------------------

  // Update field collection value by field collection id.
  $field_MY_COLLECTION = field_collection_item_load($node->field_MY_COLLECTION['und'][0]['value']);
  $field_MY_COLLECTION->field_SUB_COLLECTION['und'][0]['value'] = 'NEW_VALUE';
  $field_MY_COLLECTION->save(TRUE);

  // -------------------

  // Delete field collection values. source: https://www.drupal.org/node/2684165
  foreach ($node->[FIELD_NAME][LANGUAGE_NONE] as $key => $value) {
    // Build array of field collection values.
    $field_collection_item_values[] = $value['value'];
    // Unset them.  
    unset($node->[FIELD_NAME][LANGUAGE_NONE][$key]);
  }
  // Delete field collection items.
  entity_delete_multiple('field_collection_item', $field_collection_item_values);

  // 20170210
  function template_preprocess_node(&$variables) {
    $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
  }

  // OR change date type.
  if( isset($variables['node']->created) ){
    $created_date = format_date($variables['node']->created, 'custom', 'F d, Y');
    $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $created_date));
  }

  // OR in tpl file.

  // 20170211
  // Get theme logo from theme settings.
  global $theme_key;
  $theme_logo_url = theme_get_setting('logo', $theme_key);

// 20170214
// Get taxonomy terms by vocabulary name.
$vocab = taxonomy_vocabulary_machine_name_load('cities');
$terms = taxonomy_get_tree($vocab->vid);
foreach($terms as $term){
  $termData = taxonomy_term_load($term->tid);
}

  // 20170214
  // Get all terms from specific vocabulary by taxonomy custom field.
  $vocab = taxonomy_vocabulary_machine_name_load('VOCABULARY_NAME');
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
     ->propertyCondition('vid', $vocab->vid)
     ->fieldCondition('field_custom', 'value', 'AAAA', '=');
  $result = $query->execute();
  foreach ($result['taxonomy_term'] as $val) {
    $term = taxonomy_term_load($val->tid);
  }

  // Getting nodes between period from custom field.
  $first_day = date('Y-m-d 00:00:01', (time() - (86400*2) ) );
  $last_day =  date("Y-m-d 00:00:01", (time() - (86400*4) ) );
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
            ->entityCondition('bundle', 'CONTENT_TYPE')
            ->fieldCondition('field_CUSTOM', 'value', array($first_day, $last_day), 'BETWEEN');
  $result = $query->execute();

  // 20170218
  // Get all system users.
  $query = db_select('users', 'u');
  $query->fields('u', array('uid'))->condition('uid', 0, '>');
  $result = $query->execute();
  while($record = $result->fetchAssoc()) {
    $thisUser = user_load($record['uid'], TRUE);
  }

  // 20170220
  // Useful Drupal things.
function custom_menu_alter(&$items) {
  $items['node/add']['access callback'] = FALSE;
}

  // 20170301
  // DB query to get specific field value from database.
  $uid = db_select('users', 'u')
      ->fields('u', array('uid'))
      ->condition('name', $form_state['values']['user'])
      ->execute()
      ->fetchField();
  print $uid;

  // 20170316
  // Update field settings programmatically.
  // To be used in hook_update_N.
  $instance_info = field_info_instance('node', 'field_NAME', 'CONTENT_TYPE_NAME');
  print_r($instance_info); // Print to see the structure.
  $instance_info['description'] = 'DESCRIPTION';
  field_update_instance($instance_info);

// 20170321
/**
 * Get view result count.
 */
function custom_get_view_result_count($view_name, $view_display, $args = array(), $items_per_page = 0){
  // Source: https://api.drupal.org/comment/46928#comment-46928
  $view = views_get_view($view_name);
  $view->set_display($view_display);
  $view->set_arguments($args);
  $view->set_items_per_page($items_per_page);
  // change the amount of items to show
  //$view->set_items_per_page(4);
  $view->pre_execute();
  $view->execute();
  return count($view->result);
}

/**
 * Get view result.
 */
function custom_get_view_result($view_name, $view_display, $args = array(), $items_per_page = 0){
  // Source: https://api.drupal.org/comment/46928#comment-46928
  $view = views_get_view($view_name);
  $view->set_display($view_display);
  $view->set_arguments($args);
  $view->set_items_per_page($items_per_page);
  // change the amount of items to show
  //$view->set_items_per_page(4);
  $view->pre_execute();
  $view->execute();
  return $view->result;
}

  // Drush check if database connection is working or not.
  drush sqlq --db-prefix "SELECT uid FROM {users} WHERE uid=1"

  // check drush status with verbose and debug parameters.
  drush -vd status

// 20170327
// Helper function to create block programmatically.
/**
 * Programmatically creates block.
 * This function is helpful in automated process.
 */
function custom_create_block($attributes) {

  // Defaults
  $defaults = array(
    'title'      => '',
    'desc'       => '',
    'body'       => '',
    'format'     => 'filtered_html',
    'visibility' => 0,
    'pages'      => '', // path
    'custom'     => 0,
    'module'     => 'block',
    'roles'      => array(),
    'regions'    => array(),
  );
 
  // Attributes
  $attr = array(
    'title' => (isset($attributes['title']))?$attributes['title']:$defaults['title'],
    'desc' => (isset($attributes['desc']))?$attributes['desc']:$defaults['desc'],
    'body' => (isset($attributes['body']))?$attributes['body']:$defaults['body'],
    'format' => (isset($attributes['format']))?$attributes['format']:$defaults['format'],
    'visibility' => (isset($attributes['visibility']))?$attributes['visibility']:$defaults['visibility'],
    'pages' => (isset($attributes['pages']))?$attributes['pages']:$defaults['pages'],
    'custom' => (isset($attributes['custom']))?$attributes['custom']:$defaults['custom'],
    'module' => (isset($attributes['module']))?$attributes['module']:$defaults['module'],
    'roles' => (isset($attributes['roles']))?$attributes['roles']:$defaults['roles'],
    'regions' => (isset($attributes['regions']))?$attributes['regions']:$defaults['regions'],
  );
 
  // load the function
  module_load_include('inc', "block", "block.admin");
 
  // make believe variable
  $form_state = array();
 
  // Fill variable
  $form_state['values']['title']          = $attr['title'];
  $form_state['values']['info']           = $attr['desc'];
  $form_state['values']['body']['value']  = $attr['body'];
  $form_state['values']['body']['format'] = $attr['format'];
  $form_state['values']['visibility']     = $attr['visibility'];
  $form_state['values']['pages']          = $attr['pages'];
  $form_state['values']['custom']         = $attr['custom'];
  $form_state['values']['roles']          = $attr['roles'];
  $form_state['values']['module']         = $attr['module'];
  $form_state['values']['regions']        = $attr['regions'];
 
  // Create block
  block_add_block_form_submit(array(), $form_state);

}

  // Use:
  // Create block and assign it to Footer region.
  custom_create_block(array(
    'title' => 'TEST TITLE',
    'desc' => 'BLOCK DESCRIPTION',
    'body' => 'BODY TEXT.',
    'format' => 'plain_text',
    'regions' => array('THEME_NAME'=>'footer'),
  ));

  // Theme table pagination.
  // This will paginate all results you have.
  $header = array(
    'name' => array('data' => t('Name')),
    'date' => array('data' => t('Date')),
  );

  $rows = array();
  $rows[0]['name'] = 'Ahmad';
  $rows[0]['date'] = '2017';
  $rows[1]['name'] = 'Ibrahim';
  $rows[1]['name'] = '2016';

  // Initialize pager.
  $results_count = count($rows); // You can get this from query if results stored in your database.
  $per_page = 50;
  $current_page = pager_default_initialize($results_count, $per_page);

  // Split your list into page sized chunks.
  $chunks = array_chunk($rows, $per_page, TRUE);

  // Show the appropriate items from the list.
  $output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page]));

  // Show the pager.
  $output .= theme('pager', array('quantity', $results_count));

  print $output;

// 20170407
// Retrieve last nid inserted by user in last 30 seconds.
$uid = $user->uid;
$content_type = 'article';
$interval_seconds = 30;
$nid = db_query("SELECT nid AS count FROM {node} WHERE uid = :uid AND type = :type AND created > :created ORDER BY nid DESC",
        array(':uid' => $uid, ':type'=>$content_type, ':created'=>(time() - $interval_seconds) ))->fetchField();
print 'NID:'.$nid;

// 20170407
// Count directly from node table using db query.
$the_count = db_query("SELECT COUNT(nid) AS count FROM {node} WHERE uid = :uid", array(':uid' => $uid))->fetchField();
// Count directly from taxonomy table using db query.
$the_count = db_query("SELECT COUNT(nid) AS count FROM {taxonomy_index} WHERE tid = :tid", array(':tid' => $tid))->fetchField();

// 20170407
// Limit depth level of Simple hierarchical select shs contrib module by using hook_shs_term_get_children_alter(). 
function HOOK_shs_term_get_children_alter(&$terms, &$alter_options) {
  if($alter_options['parent'] == 2){
    $terms = FALSE;
  }
}

// 20170407
// Alter view and change filter value if has no more than 2 parents.
function HOOK_views_pre_view(&$view) {
  if ($view->name === 'taxonomy_references'){
    $view_filters = $view->display_handler->get_option('filters');
    //$view_filters['parent']['value'] = $view_filters['parent']['value'];
    if(isset($view->args) && isset($view->args[0])){
      $parents_count = count(taxonomy_get_parents_all($view->args[0]));
      if($parents_count > 2){
        $view_filters['parent']['value'] = $view_filters['parent']['value'];
      }else{
	$view_filters['parent']['value'] = 0;
      }
    }

    $overrides = array();
    $overrides['filters'] = $view_filters;
    foreach ($overrides as $option => $definition) {
      $view->display_handler->override_option($option, $definition);
    }
  }
}

  // Source: http://www.drupaldump.com/view-3-alter-filters-programmatically

// 20170407
// Limit taxonomy deep level.
// CUSTOM_CONFIG
/**
 * Implement hook_form_FORM_ID_alter().
 */
function HOOK_form_product_node_form_alter(&$form, &$form_state, $form_id) {
  // Remove third and up depth levels.
  if( isset($form['field_NAME']) && is_array($form['field_NAME'][LANGUAGE_NONE]['#options']) ){
    foreach($form['field_NAME'][LANGUAGE_NONE]['#options'] as $index => $value){
      if(strstr($value, '---')){
        unset($form['field_NAME'][LANGUAGE_NONE]['#options'][$index]);
      }
    }
  }
}

// 20170407
// Get all term related nodes.
$alltermNodes = taxonomy_select_nodes($term->tid);
print_r($alltermNodes);
print count($alltermNodes);

// 20170409
// CUSTOM_CONFIG
// Delete all terms from a vocabulary (bulk delete).
// Source: http://drupal.stackexchange.com/questions/38275/how-to-delete-all-terms-from-a-vocabulary-bulk-delete
$vocabulary = taxonomy_vocabulary_machine_name_load('my_custom_vocabulary');
foreach (taxonomy_get_tree($vocabulary->vid) as $term) {
  taxonomy_term_delete($term->tid);
}

// 20170503
// Logout all users using drush command.
// Source: https://drupal.stackexchange.com/questions/21681/how-to-logout-all-active-users/97693#97693
// You can empty the sessions table using drush
drush sqlq "TRUNCATE sessions"

// or if you have set prefixes for table names:
drush sqlq --db-prefix "TRUNCATE {sessions}"

// 20170510
// Drupal cronjob for multisite.
// Source: https://www.drupal.org/docs/7/setting-up-cron/multisite-cron
* * * * * cd /srv/www/sites; drush @sites core-cron --yes

  // 20170516
  // Create taxonomy vocabulary programmatically.
  $NAME_vocab = (object) array(
     'name' => 'NAME OF VOCABULARY',
     'description' => 'THE DESCRIPTION',
     'machine_name' => 'MACHINE_NAME_OF_YOUR_VOCABULARY',
  );
  taxonomy_vocabulary_save($NAME_vocab);

  // Delete taxonomy vocabulary programmatically.
  $NAME_vocab = taxonomy_vocabulary_machine_name_load('MACHINE_NAME_OF_YOUR_VOCABULARY');
  taxonomy_vocabulary_delete($NAME_vocab->vid);


http://browse-tutorials.com/snippet/enable-or-disable-comments-using-nodesave-drupal-7
Recommended module in Squircle List:
Field_slideshow
Suggestion for Drupal website:
- The module description should have template so developers write description depending on this template it will be better than current way when every module has own template:
https://www.drupal.org/project/reg_with_pic
https://www.drupal.org/project/simplenews
https://www.drupal.org/project/linked_field
https://www.drupal.org/project/autocomplete_deluxe
https://www.drupal.org/project/content_taxonomy
https://www.drupal.org/project/hierarchical_select

VERY GOOD WEBSITE FOR DRUPAL SNIPPETS <3
http://dropbucket.org/

Some notes for Drupal

- Group style output in views theme with title h3 for (views-view-unformatted.tpl.php) and all nested templates to be in one separate div class. 20170328 - When using menu_block module and assign it to sidebar for example and going to browsing admin/structure/menu/manage/menu-NAME while you enable translation. Then sidebar menu will have both language since it take the menu items from cached result. 20170405
I'm putting this here so I remember for my daily use. If it helps you as well then even better :)
ملفات مرفقة: 

فضلاً إذا أعجبتك هذه الصفحة لاتنسى أن تقوم بمشاركتها