Showing posts with label drupal. Show all posts
Showing posts with label drupal. Show all posts

Saturday, July 26, 2014

Configuring Apache to return CORS headers for Drupal Services

Here's what I did to configure Apache to return the proper CORS headers for my webapp consumption which is written in AngularJS:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header always set Access-Control-Allow-Headers "accept, content-type"
Header always set Access-Control-Allow-Credentials "true"

That can be set in the VirtualHost tags for your server instance. Please note that Access-Control-Allow-Origin value shouldn't be set to * in a production environment. This should only be done for testing environments. The mod_headers module must be enabled in Apache for this configuration to work.

Having these options should be sufficient. But since I'm using Drupal 7 Services, it doesn't play well with pre-flight call which uses HTTP OPTIONS method. Drupal services will return a 404 even if the correct endpoint is specified when OPTIONS method is used.

Here's the additional config using mod_rewrite to return HTTP 200 for all OPTIONS requests:

RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L,E=HTTP_ORIGIN:%{HTTP:ORIGIN}]]

Tuesday, January 28, 2014

Setting "placeholder" attribute in Drupal 7 form elements

Here's a quick way on how to use HTML5 placeholder attribute in Drupal forms. Example below is altering the login form in a custom theme:

function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login') {
    $form['name']['#attributes'] = array('placeholder' => $form['name']['#title']);
    
    $form['pass']['#attributes'] = array('placeholder' => $form['pass']['#title']);
  }
}

Thursday, August 15, 2013

Using Drupal's hook_theme() for custom theming

This is a short post on how to use Drupal's hook_theme() to customize a layout within your own custom module.

Start off with implementing the hook_theme() function in your module:

/**
 * Implements hook_theme()
 * @param type $existing
 * @param type $type
 * @param type $theme
 * @param type $path
 * @return array
 */
function mypm_theme($existing, $type, $theme, $path) {
  $themes = array(
    'chat' => array(
      'variables' => array(
        'message' => NULL,
        'author' => NULL,
        'date_posted' => NULL,
        'is_sender' => NULL,
        'product_url' => NULL,
      )
    ),
  );

  return $themes;
}

What I've declared in the function is that I have a custom theme function called "chat". It takes in 5 variables defined in the variables array. As always, remember to clear Drupal's cache once you've defined a new theme function. Now that we have declared our theme function, we'll have to implement it:

function theme_chat($variables) {
  $main_style = 'chat-holder';

  if (isset($variables['is_sender'])) {
    if ($variables['is_sender'] == TRUE) {
      $main_style .= ' chat-holder-sent';
    }
    else {
      $main_style .= ' chat-holder-received';
    }
  }
  else {
    $main_style .= ' chat-holder-received';
  }

  $output = '
'; $output .= '
'; $output .= $variables['author']; $output .= '
'; $output .= '
'; $output .= format_date($variables['date_posted']); $output .= '
'; $output .= '
'; $output .= nl2br(check_plain($variables['message'])); $output .= '
'; $output .= $variables['product_url']; $output .= '
'; return $output; }

The theme_chat function builds the HTML output based on the variables passed in. You can now use this theme function in your form or normal page callback like below:

    $chat_output .= theme('chat',
            array(
                'message' => $chat->message,
                'author' => $chat->author_name,
                'date_posted' => $chat->created,
                'is_sender' => $chat->sender,
                'product_url' => $chat->product_url,
            ));

Tuesday, July 30, 2013

SQL UNION using Drupal db_select

Here's how to use Drupal's db_select function to perform a SQL UNION like below:

select uid from users where type = 'i'
union
select uid from users_archive where type = 'i'

Bad example, but I can't think of a proper example now :)

Drupal db_select version:

$q1 = db_select('users', 'u')
       ->fields('u', array('uid'))
       ->condition('type', 'i');

$q2 = db_select('users_archive', 'ua')
       ->fields('ua', array('uid'))
       ->condition('type', 'i');

$q1->union($q2);

$results = $q1->execute();

Wednesday, July 17, 2013

SQL JOINS using Drupal db_select

Here's how to use Drupal's db_select function to perform a SQL INNER JOIN like below:

SELECT n.*, u.name FROM node n 
INNER JOIN users u on n.uid = u.uid
WHERE u.id = 3

Drupal db_select version:

$q = db_select('node', 'n');
$q->join('users', 'u', 'u.uid = n.uid');

$q->fields('n');
$q->fields('u', array('name'));

$q->condition('u.uid', 3);
  
$results = $q->execute();

Monday, July 1, 2013

Formatting Drupal's UNIX timestamp dates

Drupal stores date/time value as int columns in MySQL. Its value is UNIX timestamp based. You will not be able to determine the actual date/time by selecting from the table.

Here's a convenient way to convert the date/time columns directly from SQL:

SELECT cid, data, FROM_UNIXTIME(created) FROM main_cache

You can also use this in the WHERE clause like below:

SELECT COUNT( * ) 
FROM  main_commerce_product 
WHERE FROM_UNIXTIME( created ) 
BETWEEN  '2013-07-17 00:00:00'
AND  '2013-07-17 23:59:59'

Here's the result:


Friday, June 14, 2013

Programmatically parse webform submissions

Here's how to retrieve a webform submission and process its submission values programmatically. We'll need two IDs. First is the webform node id (nid) and the second is the submission id (sid). You can retrieve these IDs from viewing the webform results listing. The URL is something like below:

http://localhost/dt/node/124/submission/18

In this case, 124 is the node id while 18 is the submission id.

Now, on to the code.

$nid = 124;
$sid = 18;

$webform = node_load($nid);
$sub = webform_get_submission($nid, $sid);

// Capture the component IDs for easier array mapping.
foreach ($webform->components as $cid => $cfield) {
  $components[$cfield['form_key']] = $cid;
}

// Retrieve user info
$user_info = new stdClass();
$user_info->username = $sub->data[$components['username']][0];
$user_info->email = $sub->data[$components['e_mail_address']][0];

// And the rest of your processing...

You can use this method to easily reference the fields stored in the row by field name instead of index number.

Monday, May 27, 2013

SELECT COUNT(*) using Drupal db_select

Here's how to use Drupal's db_select function to perform a SQL equivalent of:

SELECT COUNT(uid) FROM users WHERE name = $username

Sunday, September 23, 2012

Formatting currency in Drupal Commerce

A project I've been involved in uses Drupal Commerce (DC) to manage currency and products.  Here's how to format "normal" values to be DC friendly.  Reason for doing so?  DC stores amount fields as INTEGER.  For instance, an amount of USD99 is stored as 9900 in the table.

There are several functions which you need to make this happen.

commerce_currency_decimal_to_amount(300, commerce_default_currency());