Sunday 21 February 2016

Drupal 7 Advance tutorial

$sq_visitors = db_select('ab_visitors', 'a')->fields('a', array('nid'));
$sq_visitors->addExpression('COUNT(ref)', 'count');    
// sub query 2
$sq_clicks = db_select('ab_actions', 'a')->fields('v', array('nid'));
$sq_clicks->join('ab_visitors', 'v', 'v.ref = a.ref');
$sq_clicks->addExpression('COUNT(', 'clicks');    
// sub query 3
$sq_details = db_select('ab_visitors', 'a')->fields('a', array('nid'));
$sq_details->addExpression('COUNT(ref)', 'details');    
// main query
$query = db_select('node', 'n')
 ->fields('n', array('nid', 'title'))
 ->fields('a', array('field_a_or_b_value'))
 ->fields('s', array('field_sister_page_target_id'))
 ->fields('x', array('count'))
 ->fields('y', array('clicks'))
 ->fields('z', array('details'))
 ->condition('n.type', 'landing_page');
$query->join('field_data_field_a_or_b', 'a', 'a.entity_id = n.nid');
$query->join('field_data_field_sister_page', 's', 's.entity_id = n.nid');
$query->addJoin('LEFT OUTER', $sq_visitors, 'x', 'x.nid = n.nid');
$query->addJoin('LEFT OUTER', $sq_clicks, 'y', 'y.nid = n.nid');
$query->addJoin('LEFT OUTER', $sq_details, 'z', 'z.nid = n.nid');
$result = $query->execute()->fetchAll();

Automatically add a field to every new webform created

I recently had a need for users to be able to attach webforms to some node types to allow users to give feedback.
Each webform could be attached to multiple nodes.
When the webform data was submitted it needed to record which node it was attached to.
This was easy enough by adding a hidden field with the default value of %get[q] to record the nid.
However I didn’t want users to have to do this manually every time a webform was created, instead I wanted this field to be automatically included on every new webform added.
To do this I needed to act on the webform node after it had been inserted into the database so hook_node_submit was out of the question.
Instead I added an additional submit function on the webform_node_form to fire after the node module and webform module had finished doing their bit:
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
 if($form_id=='webform_node_form') $form['actions']['submit']['#submit'][] = 'misc_webform_form_submit';
Now in the new submit handler we simply add the new field to the webform and save the node (which is why the node had to be already created).
function misc_webform_form_submit($form, &$form_state) {
 $node = node_load($form_state['build_info']['args'][0]->nid);
 $node->webform['components'][] = array(
  'nid' => $node->nid,
  'cid' => 1,
  'pid' => 0,
  'form_key' => 'related_document',
  'name' => 'Related Document',
  'type' => 'hidden',
  'value' => '%get[q]',
  'extra' => array(
   'hidden_type' => 'value',
   'conditional_operator' => '=',
   'private' => 0,
   'conditional_component' => '',
   'conditional_values' => ''
  'mandatory' => 0,
  'weight' => 0,
  'page_num' => 1