D7 Drupal Pragmático - pierregermain/MyDrupal GitHub Wiki

Updating

https://www.drupal.org/docs/7/creating-custom-modules/howtos/examples-for-database-update-scripts-using-hook_update_n-how

Pasar Variables a JS desde Drupal en plan global

Desde tu php

drupal_add_js(array('nombre-de-mi-array' => array('term_tid' => $term->tid)), 'setting');
drupal_add_js(array('mnombre-de-mi-array' => array('term_name' => $term->name)), 'setting');

Desde tu JS

Drupal.settings.nombre-de-mi-array.term_name

Hacking Drupal

Con este truco podemos ejecutar drupal sin cargar toda la instancia. En el docroot crear functions.php

<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

module_load_include('nombre_del_modululo_a_ser_probado');
  • todas las funciones nuevas, anteponerles un namespace nuevo para que no choquen contra otras funciones.
  • poner die en el que vamos a renderizar

Trabajo con Ajax

Callback

Esta es la función que se ejecuta al hacer Ajax

/**
 * Ajax Callback Function to change the value in DB
 * @param $form
 * @param $form_state
 * @return mixed
 */
function bs_callback($form, $form_state){

  // Obtener algún valor actual del Form
  $node = $form_state['node'];

  // Update de algun dato (ver funciones de field collection)
  bs_set_algo($node);
}

Dicha función es llamada desde nuestro Form

function bs_form($form, &$form_state, $node, $valor) {
  $form = array();

  $form_state['node'] = $node;

  // We construct the Checkbox Form with the necessary information used later
  // by Ajax
  $form['display_section'] = array(
    '#type' => 'checkbox',
    '#title' => t('Algún título'),
    '#default_value' => $valor,
    '#ajax' => array(
      'callback' => 'bs_callback',
      'event' => 'change',
      'progress' => array(
        'message' => NULL,
      )
    )
  );

  return $form;
}

Form Padre

(...)

  // Custom Checkbox used to Enable/Disable Photo Sections
  $custom_bs = drupal_get_form('bs_form', $node, $valor);

(...) 

      return theme(
        'nombre_del_theme', array(
          'filters' => drupal_get_form(...),
          'bs' => $custom_bs,
          'view' => $view_preview,
          'view_wrapper' => ... ,
        )

Imprimir en el tpl


      print render($bs);

Trabajo con Field Collection

Set de Field Collection

/**
 * @param $nid
 * @param $new_value
 * @return bool
 */
function bs_set_valores($node, $new_value){

  // Wrap it with Entity API
  $node = entity_metadata_wrapper('node', $node);

  // Get the first item from the muli-value field collection
  $raw_collection = $node->field_data->value();
  // Wrap it with Entity API
  $collection = entity_metadata_wrapper('field_collection_item', $raw_collection);
  $collection->field_of_field_collection = $new_value;

  // we save the new value to the entity
  $collection->save();

  return TRUE;
}

Inicializar Field Collection

/**
 * Function to get the field_data ID of a Field Collection
 * Also does it initialize the field_data Field Collection if not present
 * @param $node
 * @return int

 */
function bs_inicializar_fc($node){

  $fc_id = $node->field_data[LANGUAGE_NONE][0]['value'];

  // Check if fc_id is empty
  if (!isset($fc_id)){
    // We create a new Field Collection Object
    $fc_item = entity_create('field_collection_item', array('field_name' => 'field_data'));
    // We attach the FC to the Node
    $fc_item->setHostEntity('node', $node);
    // This helps to work with the values of the FC
    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc_item);
    // We initialize our Field Collection Items
    $fc_wrapper->field_machine_name_of_the_field_collection_item_1->set('1');// Agregar todos los campos aqui
    // Now save the field collection entity to the database
    $fc_wrapper->save(TRUE);
    // Now save the node
    node_save($node);

    $fc_id = $node->field_data[LANGUAGE_NONE][0]['value'];
  }

  return $fc_id;

}

Obtener Valores de un Field Collection

/**
 * Function to get the data field collection item of a Field Collection in a node
 * @param $fc_id
 * @return string
 */
function bs_get_fc_values($node){

  // This code is used to get the current value of the field collection
  // if not present in initializes the field
  $fc_id = bs_inicializar_fc($node);

  // We get the Entity of the Field Collection using its ID
  $fc_entity = entity_load('field_collection_item', array($fc_id));

  // We get the correct Field Collection item value
  $fc_item_value = $fc_entity[$fc_id]->field_item_machine_name_1[LANGUAGE_NONE][0]['value'];


  return $fc_item_value;
}

Trabajo con Taxonomías

Obtener Nombre

/**
 * Get the taxonomy name
 */
function bs_get_taxonomy_name($tid){
    $term = taxonomy_term_load($tid);
    $name = $term->name;
    return array('taxonomy_name' => $name);
}

Uso de UUID's

desde /sites/default/config

$conf['vid_machine_name']['tax1'] = '5d9f1331-f4d3-40c3-9a22-f47711a69a8b';
$conf['vid_machine_name']['tax2'] = '6d09fcc7-7455-48ad-a186-58b28fd04e16';

desde hook_init

/**
 * Implements hook_init()
 */
function mrt_photodashboard_init(){
  $vocubulary = variable_get('vid_machine_name', array());

  if ($type_vocabulary = taxonomy_vocabulary_machine_name_load('vocabulary_machine_name')) {
    
    /* Revisar 
    * @param $max_depth
    *   The number of levels of the tree to return. Leave NULL to return all levels.
    * @param $load_entities
    *   If TRUE, a full entity load will occur on the term objects. Otherwise they
    *   are partial objects queried directly from the {taxonomy_term_data} table to
    *   save execution time and memory consumption when listing large numbers of
    *   terms. Defaults to FALSE.*/
    
    if ($terms = taxonomy_get_tree($type_vocabulary->vid, 0, NULL, TRUE)) {
      foreach ($terms as $term) {
        switch ($term->uuid) {
          case $vocubulary['term_name1']:
            define ('MACHINE_NAME_VOCABULARY__TERM_NAME1__TID', $term->tid);
            define ('MACHINE_NAME_VOCABULARY__TERM_NAME1__NAME', $term->name);
            break;
          case $vocubulary['term_name2']:
            define ('MACHINE_NAME_VOCABULARY__TERM_NAME2__TID', $term->tid);
            define ('MACHINE_NAME_VOCABULARY__TERM_NAME2__NAME', $term->name);
            break;
        }
      }
    }
  }
}

Otras Funciones interesantes

Mail

/**
 * Get the User Email
 */
function bs_get_user_mail($uid){
    $user=user_load($uid);
    return array('user_email' => $user->mail);
}