title: Views: custom field for sort criteria

text:
# Question
Title: Views: custom field for sort criteria
My View has a " Global: Custom text"- Field that contains Integers (1,3, ..). The field is overwritten by a php-Template.

I want to add this field to "Sort criteria", so the view can be sorted - but how can I do this? the custom field does not show under "Sort criteria", how do i make it sortable?

# Answer
> 2 votes
You cannot sort by a global text field in views by default.

This is because global text field values are not populated until the view is being rendered, but the sorting of the view is done in the sql query, which is much before the global text field value exists.

One way to do it would be to add sorting ability with javascript. Because this would happen on the front end it could work for any fields. The views tablesorter module does this for drupal 6 table views but I have not yet found the time to make a drupal 7 version.

Another option is to make a custom views field handler that actually includes the data in the sql query or just making a custom sort handler.

For more information on creating handlers install the advanced help module and then go to the advanced help UI and look at the views help (advanced\_help/views).

---
Tags: entities, views
---


# Question
Title: Override Profile2 with account fields and values
I have created a new Profile Type with Profile2 module. Now I want to override it, importing three existing fields from my original Account (First Name, Last Name, Email) with their own values (that have already been set in the registration process).

I think I must try copying `profile2.tpl.php` on my theme page, but no changes seems to happen. Any idea about how to do it?

# Answer
> 0 votes
Profile2 modules gives profile entity apart from we have in default as user.I am not putting the codes , but here is my idea,

1. manually add those three fields to the profile you have created.
2. loop through all users, load their profile, I guess you can use profile2\_load\_by\_user() to load the profile inside the loop
3. Check if you are getting the added fields in the loaded profile object.
4. Map the fields on user entity to profile entity.
5. save the profile using profile2\_save() 5.
6. Delete the fields from user entity, once you ensure mapping is in the way you want.

**NOTE:** function listed may need a replacement,as I have not tested the workflow.

---
Tags: theming
---


# Question
Title: Remove Caption and next/previous arrows from Colorbox for Node
To display Node in Modal, I am using colorbox node module

I changed the settings in Colorbox module to not display any information like Current, Next, Previous, etc. like:

however I can still see that small arrow and node count as shown in the picture below:

How do I remove these small arrows and count overall and only have that Cross(X) to close the Modal.

**Edit**: I cleared the cache and this 4 of 41 is gone... but those arrows are still there.

# Answer
This is fixed in the latest DEV version.
> 0 votes

# Answer
> The only way I found to do this was to change my theme css file (I use an Omega \>theme so used global.css) and add:
>
> #cboxPrevious, #cboxNext { width:0; }
>
> I initially tried display:none but something is overriding it.

display:none works if you use !important
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How can I disable the node page for a specific content type? (But still use colorbox-node)
I use colorbox en colorbox-node to show the content of a node but I don't want people to access the node page for that content type.

How can I disable the node's detailpage and still access all the content in colorbox-node?

# Answer
> 0 votes
In node.tpl.php you can test if node is accessed directly, and if so - redirect him to page with the same node inside colorbox. Or any other page, of course.

# Answer
> 0 votes
Check for the "view mode" in your node template.

```
$view_mode: View mode; for example, "full", "teaser", "colorbox".

```

---
Tags: nodes, javascript
---


# Question
Title: Migrate Module and AddressField Locality/City Lookup in PrepareRow Fails
I'm running a migration to move volunteers from a csv file to drupal. I have written the following code.

```
<?php
/**
    * @file
    * Migration for Volunteer File
*/

ini_set('auto_detect_line_endings', TRUE);

class VolunteerMigration extends Migration {

public function __construct($arguments) {
    parent::__construct($arguments);

    $this->description = t('Imports Volunteers from CSV file ');

    // Create a source object
    $columns = array(
        0 => array('pkid', 'PKID'),
        1 => array('fname', 'First Name'),
        2 => array('lname', 'Last Name'),
        3 => array('email','Email'),
        5 => array('dayphone','DayPhone'),
        6 => array('eveningphone','EveningPhone'),
        7 => array('address','Address'),
        8 => array('city', 'City'),
        9 => array('state','State'),
        10 => array('postalcode','zip'),
        11 => array('occupation','Occupation'),
        12 => array('interests','Interests'),
        13 => array('created','Timestamp'),
    );
    $address_arguments = array(
        'first_name' => array('source_field' => 'fname'),
        'last_name' => array('source_field' => 'lname'),
        'thoroughfare' => array('source_field' => 'address'),
        'locality' => array('source_field' => 'city'),
        'administrative_area' => array('source_field'=>'state'),
        'postal_code' => array('source_field' => 'postalcode'),
    );
    $this->source = new MigrateSourceCSV('/mnt/www/cylindrical/theoregonproject.com/data/drvollist.csv', $columns, array('header_rows' => 1));

    // Create a destination object
    $this->destination = new MigrateDestinationNode('volunteers');

    // Create a map
    $this->map = new MigrateSQLMap(
        $this->machineName,
        array(
            'pkid' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
            ),
        ),
        MigrateDestinationNode::getKeySchema(),
        'campaign_migration'
    );

    // Create Mappings
    $this->addFieldMapping('title', NULL)->DefaultValue('Volunteer');
    $this->addFieldMapping('field_volunteer_address')
        ->arguments($address_arguments);
    $this->addFieldMapping('field_volunteer_id', 'pkid');
    $this->addFieldMapping('field_email', 'email');
    $this->addFieldMapping('field_dayphone', 'dayphone');
    $this->addFieldMapping('field_eveningphone', 'eveningphone');
    $this->addFieldMapping('field_occupation', 'occupation');
    $this->addFieldMapping('field_interests', 'interests')
            ->separator(',');
    $this->addFieldMapping('created','created');

}

public function prepareRow($row) {

    if ( $row->zip ) {
        $row->city = zipcity($row->zip);
    }
}

public function zipcity($zip) {
    $ch = curl_init('http://ziptasticapi.com/' . $zip);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    $result = curl_exec($ch);
    curl_close($ch);

    $json = json_decode($result,true);

    return $json['city'];
}
}
?>

```

I'm am using the ziptastic api to fill in the cities using the zipcode. Running the migration returns all except the address portion of the migration. The zipcity function works as expected (returns city given a zipcode) but none of the address arguments are migrated.

I have adapted this code from a previous and successful migration minus the preparerow / zipcity additions.

Mark

# Answer
Found the issue. When using the addressfield module, you should have field mappings that allow for preparerow to work. I thought that the address\_arguments array was enough to create the field maps. Also I was using the csv column title 'Zip' instead of the the mapped field title 'postalcode'

Under my address field mapping I added the following code.

```
    $this->addFieldMapping(NULL, 'fname');
    $this->addFieldMapping(NULL, 'lname');
    $this->addFieldMapping(NULL, 'address');
    $this->addFieldMapping(NULL, 'city');
    $this->addFieldMapping(NULL, 'state');
    $this->addFieldMapping(NULL, 'postalcode');

```

I also moved the function zipcity to my helper function file to allow other migrations to use it if needed.

This post https://drupal.org/node/1326044 was key into figuring out the missing link.
> 1 votes

---
Tags: migrations, entities
---


# Question
Title: Allow views custom plugins on a particular filter criteria only
I have started to create a custom views plugin to sort the fields in view according to the video views(not node views but youtube views) on my video content type.
This is how I've implemented `hook_views_data()`:

```
$data = array();

$data['post_video_views']['table']['group'] = t('PROJECT_NAME');

$data['post_video_views']['table']['join'] = array(
  'node' => array(
    'left_field' => 'nid',
    'field' => 'nid',
  ),
);

$data['post_video_views']['popular'] = array(
  'title' => t('Popular videos'),
  'help' => t('Youtube views'),
  'field' => array(
    'handler' => 'views_handler_field',
  ),
  'sort' => array(
    'handler' => 'views_handler_sort',
  ),
);

```

This gives me an option to sort ascending and descending and also provides the fields to add. Everything working fine till this step.

Now, I want that this options should only appear when when I have the following filter criteria satisfied: `Content: Type (= Video)`. How can this be done? I know this should be simple to do but just don't know where to do it.

P.S: I am using Views 3 with D 7.22.

# Answer
> 0 votes
You can use a hook\_form\_alter to add a conditional display of your filter based on the video selected option.

```
 /*
  *Implement hook_form_alter
  */

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
   //dsm($form) -> to get the form['#id']
   if ($form['#id'] == 'views-exposed-form-YOUR_VIEWS_NAME-DISPLAY') {
      $form['YOUR_FIELD_NAME']['#states'] = array(
       'visible' => array(
        ':input[name="THE_VIDEO_FIELD_NAME"]' => array('value' => 'THE_VIDEO_KEY'),
        ),
     );

   }
}

```

YOUR\_FIELD\_NAME is the field to display conditionally

---
Tags: 7, views
---


# Question
Title: How to print uc-auction-bid-table-form seperately in product node template using ubercart?
I am trying to print uc-auction bid table separately in product node template. I have printed the add-to-cart button separately like this in the node--product.tpl.php.

```
<?php
 print drupal_render(drupal_get_form('uc_product_add_to_cart_form_'.$node->nid, $node));
?>

```

Similarly how can i print uc\_auction form(uc-auction-bid-table-form) separately. I can't able to print like above for uc-auction because it doesn't have any nids associated it. Any help will be really appreciated.

Thanks in advance.

# Answer
In your module which implements hook\_node\_view, to accomplish this, do something along these lines:

```
   function module_node_view($node, $view_mode, $langcode) {
      // Do business logic here like if these node should have the form then...
      $node->content['your_from'] = array(
        '#markup' => drupal_render(drupal_get_form('uc_auction_bid_table_form')),
        '#weight' => 10,
        // you may or may not need this based on your implementation : '#theme' => 'theme_uc_auction_bid_table',
      );
    }

```

Drupal 6: use hook\_nodeapi

```
function modulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'view':
      // Do business logic here like if these node should have the form then...
      $node->content['uc_auction_bid_table'] = array(
        // Try drupal_render if theme does not work
       '#value' => theme('uc_auction_bid_table', drupal_get_form('uc_auction_bid_table_form')),
        '#weight' => 10,
      );
      break;
  }
}

```
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: Adding rel=canonical meta tag in comment paginated node pages
I posted this question: Google showing pages with ?page=2 urls and also read this post from Google: http://googlewebmastercentral.blogspot.in/2013/04/5-common-mistakes-with-relcanonical.html

I understand that node comments whether paginated or not are of low importance with respect to the node content itself. So all the paginated node pages reached by clicking links in the bottom just above "Post New Comment"( as in attachment) should have rel=canonical pointing to the main node page.

So these pages:

* example.com/node?page=1
* example.com/node?page=2 and so on

should have "rel=canonical" in the head section of html page pointing to example.com/node.

Though as mentioned in the Google's blog, even "rel=prev" or "rel=next" may also be desirable in case of such urls.

So I need help how to add rel=canonical in those paginated node page. How can I do it?

# Answer
It can be done using Nodewords module as described here:

> Nodewords project allows you to add meta tags to Drupal pages, both manually and automatically based on various settings. Paying attention to meta tags, such as keywords, description and canonical URL, may help obtain better search engine positioning.
> -1 votes

---
Tags: 6, meta-tags
---


title: hook_user_login being called twice?

text:
# Question
Title: hook_user_login being called twice?
I'm storing the session details from Drupal to share with another system, so users don't have to log in twice for each system.

It appears that my `hook_user_login` is being called twice. Right now I'm just calling:

```
mymodule_user_login(&$edit, $account) {
  debug(session_id());
}

```

to see if the session I'm storing is the same as the session being used.

I'm getting the debug statement twice, with two different `session_id` values. Am I missing something here?

# Answer
> 1 votes
I know this is not an answer (I don't yet have enough reputation to post a comment); I am also uncertain if you are still looking for answer. It is possible sometimes for distributed modules to call `user_login_submit`.

For example, the D7 LDAP module's `_ldap_authentication_user_login_authenticate_validate` calls `user_login_submit`, which causes the user login form to fork two calls to `user_login_finalize`, both of which triggers `hook_user_login`. If you are still experiencing this problem, one possible way to debug your application is to use PHP XDebug, and `dsm` function traces.

After you have installed XDebug, you can use `xdebug_call_function()` on `user_login_submit`, `user_login_finalize`, `user_module_invoke` to see where the two calls of `hook_user_login` are coming from. I hope this helps.

---
Tags: 7, hooks, users
---


# Question
Title: How to increase the speed of exposed autocomplete field in views using drupal 6?
I have an exposed auto-complete taxonomy filter, It takes time(2sec) to load the values. How to increase the **performance** to load the values quickly and I'm using views 2.x.

# Answer
> 2 votes
Assuming a Drupal installation configured for a production environment (including Apache and MySQL tuning), there are two things that impact autocomplete latency.

One, is a built-in delay between user input and running searches. This is baked into misc/autocomplete.js. The value is set to 300ms (line 245), and get used in `Drupal.ACDB.prototype.search` (line 287).

The second is that searches will run on a single character. If your autocomplete result set is large, this can have huge performance impacts.

Unfortunately, there isn't a good way to alter either of these behaviors. You can add your own Javascript and redeclare `Drupal.ACDB` to use a shorter delay, eg

```
Drupal.ACDB = function (uri) {
  this.uri = uri;
  this.delay = 100;
  this.cache = {};
};

```

and `Drupal.ACDB.prototype.search` to add in some logic to enforce a minimum number of characters, eg

```
...
// See if this string needs to be searched for anyway.
searchString = searchString.replace(/^\s+|\s+$/, '');
if (searchString.length <= min ||
  searchString.charAt(searchString.length - 1) == ',') {
  return;
}
...

```

However, 400 results isn't a huge number. I have mainly seen the delays this with 10000+ results. This suggests that you may need to do some additional profiling on your server.

---
Tags: 6, views
---


title: Click on a day to create an event

text:
# Question
Title: Click on a day to create an event
I'm wondering whether it is possible to simply click on a Drupal calendar tile (month view) and be automatically taken to the page for creating an event. The only thing I've found that comes close to this is the event calendar module, specifically the *In-place Add/Edit/View of events in pop-up* functionality. However I need more control over this and want it to use my own content type for creation.

My colleague, who creates many calendar events, wanted this functionality to save time.

# Answer
> 0 votes
If you have custom module you can implement hook\_views\_pre\_render(). It will allow you to change the views title before rendering.

```
function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'your_view_name') {
    $title  = drupal_get_title();
    drupal_set_title(l($title,"node/add/event"));
  }
}

```

Not exactly but close to what you need.

# Answer
> 0 votes
The Calendar module has this functionality out-of-box.

1. Edit your calendar view
2. Under 'Format' Section, click 'Settings' for 'Show: Calendar Entities'
3. Scroll down and find 'Add new date link' and select your content type.

---
Tags: views, datetime
---


# Question
Title: Flood table not respecting X_FORWARDED_FOR
The flood table IPs are listing the IP of the load balancer, not the one of the request, which is in the X\_FORWARDED\_FOR header.

I have the 'reverse\_proxy' set to `TRUE` in setting.php, and it works with the CDN as expected, but not with the flood table.

The site hosted at AWS using the CloudFront CDN.

How can I make the flood table look at the IP reported in the X\_FORWARDED\_FOR header?

# Answer
> 2 votes
`$conf['reverse_proxy_addresses']` had my old load balancer IP, thanks to AWS changing the IP without telling me. Once I updated with the current LB address, it worked as expected.

---
Tags: cdn, proxies
---


title: Proximity Search

text:
# Question
Title: Proximity Search
So i'm trying to set up an online store kinda thing. The user uploads items and others see it in their news feed. I want items listed based on the location proximity of the user.

Say there are 3 people accessing the news feed. The item closest to that person should come up first in the news feed.

I'm getting the location of the user during registration and i want this location to get attached with the item.

# Answer
I once put together a similar system for users physically near each other to find and contact each other, but the best way I ever came up with was to store every distance in the database.

Essentially, I saved the lat/lon location (via the Google Maps API) of each user when they registered. Then (via cron) I calculated that user's distance from every other user and saved that distance in a custom table. That allowed me to simply query the database sorting by shortest distance.

This requires a substantial amount of overhead, depending on the number of users (and items, in your case), but it worked reasonably well.

I know that some databases have custom geo data types now, that allow this kind of query automatically, but that's somewhat outside the realm of Drupal.
> 0 votes

---
Tags: 7, search, location
---


title: How to apply Chosen on AJAX load

text:
# Question
Title: How to apply Chosen on AJAX load
I have a custom form within my module that is AJAX-enabled. The form contains a fieldset with a number of fields, and the user can click 'add more' to add another fieldset.

One of the fields within the fieldset is a select list, and all select lists on the site are replaced with a Chosen widget via the Chosen jQuery plugin contained in the Chosen module. The problem is, when AJAX refreshes the page, all Chosen widgets on the page revert back to select lists.

I already have an issue on drupal.org for the Chosen module, but there have been no responses yet--I was hoping somebody here knew of a way to use Chosen with an AJAX form.

I would assume that Chosen would be dynamically loaded on AJAX content by the Drupal behavior within the Chosen module, but apparently it doesn't work this way. Maybe I need to load it manually?

```
function manual_import_menu() {
  $items['manual_import'] = array(
    'title' => 'Manual Import',
    'description' => 'Manual import form.',
    'page callback' => 'manual_import_page',
    'access callback' => TRUE,
  );
  $items['admin/config/manual_import'] = array(
    'title' => 'Configure Manual Import',
    'description' => 'Select which taxonomy terms will be used in the
      manual import form.',
    'page callback' => '',
    'access arguments' => TRUE,
    );
  return $items;
}

function manual_import_page() {
  $build = array(
    'header_text' => array(
      '#type' => 'markup',
      '#markup' => '<div class="grid_8"><p>' . t('Manually import content into Repair Central.  Content
        is imported in a group, which is assigned an import scenario,
        which determines the tasks created for the items.') . '</p></div>',
    ),
    'manual_import_form' => drupal_get_form('manual_import_form'),
  );
  return $build;
}

function manual_import_form($form, &$form_state) {
  //set up options for select list
  $task_options = get_task_options();
  $location_options = get_location_options();
  $model_options = get_model_options();

  $form['#attached'] = array(
    'css' => array(
      'type' => 'file',
      'data' => drupal_get_path('module','manual_import') . '/manual_import.css',
    ),
    'js' => array(
      'type' => 'file',
      'data' => drupal_get_path('module','manual_import') . '/manual_import.js',
    ),
  );
  $form['#tree'] = TRUE;
  $form['scenario'] = array(
    '#type' => 'select',
    '#title' => t('Import Scenario'),
    '#options' => array(
      'shipment' => t('Shipment'),
      'location' => t('Location'),
      'manual' => t('Manual'),
      ),
    '#prefix' => '<div class="grid_12">',
    '#suffix' => '</div>',
    '#default_value' => 'shipment',
  );
  $form['scenario_shipment'] = array(
    '#type' => 'fieldset',
    '#title' => t('Associate Group To Shipment'),
    '#description' => t('Associate a group of items to a shipment, and auto-generate tasks'),
    '#states' => array(
      'visible' => array(
        ':input[name="scenario"]' => array('value' => 'shipment'),
      ),
    ),
    '#prefix' => '<div class="grid_4">',
    '#suffix' => '</div>',
    '#collapsible' => TRUE,
    '#collasped' => FALSE,
  );
  $form['scenario_shipment']['shipping_list_number'] = array(
    '#type' => 'textfield',
    '#title' => t('Shipping List'),
    '#prefix' => '<div class="manual-import-shipping-list">',
    '#suffix' => '</div>',
  );
  $form['scenario_shipment']['shipping_from'] = array(
    '#type' => 'select',
    '#title' => t('Shipping From'),
    '#options' => $location_options,
    '#default_value' => 283,
  );
  $form['scenario_shipment']['shipping_to'] = array(
    '#type' => 'select',
    '#title' => t('Shipping To'),
    '#options' => $location_options,
    '#default_value' => 283,
  );

  $form['scenario_location'] = array(
    '#type' => 'fieldset',
    '#title' => t('Associate Group To Location'),
    '#description' => t('Associate a group of items to a location, and auto-generate tasks'),
    '#states' => array(
      'visible' => array(
        ':input[name="scenario"]' => array('value' => 'location'),
      ),
    ),
    '#prefix' => '<div class="grid_4">',
    '#suffix' => '</div>',
    '#collapsible' => TRUE,
    '#collasped' => FALSE,
  );
  $form['scenario_location']['location'] = array(
    '#type' => 'select',
    '#title' => t('Location'),
    '#options' => $location_options,
    '#default_value' => 283,
  );
  $form['scenario_manual'] = array(
    '#type' => 'fieldset',
    '#title' => t('Manually Create Tasks'),
    '#description' => t('Manually select the tasks to be created for the items in the group.'),
    '#states' => array(
      'visible' => array(
        ':input[name="scenario"]' => array('value' => 'manual'),
      ),
    ),
    '#prefix' => '<div class="grid_4">',
    '#suffix' => '</div>',
    '#collapsible' => TRUE,
    '#collasped' => FALSE,
  );
  $form['scenario_manual']['task'] = array(
    '#type' => 'select',
    '#title' => t('Task Type'),
    '#options' => $task_options,
  );
  $form['import_items'] = array(
    '#type' => 'container',
    '#prefix' => '<div id="import_items" class="grid_8">',
    '#suffix' => '</div>',
  );
  if (empty($form_state['import_item_quantity'])) {
    $form_state['import_item_quantity'] = 1;
  }
  for ($i = 1; $i <= $form_state['import_item_quantity']; $i++) {
    $form['import_items'][$i] = array(
      '#type' => 'fieldset',
      '#title' => t('Import Item @item', array('@item' => $i)),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );
    if ($i == $form_state['import_item_quantity']) {
      $form['import_items'][$i]['#prefix'] =
        '<div class="manual-import-item-last">';
      $form['import_items'][$i]['#suffix'] =
        '</div>';
    }
    $form['import_items'][$i]['ticket_number'] = array(
      '#type' => 'textfield',
      '#maxlength' => 32,
      '#title' => t('Ticket Number'),
      '#class' => 'manual-import-item-field',
      '#prefix' => '<div class="manual-import-item-field manual-import-item-ticket">',
      '#suffix' => '</div>',
    );
    $form['import_items'][$i]['device_id'] = array(
      '#type' => 'textfield',
      '#maxlength' => 32,
      '#title' => t('Device ID'),
      '#prefix' => '<div class="manual-import-item-field manual-import-item-device-id">',
      '#suffix' => '</div>',
    );
    $form['import_items'][$i]['device_model'] = array(
      '#type' => 'select',
      '#title' => t('Make/Model'),
      '#options' => $model_options,
      '#prefix' => '<div class="manual-import-item-field manual-import-item-device">',
      '#suffix' => '</div>',
    );
    if ($i == $form_state['import_item_quantity']) {
      $form['import_items'][$i]['device_model']['#prefix'] =
        '<div class="manual-import-item-field manual-import-item-device manual-import-item-last-field">';
    }
  }
  $form['import_items']['item_add'] = array(
    '#type' => 'submit',
    '#value' => 'Add another!',
    '#ajax' => array(
      'callback' => 'manual_import_item_ajax_callback',
      'wrapper' => 'import_items',
    ),
    '#submit' => array('manual_import_item_add'),
  );
  return $form;
}
function manual_import_item_ajax_callback($form, $form_state) {
  return $form['import_items'];
}

function manual_import_item_add($form, &$form_state) {
  $form_state['import_item_quantity']++;
  $form_state['rebuild'] = TRUE;
}

```

# Answer
You can add the class `chosen-widget` directly to the form element like this:

```
$form['your_form_field']['#attributes']['class'] = array('chosen-widget');

```

And an example for your code would be:

```
$form['import_items'][$i]['device_model'] = array(
  '#type' => 'select',
  '#title' => t('Make/Model'),
  '#options' => $model_options,
  '#prefix' => '<div class="manual-import-item-field manual-import-item-device">',
  '#suffix' => '</div>',
  '#attributes' => array(
    'class' => array('chosen-widget'),
  ),
);

```
> 2 votes

---
Tags: forms, ajax
---


# Question
Title: Form Redirect not working if 'destination' is in URL
In one of my forms, I'm trying to set a `$form_state['redirect']` so the form will go to that destination after the user clicks one of the action buttons.

If I inspect `$form_state['redirect']` both before and after I add the redirect, it is NULL before, and after contains the proper array. Here's how I'm setting up the redirect:

```
$form_state['redirect'] = array(
  'my/custom/path/' . $nid,
  array('query' => drupal_get_destination()),
);

```

I want to preserve the destination from the form that the user's viewing to the next path (that's why I'm calling `drupal_get_destination()`, which returns an array with `'destination' => 'some/path/here'` inside.

It seems that, because there's already a destination in the path of the current form, the form redirects to that destination no matter what I put in my own form submit handler (see above code). I even tried using drupal\_goto() and that didn't redirect the user either.

# Answer
> 28 votes
When a form is processed, the value of `$form_state['redirect']` is sent to `drupal_goto()`, and `drupal_goto()` always favors `$_GET['destination']` over its own `$path` parameter.

For the sake of completeness, in Drupal 6, you were somewhat out of luck without setting your own headers in `hook_exit()`:

```
function mymodule_exit($destination = NULL) {
  $my_destination = 'foo/bar';
  header('Location: ' . url($my_destination));
  exit;
}

```

In Drupal 7, `hook_drupal_goto_alter()` was added for this specific use case:

```
function mymodule_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  $path = 'foo/bar';
}

```

Another option for Drupal 7, which is closer to what you want to do, is to reset the static cache for `drupal_get_destination()` in your submit handler using `drupal_static_reset()`:

```
function mymodule_form_submit($form, &$form_state) {
  // See note
  $form_state['redirect'][] = drupal_get_destination();
  $form_state['redirect'][] = 'foo/bar';

  unset($_GET['destination']);
  drupal_static_reset('drupal_get_destination');
  drupal_get_destination();
}

```

Since you call `drupal_get_destination()` immediately after the reset, Drupal is blissfully unaware of the destination parameter for the rest of the page build, including when it calls `drupal_goto()`.

**Note:** I changed the code for defining `$form_state['redirect']` because you never want to overwrite the variable: other submit handlers might've defined their own redirects. Drupal will always use the *last* item in the array, so if you want `foo/bar` to override the destination parameter (and every other redirect defined up to that point), it needs to be last.

# Answer
> 4 votes
Thanks for this, but for some reason this didn't work when I tried it. I got a fatal error -- the data sent in the example answer above doesn't satisfy the requirements of `drupal_goto()`

It may be because this answer is rather old, but I was able to get it work with this instead:

```
function mymodule_form_submit($form, &$form_state) {

  $form_state['redirect'] = array(
    'foo/bar', array(
      'query' => drupal_get_destination()
    )
  );

  unset($_GET['destination']);
  drupal_static_reset('drupal_get_destination');
  drupal_get_destination();

}

```

I know this violates this note:

> you never want to overwrite the variable: other submit handlers might've defined their own redirects.

But, in this case, you do definitely want to overwrite the variable. You wouldn't be setting this value unless you wanted to disregard other module's set values. Also, I think you have to because of the way `drupal_goto()` works with the query parameter. This may also be why the original answer was throwing fatal errors on my site.

# Answer
> -2 votes
set form **#action**

```
global $base_path;
$form['#action'] = $base_path . '/node/'.$form_state['node']->nid.'/mytab';

```

---
Tags: 7, forms, redirection
---


# Question
Title: Newly created node type is always disabled
I have created a new node type using a custom module on Drupal 7. However when I check the content type under the structure menu item it isn't listed. Looking in the node\_type table, I see that it is listed as disabled. My question is how do I get the content type to be enabled?

Here is my content type creation function located in mymodule.install file:

```
// define the node type
  $type = array(
    'type' => $machine_name,
    'name' => $t($parameters['name']),
    'base' => 'room_reservations',
    'module' => 'room_reservations',
    'description' => $t($parameters['description']),
    'has_title' => TRUE,
    'title_label' => $t($parameters['title_label']),
    'custom' => FALSE,
    'locked' => TRUE,
    'disabled' => FALSE,
  );

// set other node defaults not declared above
  $content_type = node_type_set_defaults($type);

// add the body field
  node_add_body_field($content_type, $t($parameters['body_label']));

// save the content type
  node_type_save($content_type);

```

I believe this is correct but it obviously doesn't work. Any ideas

# Answer
Drupal base install uses this configuration to create the `basic page` content type. Try to modify the `custom` value just like the example underneath:

```
$type = array(
    'type' => 'page',
    'name' => st('Basic page'),
    'base' => 'node_content',
    'description' => st("Use <em>basic pages</em> for your static content, such as an 'About us' page."),
    'custom' => true,
    'locked' => true,
    'modified' => true,
    'disabled' => false,
);

```

**Edit**

I've just checked the code of some Drupal core modules how they manage the creation of content types within code.

The `Blog` module defines the content type within the `HOOK_node_info` (just like you did). This to notify Drupal about the new type. The `HOOK_install` only add fields to the content type. The module also implement the `HOOK_form` for the content creation form and `HOOK_view` for the rendering.

```
// blog.install
function blog_install() {
  // Ensure the blog node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['blog']);
}

// blog.module
function blog_node_info() {
  return array(
    'blog' => array(
      'name' => t('Blog entry'),
      'base' => 'blog',
      'description' => t('Use for multi-user blogs. Every user gets a personal blog.'),
    )
  );
}

```

}
> 0 votes

# Answer
A possible answer to my own question. I believe that along with using hook\_install() you must also use hook\_node\_info() as well. I was under the impression from reading the documentation that when adding fields to your node type, all you needed to do was use hook\_install() as shown in the original question. That didn't work for me. It did work when I included hook\_node\_info() and that seemed to make the node types enabled. Am I correct that you have to use both these hooks in order to get custom node types to display?
> 0 votes

---
Tags: 7, installation
---


title: How to contribute a converted module?

text:
# Question
Title: How to contribute a converted module?
I recently converted a Drupal 6 contributed module to Drupal 7 for one of my client project. I would like to contribute this converted module to the community. How to upload this in the existing project page? Do I have to create a patch or will it be a sandbox project?

# Answer
For this you need to create a sandbox project and open up an issue in the issue queue of the existing module, posting a link there and urging the maintainer of that project to have a look.

If they wish, they can commit that module as the official 7.x version, or might even add you as a co-maintainer of the module if you are interested. In case they do not find this module interesting, you can create it as a separate project: Create the sandbox, apply for project application approval in the Drupal.org project approval queue, and get this published as independent module.
> 11 votes

# Answer
I'd probably create an issue in the existing project page, and upload as a patch there.

@Chapabu's sandbox suggestion IMO is an optional extra. The main thing is creating the issue so it's visible to the community. A patch is fine (although having ready access to a tarball is a good feature for facilitating testing by others).

If the D6 project is not upgraded to D7 by now, you might find the maintainer is no longer engaged with the project.
> 0 votes

---
Tags: community-official-site, version-control
---


# Question
Title: how to have block show up on specific pages AND specific content types
I want to be able to have a particular menu block show up on specific pages, as well as on specific content type pages. My content type pages don't start with /node, so I can't simply say

```
pagename
/node/*

```

in the block settings. (I am trying to do this from the UI. If thats not possible, then please tell me what the best way to do this in code is.)

# Answer
> 1 votes
The Context module makes advanced block placement very easy in the ui. In your case you would:

1. Download Context and enable Context and Context UI,
2. go to admin/structure/context,
3. click add,
4. give your context a Name in machine name format (no spaces, use lowercase and underscores) ie. my\_context
5. Under "Conditions" add a condition of "Node Type"
6. Select your Content Types
7. Add another condition, of "Path"
8. Enter the specific paths that you would like the block to appear on, one path per line
9. Add a "Reaction" of type Block
10. Check your block or blocks off to the right and click the "+ Add" button in the region that you would like to place the block.

---
Tags: blocks
---


# Question
Title: Where can I learn about how to create a custom exposed filter for Views 3 and D7?
I am trying to learn how to create a custom exposed filter for a contributed module (select or other). I found this tutorial for Drupal 6 but the code doesn't appear to work out-of-the-box on Drupal 7.

I also tried looking at the code in the hierarchical select module but it seems to be much more complex than what I am trying to do.

Does anyone have any suggestions for tutorials or modules that implement custom exposed filters in a relatively simple way (e.g., not a huge number of custom handlers like the location module) that I can learn from?

# Answer
Short answer : nowhere.

But you can find bits of information here and there.

The first place to look is in Views sources, particularly the implementation of existing filters, starting with the simplier ones.

Personnaly, I participated in this thread which was very instructive but not completely satisfactory, as you'll see if you go read it. I think the info here is useful though, and I can at least say it was acurate at the time it was written.
> 6 votes

# Answer
I was lurking around the internet trying to find answer for the same question and this is what I've got in result:

1. Implement several hooks in your custom module. Replace `modulename` and `filtername` with your actual names.

```
/**
 * Implements hook_views_api().
 */
function modulename_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'modulename') . '/inc',
  );
}

/**
 * Implementation of hook_views_handlers() to register all of the basic handlers
 * views uses.
 */
function modulename_views_handlers() {
  return array(
    'info' => array(
      // path to handler files
      'path' => drupal_get_path('module', 'modulename') . '/inc',
    ),
    'handlers' => array(
      // register our custom filter, with the class/file name and parent class
      'modulename_handler_filter_filtername' => array(
        'parent' => 'views_handler_filter',
      ),
    ),
  );
}

function modulename_views_data() {
  $data = array();

  $data['node']['filtername'] = array(
    'group' => t('Custom'),
    'real field' => 'my_custom_filter_field',
    'title' => t('My custom filter'),
    'help' => t('Some more detailed description if you need it.'),
    'filter' => array(
      'handler' => 'modulename_handler_filter_filtername',
    ),
  );

  return $data;
}

```
2. Create folder named `inc` inside your module folder and create file named `modulename_handler_filter_filtername.inc` there (see code above for implicit reference to this file). Don't forget to use actual module and filter names.
3. Paste following code into that `modulename_handler_filter_filtername.inc` file. The code I used for this example creates a set of radio buttons that present years. So you can filter nodes by year created, using only years in which nodes were created.

```
class modulename_handler_filter_filtername extends views_handler_filter {

  /**
   * Options form subform for setting exposed filter options.
   */
  function value_form(&$form, &$form_state) {
    parent::value_form($form, $form_state);

    // get list of years from database
    $query = db_select('node', 'n');
    $query->addExpression("FROM_UNIXTIME(n.created, '%Y')", 'year');
    if (isset($this->view->filter['type'])) {
      $query->condition('n.type', $this->view->filter['type']->value, 'IN');
    }
    $result = $query->orderBy('year', 'ASC')
      ->execute()
      ->fetchAllAssoc('year');

    $years = array(
      '0' => t('All'),
    );
    foreach ($result as $k => $v) {
      $years[$k] = $k;
    }

    // create form element with options retrieved from database
    $form['value']['year'] = array(
      '#type' => 'radios',
      '#options' => $years,
      '#default_value' => end($years),
    );
  }

  /**
   * Alters Views query when filter is used.
   */
  function query() {
    // make sure base table is included in the query
    $this->ensure_my_table();

    // retrieve real filter name from view options
    // this requires 'real field' filter option to be set (see code above)
    $real_field_name = $this->real_field;
    // get the value of the submitted filter
    $value = $this->view->exposed_data[$real_field_name];

    // finally, alter Views query
    if (is_numeric($value) && $value != 0) {
      /*
        Having several custom exposed filters, make sure subsitution patterns
        (e.g. :filtername_value below) don't match across different filters.
        I spent some time figuring out why all my filters had the same value.
        It looks like the query skeleton is built first and then all replacements
        are made in bulk. Prefixing value with filter name looks good imo.
      */
      $this->query->add_where_expression($this->options['group'],
        "FROM_UNIXTIME(node.created, '%Y') = :filtername_value",
        array(':filtername_value' => $value));
    }
  }
}

```

That's all you need to get simplest custom exposed filter working!

Note that using `FROM_UNIXTIME` in condition of `SELECT` query may slow your database.
> 10 votes

# Answer
1. Drupal 7 Tutorial: Creating Custom Filters in Views in English
2. Tutorial in Russian
> 5 votes

---
Tags: views
---


# Question
Title: Shopping cart views are not show product links
I am using Commerce Kickstart V t-7.x-2.2

I realized the next: When I add a new product and I add to cart it, not show the link "view product" . But when I edit that product and modify something on product variation and save again. The link "view product" appears in Shopping cart.

Somebody could tell me what is happening? Is it a bug of the commerce kickstart ? or Am I doing something wrong?

Any help will be highly appreciated. Thanks.

# Answer
Try to edit the shopping cart views, go to admin/structure/views/view/commerce\_cart\_form/edit/default

On the Fields Setting Make sure there is Display path field, exclude from display. see the Global: Custom text, and you must inlcude the Dsiplay path field token there
> 0 votes

---
Tags: commerce
---


# Question
Title: Can't translate the messages of the flag module
I'm using Drupal 7.20 with Commerce. I installed the following modules: \- internationalization module \- translation helper \- flag module

I have customized the text for my flag links to be 'add to my favorites' and 'remove from favorites'. I want to translate them, but they don't appear in the translate interface.

Does anyone have a clue?

# Answer
See this from the Flag module issue queue

> Each string you enter as an administrator is available in the Translate Interface section, but you first have to switch to a different language, then view a page that contains that message (such as trying to flag/unflag a piece of content). Afterwards, the string will be flagged as needing a translation and you can find it in the Translate Interface section.
> 3 votes

# Answer
You can translate everything if it's passed through `t()` function, for this purpose you can use String overrides module. If this values passed without `t()` function you need to find that `flag module` form function and override it in your module with t().
> 0 votes

---
Tags: i18n-l10n, flags
---


title: Vertical Tabs in Panel Pages

text:
# Question
Title: Vertical Tabs in Panel Pages
I am trying to have three forms available to the public on my site and would love to have them configured in in the vertical tabs layout. Initially I was going to have them available through node/add/form but I have since decided I would rather have them in a panel page to lose that path of node/add. Now that I have the forms in the panel page they no longer have the vertical tab/fieldset layout. How would I go about putting the forms back in that tabbed layout while staying in a panel page?

# Answer
It looks like someone has fixed this in style! https://drupal.org/project/node\_vertical\_tab\_elements

Haven't tried it myself, but it looks made exactly to fix this issue.
> 0 votes

---
Tags: panels, forms
---


title: Problem with node_save within a loop

text:
# Question
Title: Problem with node_save within a loop
Within an instance of hook\_submit (for a custom form), I'm trying to iterate over a list of nodes, updating each of them. The general outline is

```
$x = node_load_multiple($nids);
$data = array(--some data--);

foreach ($data as $row) {
  $node = $x[$row['nid']];
  $node->field_some_field['und'][0]['value'] = $row['some_field'];
  node_save($node);
}

drupal_set_message('Nodes updated');

```

The problem I'm having is that rather than looping through the whole data array and then posting my confirmation message on the form page, Drupal updates the first node, *exits the loop*, and redirects to the user's home page with the message 'contenttype TITLE updated.'

Possibly relevant: I could have sworn this code block worked when the site was 7.2, but after updating to 7.23 I'm seeing this.

# Answer
> 2 votes
To summarize one of the comments, when you encounter weirdness with the API, you need to do two things.

First, look at the API call you are using, and see what hooks it invokes. Then, check your code for any hook implementations that could cause the weirdness. In this case `node_save()` invokes a few: `hook_node_presave()`, `hook_entity_presave`, `hook_node_update`, and `hook_node_update` for nodes that exist.

Second, you need to check any Rules that are attached to the the API call you are doing. In this case, you would check for rules that run when nodes are saved.

Doing these two things will usually lead you to the problem.

---
Tags: nodes
---


# Question
Title: Multiple blogs per user, each with a blog profile page
I'm trying to to create a site where users upon admin approval, can have multiple blogs, typically differentiated by language.

Each blog should have a profile/landing page specific to that blog.

I can simply create a taxonomy term where a given term is a given blog name and I can use the Taxonomy Permissions module to restrict a given term to a given user.

The part that I'm having trouble thinking through is the admin side setup so that someone who doesn't know a lot about Drupal would be able to simply set up a new blog.

# Answer
In the end, I decided it was easier to do this with node references and let the user choose a parent from the "add blog post" screen.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: What's the advantage of using Git submodules for Drupal core and contrib?
I've seen a number of questions/blog posts about setting up a Git repository with Drupal Core and Contrib Modules as submodules, such as Setting up the ideal multiple repository Drupal Site version control with a DVCS.

What advantages do you get from this kind of repository set up?
Many people say things like "core and module updates are really easy," but what makes this approach easier/better than have a single repository containing everything for the site and using Drush to update Core and Contrib, then committing back to your repository?
I can see this being great for contributing to those projects since each module is a separate repository, but what benefits does to provide when focusing on building your own site?

# Answer
At our workplace we avoid git submodules as they add unneccessary complexity to the system.

We run one git repo for each site, and we have drupal core as an upstream remote. This makes merging in 7.12 for example as easy as:

* `git fetch upstream`
* `git merge 7.12`

As for contrib, drush is king

* `drush dl views`
* `git add -A`
* `git commit -m 'bumps views to next stable'`

Hope this helps
> 5 votes

# Answer
Here are some of the advantages of using Git submodules with Drupal:

1. You can git fetch/merge/pull updates for your contributed modules directly from Drupal.org. There is no need to manually download a new version of each, unpack and then commit.
2. You can see upstream version history in your own Git log. This makes it easy to see where you're at; you can check if you've got specific upstream commits. Otherwise, all you can see are local changes and "Upgraded Blah from 2.3 to 2.4." log messages.
3. You don't need to reapply (cherry-pick) custom changes to your contributed modules after upgrading them. If you use the one-Git-repository method, each contributed-module upgrade will overwrite anything you're previously patched and committed. This is a huge problem because developers often forget to do the reapplying, and then you're left with resolved issues that have been reverted. If you're using submodules, you simply maintain a custom branch, and merge upstream tags (or commit IDs) into it.
> 1 votes

---
Tags: version-control
---


# Question
Title: How to theme each nodes in a taxonomy term page seperately in drupal 7
I know there are many similar questions but none of them gave me a correct solution for my particular requirement. In drupal 7 in taxonomy term page nodes are displayed as a row of nodes one below another. But I want the first node to be displayed with a bigger image in the first row and the rest of the nodes as two nodes per row. How can i do that programmatically.

# Answer
this could be done with view.

1. Create a taxonomy view of the type page.
2. Set the path as taxonomy/term/% this will override the default taxonomy path and will show the views page instead.
3. Add the fields that needs to be shown in all the nodes accept the first one.
4. Add a contextual filter of taxonomy term id.
5. With in the pager settings give an offset 1 so that the first node is skipped.
6. Set the Format to grid and give number of columns as 2 so that it displays in two columns

The above steps will display all the nodes except the first one in two columns.

Next we need to create a block to display the first node.

1. With in the current view add a block.
2. Set the pager to display only one element without the pager being shown.
3. Add the required fields. (Image in the size you want etc.)
4. Add a contextual filter of taxonomy term id.
5. Now go back to the page view and add a header.
6. Select "Global:view Area"
7. Choose the block we created above form the drop down and tick "Inherit contextual filters."

Now your taxonomy page would display as you wanted.
> 2 votes

# Answer
you need to override the taxonomy-term.tpl.php here. copy the file from modules/taxonomy/ to your theme folder. Clear cache. now the one you have copied will take effect. You need to modify that.

implement a function themename\_preprocess\_taxonomy\_term(&$vars) in your template.php. in it, $vars\['content'\] will contain all the nodes. Do whatever logic you want to do on it. In your case, get the first one from the array, theme it as required and store it in a separate variable say, $vars\['first\_node'\]. Unset it from the rest of the array. Now in your taxonomy-term.tpl.php file you will have two variables, $content for the rest of the nodes and $first\_node with the first node html.
> 0 votes

# Answer
You can do that with Views and Views Nodes Split modules.

Views module has a default view to override taxonomy pages which is disabled by default. You need to enable it first. Then, with the Views Nodes Split module, you can set different row style for the first X results.
> 0 votes

---
Tags: theming, taxonomy-terms
---


title: MAMP Pro and Drush mem exhaustion

text:
# Question
Title: MAMP Pro and Drush mem exhaustion
I have mamp 6.0 installed. When trying to drush up and confirming "yes", I get:

> PHP Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 12288 bytes) in /Users/me/Sites/jla copy/sites/all/modules/contrib/ctools/includes/stylizer.inc on line 911 Drush command terminated abnormally due to an unrecoverable error. \[error\] Error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 12288 bytes) in /Users/me/Sites/jla copy/sites/all/modules/contrib/ctools/includes/stylizer.inc, line 911 Your memory limit is set to 32M; drush needs as much memory to run as\[error\] Drupal. Please check your configuration settings in /Applications/MAMP/bin/php/php5.4.10/conf/php.ini or in your drush.ini file; see examples/example.drush.ini for details. The external command could not be executed due to an application \[error\] error. Illegal string offset 'site' backend.inc:1013 \[warning\] The command could not be executed successfully (returned: PHP Fatal \[error\] error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 12288 bytes) in /Users/me/Sites/jla copy/sites/all/modules/contrib/ctools/includes/stylizer.inc on line 911 , code: 255)

This is the result of my drush status: Drupal version : 7.10
Site URI : `http://default`
Database driver : mysql
Database username : root
Database name : jla\_d7
Database : Connected
Drupal bootstrap : Successful
Drupal user : Anonymous
Default theme : jlasitetheme
Administration theme : seven
PHP executable : /Applications/MAMP/bin/php/php5.4.10/bin/php
PHP configuration : /Applications/MAMP/bin/php/php5.4.10/conf/php.ini PHP OS : Darwin
Drush version : 6.0
Drush configuration :
Drush alias files :
Drupal root : /Users/me/Sites/jla copy
Site path : sites/default
File directory path : sites/default/files
Temporary file directory path : /Applications/MAMP/tmp/php

I know that I have set a 128MB memory\_limit in the MAMP php5.4.10 file.

# Answer
n.b. The error message says that your memory limit is 32MB, not 128MB. The 128MB setting must be for your web server. Check the php.ini for PHP CLI; it's quoted in the output of Drush status, above: /Applications/MAMP/bin/php/php5.4.10/conf/php.ini. You should find that memory\_limit is 32M, or perhaps unset. Set it to 128M, or perhaps even 256M or more, and you should be fine.
> 4 votes

---
Tags: drush
---


# Question
Title: Function in template.php to override Profile2
How can I make Profile2's overrides (profile2.tpl.php) work? Do I have to include a function "mytheme\_preprocess\_page" with "theme\_hook\_suggestions" in template.php?

# Answer
I have crossed checked the suggested way on my local and I can see it working.Here are some pointers.I copied the profile2.tpl.php present inside profile2 module and paste it inside site default theme templates folder and finally clear the caches.In order to see what profile is working I added some test content on both templates and found content from profile2.tpl.php from my theme is working.

As a side Note:You can make theming experience far more easy using Theme Developer module,

> Firebug for Drupal themeing.Note that this module injects markers into the DOM to do its magic. This may cause some themes to behave erratically and less capable browsers may make it worse (especially IE)/. Enable it when needed, and disable it afterwards.
> 0 votes

---
Tags: theming, users
---


title: How to create a url/link preview?

text:
# Question
Title: How to create a url/link preview?
I'm managing a content sharing site built on drupal 7 and I would like to let users submit links as content.

Is there a simple way of creating a thumbnail / preview of the link (like on facebook)?

# Answer
> 2 votes
I think Opengraph Filter is a better solution than Facebook-Style Micropublisher since FBSMP relies on Statuses module and both modules are not very stable yet and also they serve for a more specific purpose. Opengraph Filter does only that what you need.

# Answer
> 1 votes
This module might help

Facebook-style Micropublisher

> This module lets users publish content (links, images, videos and documents) in a stream
>
> **Features**
>
> * Attaches content using AHAH which keeps everything smooth.
> * Ability to re-share/re-post attachments (links, images, etc).
> * API to allow users to share content (URL) from other sites on your website (similar to Google Bookmarks, Digg, Reddit links). More...
> * Publish links, photos, videos, documents (ppt, doc, pptx, odt, etc) out of the box.
> * Extensible to publish any kind of content.
> * Integration with Activity 2, Twitter, Rules, Heartbeat, Triggers/Actions, Input Filters, Views, ImageCache, Token,
> Application Toolbar(Appbar), Emvideo, Emaudio, Userpoints (through
> Rules), SlideShare.net API and more.
> * Extensive developer API (including hooks) and theming methods. More...

---
Tags: 7, uri, navigation, entities
---


title: Creating a News Blog in Drupal

text:
# Question
Title: Creating a News Blog in Drupal
Can anybody help me with this, any help is appreciated.

I want to create a news blog where any anonymous user can put the news post, but for posting news article, the user must provide their valid email, the verification mail should be sent to that user. News should only be posted after only the email is verified.

# Answer
> 2 votes
This has been discussed at Use email to validate post, not unlike craigslist.

A module that is still in alpha is also available:

https://drupal.org/project/anonymous\_publishing

The module is not widely used, thus not extensively tested. It might be safer to write your own rules as discussed in the first link.

---
Tags: forms, nodes
---


title: CORS localhost ajax request

text:
# Question
Title: CORS localhost ajax request
I have an HTML page (`http://localhost:8888/test/test.html`) in which I'm trying to pull data from a Drupal 7 website.

I'm using this AJAX code with HTML-Request. I have tried JSON and the website prevents me from pulling, even I have added the following code to pull the data.

```
<?php header('Access-Control-Allow-Origin: *'); ?>

```

This is the HTML page that requests AJAX from Drupal 7 website. Could you please check it for me?

```
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
  (function ($) {
    $(document).ready(function () {
      $.ajax({
        // The link we are accessing.
        url: "http://horizon-websolutions.com",
        // The type of request.
        type: "get",
        // The type of data that is getting returned.
        dataType: "html",
        error: function () {
          alert("error");
          // Load the content in to the page.
          $("#output").html("<p>Page Not Found!!</p>");
        },
        beforeSend: function () {
          alert("not yet");
        },
        complete: function () {
          alert("done");
        },
        success: function (strData) {
          alert("success");
          // Load the content in to the page.
          $("#output").html(strData);
        }
      });
      // Prevent default click.
      return(false);
    });
  })(jQuery);
</script>
<div id="output"></div>

```

Please help me telling the website to accept my localhost request to pull data from the server. I have tested the same code on a pure PHP page and it is working fine.

# Answer
> 0 votes
You should wrap you javascript to user `$` for `jQuery`, since it does not automatically refer to `jQuery` in Drupal 7. Try like that:

```
(function ($) {
  // Your code here
  $(document).ready(function() {
    // ...
  });
})(jQuery);

```

Reference: Managing JavaScript in Drupal 7

---
Tags: ajax
---


# Question
Title: Setup right field type and widget for field
I'm using Drupal 7.23 to build an online catalog for a shop. I made an "articles" content type and I've built all the required fields. I need to setup the Price field in a way that it's a list, and each row of the list will show something like "buy x at yx", like "buy 1 at 5, buy 2 at 9, buy 3 at 12" and so on, and I need it to be treated as numbers (5,9,12). How can I accomplish this?

I have also the image field, I need to have up to 10 images for the same article, and I want to show a gallery (more or less like Amazon does), where you click on the photo and it enlarges. It is handled by Drupal already? Do I have to setup something special to do this?

# Answer
> 1 votes
For the first issue you can actually add it as a key|label pair.

Where the key would be the number and the Label would be what is displayed. for example 5|buy 1 at 5

this would show "buy 1 at 5" in the dropdown but the value would be five. you want to work with numbers you might want to select List(integer) as your field type.

For the second problem you might want to take a look at the Cloud Zoom Module.

> This addon provides a small, thumbnail sized image, with an on-hover popup, zoomed and centred on a larger version of the image.

OR

jQZoom

> The jQZoom module is a wrapper for the jQuery plugin jQZoom. The module provides a javascript magnification effect for images. When a user mouses over an image, a larger version of the area under the cursor will be displayed beside the image.

---
Tags: 7, entities, nodes, media
---


# Question
Title: I would like to be able to use some tokens like %post[key]used in webform, in my custum module how to call these up in my custum module
I am creating a custom module webform3rdparty integration to icontact .Using my module create an extra field in weform field to add icontact field(mapping purpose).I want to use token replacement patterns in my field.How to call these replacepatterns in my custom module.

# Answer
I think you need these hooks:

1. hook\_token\_info() \- this hook will allow you to define empty placeholders. Define a few placeholders which you want to make available to the webform.
2. hook\_tokens() \- corresponding to the plkaceholders you have defined, pass in appropriate stuff and define a replacement pattern for each placeholders you have defined in your earlier hook\_implementation.
3. Finally, while rendering user submitted value, apply token\_replace() function to replace the placeholders entered by user with appropriate values.

UPDATE:

Got you. Have a look at this function \_webform\_filter\_values(). This funciton is responsible for replacement of webform tokens. you can use this funciton in your code, pass in the stuffs you want to replace and the node and submiccions object and have the value replaced.

It will be impossible for me to give you exact direction, as i am not familiar with what you are doing. But i can give you a general idea. Token replacement often happens at the output stage. So it is more concerned with output. So mostly, you need to apply this to your code which displays/prints/uses the webform submission result of your field.

Say you create a webform field. I as an end user, enter a string to it which contains this: %post\[key\]. Now your submit handler code will need to use the said function. When you pass the input i entered through that function, my %post\[key\] is replaced by appropriate value.
> 1 votes

---
Tags: tokens
---


title: Adding a block?

text:
# Question
Title: Adding a block?
I've just installed Drupal and I'm familiarizing myself with all of the core features. The first thing that's not obvious to me is When I add a block in the structure screen I don't have any ability to choose the block type, I only have an area in which to add HTML. How do I create more useful, pre-built blocks of content?

# Answer
> 2 votes
You can create blocks in many ways.

1. The default way you know already
2. Views module allows you to create blocks with lists of content, or practically anything you might want
3. Nodeblock module allows you to use nodes as a blocks if you wish to do so
4. Boxes are a vision how the built-in blocks should have been implemented in the first place
5. Many modules ads their own blocks, but it depends on functionality you need on your page; if you will enable a module that provides it's blocks, you will see these blocks on the structure page just like you see the ones that are already there
6. And you can always write your own module that will add some blocks, see Examples for Developers to know how to do it

# Answer
> 1 votes
Adding a block is not meant for adding any specific type of block. It is used to add a custom content with in a block region.

Blocks are created by modules. For example the core user module creates the User **Login Block.**

Another example would be views. When you create a new view of the type block it would be displayed with the block page and you can place the same in any of the regions.

When you add a new module and if the module has defined a block then it would appear with in the structures-\>blocks page.

You can also define a block with in your custom module.

---
Tags: blocks
---


title: Update field value after save a node

text:
# Question
Title: Update field value after save a node
My content type has a field call tracking code, I have granted permission for users are able to create content. When they create content, they cannot see tracking code field but after they submit the content, they will see a tracking code string in message area.

In that node I also have reference field with other content type, so the string that I expect to show must include the id of reference node and id of the node being created.

EX: P1C2 (1 is id of reference node, 2 is id of node being created)

Does drupal have any modules support to do that or I must do it programmatically and how can I build the coding for that? Thank you all!

# Answer
You could use the computed field module.

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

You can get all the information that you add in other fields with in the computed field. Since you have not yet saved the node you might want to add the following code at the beginning to make the nid available.

https://drupal.org/node/149225
> 3 votes

---
Tags: nodes, entities
---


# Question
Title: Organic Groups - How to view articles in the context of the group
I have OG setup on a site I am developing. The configuration is set to remove the main sites side bars when a Group is viewed. If an article that is only published in that group is viewed, it is opened in the context of the main Drupal site (All side bars are visible from the main site)

Is there a way to view the article so that it appears the user feels they are still in the group?

# Answer
You can adjust Group context detection at admin/config/group/context when you have Organic groups context enabled. This will add the appropriate css classes in the body element, which will allow you to theme the rest of the page.
> 1 votes

---
Tags: organic-groups
---


# Question
Title: filter entity reference by another entity reference field in create content
there is two content types "country" and "state". content type "state" has entity reference field for "country".

there is another content type called "shop" which has two entity reference field for "country" and "state".

when i creating "shop" it display all the "state" .

but i want something like when user select one country, the corresponding states to the country should display.

how to do that help needed .

# Answer
It appears like you are looking for Reference field option limit module. Your case is their first example:

> Example 1: countries and cities
>
> Suppose you want to label articles (or products, or businesses, etc) by both city and country so both can be used for filtering and searching. You could use a hierarchical taxonomy with city terms as children of country terms, but that doesn't make sense when you come to set up Views filters.
>
> With this module, create two separate taxonomies for country and city (or content types, or whatever entity you want to use). Then add a reference field so that each city points to its country: eg, the term 'Paris' has a reference to 'France'.
>
> Then when editing an article, selecting 'France' in the country field will cause the city field to update to show only cities in France.

And yes, it works with nodes just as well as with taxonomies, as both kinds are entities.
> 2 votes

---
Tags: entities
---


# Question
Title: PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value --- when trying to run cron
I am using search file attachments module, after adding some content with attached files, when I try to run cron the whole site is not indexing. But when I add content with just title and body it is working file, if I attached a file to node then I am unable to search the file contents.

Log report says

> PDOException: SQLSTATE\[HY000\]: General error: 1366 Incorrect string value: '\xF0\x9D\x90\xBF ...' for column 'data' at row 1: INSERT INTO {search\_dataset} (sid, type, data, reindex) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3); Array ( \[:db\_insert\_placeholder\_0\] =\> 26 \[:db\_insert\_placeholder\_1\] =\> file \[:db\_insert\_placeholder\_2\] =\> filename 6 hl bu slides r2 may 2 2012pdf content head loss back up slides head loss calcula3ons casa grande requires a correla3on to determine head loss over the range of relevant condi3ons debris loads fiber par3culate microporous chemical flow rate temperature npsh margin slide 2 porous media head loss correla3ons porous media head loss correla3ons follows the classical porous media ﬂow equa3ons dp a u b u2 dl where a coeﬃcient for viscous term b coeﬃcient for iner3a term nureg cr 6224 correla3on is a semi theore3cal correla3on developed based on ﬂat plate ver3cal loop head loss tes3ng with nukon ﬁberglass ﬁbers nominally 7 micron diameter and bwr suppression pool sludge iron oxide nominally 10 micron diameter nureg cr 6224 experimental data were performed at ﬂuid temperatures ranging from 60of to 125of debris bed thicknesses ranging from 125 in to 4 in and approach veloci3es ranging from 15 c s to 15 c s slide 3 nureg cr 6224 correla3on where δh head loss c water sv surface to volume ra3o of the debris c2 c3 µ dynamic viscosity of water lbm c sec u ﬂuid approach velocity c sec ρ density of water lbm c3 αm mixed debris bed solidity one minus the porosity δlm actual mixed debris bed thickness in λ 41528x10 5 c water in lbm c2 sec2 conversion factor for english units m m m vmmv lssh δ λ δ 23512 u 1 660u57153 ρ α α µαα slide 4 nureg cr 6224 correla3on the very low approach velocity at stp 1 c sec suggests that the head loss will be dominated by the viscous term the viscous term of the nureg cr 6224 correla3on is based on experimental work by c n davies proceedings of ins3tute of mechanical engineers london b1 p 185 1952 for stp condi3ons the nureg cr 6224 correla3on could be simpliﬁed to slide 5 mmmv lsh δ λ δ u57153 3512 µαα nureg cr 6224 correla3on suppor3ng compression equa3on nureg cr 6224 based on w l ingmanson et al internal pressure distribu3on in compressible mats under fluid stress tapi journal vol 42 no 101959 where α and ϒ are empirically based currently α 13 and ϒ 38 alterna3ve clint shaﬀer 2005 1 1 where α ϒ and ф are empirically based currently α 65 ϒ 38 and ф 35 1 6224 correla3on training session nrc headquarters april 12 2005 slide 6 shaﬀer compression alterna3ve 1 slide 7 1 6224 correla3on training session nrc headquarters april 12 2005 head loss correla3on reﬁnements perform ver3cal loop tes3ng to acquire head loss data at stp speciﬁc condi3ons ie low approach velocity and representa3ve ﬁber par3culate loadings adjust correla3on suppor3ng equa3ons to best ﬁt the experimental results determine from integrated chemical eﬀects tests the impact of chemical precipitates on head loss slide 8 strainer geometry calculate strainer area and gap dimensions based on strainer drawings calculate average approach velocity based on total strainer area calculate inters33al volume based on gap dimensions calculate increased approach velocity for large debris loads based on circumscribed strainer area slide 9 strainer dimensions strainer area per train 18185 c2 circumscribed area per train 4190 c2 inters33al volume per train 818 c3 photos of stp pci strainer slide 10 flow rate and temperature input total ﬂow rate through each eccs strainer for the speciﬁc case analyzed maximum of 7020 gpm per train at stp based on 1620 gpm per hhsi pump 2800 gpm per lhsi pump and 2600 gpm per cs pump calculate debris accumula3on on each strainer based on rela3ve ﬂow split calculate pool ﬂuid density and viscosity for a given pool temperature slide 11 npsh margin input npsh margin for each safety injec3on and containment spray pump compare calculated debris bed head loss to the pump npsh margin to determine whether the pump would fail npsh required lhsi pumps 165 c hhsi pumps 161 c cs pumps 164 c npsh available excluding clean strainer and debris losses start of recircula3on 267 f 22 c 24 hours 171 f 42 c 30 days 128 f 51 c slide 12 nureg cr 6224 head loss correla3on mixed debris bed solidity the mixed debris bed solidity αm is given by where αo the solidity of the original ﬁber blanket ie the as fabricated solidity η mp mf the par3culate to ﬁber mass ra3o in the debris bed m σ mi is the total par3culate mass lbm ρf the ﬁber density lbm c3 ρp the average par3culate material density lbm c3 σ ρivi σ vi c the head loss induced volumetric compression of the debris inches inch slide 13 nureg cr 6224 head loss correla3on sv averaging for mixed debris bed the averaged surface to volume ra3o for a mixed debris bed is given by where svn sv of the nth cons3tuent vn volume of the nth cons3tuent slide 14 sv sqrt σ svn2 vn σ vn \[:db\_insert\_placeholder\_3\] =\> 0 ) in search\_index() (line 705 of /var/www/vhosts/praappsmgr.com/pilogix/praapps/modules/search/search.module).

Can any one know what is happening and how to fix this?

# Answer
> 4 votes
This is a completely wild guess, but here goes:

1. You run mysql
2. Your tables are "UTF-8"
3. The data you are inserting into the index contains "unusual" UTF-8 characters.

If those three are true, then there's your problem.

MySQL "cheats" on their UTF-8 implementation. Drupal will always instruct MySQL to create UTF-8 tables, but by default, UTF-8 in MySQL doesn't cover the entire UTF-8.

You will need to manually convert your tables to `utf8mb4`, and then also manually "upgrade" the connection to mysql whenever you handle this data. I stuck some code in a sandbox at one point that partly addresses this, but it's not generally applicable at this time.

Or you switch to Postgresql, that actually gets this right by default.

There's an issue on Drupal.org for resolving this.

---
Tags: 7
---


title: Use Zen grids with Views

text:
# Question
Title: Use Zen grids with Views
We are using Zen 7.x-5.x with responsive settings and I want to create a grid for some items. That is responsive and adaptive so first the grid is 3 items and then when the viewport gets narrower there is 2 or one.

How can I use Zen grids with Views is there an automatic way of specifying a n column(s) responsive grid out of views? Is there a connection or are there any specific classes I can use in my views?

Thanks!

# Answer
Here there are lot of examples how to make a grid with 3 items etc. About views and zen grids, I do not think that there is such a module because if you are use zen grids you use the grid for the entire site, if you need to specify grid for some items you can use `mix-ins` here you can read about them.

> **zen-nested-container()** Apply this to any grid item that is also a grid container element for a nested grid. It must be applied after the zen-grid-item() mixin is applied. This mixin ensures the container does not have a gutter since the nested grid items will have their own gutters.
> 3 votes

# Answer
You can create grids inside the main container or others.

You can look at these 2 modules for views and grids:

Views Responsive Grids

Views Column Class

Then you only need to create your own grid for that view. And of course you can select n columns with nth-child

For example: A view with Views Responsive Grids of 3 columns and N rows

```
  .your-view-class {
  $zen-column-count:  3;
  @include zen-grid-container();
  div:nth-child(n+1) {
    .views-column-1 { @include zen-clear(); @include zen-grid-item(1, 1);}
    .views-column-2 { @include zen-grid-item(1, 2);}
    .views-column-3 { @include zen-grid-item(1, 3);}
  }

}

```
> 4 votes

---
Tags: theming
---


# Question
Title: Drush sql-sync: Access denied; you need the SUPER privilege for this operation
I am trying to use drush to move my live database down to my dev database. I am doing

```
drush sql-sync @live @devel --sanitize

```

However I get the error:

> "ERROR 1227 (42000) at line 1478250: Access denied; you need the SUPER privilege for this operation"

I think it is due to the views in the db from uc\_views module, is there any way around this?

I also tried to do

```
drush sql-sync --skip-tables-key uc_views @live @devel --sanitize

```

where uc\_views is an option declared in drushrc.php with an array of the db views from uc\_views, but to no avail. Here is my drushrc.php

```
$options['skip-tables']['uc_views'] = array('uc_order_products_pair_vw', 'uc_order_products_qty_vw', 'uc_order_products_user_vw');

```

I would actually prefer to copy the database views from uc\_views rather than exclude them if that is possible.

# Answer
The user defined in settings.php on one or both sides of the sync lacks the SUPER privilege on the database.

Log in as the mysql root user and do

```
GRANT SUPER ON [db_name] TO '[username]'@'localhost' IDENTIFIED BY '[password]';

```

If you are security-conscious (as you should be), it's worth taking the following into account:

> Do not grant the PROCESS or SUPER privilege to nonadministrative users. The output of mysqladmin processlist and SHOW PROCESSLIST shows the text of any statements currently being executed, so any user who is permitted to see the server process list might be able to see statements issued by other users such as UPDATE user SET password=PASSWORD('not\_secure').
> 6 votes

# Answer
We ran into the same problem with aegir, the problem isn't the export but the export contains a DEFINER statement containing the user that originally created the view. It's solved in by using sed to remove those lines, see http://drupal.org/node/881496#comment-4516064

For a more permanent solution, you'll have to file an issue for drush or have a look at http://drupal.org/node/518184
> 4 votes

# Answer
use same username in both the DB servers. take the dump using the same user privileges. this will fix your issue. use mysql -h option while taking dump.
> -3 votes

---
Tags: 6, drush, database
---


title: Add Javascript with 'id' attribute?

text:
# Question
Title: Add Javascript with 'id' attribute?
I've been asked to add the following to a page :

```
<script id="dsxc_script" type="text/javascript" src="https://www.docserver1.co.uk/dsxc/client.js?acc=xx&integrated=true"></script>

```

However I don't think the drupal\_add\_js() function will allow me to set an 'id' attribute.

How should I proceed ?

# Answer
drupal\_add\_js does not support an ID attribute as it seems. However, as a workaround, you can use drupal\_add\_html\_head to add stuff to the head section.

Ex:

```
$element = array(
  '#tag' => 'script',
  '#type' => 'html_tag',
  '#attributes' => array(
    'src' => 'https://www.docserver1.co.uk/dsxc/client.js?acc=xx&integrated=true',
    'type' => 'text/javascript',
    'id' => 'dsxc_script',
  ),
);
drupal_add_html_head($element, 'dsxc');

//dpm(drupal_render($element)); Gives the following:
// <script src="https://www.docserver1.co.uk/dsxc/client.js?acc=xx&integrated=true" type="text/javascript" id="dsxc_script" />

```

You can always embed these scripts in your html.tpl.php file, but if you want to add the stuff conditionally, I think this will work.
> 7 votes

---
Tags: javascript
---


title: Breaking on to new lines?

text:
# Question
Title: Breaking on to new lines?
If I have a long line of code that exceeds 80 characters, like this:

```
$last_response = '<strong>' . t('Last response: ') . '</strong>' . format_interval((time() - $last), 1) . t(' ago');

```

Should I break it on to a new line and indent once? I'm sure I've read this in the coding standards somewhere, but now I cannot find where I read it, if I did, like this.

```
$last_response = '<strong>' . t('Last response: ') . '</strong>'
  . format_interval((time() - $last), 1) . t(' ago');

```

# Answer
> 3 votes
The answer is yes, you should break and indent.

For the more details, including exceptions to this rule, see the official Drupal coding standards on line length and wrapping and indenting.

A handy tool to check whether your source code follow the official Drupal codings standards is Coder. It is also available as SaaS, as part of PAreview.

---
Tags: coding-standards
---


title: Child of a child theme

text:
# Question
Title: Child of a child theme
I am building a series of very similar sites, and so opted to run them all from a singe installation of Drupal 7. I have this all set up and working correctly.

As mentioned, these sites will be almost identical, but branded differently - the only changes being different logos, colours etc. Structurally, they will all be a match.

I am using Zen and building child themes for each of these sites, but I would really like to be able to make a 'master' Zen child theme which contains the bulk of the customisations, then each site could have a child of that with the few applicable brand changes required.

1) I could change the name of the parent Zen theme and customise away (and am actually tempted to do that). Its not good form though.

2) I could make one of these sites the 'master' and symlink the important bits to the other sites.

3) I could stop trying to find a solution, and just get on with the job, copy/paste in hand.

Does anyone know if there is a 'proper' way to do something like this? I'm totally flexible on any of the details - don't have to use Zen, for example.

Thanks!

# Answer
Yes you can do this.

I often use zen as a base theme and have some common things that are always in the sites we're building, so we have a common sub-theme theme of zen, and then each site has a sub-theme of the common sub-theme. For things like this it is great to use this kind of setup.

So you have: Zen \> Zen sub-theme \> Zen sub-sub-theme

In the sub-sub-theme the base theme would be the sub-theme.

For more detailed information on how it all works, see the Creating a sub-theme page.
> 3 votes

---
Tags: theming
---


# Question
Title: How do you add Meta-Description with Metatag?
In the Node's options for Metatag, I have a token for the metatag "Description", i.e.: `[node:summary]`.

If I want to write the description, should I delete it? Or write it in where the "summary" appears?

# Answer
If you want to write a manual description you should delete the whole "\[node:summary\]" part and put your text in its place.

The square brackets are part of the token notation and aren't needed unless you are using replacement tokens.
> 2 votes

---
Tags: nodes, meta-tags
---


# Question
Title: admin/config/people/accounts/fields not displaying
I am new to drupal and have inherited a site. I want to tidying and edit some of the fields n the user profile that already have been added, however admin/config/people/accounts/fields does not appear as a tab in admin/config/people/accounts and nothing happens if i try to access admin/config/people/accounts/fields directly.

How can I enable this tab?

# Answer
The page you are looking for is provided by Field UI core module. Go to /admin/modules and enable it.
> 1 votes

---
Tags: users
---


# Question
Title: How do I use a submit callback on a Drupal admin settings form?
I'm using this code to make my admin form:

```
function custom_orders_admin(){
  $form = array();

  $form['custom_ignore_terms']['ignore_terms'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Don\'t display these'),
    '#default_value' => variable_get('custom_ignore_terms', array()),
    '#options' => drupal_map_assoc($termTypes),
    '#description' => t("Choose the terms you do not want displayed."),
    '#required' => FALSE,
  );

  return system_settings_form($form);
}

```

But I notice that if I do this:

```
function custom_orders_admin_submit($form, &$form_state) {
  exit(var_dump($form_state));
}

```

I can't exit. I'm guessing this is because `system_settings_form()` takes care of submitting. How do I get my control back? I need to do some custom processing in that \_submit handler...

# Answer
> 33 votes
The default submit handler of `$form_id . '_submit'` only fires if no other submit handlers have been set.

Because system\_settings\_form() sets a submit handler, the default handler doesn't fire, so you have to specify it if you want to use it.

You can do so like this:

```
/**
 * A custom form.
 */
function custom_form() {
  $form = array();

  $form['custom_form_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom form field'),
    '#default_value' => variable_get('custom_form_field', ''),
  );

  // Set a submit handler manually because the default submit handler
  // gets overridden by the system_settings_form() submit handler.
  $form['#submit'][] = 'custom_form_submit';

  return system_settings_form($form);
}

/**
 * Submit handler for the custom form.
 */
function custom_form_submit($form, &$form_state) {
  // Submit code here.
}

```

Adding your submit handler like this means yours will run before the system\_settings\_form() submit handler.

If you want yours to run after, instead of:

```
// Set a submit handler manually because the default submit handler
// gets overridden by the system_settings_form() submit handler.
$form['#submit'][] = 'custom_form_submit';

return system_settings_form($form);

```

Do:

```
$form = system_settings_form($form);
$form['#submit'][] = 'custom_form_submit';
return $form;

```

Make sure not to do this though:

```
$form = system_settings_form($form);
$form['#submit'] = array('custom_form_submit');
return $form;

```

because that would overwrite the system\_sttings\_form() submit handler, which would defeat the purpose of using the system\_settings\_form() function in the first place.

---
Tags: 7, forms
---


# Question
Title: Making a variable in a certain node type and access that variable in another node type
I'm fairly new to Drupal. But I'm trying to learn.

What I'm try to accomplish is have a variable in a certain node type (artist) and I want to access this variable in another node type (news). Is this possible?

Let's say I have two content types, Artists and News. The artist node will have (at some point) related pictures, songs, and news. But at default it does not have any. So I wanted a variable that acts like a flag that if there are any related pictures the flag is changed. In the news node, I have tags that point to an artist if the news is related to him/her, then I'll show the same related songs, pictures of the same tagged artist. I want the flag variable as a checker if there are truly related songs/pictures. In that way I'll just use the flag and before I query the related pictures/songs

# Answer
> 1 votes
What you are looking for is, basically, Entity Reference, as mentioned by Jimajamma and Bala:

> Provides a field type that can reference arbitrary entities

Just add entity reference field to news and allow artists to be selected. For pictures and songs, use either simply fields in Artist content type, or repeat the process - create content types for them, and add entity reference fields to artist content type.

Now, for display consider Views \- it can use entity reference field to show all songs by artist in setup like that. I believe that's the easiest way.

# Answer
> 0 votes
If you are using terms to relate the nodes, you can create a view that shows the related content by using relationships via the taxonomy term.

Then show the view on your node page and if there are no related content then the view will just not display.

You will still be running the query even if there are no results, but that shouldn't really be an issue unless you have a very complex view and very large amounts of content and no caching.

Another way you could do it if you prefer is to create a checkbox field on your node as the flag you refer to, then using the rules module you could set that flag on node save, based on other field data.

Then you could use that flag to do whatever you are planning.

I would recommend the first option though.

---
Tags: nodes
---


# Question
Title: How to list all nodes of nodetype A which has the current node referenced?
So this is what I'm trying to do in Drupal 6:

Node type A is video, node type B is a person Nodetype A has a reference field where you can enter a reference to any Node from nodetype B

how can I create a block view which will be displayed on nodes from node type b, which will show all the nodes from node type A where the current node from node type B is referenced?

# Answer
Simplest way would be to make references two-way. To do this, use:

That way, current node will reference all nodes that reference it - and from this point creating a view is trivial - or **you can simply display the field** created for back reference, *without need for a views module at all*.

**Other way is to use Views**. Create a view displaying nodes from content type A, add argument *content reference field \> provide default argument \> node ID from URL* and display this block view on the nodes from content type B.
> 1 votes

---
Tags: nodes, views
---


# Question
Title: How to output Get Locations coordinates as a separate field?
I have Get Locations module enabled, and I would like to **output the coordinates of a given location as a separate field** (longitude, latitude) **when displaying a given node**.

Somehow like this:
**GPS**: 45° 59' 45.24" N, 18° 40' 47.28" E

What's the best solution to do this?
Should I use Display Suite \+ "Add a code field" or is there a better solution?

# Answer
Finally, I solved it with creating a custom Display Suite field, which can be dragged on the admin interface similar to "regular" fields.
I can suggest this article for quick understanding: http://previousnext.com.au/blog/creating-custom-display-suite-fields-or-how-i-learned-stop-worrying-and-use-hookdsfieldsinfo

To get the necessary data from the field, I used `field_get_items()` like this article suggests (this is a must-read!): http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

This is how I created my custom Display Suite field for getting GPS data from the Get Locations field:

```
/**
 * Implements hook_ds_fields_info().
 * @see http://drupalcontrib.org/api/drupal/contributions!ds!ds.api.php/function/hook_ds_fields_info/7
 */
function TESTMODULE_ds_fields_info($entity_type) {
  $fields = array();

  $fields['node']['MYNODETYPE_gps'] = array(
    // title: title of the field
    'title' => t('GPS'),
    // type: type of field
    // - DS_FIELD_TYPE_FUNCTION   : calls a custom function.
    'field_type' => DS_FIELD_TYPE_FUNCTION,
    // ui_limit : only used for the manage display screen so
    // you can limit fields to show based on bundles or view modes
    // the values are always in the form of $bundle|$view_mode
    // You may use * to select all.
    // Make sure you use the machine name.
    'ui_limit' => array('MYNODETYPE|*'),
    // function: only for DS_FIELD_TYPE_FUNCTION.
    'function' => 'TESTMODULE_MYNODETYPE_ds_field_gps',
  );

  if (isset($fields[$entity_type])) {
    return array($entity_type => $fields[$entity_type]);
  }
  return array();
}

/**
 * Generate GPS coordinates as a DS field
 * Example: 46° 2' 27.24" N 18° 40' 37.2" E
 */
function TESTMODULE_MYNODETYPE_ds_field_gps($field, $title = NULL){
  $output = '';

  // http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way
  // instead of the ugly $on_the_map_getlocations_field_data = $field['entity']->field_MYNODETYPE_on_the_map['und'][0];
  $on_the_map_getlocations_field = field_get_items('node', $field['entity'], 'field_MYNODETYPE_on_the_map');

  if(isset($on_the_map_getlocations_field[0])){
    $on_the_map_getlocations_field_data = $on_the_map_getlocations_field[0];

    if(isset($on_the_map_getlocations_field_data['latitude']) && isset($on_the_map_getlocations_field_data['latitude'])){
      $output .= theme('getlocations_latitude_dms', $on_the_map_getlocations_field_data);
      $output .=  ' ';
      $output .= theme('getlocations_longitude_dms', $on_the_map_getlocations_field_data);
    }
  }

  return $output;
}

```

That's all!
> 0 votes

# Answer
Check out the geofield module. Even the Get Locations module supports it.
> 1 votes

# Answer
Get Geolocations seems to have support for Views.

If you add a view can't you add a field with the geolocation info and display them as lat/lon?
> 0 votes

---
Tags: 7, google-maps, location
---


# Question
Title: How to avoid url conflict when defining menu items, and make sure path without wildcards will be used in favor of path with %?
In `hook_menu`, I have

```
$path = "events"

$items[$path] = array(
  'title' => t('Events'),
  'page callback' => 'my_events_page',
  'access arguments' => array('view my events'),
  'type' => MENU_NORMAL_ITEM,
  'file' => 'my_events.pages.inc',
);

$items[$path . '/past'] = array(
  'title' => t('Past events'),
  'page callback' => 'my_events_past_page',
  'access arguments' => array('view my events'),
  'type' => MENU_NORMAL_ITEM,
  'file' => 'my_events.pages.inc',
);

$items[$path . '/%'] = array(
  'title' => t('Events'),
  'page callback' => 'my_events_page',
  'page arguments' => array($depth),
  'access arguments' => array('view my events'),
  'type' => MENU_CALLBACK,
  'file' => 'my_events.pages.inc',
);

```

They were working, but not now.

If I change `$items['events/past']` to `$items['events/past1']`, it works.

Does it mean I have path conflict? If so, how can I resolve it?

Rows in my `{menu_router}` table are as follows:

```
path: events
page_callback: views_page (but I set it to xxx_events_page in hook_menu)
fit: 1
include_file: empty (should not be empty)
--
path: events/%
page_callback: xxx_events_page (good)
fit: 2
include_file: a file path is there
--
path: events/past
page_callback: views_page (but I set it to xxx_events_past_page in hook_menu)
fit: 3
include_file: empty (should not be empty)

```

If I update the `page_callback` and `include_file` it works. If I clear the cache, everything set back to default.

# Answer
> 0 votes
Assuming you are using Drupal 7:

Order matters only a bit - `menu_router_build()` saves all path into the `{menu_router}` table just the way they are set. But there are no guarantees database will return elements in that order. Logic to decide which menu item should be executed is in `menu_get_item()`.

Actual query is:

```
$router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();

```

As you can see, fitting elements are ordered by `fit` column, most specific first.

As you can see in actual `_menu_router_build()`, `$fit` gets initially set to 0 for each menu item:

```
foreach ($callbacks as $path => $item) {
  $load_functions = array();
  $to_arg_functions = array();
  $fit = 0;

```

It means it shouldn't be possible for the order of menu elements in `hook_menu()` to affect order of routing. Actual code is a bit complicated to understand, but elements specific should have higher `fit` than elements with '%' in them. As the comment in code says: *// If there is no %, it fits maximally.*

# Answer
> 0 votes
I use this code bellow in a custom module "mymodule" with drupal 7 and everthing work well. What version of Drupal do you use ?

```
 <?php

    function mymodule_menu() {
        $path = "events";

        $items[$path] = array(
            'title' => t('Events'),
            'page callback' => 'my_events_page',
            'access arguments' => array('access content'),
            'type' => MENU_NORMAL_ITEM,
            //'file' => 'my_events.pages.inc',
        );

        $items[$path . '/%'] = array(
            'title' => t('Events'),
            'page callback' => 'my_events_page',
            'page arguments' => array($depth),
            'access arguments' => array('access content'),
            'type' => MENU_CALLBACK,
            //'file' => 'my_events.pages.inc',
        );

        $items[$path . '/past'] = array(
            'title' => t('Past events'),
            'page callback' => 'my_events_past_page',
            'access arguments' => array('access content'),
            'type' => MENU_NORMAL_ITEM,
            //'file' => 'my_events.pages.inc',
        );

        return $items;
    }

    function my_events_page(){
        print "hello";
    }

    function my_events_past_page(){
        print "past";
    }

    ?>

```

---
Tags: hooks, routes
---