# Question
Title: How do I show the weather block based on Geofield on a Taxonomy Term
The Weather module has a block to show weather based on IPs on a node defined by the geofield module. There doesn't seem to support if it is on a taxonomy term. How can I modify this code to support taxonomy terms?

```
   case 'geofield':
  if (user_access('access content')) {
    // Set up the node geofield weather block.
    if (arg(0) == 'node' and is_numeric(arg(1))) {
      $node = node_load(arg(1));
      $block['subject'] = t('Weather nearby');
      $block['content'] = '';
      $display = weather_get_display_config('default');
      $display->detailed = FALSE;
      // Get a list of all field names which are geofield fields.
      $geofield_field_names = db_select('field_config', 'fc')
        ->fields('fc', array('field_name'))
        ->condition('type', 'geofield', '=')
        ->execute()
        ->fetchCol();
      foreach ($geofield_field_names as $geofield_field_name) {
        if (isset($node->$geofield_field_name)) {
          // The node has geofield fields, determine if there's usable data.
          // First cycle through the language codes (will mostly be 'und').
          foreach ($node->$geofield_field_name as $language) {
            // Now cycle through the different locations.
            foreach ($language as $location) {
              if (($location['lat'] != 0) or ($location['lon'] != 0)) {
                $place = weather_get_nearest_station($location['lat'], $location['lon']);
                $forecasts = weather_get_weather($place->geoid, $forecast_days, $display->detailed);
                $weather[0]['forecasts'] = $forecasts['forecasts'];
                $weather[0]['utc_offset'] = $forecasts['utc_offset'];
                $weather[0]['name'] = $place->displayed_name;
                $weather[0]['geoid'] = $place->geoid;
                $link = _weather_get_link_for_geoid($place->geoid, 'default');
                $weather[0]['link'] = l($place->displayed_name, $link);
                $link = _weather_get_link_for_geoid($place->geoid, 'yr.no');
                $weather[0]['yr.no'] = $link;
                $weather[0]['station'] = array('distance' => $place->distance, 'bearing' => $place->bearing);
                $block['content'] = theme('weather_forecast_preprocess',
                  array('weather' => $weather, 'display' => $display));
              }
            }
          }
        }
      }
      // Do not show block if no lat/long information has been found.
      if (empty($block['content'])) {
        return;
      }
    }
  }

```

# Answer
Here's a stab at it. You'll obviously need to test as I haven't tested it at all. Basically I added in some checks to see if it was a node or a term and then tried to test the fields for either one. Let me know if it helps!

```
 case 'geofield':
    if (user_access('access content')) {
        // Set up the node geofield weather block.
        if (arg(0) == 'node' and is_numeric(arg(1))) {
            $node = node_load(arg(1));
        } else if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
            $term = taxonomy_term_load(arg(2));
        }

        $block['subject'] = t('Weather nearby');
        $block['content'] = '';
        $display = weather_get_display_config('default');
        $display->detailed = FALSE;
        // Get a list of all field names which are geofield fields.
        $geofield_field_names = db_select('field_config', 'fc')
            ->fields('fc', array('field_name'))
            ->condition('type', 'geofield', '=')
            ->execute()
            ->fetchCol();
        foreach ($geofield_field_names as $geofield_field_name) {
            $geofieldname = array();
            if (isset($node->$geofield_field_name)) {
                $geofieldname = $node->$geofield_field_name;
            } else if (isset($term->$geofield_field_name)) {
                $geofieldname = $term->$geofield_field_name;
            }

            if (!empty($geofieldname)) {
                // The node/term has geofield fields, determine if there's usable data.
                // First cycle through the language codes (will mostly be 'und').
                foreach ($geofieldname as $language) {
                    // Now cycle through the different locations.
                    foreach ($language as $location) {
                        if (($location['lat'] != 0) or ($location['lon'] != 0)) {
                            $place = weather_get_nearest_station($location['lat'], $location['lon']);
                            $forecasts = weather_get_weather($place->geoid, $forecast_days, $display->detailed);
                            $weather[0]['forecasts'] = $forecasts['forecasts'];
                            $weather[0]['utc_offset'] = $forecasts['utc_offset'];
                            $weather[0]['name'] = $place->displayed_name;
                            $weather[0]['geoid'] = $place->geoid;
                            $link = _weather_get_link_for_geoid($place->geoid, 'default');
                            $weather[0]['link'] = l($place->displayed_name, $link);
                            $link = _weather_get_link_for_geoid($place->geoid, 'yr.no');
                            $weather[0]['yr.no'] = $link;
                            $weather[0]['station'] = array('distance' => $place->distance, 'bearing' => $place->bearing);
                            $block['content'] = theme('weather_forecast_preprocess',
                                array('weather' => $weather, 'display' => $display));
                        }
                    }
                }
            }
            unset($geofieldname);
        }

        // Do not show block if no lat/long information has been found.
        if (empty($block['content'])) {
            return;
        }

    }

```
> 0 votes

---
Tags: location
---


# Question
Title: commerce_cart_order_load not working for anonymous user in drupal commerce
I have created an order programmatically, the order is created and shown in backoffice order listing, but most of the time in the cart it shows empty.When I checked I found that commerce\_cart\_order\_load for anonymous user return false.

Please help me to find the solution.

Here is the code on submit function i have written :

```
global $user;
$product_id = $form_state['input']['product_id'];
$quantity = $form_state['input']['quantity'];
$audience = $form_state['input']['audience_id'];
$material = $form_state['input']['material_id'];
if ($product = commerce_product_load($product_id)) {
  $threshold = $product->field_threshold_quantity['und'][0]['value'];
  if(is_numeric($threshold) && $threshold != ''){
    if($quantity >= $threshold){
      $box_code = $product->field_box_code['und'][0]['value'];
      $product->sku = $box_code ;
      $quantity = 1;
    }

  }
  if (!commerce_cart_order_session_exists())
   {
                $order = commerce_cart_order_new();
               $order->log = t("Created by checkout page.");
               commerce_cart_order_session_save($order->order_id);
     }
  // Attempt to load existing order for user from session
   $order = commerce_cart_order_load();
    if(!$order){
      $order = commerce_cart_order_new($user->uid);
    }

  // Save new order to get order id
  if(empty($order->order_id)){
    $order->revision = FALSE;
    commerce_order_save($order);
  }
  $order_id = $order->order_id;
  // Wrapper for easy field access and adding line items, order passed by reference
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  //uid of the logged in user
  $uid = $user->uid;
  $line_item = commerce_product_line_item_new($product, $quantity);
  $line_item->field_line_item_audience['und'][]['tid'] = $audience;
  $line_item->field_line_item_item_type['und'][]['tid'] = $material;
  $line_item_added = commerce_cart_product_add($uid, $line_item, FALSE);
  //$order_wrapper->commerce_line_items[] = $line_item;
  commerce_line_item_save($line_item);
  if($uid  == 0 ){
      commerce_cart_order_session_save($order_id);
  }
 //
  // Save new line item to get line item id

 // Add line item to order wrapper
//

  // Save order with new order number and line item added
  $order->revision = FALSE;
  $order_wrapper->save();

```

# Answer
> 4 votes
Every thing is ok,I had the same problem after spend a half night I found that sometimes drupal dont start session for anonymous users then you should start it manually if begin of your function

```
   drupal_session_start();

```

---
Tags: commerce
---


# Question
Title: How to force caching to work for View with filter by date offset?
Faced with a strange situation: if a View uses filter "Post date" (or similar) with an offset (eg, "\> = -1 month"), this View won't cache.

Example: I create a simple View with Block display.

* Field: "Content: Title"
* Caching: "Time-based | 1 hour/1 hour"
* Block caching: "Cache once for everything (global)"

Of course, global setting "Cache blocks" is on.

If I place this block on a page, it is cached properly.

I want to filter nodes for a certain period of time. I add filter with an offset from the current time: "Content: Post date (\>= -1 month)". And this block will no longer be cached! Every time I load a page with this block, there is a new call to the database ("SELECT node.title AS node\_title ..."). In addition, the table "cache\_views\_data" is filling with multiple records like "my\_view:block\_1:results:1a2s3d4d" and "my\_view:block\_1:output:m0n9b8v7".

How could I force caching of this block to work?

# Answer
Finally, I found a particular workaround here.
> 0 votes

# Answer
In Drupal caching system, there's an option to cache pages/blocks for anonymous users only, maybe it's the same thing for **Views**. Check if it works with a not logged in user.
> 0 votes

---
Tags: views, caching
---


# Question
Title: What version of Drush is compatible with Drupal 6 / PHP 5.2
Just installed drush on a system using PHP 5.2. However, when I run drush, a message is displayed saying `Your command line PHP installation is too old. Drush requires atleast PHP 5.3.0. To suppress this check, set the environment variable
DRUSH_NO_MIN_PHP=1`. Since I am using Drupal 6 I need to use PHP 5.2. Could someone please tell me which version of Drush is compatible with Drupal6 / PHP5.2.

# Answer
> 1 votes
A list of Drush versions and their compatibility can be found here. Appears Drush Version 5.x is compatible with php5.2.

Here is the current compatibility table reproduced from the link above

---
Tags: 6, drush
---


title: How to get the path to a node

text:
# Question
Title: How to get the path to a node
I'm using a view template to override how a field is displayed.

I want to include a link to the node in the field.

Given a node, how do I get the URL (relative is fine) for a node?

I've got the node in the overridden template, but not sure where to go from there:

```
$node = node_load($row->{$field->field_alias});
$wrapper = entity_metadata_wrapper('node', $node);

$path_to_node = ???

?><a href="<?php print $path_to_node ?>">Go to Node</a>

```

# Answer
> 2 votes
You don't need entity\_metadata\_wrapper in this case. You can get path of node using `url()` function.

```
$node = node_load($row->{$field->field_alias});
$nid = $node->nid;
$path_to_node = url("node/$nid");

```

And I agree with Елин Й's answer. You can use `l()` function. It already uses `url()` function. So you can build link with node pathauto alias using:

```
$node = node_load($row->{$field->field_alias});
print l(t('Go to Node'), 'node/' . $node->nid);

```

# Answer
> 1 votes
In your view, you need to output the Node: Path field. Then you can access the information in the view using:

```
$fields["path"]->content;

```

# Answer
> 0 votes
A views template should have the $view variable available, so you could use:

```
$nid = $view->result[$id]->nid;
$path = "node/".$nid;

```

# Answer
> 0 votes
URL to a node is `node/$node->nid`. I would strongly recommend you to use l() function to generate links, so that it will always print the right URL.

# Answer
> 0 votes
In your code example it would be:

```
$node = node_load($row->{$field->field_alias});
$wrapper = entity_metadata_wrapper('node', $node);
print l(t('Go to Node'), 'node/' . $node->nid);

```

# Answer
> 0 votes
For a proper seo friendly url use the lookup path function:

$ path = drupal\_lookup\_path('alias',"node/".$node-\>nid)

---
Tags: views, theming, nodes
---


title: Deleting unused Distribution modules

text:
# Question
Title: Deleting unused Distribution modules
In the past, when working with Drupal Commerce, I have built it from scratch. This is usually to fine tune exactly the modules I need, and to keep an eye on performance as I add each module.

After doing a few sites this way, I get pretty sick of the process of configuring it all every time, and so with this next project, I have decided to save myself some time, and use Commerce Kickstart 2. I have downloaded it and a had a quick play on WAMP, and its great to have a working site ready to go, with a huge amount of time and worked saved.

However, it feels slow compared to the sites I build from scratch, and there is a lot of modules in this distribution that I wont be needing, and so I will go through and disable/uninstall the modules I don't need.

This still leaves a huge list of modules on the modules page, and even though there is a quick search/filter on the modules page, I would just rather they weren't there.

My question(s) is/are, am I OK to just go and delete all of the modules from the Kickstart profiles folder once I have uninstalled them? Is this considered bad practice for any reason? Will I see any sort of performance increase by deleting them? (I think I will as the system table will be much smaller)

# Answer
> 1 votes
By disabling modules enabled by the profile, you may be working against yourself. There is known issue that D7 does not enforce module dependencies listed in the .info of a profile. So if some of the modules you are disabling were enabled on install because they are listed in http://cgit.drupalcode.org/commerce\_kickstart/tree/commerce\_kickstart.info, then you will find that the profile itself is actually disabled. You can tell if this has happen by looking in the system table and/or the status report. In the system table, the status on of the profile will be 0. In the status report you'll see the profile's name, but no version number. You can read more about the D7 issue in https://www.drupal.org/node/1170362. Some progress has been made on addressing this in D8 in https://www.drupal.org/node/820054.

Because Drupal also uses a variable to tell which profile is being used, a disabled profile may not cause any issues beyond preventing update status lookups. But if a module is being included as a dependency in the .info, it's worth taking the time to understand why the profile's maintainer added that dependency in the first place.

As far as removing modules with a status of 0 to achieve a slightly smaller system table, that is unlikely to have a measurable impact on performance. Where you may see a performance hit is from lots of extra .info and .install files. Creating the list of modules at admin/modules requires scanning several directories for .info files. Checking for updates scans the .install files for any update hooks that haven't already been applied. Beyond that, modules that are not enabled shouldn't be impacting the performance when Drupal renders a page.

You should consider using https://www.drupal.org/project/profiler\_builder to generate your own profile and .make from one of the sites you built from scratch. That would give you the advantage of getting another site started quickly without the overhead of a general purpose kickstarter style profile and distribution.

If you do create your own profile, please consider sharing it on Drupal.org so that other members of the community can benefit from the a more efficient (while less robust) Commerce configuration.

---
Tags: 7, commerce
---


# Question
Title: How do I programatically submit a webform via drupal_form_submit?
Drupal 7, Webform 3

I want to programmatically submit a webform via drupal\_form\_submit. However, I'm having difficulty finding a $form\_state structure that works. I've submitted my webform via the ui and examined the $form\_state variable in my validate callback function, but I still can't get it to work.

My webform has one textfield named "first\_name". Below is a snippet of code I've used to test. Whenever I run it, $form\_errors is `null`. With no errors, I would expect the code to have worked. However, when I check the webform results, it says there are no submissions.

```
<?php
$form_id = 'webform_client_form_55805';
$form_state = array(
  'values' => array(
    'submitted' => array(
      'first_name' => 'David',
    ),
  ),
);
$node = node_load(55805);
$submission = (object) array();

drupal_form_submit($form_id, $form_state, $node, $submission);
$form_errors = form_get_errors();
?>

```

Am I doing it wrong? Is there a better way? Should I be using webform\_client\_form\_submit instead?

I looked at this Q&A, but it doesn't work for me and seems a bit convoluted: How to submit webform programmatically with Ajax?

# Answer
I used PhpStorm and xdebug to step through the form.inc code and finally found the correct structure for my $form\_state. The structure I posted was close, just needed to add the `'op' => t('Submit')`. See my final working code below.

To answer my questions:

1. Yes, drupal\_form\_submit is what I should be using.
2. See code below for the magical $form\_state structure.

```
<?php
$form_id = 'webform_client_form_55805';
$form_state = array(
  'values' => array(
    'submitted' => array(
      'first_name' => 'David',
    ),
    'op' => t('Submit'),
  ),
);
$node = node_load(55805);
$submission = (object) array();

drupal_form_submit($form_id, $form_state, $node, $submission);
$form_errors = form_get_errors();
?>

```
> 5 votes

# Answer
I had to make a slight amendment to David's answer above (I can't comment as I don't have enough points). The data was not submitting as the op didn't match the text on the submit button. I have correct by reading it in from the webform info attached to the node.

```
<?php
$node = node_load(55805);
$form_id = 'webform_client_form_55805';
$form_state = array(
  'values' => array(
'submitted' => array(
  'first_name' => 'David',
    ),
    'op' => empty($node->webform['submit_text']) ? t('Submit') : t($node->webform['submit_text']),
  ),
);

$submission = (object) array();

drupal_form_submit($form_id, $form_state, $node, $submission);
$form_errors = form_get_errors();
?>

```
> 0 votes

---
Tags: forms, webforms
---


# Question
Title: Programmatically create user reference field
I want to add a user reference field in taxonomy term. I create field and it's instance:

```
$field = ['field_name' => 'mymodule_employee',
        'label' => t('Employee'),
        'type' => 'entityreference',
        'cardinality' => 1,
        'settings' => [
            'target_type' => 'user',
            'handler' => 'base',
            'handler_settings' => [
                'target_bundles' => ['user']
            ],
        ],
];
field_create_field($field);

$instance = ['mymodule_employee' => [
            'entity_type' => 'taxonomy_term',
            'bundle' => 'my_vocabulary',
            'field_name' => 'mymodule_employee',
            'label' => t('Employee'),
            'widget' => array(
                'type' => 'options_select',
                'active' => 1,
            ),
            'settings' => array(
                'target_type' => 'user',
                'handler_settings' => array('target_bundles' => null),
                'handler' => 'base',
            ),
            'display' => array(
                'default' => array('label' => 'inline', 'type' => 'entityreference_label'),
            ),
            'required' => 0,
            'default_value' => null,
        ],
];
field_create_instance($instance);

```

Everything goes ok. But when I'm creating the term and try to choose a user there is an empty list. When I go to the field settings in admin form and just save it, everything begins to work.

What do I forget creating field and instance?

# Answer
> 1 votes
Check if Entity Reference Autocomplete module helps you. The module page says

> This module defines a new form element type, called "entityreference", that allows developers to add autocomplete fields to forms, so that users can reference any entity in the same way they would do through an Entity Reference field.

# Answer
> 1 votes
To add a reference to the user, use the References module, and then enable the User Reference module defined by it.

Then you will need to define the field in your hook\_enable or hook\_install function. Do something like the following:

```
$field = array(
  'field_name' => 'vendor_user_reference',
  'type' => 'user_reference',
  'cardinality' => 1,
  'entity_types' => array('commerce_product'),
  'translatable' => FALSE,
  'settings' => array(
            'referenceable_status' => array(
               0 => 0,
               1 => '1',
             ),
    )
);
field_create_field($field);

```

You MUST define a value for referenceable\_status. If you don't, the user list will not populate in the interface. You can also at this time define the referenceable\_roles array too. It would look something like this: 'referenceable\_roles' =\> array( 2 =\> 0, 3 =\> 0, 4 =\> '4', 5 =\> 0, 6 =\> 0, ),

where you set the role you want to the rid from the role table.

You will then need to create an instance of the field on your entity. I did the following for a Drupal Commerce Product. (for Commerce Kickstart 2.0, this goes in the hook\_commerce\_product\_type\_insert($product\_type, $skip\_reset) for a product type entity.)

```
$new_instance = array(
  'field_name' => 'vendor_user_reference',
  'entity_type' => 'commerce_product',
  'bundle' => $product_type['type'],
  'label' => t('Vendor User Reference'),
  'required' => TRUE,
  'widget' => array(
                'active' => 1,
                'module' => 'options',
                'settings' => array(
                        'apply_chosen' => '',
                ),
                'type' => 'options_select',
                'weight' => '40',
        ),
   'display' => array(),
);
field_create_instance($new_instance);

```

Now, if you want to set the value of the select list that is created for the users (say the logged in user), You will need to modify your hook\_form\_alter function to add the following:

```
$entity_form['vendor_user_reference']['und']['#default_value'] = (string)$user->uid;

```

I am not quite sure why I need the \['und'\] for my form, but it wouldn't work without it.

---
Tags: 7, taxonomy-terms, users, entities
---


# Question
Title: How do I get the default billing/shipping customer profile in code?
Is there a way to get the default billing/shipping customer profile from a user?

I'm getting all customer profiles with:

```
$profiles = commerce_customer_profile_load_multiple(array(), array('uid' => $user->uid));

```

But which customer profile was set as default by the user?

# Answer
> 3 votes
You can get default user profile address with

```
commerce_addressbook_get_default_profile_id($uid, $type)

```

**Returns the default profile id for a specific uid and profile type.**

**@param $uid** The uid of the user whose default profile id should be returned.

**@param $type** The type of customer profile to look up.

**@return** The id of the default profile if set, FALSE otherwise.

An example if want get current user `shipping` addresss use below code :

```
global $user;
$default_pid=commerce_addressbook_get_default_profile_id($user->uid,'shipping');

```

# Answer
> 1 votes
I'm guessing that if you refer to the default field in relation with the user, you're using Commerce Addressbook, you've got an api function to get the default profile given a user id and the profile type: commerce\_addressbook\_get\_default\_profile\_id

If you're not, you can get the profiles used by a given customer using the customer profile reference field for *billing / shipping / whatever* and consulting the variable `commerce_customer_profile_' . $type . '_field'`

So for loading the profiles of a given type you can use Entity Field Query using the customer user id against the order entity.

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'commerce_order')
  ->propertyCondition('uid', 0)
  ->execute();
if (!empty($result['commerce_order'])) {
  $orders = entity_load('commerce_order', array_keys($result['commerce_order']));
}

```

And then wrap the entity or use field\_get\_items:

```
$field_name = variable_get('commerce_customer_profile_billing_field', '');
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->{$field_name}->value();

```

# Answer
> 0 votes
This might Help (Only billing i have mentioned here, you can change your condition depending on your needs).

```
$uid = "1"; //Define user id for which default address is to be found
$query = db_select("commerce_addressbook_defaults","c");
$query->fields("c",array("profile_id"));
$query->condition("uid",$uid);
$query->condition("type","billing");
$output = $query->execute()->fetchObject();

$profile_id = $output->profile_id;
if(!empty($profile_id)){
    $franchisee_info = commerce_customer_profile_load ($profile_id);
    echo "<pre>";
    print_r($franchisee_info);
    echo "</pre>";
}

```

---
Tags: commerce
---


# Question
Title: How can I add an existing field to a new content type?
I have a content type with name category and have title and an image under it. I want a select option with this category name while for my new content type "videos". How can I do this?

# Answer
> 2 votes
You can find an option to select existing field under the list of fields :

---
Tags: 7, nodes, files, media
---


# Question
Title: Resource interpreted as Image but transferred with MIME type text/html
I've been embedding an image with my page using item type form control in Drupal 7 Forms API.Below are my codes:

```
function myid_user_page_form(){
    $form = array();
    $form['id'] = array(
        '#type' => 'fieldset',
        '#title' => t('ID Information'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );

    $form['id']['myid'] = array(
        '#type' => 'item',
        '#markup' =>
            '<div id="divID"><img src="images/id-background.jpg" alt="ID Picture"/></div>'
    );
    return $form;
}

```

My image doesnt show up and is broken eventhough the path is correct and file permissions are set properly.

What Shall I Do? Below is the error:

```
Resource interpreted as Image but transferred with MIME type text/html: "http://localhost/drupal-7.34/user/7/images/id-background.jpg".

```

Below is a screen capture of my page.

# Answer
> 0 votes
Image path is incorrect. It will pick the path of image as `http://current_path/images/id-background.jpg`.

```
global $base_url;
$path = $base_url . drupal_get_path('module', 'mymodule') . '/images/id-background.jpg'; // considering the image is placed in your custom module's image directory
$form['id']['myid'] = array(
  '#type' => 'item',
  '#markup' => '<div id="divID"><img src="' . $path . '" alt="ID Picture"/></div>'
);

```

---
Tags: media, .htaccess
---


# Question
Title: Secondary & Tertiary links next to Parent links
How can I print expandable secondary and tertiary links to the right of the parent? For mobile, the secondary and tertiary links will need to stack below the parent links. Below is an example of what I am looking to achieve.

Menu tree Menu on front end

# Answer
You can achieve this by using the module menu block. This module allows you to display certain levels of a menu considering the selected parent item.
> 0 votes

---
Tags: routes, navigation
---


# Question
Title: node anchors on single front page website
I'm building a single page website Omega subtheme on drupal 7. I've got a menu on top with 5 items which I want to link them with an other 5 nodes on the same page. Obviously we need **anchors** here.

Which way do you think is smarter to achieve this?

PS:No, I don't want to use Single Page Website module

# Answer
We created the Single Page Site module, to incorporate one page websites into Drupal. This is an example of a website using it: http://starfisk.com

Some more details about this module (from its project page), which is available for both D7 and D8:

> This module provides functionality to create a single page website.
>
> It allows you to automatically create a single page from a menu. The module will render all the content from the links, that are configured in the menu, on one page. It will then override the menu links so that they refer to an anchor instead of a new page.
> 2 votes

# Answer
I think you could use the hook\_menu and create custom menu entries for this. The hook has an options array where you can pass such values.

> "options": An array of options to be passed to l() when generating a link from this menu item. Note that the "options" parameter has no effect on MENU\_LOCAL\_TASK, MENU\_DEFAULT\_LOCAL\_TASK, and MENU\_LOCAL\_ACTION items.

Not tested, but i think you can pass a "fragement" to the hook\_menu options array like: `array('fragment' => 'idofanchor')`
> 0 votes

---
Tags: 7, nodes, navigation
---


# Question
Title: How to give a path to a link with filter?
I am trying to give a path to a submenu with Filter(field) as

my-view&field\_subject=C

but it shows error like 'path is either invalid or you do not have access to it.'

when i give 'my-view' it works perfectly.

But i want to show the view with 'Subject' column with Value C only.

# Answer
'&' is used to divide query parameters, to split the page and parameters, use '?'

e.g. my-view?field\_subject=C
> 3 votes

---
Tags: views, uri
---


# Question
Title: Change Views Handler for entity schema field
I want to have a numeric value in my db treated as boolean by drupal.

the field is defined in the hook\_schema like this

```
    'myfield'  => array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => FALSE,
    'default' => NULL,
    'description' => "a field",

```

So Drupal Views module rightfully detects and displays it as a number. However i want it to be a Boolean, so in my hook\_entity\_info i have

```
'views controller class' => 'StrutturaViewsController',

```

and then

```
class StrutturaViewsController extends EntityDefaultViewsController {

  public function views_data() {
    $data = parent::views_data();

    $data['struttura']['myfield']['field']['handler'] = 'views_handler_field_boolean';

    return $data;
  }
}

```

'struttura' is the name of the entity that i created, and the name of the table with the 'myfield' coloumn

My problem is that Drupal is still treating the value as numeric.

Am i missing something?

# Answer
> 0 votes
Sure. Adding a new answer to clarify.

To my knowledge (and by that i mean my "very limited Drupal Knowledge") there are 2 ways of mapping the information between schemas and Druapl handlers: by using a custom view controller as i tried to do in the first post, and by implementing the hook\_entity\_property\_info\_(). I still don't know why the former approach didn't work but the solution for me was to go with the latter. That is, i had to write

```
'myfield' => array(
  'type'  => 'boolean',
  'label' => t('clever label'),
  'description' => t('clever description'),

  // Map here the field from hook_schema().
  'schema field' => 'insert_name_of_schema_field_here',
),

```

Mind that you will have to map EVERY AND EACH of your fields in the schema once you start with this approach.

I also noticed that sometimes doing stuff (like changing ajax config) on the view rendering my entity seems to break the mappings, and i have to clear all caches to bring back my settings.

You can find more information Here

# Answer
> -1 votes
I implemented hook\_entity\_property\_info\_() instead of changing the view controller, and everything went fine

---
Tags: views, entities
---


# Question
Title: How to print and/or manipulate individual image attributes and suppress width and height via the image.html.twig template
I had to get rid of the width and height attributes in my images and wanted to learn better the possibilites of Twig in Drupal.

# Answer
> 0 votes
Copy the image.html.twig file from core/modules/system/templates/ to your theme /templates folder.

If you want to simply hide width and height as image attributes:

```
{%
set classes = [
    style_name ? 'image-style-' ~ style_name|clean_class,
]
%}
<img{{ attributes|without('width','height').addClass(classes) }} />

```

If you want to do further things it would be probably better to use template preprocessing functions in the theme file (because of too much logic here) - so this is more a use case for the possibilities in twig files ...

If you want to hide width and height and also want to hide empty class and alt attributes for example:

```
{%
    set classes = [
        style_name ? 'image-style-' ~ style_name|clean_class,
    ]
%}
{% set printattributes = attributes.addClass(classes)|without('src','alt','class','width','height') %}
{% set printclass = attributes.class.value() ? 'class="' ~ attributes.class ~ '"' : '' %}
{% set printalt = alt ? 'alt="' ~ alt ~ '"' : '' %}

<img {{ printclass|passthrough }} src="{{uri}}" {{ printattributes }} {{ printalt|passthrough }} />

```

This is also very useful in this context: http://drupal.stackexchange.com/questions/137652/override-image-formatter-html-twig/141340#141340

---
Tags: theming, 8, media
---


title: Why are my HTML emails so garbled?

text:
# Question
Title: Why are my HTML emails so garbled?
I'm using the Mimemail, Mail System and SMTP Authentication Support modules (plus a few others) to send html email. I'm basically following these guidelines, except I'm using Mimemail instead of Htmlmail so I will have the option of sending attachments in the future.

I have this working on another server, so I'm sure this is a configuration issue, but right now any emails I send out as HTML come through Gmail like this:

I have seen this happen a number of times so far and have figured out a few of the causes, but my guess is that it is on Drupal's side, probably when mimemail/htmlemail is composing the email.

I have seen this break down like this when:

* an \<html\> tag was included in my markup
* some tags included valid microdata attributes
* but also when using this test string:

*\<div style="width:500px; margin: 20px auto; color:green;"\>test\</div\>*

I don't know what the underlying problem is, which makes it hard to troubleshoot. Has anyone else experienced this? What's going on?

The raw content of the email is as follows:

```
Delivered-To: micah.mutrux@gmail.com
Received: by 10.96.110.138 with SMTP id ia10csp225196qdb;
        Tue, 14 Jan 2014 13:10:59 -0800 (PST)
X-Received: by 10.49.119.66 with SMTP id ks2mr6855038qeb.14.1389733858933;
        Tue, 14 Jan 2014 13:10:58 -0800 (PST)
Return-Path: <brandthropologist@brandthropology.com>
Received: from mail-qe0-f42.google.com (mail-qe0-f42.google.com [209.85.128.42])
        by mx.google.com with ESMTPS id ni15si2151378qeb.90.2014.01.14.13.10.58
        for <micah.mutrux@gmail.com>
        (version=TLSv1 cipher=ECDHE-RSA-RC4-SHA bits=128/128);
        Tue, 14 Jan 2014 13:10:58 -0800 (PST)
Received-SPF: neutral (google.com: 209.85.128.42 is neither permitted nor denied by best guess record for domain of brandthropologist@brandthropology.com) client-ip=209.85.128.42;
Authentication-Results: mx.google.com;
       spf=neutral (google.com: 209.85.128.42 is neither permitted nor denied by best guess record for domain of brandthropologist@brandthropology.com) smtp.mail=brandthropologist@brandthropology.com
Received: by mail-qe0-f42.google.com with SMTP id b4so205383qen.15
        for <micah.mutrux@gmail.com>; Tue, 14 Jan 2014 13:10:58 -0800 (PST)
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=1e100.net; s=20130820;
        h=x-gm-message-state:date:to:from:reply-to:subject:message-id
         :mime-version:content-type;
        bh=q863iUWoCdb0QZ/E9G4JcaTazlYbBVv/2KBPGt9MjWE=;
        b=R/76jgNUVqjJAKnHYvDDo9wbdQ3CJRm0xEbsk25O2ZstnH2uqcRNxJ4imF+5a2JaSq
         0rJRp4buE44SnVrfeNthjUFo1WB6+9P26PHFlh1PPXQp2RAc5Wyjz1TB2ZHIKj0roWNr
         iBnLThIB2OCIcdgKDElEkUDC/cYm6AlGcvfidFWPQqffjdSMC5u+fDZ/8xCnH4DsTXud
         HMIGvFxQvuoYEIvj8ZEbaQwWxnI1bSDyKKr/BPNaz3l4wpB41NknyFID191hYnPsaoiX
         SaS1AzxSbOiHJRBBqEvAm45HtQvvxo2aOTCatZ+I1j6OG33DP2jiNmwlmab1MvBg4ecC
         ndLQ==
X-Gm-Message-State: ALoCoQn44cG6SY12THEWYWjpjhN40xzudvrqezMfoTbnIw0tyyVXtPNxjvWTg+sz7T5JCN8lWCC2
X-Received: by 10.224.43.72 with SMTP id v8mr7141008qae.52.1389733858586;
        Tue, 14 Jan 2014 13:10:58 -0800 (PST)
Return-Path: <brandthropologist@brandthropology.com>
Received: from staging.burlingtonelectric.com ([64.207.185.89])
        by mx.google.com with ESMTPSA id g10sm2538269qaf.9.2014.01.14.13.10.57
        for <micah.mutrux@gmail.com>
        (version=TLSv1.2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Tue, 14 Jan 2014 13:10:57 -0800 (PST)
Date: Tue, 14 Jan 2014 16:10:55 -0500
Return-Path: brandthropologist@brandthropology.com
To: micah.mutrux@gmail.com
From: "Burlington Electric Dept." <brandthropologist@brandthropology.com>
Reply-to: brandthropologist@brandthropology.com
Subject: Thank you for contacting Burlington Electric!
Message-ID: <4a65e76f1c8243dcfd2db906a0c0a45d@staging.burlingtonelectric.com>
X-Priority: 3
X-Mailer: PHPMailer 5.1 (phpmailer.sourceforge.net)
MIME-Version: 1.0
Content-Type: multipart/alternative;
    boundary="b1_4a65e76f1c8243dcfd2db906a0c0a45d"

--b1_4a65e76f1c8243dcfd2db906a0c0a45d
Content-Type: text/plain; charset = "UTF-8"
Content-Transfer-Encoding: 8Bit

test

--b1_4a65e76f1c8243dcfd2db906a0c0a45d
Content-Type: text/html; charset = "UTF-8"
Content-Transfer-Encoding: 8Bit

PGh0bWw+CiAgPGhlYWQ+CiAgICA8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRl
bnQ9InRleHQvaHRtbDsgY2hhcnNldD11dGYtOCIgLz4KICAgICAgICA8c3R5bGUgdHlwZT0idGV4
dC9jc3MiPgogICAgICA8IS0tCiAgICAgIC5jbGVhcmZpeHsqem9vbToxfS5jbGVhcmZpeDpiZWZv
cmUsLmNsZWFyZml4OmFmdGVye2Rpc3BsYXk6dGFibGU7bGluZS1oZWlnaHQ6MDtjb250ZW50OiIi
fS5jbGVhcmZpeDphZnRlcntjbGVhcjpib3RofS5oaWRlLXRleHR7Zm9udDowLzAgYTtjb2xvcjp0
aWdjYXB0aW9uLGZpZ3VyZSxmb290ZXIsaGVhZGVyLGhncm91cCxuYXYsc2VjdGlvbntkaXNwbGF5
OmJsb2NrfWF1ZGlvLGNhbnZhcyx2aWRlb3tkaXNwbGF5OmlubGluZS1ibG9jazsqZGlzcGxheTpp
bmxpbmU7Knpvb206MX1hdWRpbzpub3QoW2NvbnRyb2xzXSl7ZGlzcGxheTpub25lfWh0bWx7Zm9u
dC1zaXplOjEwMCU7LXdlYmtpdC10ZXh0LXNpemUtYWRqdXN0OjEwMCU7LW1zLXRleHQtc2l6ZS1h
ZGp1c3Q6MTAwJX1hOmZvY3Vze291dGxpbmU6dGhpbiBkb3R0ZWQgIzMzMztvdXRsaW5lOjVweCBh

  [[this goes on for ~3000 lines]]

aGVhZD4KICA8Ym9keSBpZD0ibWltZW1haWwtYm9keSIgY2xhc3M9Im1pbWVtYWlsLWNvbnRhY3Qt
dXMtbm90aWZ5LXNlbmRlciI+CiAgICA8ZGl2IGlkPSJjZW50ZXIiPgogICAgICA8ZGl2IGlkPSJt
YWluIj4KICAgICAgICA8ZGl2IHN0eWxlPSJ3aWR0aDo1MDBweDsgbWFyZ2luOiAyMHB4IGF1dG87
Ij4KdGVzdAo8L2Rpdj4gICAgICA8L2Rpdj4KICAgIDwvZGl2PgogIDwvYm9keT4KPC9odG1sPgo=

--b1_4a65e76f1c8243dcfd2db906a0c0a45d--

```

# Answer
I've asked a friend that has e-mail experience. He's saying that the e-mail header is saying the encoding is text, but the garbled text looks like Base64 encoding. I'm using Mimemail quite a bit and never ran into this issue...

Any strange config to speak of?

I went to this site: http://www.opinionatedgeek.com/dotnet/tools/base64decode/ and pasted in the first part of your garbled text and got this:

```
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <style type="text/css">
      <!--
      .clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:tigcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}a:focus{outline:thin dotted #333;outline:5px a

```

I'm assuming that looks familiar. So I can tell you that your encoding is wrong, but as to how to fix that...
> 3 votes

# Answer
--b1\_4a65e76f1c8243dcfd2db906a0c0a45d Content-Type: text/html; charset = "UTF-8" Content-Transfer-Encoding: **8Bit**

PGh0bWw+CiAgPGhlYWQ+CiAgI

The issue is incorrect encoding value in mail when the content is encoded Content-Transfer-Encoding: 8Bit ==\> needs to be Content-Transfer-Encoding: base64

Though the multi-part MIME content is encoded, it's value is shown as 8Bit in the mail content pasted above.

If you open saved .eml file in notepad and change that one line and save it (as .eml), it will open properly in any mail client!
> 1 votes

---
Tags: 7, emails
---


# Question
Title: Is it possible to show Poll results as a table in Views?
I want to show the results of a Poll (core module) in Views.

However, the only way to show any Polls in Views is just as a full node (as they appear to a normal user).

I want to be able to display it as a table so that I can make it easily exportable to Excel (using the Views Export XLS module).

Any ideas?

# Answer
Try to use below modules :

1. Responsive Tables
2. Data
3. FooTable
> 0 votes

---
Tags: views, importing-exporting, polls
---


# Question
Title: Display link after complete countdown time
I am using Field Timer module.

Is there any option to display a link after finishing countdown ?

# Answer
> 0 votes
Alternatively you can achieve that using the jQuery Countdown module

**Example for development usage:**

*In this example, we display an alert box saying "You are done!" after counting down from 10...*

```
<?php
  echo '<div class="countdown">10 seconds!</div>';
  jquery_countdown_add(".countdown", array("until" => 10, "onExpiry" => "finished"));
  drupal_add_js("function finished() { alert('You are done!'); }", 'inline');
?>

```

---
Tags: 7
---


# Question
Title: How to get search results sorted by language in solr?
We have used Apache solr multilingual module for language specific search. But we want the other language results to be shown below the current language search result. How we can achieve it using solr?

Is there any module needed or any custom coding require?

Below is the example for displaying search results :-

> If I am currently using site in german and searched for any content then german results needs to be appear first and then other language content.

# Answer
You could build your search with the apachesolr\_views module (https://www.drupal.org/project/apachesolr\_views), allow all languages and then group by language in the view.
> 1 votes

---
Tags: search
---


title: Accessing files from a local cdn

text:
# Question
Title: Accessing files from a local cdn
I know that drupal comes along with 2 default stream-wrappers(public and private). What I want to achieve is to have my images placed in an another server, where they can be accessed by a url similar to http://cdn.mysite.com/image/etc.png.

https://www.drupal.org/project/remote\_stream\_wrapper allows the use of http, and https as stream wrappers. How am I suppose to use this programmatically?

When a file is loaded "public://" is replaced by the actual public URL, how does this work with the above module? Could you provide any other info on how to tackle this issue?

# Answer
> 1 votes
I use Storage API for this sort of thing with S3 and cloudfront. I think it supports custom sub domains. It handles all the replication (copying,moving, deleting) itself. I have had a couple of minor compatibility issues with other contrib modules during upgrades.

https://www.drupal.org/project/storage\_api

---
Tags: files, cdn
---


# Question
Title: Why does cloning a private git repository via Drush make file fail using SSH authentication?
I have multiple private git accounts set up with SSH system's keychain authentication for each git repo.

It works to clone private git repos from command line:

```
git clone git@git_ssh_alias:git-account/some_repo.git

```

The `git_ssh_alias` is the alias name declared in `.ssh/config` file that specifies the SSH key that should be used.

However, this same clone doesn't work when running from make file via Drush script as following.

### From Make file:

```
projects[theme_name][type] = "theme"
projects[theme_name][version] = 7.x-1.0
projects[theme_name][download][type] = "git"
projects[theme_name][download][url] = "git@git_ssh_alias:git-account/some_repo.git"
projects[theme_name][download][branch] = "master"

```

### From Drush script:

```
drush_invoke_process('@self', 'make', array($make_file), $options)

```

where `$make_file` is a path to a make file and options are:

```
$options = array();
$options['no-core'] = TRUE;
$options['yes'] = TRUE;
$options['contrib-destination'] = 'sites/all';

```

**My question**: How to clone private git repo with local ssh keychain authentication enabled?

# Answer
> 0 votes
Using modules and not theme\_name may resolve this.

```
projects[modules][type] = modules
projects[modules][download][type] = git
projects[modules][download][url] = git@bitbucket.org:company/repo.git
projects[modules][download][branch] = master

```

Here are a couple of useful links:

https://groups.drupal.org/node/194303#comment-918073 http://www.systemseed.com/blog/drush-make-private-git-repository-github

---
Tags: version-control, drush
---


# Question
Title: Second product attribute resets if first product attribute is changed
I have a tshirt product on my Drupal Commerce webstore. The shirt has these options, in this order:

Size / Color / Sleeve Length

All shirts are available in all sizes/colors/sleeve lengths, so any combination of those three fields will yield a valid product.

If I choose a size, then a color, and then a sleeve length, there are no issues. However, if I choose a color first, and then choose a size, it resets my color to the original, default color. The same thing happens if I choose a sleeve length first and then change one of the other options.

Is there any way to fix this behavior so that the customer doesn't lose their selections? I'm afraid that they might not realize that their previously-selected options have been reverted to the defaults and I might end up with orders for the wrong size, color, or sleeve length.

Thanks!

# Answer
This is addressed in a pending feature request that probably just needs a little more patch review before being committed to Drupal Commerce: https://www.drupal.org/node/1286244
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Is it possible to use an Oracle database for Drupal 8?
We are evaluating Drupal 8, and one of our needs is to use Oracle as the main (and only) database.

Is it possible to use Oracle as the Drupal 8 database? Can be a problem with the external modules?

And another question: The database access layer in Drupal 8 is Doctrine, or module developers can use hand-written queries (so, MySQL dependant queries)?

# Answer
As of now no. only in Drupal 7 we have. Drupal 8 supports MySQL 5.0.15 or higher (or MySQL 5.1.30 or higher) with InnoDB as the primary storage engine, and requires the PDO database extension. https://www.drupal.org/requirements/database

https://www.drupal.org/project/oracle \- drupal 7

see the here for further info the thread is postponed as of now

https://www.drupal.org/node/2037119
> 2 votes

---
Tags: 8, database
---


# Question
Title: Obfuscation or e-mail spam protection for content displayed through Views module
Currently, SpamSpan seems to work well for anything outside of Views. Having a hard time finding a solution for e-mails that are displayed through the Views module.

Any help would be very much appreciated.

# Answer
SpamSpan can do that for views too. You need to select te SpamSpan formatter on your display settings of the field.
> 1 votes

---
Tags: views, advertising
---


title: Unable to send e-mail

text:
# Question
Title: Unable to send e-mail
i want to create a new user, for this , i have done the following things. 1.Installed SMTP module through drush 2.Installed sendmail through apt-get 3.and created the new user, when i trying to create a user it shows the error as mentioned in image. Please someone help me to get out of it.

# Answer
You dont necessary need the SSMTP module.

I think this is a bad configuration with your local environment. For testing purpose you should consider using Gmail.

> Debian/Ubuntu users can Install with this command or click here to open up apt:
>
> `sudo apt-get install ssmtp`
>
> We need to then need to edit, `‘/etc/ssmtp/ssmtp.conf’`:

```
root=username@gmail.com mailhub=smtp.gmail.com:587 rewriteDomain= hostname=username@gmail.com UseSTARTTLS=YES AuthUser=username AuthPass=password FromLineOverride=YES

```

> Then add each account that you want to be able to send mail from by editing, ‘/etc/ssmtp/revaliases‘:

```
root:username@gmail.com:smtp.gmail.com:587
localusername:username@gmail.com:smtp.gmail.com:587

```

If you do not want to used Gmail here is another tutorial with an alternative Sendgrid.
> 0 votes

---
Tags: 7
---


# Question
Title: Programmatically created node gets created three times, produces error
I'm creating one of my first Drupal modules which should create a node (type= page) when you activate the module, and then add some javascript to site.

But when I activate the module, it creates three nodes with the desired node-title, and drupal produces an error:

```
Notice: Undefined index: module i FieldInfo->prepareInstanceWidget() (linje 591 af /var/www/SITENAME/public_html/modules/field/field.info.class.inc).
Notice: Undefined index: module i FieldInfo->prepareInstanceDisplay() (linje 626 af /var/www/SITENAME/public_html/modules/field/field.info.class.inc).
Notice: Undefined index: module i FieldInfo->prepareInstanceDisplay() (linje 626 af /var/www/SITENAME/public_html/modules/field/field.info.class.inc).

```

I am creating the node in the .module file like this:

```
$node = new stdClass();
$node->type = "page";
$node->title = "Page title";
$node->language = LANGUAGE_NONE;
$node->path = array('alias' => 'some-path');
node_object_prepare($node);
$node->uid = 1;
// Let's add standard body field
$node->body[$node->language][0]['value'] = 'This is a body text';
$node->body[$node->language][0]['summary'] = '';
$node->body[$node->language][0]['format'] = 'full_html';
$node = node_submit($node);
node_save($node);

```

The above code is based on this article

If i were to use the above path for the node, i would get three pages created with the following paths (i have pathauto installed):

```
/some-path
/some-path
/page-title.html

```

All of the pages have the "Page title" title set, and if i edit them they all have the 'This is a body text' body content.

Any help would be appreciated.

# Answer
> 0 votes
Have you installed the drupal for a specific language. If yes than please take care of the language on the time of node creation. e.g. for engisg code is en.

Also please make sure that the function you are calling is attached to only 1 menu. It should not be called by several other source on that module. So, please check HOOK\_install, HOOK\_menu, HOOK\_init wherever you add code for the same.

---
Tags: 7, nodes
---


# Question
Title: Menu tree page data not rendering any data if the page does not exist in drupal 7
I have this code to render the menu. I need to make extensive modifications of the elements, so this is why I extract it in this way (multidomain-multilanguage site, I tried everything and this was the only solution I found):

```
$a = menu_tree_output( menu_tree_page_data("main-menu") )

```

It works perfectly and $a is an array full of content. Works for every page, except for 404 not found pages. There it returns an empty array.

Any help would be appreciated. I was thinking of storing the menus for the different languages and domains in the database in a personal table and checking if array is empty, in order to extract the info, but I think that is not a good solution. Thank you!!!

# Answer
I have guessed what happens. It seems that Drupal does not render much of the content in order to aliviate load of the system. So in admin / site / site-information, you establish a different page for 404, and you can customize it. It will now include all menu, links, etc. and personal translatable messages you want to add.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: Listen to AJAX complete event from a behavior
I have a form that has an AJAX button. When I click it, it updates a bunch of stuff as expected which is fine.

I was wondering if there is a way to create a listener in behavior that gets called when the AJAX call is complete?

Thanks

# Answer
Yes, there is :

```
Drupal.behaviors.YourBehaviour = {
attach: function(context, settings) {
  $('#yourform').ajaxComplete(function(event, xhr, settings) {
    if ($(event.target.id) == 'the-id-of-your-item') {
      // Your code here
    }
  });
 }
}

```
> 21 votes

# Answer
For versions of jQuery 1.8+, it seems you now must attach the .ajaxComplete function to the document, not the form or the view itself (see http://api.jquery.com/ajaxcomplete/)

The following worked for me on D7 with Jquery 1.10 and Views 7.x-3.8, where "your\_view\_id" is the machine name of the view set in the view's "Other" settings panel. There is a lot of other info in event, xhr and settings to key off of to determine if the ajax result is for the view you want, but this worked for my situation:

```
jQuery(document).ajaxComplete(function(event, xhr, settings) {
    if(typeof settings.extraData != 'undefined' && typeof settings.extraData.view_display_id != 'undefined') {

        switch(settings.extraData.view_display_id){

            case "your_view_id":

                console.log('your_view_id ajax results!');

                break;

            default:

                console.log('some other ajax result...');

                break;

        }
    }

});

```
> 15 votes

# Answer
**None** of the given solutions worked for me with *Drupal 7.24, jQuery 1.11* and *Views 7.x-3.8*.

What *user1193694* suggested was not bad, but the settings object that I received didn't have the *extraData* parameter.

When parsing the settings object i saw that the settings.data propertiy contains '*view\_name=*' and your view's machine name, so thats what i am filtering for:

```
jQuery(document).ajaxComplete(function(event, xhr, settings) {

    // see if it is from our view
    if (settings.data.indexOf( "view_name=your_views_name") != -1) {

            console.log('your_view_id ajax results!');

    }
});

```

Replace '*your\_views\_name*' with the machine name of your view.
> 5 votes

---
Tags: ajax, javascript
---


# Question
Title: Get access to node titles and nid's only
there are two content types on my site: Projects and Employees. Employees has a user reference field, Projects have several node reference fields to Employees (according to different project roles). I grant rights to users with Node access user reference and Node access node reference modules so they can view and edit only the nodes they are referenced to (either directly or indirectly). Certain referenced users (project managers) should be able to add other Employees in Project nodes but in the same time they must not see their personal data. Therefore they haven't got any referencable Employee nodes. Would it be possible to grant access to the node titles (and nid's for referencing) only and hide other fields?

# Answer
> 2 votes
Yes you can, with field\_permissions module you can set permissions according to the fields.

---
Tags: 7, nodes, users
---


# Question
Title: Per instance settings on blocks with context?
Blocks normally have a single global configuration.

What options are there to provide "per instance" settings on blocks, so that I can vary them depending on where they are displayed, when they are handled with Context?

# Answer
If you use Context module for block positioning - you don't need to make any changes at /admin/structure/block page.

All configuration are done in context /admin/structure/context

If you need to display the same block on different places/pages/regions - just create different context for each condition.
> 0 votes

# Answer
it's not good answer but it's fair work around for now !

implement

> Implements hook\_preprocess\_block

help to overwrite some values

also i use value from request like $\_GET\['q'\]

i hope to see another answer
> 0 votes

---
Tags: blocks, 7
---


# Question
Title: Base field provided by a module is not accessable
this is a follow up to my question here. In my `.module` file I use the following code to add a base field to all my nodes:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
 */
function seo_fields_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $form['seo_fields'] = array(
    '#type' => 'details',
    '#title' => t('Metadata for SEO'),
    '#open' => FALSE,
    '#group' => 'advanced',
    '#weight' => 110,
  );

  $form['seo_description']['#group'] = 'seo_fields';
}

/**
 * Implements hook_entity_base_field_info().
 */

function seo_fields_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'node') {
    $fields = array();

    $fields['seo_description'] = BaseFieldDefinition::create('string_long')
          ->setName('seo_description')
          ->setLabel(t('SEO description for this entity'))
          ->setDescription(t('If not present, the module will try to create it from entity body.'))
          ->setDefaultValue('')
          ->setSetting('case_sensitive', TRUE)
          ->setDisplayOptions('view', array(
            'label' => 'hidden',
            'type' => 'string',
            'weight' => -4,
          ))
          ->setDisplayOptions('form', array(
            'type' => 'string_textarea',
            'weight' => 1,
            'settings' => array(
              'rows' => 4,
            ),
          ));

    return $fields;
  }
}

```

After running update.php the field is created without any error, I am able to edit it in the node form and it saves values to the database, but once I try to access it's value (in templates or preprocess functions / through `EntityInterface`) I always get an empty string. Even the node form shows an empty field after input and saving (even though the value clearly exists in the DB). Any help?

# Answer
> 0 votes
I'm going to guess and say that this is because of Unrevisioned base fields are ignored during entity load.

As a workaround (or maybe it actually makes sense to do so), add `->setRevisionable(TRUE)`.

---
Tags: nodes, database, entities, 8
---


# Question
Title: Different product prices per line item options
I'm working with Drupal Commerce, and i have a node type called "travel" with a product entity. This product have some static fields types like "city" which are used to define different prices supplements depending the departure city (Aka NY (+$15 extra transport charge), L.A(+$25 extra transport charge), S.D (+$20 extra transport charge) etc.). These fields are static, that mean i don't have to jump too often in the Store options to add my cities. (But i can set the price in the node edition as it is an option set.)

But i have another field: Range date of Departure/Arrival, this field is dynamic, i may have to set custom entries for each added nodes.

In the example below, my node is a travel to London (base price of $1500). The departures are: Los Angeles (+$30 e.t.c), New York (+$50 e.t.c), San Diego (+$25 e.t.c). But in the node i have to set different sojourn range dates:

Available dates: -2014-01-20 to 2014-01-30 -2014-02-20 to 2014-02-30 -2014-03-20 to 2014-03-30 ...

Each of these dates directly alters the travel price. My wish is to set a different travel price per range date like this:

-2014-01-20 to 2014-01-30 ($1600) -2014-02-20 to 2014-02-30 ($1650) -2014-03-20 to 2014-03-30 ($1450)

OR A discount/extra charge to the main sojourn price ($1500) like this:

-2014-01-20 to 2014-01-30 (+$100) -2014-02-20 to 2014-02-30 (+$150) -2014-03-20 to 2014-03-30 (-$50)

Of course, those changes are not directly visible on the front-side, the visitor will just see "10 days of travel to London from 2014-03-20 to 2014-03-30 for $1450".

Now the technical problem is not really the front integration, but most likely the back-office configuration. Which product field configuration/combination should i use ? Remember that prices per dates should be set from ***the node creation form***.

In the first approach, i was thinking about a multi-field field type combined with a sub-option set, but it seem that drupal did not appreciate that combination and doesn't recognize those fields as it mixes html id/classes like hell :/

So i'm now, my head in my hands, awaiting for a Drupal SuperHeroes.

Regards, Geo

# Answer
> 0 votes
If I understand what you're trying to do here correctly, you may need to create some custom Rules.

Event: Calculating sell price of product.

Conditions: This is where it gets tricky. If the date range is not on the product entity, you'll need a way to get the values from the product display node, that could be annoying in and of itself.
Now, if pricing for date ranges are statically calculated (ie: a 3 day trip ALWAYS adds $50), you could set up some custom code to dynamically do things like that.
On the flip side, if those range rates are different per product, it seems it would be necessary to define those on the product entity. And furthermore, you would probably need to create products for each variation (as in, variation for every combination of departure city AND date range).

Action: Add amount to product price (or something like that, I'm not looking at Rules directly).

# Answer
> 0 votes
You should use Rules but you should install Conditional Rules. You can build as many layers of logic into the rule as you need.

---
Tags: nodes, entities, commerce
---


# Question
Title: different views for different taxonomy vocabularies at taxonomy/term/%
I have two different content types: cars and boats. each one has a taxonomy vocabulary of the same name associated with it. I have two views, one for each, that shows listings based on this content type. I have to use the taxonomy/term/% to use the taxonomy term or id as an argument.

My problem is that this would work if both views had the same fields, but they don't they are quite different.

How can I get views to show results based on my taxonomy term as well as show different fields for each view? I would prefer not to use an existing module to handle this. Maybe I can configure the views differently or use a php snippet?

# Answer
Best Solution is using the : Taxonomy Views Integrator allows you to choose which view to associate with which taxonomy through a very handy and intuitive drop down menu.

More Detail are Found here:
> 3 votes

# Answer
Give a try to Taxonomy Display module

> The taxonomy display module allows administrative configurable term display pages. This allows administrators to override the default presentation of taxonomy term pages per vocabulary
> 2 votes

# Answer
You do not need an add-on module for this, just a contextual filter per view.

1. Create two separate views, one for Cars, one for Boats,
2. Filter them both by their content type
3. Set a path with an argument for each view ex: boats/%/list & cars/%/list
4. Add a contextual filter to each view with each taxonomy vocabulary of type: Content: Has taxonomy term ID (with depth)
5. Configure the Contextual Filter

1. When the filter value is NOT available: Provide Default Value: Taxonomy Term ID from URL
    2. Check Load default filter from node page, that's good for related taxonomy blocks
    3. Select your vocabulary
    4. When the filter value IS available or a default is provided: Specify validation criteria: Taxonomy Term
    5. Select your vocabulary
    6. Filter value type: Term name
6. Save view

Test your filter: go to cars/red/list and see if your taxonomy terms are filtering per content type.
> 1 votes

# Answer
Another way to approach this problem is using panels.

Instead to use a view for overwrite taxonomy/term/%term, panels also has a pre-created panel for overwrite taxonomy/term/%term page, and panels let you create "variations" where you can add "selection rules" for choice which view will be displayed.

In this way, you will be able to use the same path taxonomy/term/%term but display the content in a different way.
> 0 votes

# Answer
I cannot comment on arpitr's response so I have to write a separate answer but Taxonomy Display module worked for us along with these instructions to configure
> 0 votes

---
Tags: 7, taxonomy-terms, views
---


# Question
Title: field is Integer and I am getting PDOException error thrown
I have a field called "blog\_post\_guid" and it is set as Integer.

Recently, it is throwing this error:

> PDOException: SQLSTATE\[22003\]: Numeric value out of range: 1264 Out of range value for column 'blog\_post\_guid\_value' at row 1: INSERT INTO {field\_data\_blog\_post\_guid} (entity\_type, entity\_id, revision\_id, bundle, delta, language, blog\_post\_guid\_value)

Running a search revealed this article.

Based on this information I thought I should install and enable BigInt.

Is there any other relevant solution to this issue for Integer field and Drupal 7?

# Answer
> 2 votes
Using bigInt module is the best way for achieve this job, there is another solution like altering database table but it not recommanded

---
Tags: 7, entities
---


# Question
Title: Autocomplete Widget for Hierarchical Taxonomy
I would like to be able to use a widget along the lines of active tags autocomplete that would allow me to maintain a taxonomy hierarchy. I need to be able to select multiple terms, including multiple children for one parent. Any recommendations?

# Answer
There is a module for that. Probably the only way to select multiple is to allow the field to have multiple values. http://drupal.org/project/term\_ref\_autocomplete
> 1 votes

# Answer
Use autocomplete deluxe module https://www.drupal.org/project/autocomplete\_deluxe thi replaces the normal autocomplete box with another textbox with auto complete with ability to add more terms (like when entering multiple emails in the email)
> 0 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: Remove `/node` from front page when using a template file (page--front.tpl.php)
As it stands I have no content going to the front page, i am simply using a template file for the front. When I sign out and sign in as any role of user on my site my front page url turns into: `www.mysite.com/node`

I do not want this behavior, and have tried several methods but nothing seems to work.

I have tried adding this snippet to setting.php:

`function custom_url_rewrite_inbound(&$result, $path, $path_language) {
 if ($path == 'node') {
 $result = '';
 }
}`

I have tried creating a custom module and have tried every suggestion from https://www.drupal.org/node/500296 nothing works.

I have encountered this behavior before, and to solve the issue i added the Node Page Disable module and deselected the `Retain /node as an active url?` checkbox which removed the `/node` from the home page URL.

Now when I implement the module and deselect the checkbox and save the form, the checkbox goes back to being selected after the form is submitted. I cannot figure out what is going on, I have cleared every cache known to man-kind, used different machines and operating systems so obviously something is conflicting. I just don't know where to look.

I cannot post a bug/issue to the module page because drupal site is currently broken for creating new users... This is a nightmare. If anyone could give me some insight on possible conflicts or have any crazy ideas how I could get around removing this useless `/node` from the home page after a user signs in; it would mean the world to me. Thanks regardless.

# Answer
I used Global Redirect and it seems to do the trick. I'll still accept someone else's answer if anyone can give any insight on what might of been the solution to my original issue.
> 1 votes

---
Tags: uri
---


# Question
Title: admin toolbar not showing sub-navi in Firefox any more
First the admin toolbar worked perfectly fine in Mac-OS-FF – then suddenly the sub-navigation (the fly-out sub-pages) stopped showing – partly. The sub-navigation seems to be covered or cut off:

At that time I neither updated FF nor added/removed any browser-plugins or dp-modules. The same happened to three different dp7 installations simultaneously. I then updated FF – no change.

In chrome everything works fine.

Has anybody else witnessed similar behavior? Any pointers / tips would be much appreciated.

# Answer
> 1 votes
It was a bug in the admin menu module. I think it was fixed in the latest stable version (if not in stable, then in dev). Try updating to the latest stable version of admin menu (currently 7.x-3.0-rc5).

---
Tags: toolbar
---


title: Drupal Subscription Webforms

text:
# Question
Title: Drupal Subscription Webforms
I have Subscription webFrom which I need to use it with different products.

Subscription Webfrom will ask Email and Name to be submitted.

When I click on the product it take to the subscription form where the user enters the name and the email. How do I know to which product the subscription form was submitted. How do I pass the product information to the subscription webform without user having to select the product again or avoid create a same subscription form to each product.

Thanks

B L Praveen

# Answer
I found a solution to my problem it can be done by passing information through url as said here
> 0 votes

---
Tags: webforms
---


# Question
Title: display link after finishing coutdown time
I am using Jquery Countdown module. In this, user can display text message after completing countdown. But I want to display a link after completing countdown.

# Answer
Have a look at the project page. It says

You can use jQuery Countdown in two different ways, one is using `theme('jquery_countdown')`, the other is using `jquery_countdown_add()`.

In the following example, we display an alert box saying "You are done!" after counting down from 10...

```
<?php
  echo '<div class="countdown">10 seconds!</div>';
  jquery_countdown_add(".countdown", array("until" => 10, "onExpiry" => "finished"));
  drupal_add_js("function finished() { alert('You are done!'); }", 'inline');
?>

```

You can use the above example to achieve your requirement.
> 2 votes

---
Tags: javascript
---


# Question
Title: Dont Refresh Drupal's Page after a button is click in Forms API
I had started developing a module in Drupal. I made two form controls: a fieldset and a button. The button calls a javascript function "myphoto\_options" when it is click. This function only does an alert function. After executing the called function, the page then immediately refreshes the page. How to prevent the page from reloading?

Below are my codes:

```
function myid_user_page_form(){
    $form = array();
    $form['id'] = array(
        '#type' => 'fieldset',
        '#title' => t('ID Information'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );
    $form['id']['myphoto_button'] = array(
        '#type' => 'button',
        '#value' => '...',
        '#attributes' => array(
        'onclick' => "myphoto_options();",),
    );
    return $form;
}

```

Javascript function:

```
function myphoto_options(){
    alert("Hey");
    return false;
}

```

Any help would be very much appreciated. Thanks.

# Answer
You should do something like this:

```
function myid_user_page_form() {
    $form = array();
    $form['id'] = array(
      '#type' => 'fieldset',
      '#title' => t('ID Information'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );
    $form['id']['myphoto_button'] = array(
      '#type' => 'button',
      '#value' => '...',
      '#attached' => array(
        'js' => drupal_get_path('module', 'your_module') . '/js/your_file.js'
      ),
    );
    return $form;
}

```

Then, add a directory "js" in your module and a js file. In that js file use:

```
(function ($) {
    Drupal.behaviors.yourModule = {
        attach: function (context, settings) {
            $('#your-element').click(function(e){
                e.preventDefault();

                // Your functionality.

                return false;
            });
        }
    };
})(jQuery);

```
> 3 votes

---
Tags: 7, forms, javascript
---


# Question
Title: Administration views change filter on my content type fields
I'm using **Administration views** and I would like to be able to search by the **last name** field in my "Registration" content type. Currently, I can search by **first name via the 'title' field** on the content type as I replaced title field with my "first name" field. But now I would like to search on "Last Name" field.

Please provide a recommended approach to resolve this.

# Answer
> 0 votes
Go to admin/structure/views/view/admin\_views\_node and add a filter criteria on the field "last name". While adding the field check "Expose this filter" and you will be able to search on last name

---
Tags: views, nodes, users
---


# Question
Title: Setup existing drupal 6 site on local server
so far I've worked with Drupal 7 sites and have no experience importing Drupal 6 site to local server, so maybe you could help. I have 2 folders and .sql database file.

1. First folder is named 'files' which has sub-folder 'design' which consist all files stored in site (css, images, js, models etc.).
2. Second folder is named 'sites' which has two sub-folders - 'themes', 'models' and settings.php file.

I'm using Acquia Dev Desktop 2. So far I've created new site and database importing .sql dump file. And have plain text entering the site. Where should I override these two folders and should I rename them? My project is called 'project.dd', should 'design' folder be called as project name?

# Answer
> 0 votes
Steps to setup a Drupal Site :

1. Place your Drupal 6 directory in your `htdocs` directory of `xampp` folder. All files and design folder should be at same place where they are on live version of site.
2. Open your `settings.php`, change the database credentials according to your local server.
3. Restore your database using `phpmyadmin`.
4. May be some image would not be shown up on site so you need to setup a domain in apache's `vhost` file.

---
Tags: 6, database, importing-exporting
---


title: How to render protected element?

text:
# Question
Title: How to render protected element?
I want to print \[entityInfo:protected\] present in below image.

I am able to print all element except \[entityInfo:protected\] and \[entityType:protected\]

# Answer
> 1 votes
You can't (without reflection). Protected members of a class are available only to the defining class and its subclasses - it's the whole point of using access modifiers in the first place - if you can get access to a protected value directly from the object, then the language has failed. Miserably.

If a method doesn't exist to expose that data already, you'll need to extend the class that represents that object to provide getter methods for the protected properties.

---
Tags: entities
---


# Question
Title: How can I create a time counter by aggregating a view?
I need to create a time counter that will take a users input of time in hours and minutes, add them and then display the cumulative results?

I am not sure how to accomplish this. It has been suggested to create a content type with a time field and then aggregate the results.

Any advice/direction will be appreciated.

# Answer
> 0 votes
Disclaimer: I'm a total hack with Drupal

I would use the View type of "Table", then create a views-view-table--VIEWNAME.tpl.php

You'll see that it's set in to a real easy to read loop through the rows. Modify the HTML structure to suit your needs, but also add in a simple $var++; and then place that at the end of your rows.

---
Tags: views
---


title: How do I configure cron in Drupal 6

text:
# Question
Title: How do I configure cron in Drupal 6
In my GoDaddy control panel I have scheduled it to run this script every day: `/web/cgi-bin/php5 "$HOME/html/my_site/cron.php`

However I cant figure out how I create tasks that will be run when cron.php is run. I have gone through all the documentation and can't find this anywhere (The D6 video tutorial link seems to be down).

For example how would a go about deleting the contents of a temporary folder?. Do I just add some PHP using the `unlink` command to the cron.php (in which case drupal is not really involved) or is there some setting page that I havent discovered that allows you to create tasks?

# Answer
> 1 votes
Use hook\_cron, and implement your functionality in it. This functionality will get executed when the server will ping cron.php.

You just need to set specific time period on which cron will be executed.

---
Tags: 6, cron
---


# Question
Title: How to change the Zen theme to a single sidebar layout?
I'm using Zen (version 7.x-5.5) as a base theme.

The problem is that it's showing with 2 sidebars layout. I searched in the documentation but I didn't find a way to change it to 1 sidebar layout (with main content of course ).

I changed the SCSS files in `_responsive.scss`, but nothing changed.

Is there any way to make this work?

# Answer
> 2 votes
In page.tpl.php, at line 109 and line 110, delete the sidebar you don't want

In style.css change this class .region-sidebar-second{ float:left;width:20%;margin-left:0%;margin-right:-20% }

to be .region-sidebar-second{ float:left;width:20%;margin-left:0%;margin-right:-20%;display:none;//add a display:none }

and change .two-sidebars #content { float: left; width: 60%; margin-left: 20%; margin-right: -80%; }

to be

.two-sidebars #content { float: left; width: 80%; //change 60% to 80% margin-left: 20%; margin-right: -80%; }

# Answer
> 0 votes
Have you installed sass and compass? As I understand zen 5.5, the scss files are not executed until compass recognizes a change in the sass (.scss) files and then regenerates the resulting css, which is what your browser is actually using to display your page. As far as I can see, compass does this by putting the new css in the styles.css file. Check the date on your styles.css file (listed in yourzensubtheme/css) and see if it has been updated. If not, then you may be still running the old configuration and that's why you don't see any changes.

Oh, and don't forget to clear all caches so that Drupal knows that something has changed.

---
Tags: theming
---


# Question
Title: new created zen subtheme - content offpositioned
I just created a new zen subtheme using drush. Everything went smooth but I think there is some kind of problem with css - #content container is completely off positioned from page. I did not make any changes to files. Is it some kind of bug or this needs some tweaking? I have sass and compass installed. I use zen 7.x-5.5 version. Please see screenshot. Thank you.

# Answer
> 1 votes
Ahhh. I had this same problem yesterday and it turned out that I was using the wrong version of compass. I installed version 0.12.6 and the content returned to where it was supposed to be.
You can either unistall compass and then reinstall https://stackoverflow.com/questions/3088454/how-do-i-downgrade-to-an-old-version-of-compass-using-gem-instal

or just add the old version and explicitly invoke the older version like so: compass *0.12.6* watch

---
Tags: 7, theming
---


title: Form state values problem

text:
# Question
Title: Form state values problem
I dont understand the problem im facing.

I'm building a big form (in which you can add products, modify quantity, etc etc and validate.

I'm getting consistency data problem between what's in `$form_state['values']` and what's in `$form_state['input']`

`$form_state['values']` are never up-to-date ...

if I change a quantity field value, and then validate the ofrm, I will find the right quantity in `$form_state['input']` but not in `$form_state['values']`.

Say it passes the validation step, if I submit a second time the form, then I will have the correct values in `$form_state['values']`.

**Another example** : The validation fails if a quantitu is set to 0. When the form display itself after the failure, all quantity fields are reset to the value they were after the previous form loading (Am I clear enough ?)

I dont understand what could make this happen ...

Found this post : When are '$form\_state\['values'\] copied to '$form' on rebuild?

Petroll commented it :

> When you submit a form with user input, the input gets stored in $form\_state\['input'\] and later (after validation) in $form\_state\['values'\]. But when you, then, rebuild the form, the values are (and AFAIK have to be) are ?somehow? given as parameters to element process functions (that create the FAPI arrays of elements).

That make sense... If validation fails, `$form_state['values']` is not updated with `$form_state['input']`. So the form is rebuild with the old values.

But What I dont understand is why all the values are reseted ...

Lets say Ive 5 products. If I modify each quantity, and I set one of them to 0, the validation will fail and all my inputs will be lost.

# Answer
Did find a solution : #after\_build attribute added to my textfield.

Then added a new function to check if the `form_state['input']['mytextfield']` is set. If so, using it to change the `#value` of the element.

important : altering `#default_value` in the after\_build function didn't work, had to change the #value
> 0 votes

---
Tags: forms
---


# Question
Title: How to add a menu under Webform Results?
In Drupal 7, I know we can use Views to add sub menu or menu tab on "My Workbench". The form result I have in "mydomain.com/node/99/webform-results" contained Submissions, Analysis, Table, Download, and Clear sub-menus. How can I add another sub menu next to "Submission"? I have tried to use the same method from Workbench, but it does not seem to work.

**My new sub-menu setting in Views**

```
Type: page
path: /node/99/webform-results/details
menu: Menu Tab: Navigation

```

# Answer
> 2 votes
Try to select `Default menu tab` instead of `Menu tab`.

---
Tags: views, webforms, routes
---


# Question
Title: drupal  shows empty content because of memcache
I have a Drupal (pressflow 6.22) website and I am using memcache as a caching level for my website/server. Sometimes some node (articles) that has been published on my website shows empty content when browsed (Specially with IE).

When I do below on the server that has memcache

```
$ telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
flush_all
OK
quit

```

and refresh the page using the same browser, it is displayed properly. Has anybody faced the same issue?

# Answer
> 0 votes
@Walter Jenner: memcached should be flushed from time to another, so i have fixed it by applying the following crontabs

```
0 */1 * * * echo "flush_all" | nc 127.0.0.1 11211
1 */1 * * * ps aux |grep flush_all | grep -v grep |awk '{print $2}' |xargs kill -9
1 */1 * * * ps aux |grep "nc 127.0.0.1 11211" | grep -v grep |awk '{print $2}' |xargs kill -9

```

# Answer
> 2 votes
Have you installed and configured drupal with the module for memcache - http://drupal.org/project/memcache ?

There is also a handbook page that will be able to help you http://drupal.org/node/1131458

# Answer
> 2 votes
We recently went through a through troubleshooting of this issue.

We found that the fields table should not be served from Memcached.

$conf\['cache\_class\_cache\_field'\] = 'DrupalDatabaseCache';

Reference: https://www.drupal.org/node/1679344#comment-7895709

---
Tags: 6, caching
---


# Question
Title: How might I display a field twice in a node using different field formatters?
**Question:**

How can I show the `field_showcase_headshot` field both as a picture on screen and as a download link?

**Set up**:

From the load tab of Devel, I have a few fields on this node.

The field here is Showcase Headshot. It is currently set to display on the screen as follows

But we'd like to include a download link to the original image in the fashion shown here.

That is, we'd like to append something like the following to the text on the page.

Showcase Download: headshot

# Answer
Use the Display Suite module to create a new dynamic field. On the manage display page select the field from the Node section.

https://www.video2brain.com/en/lessons/using-display-suite-dynamic-fields
> 0 votes

# Answer
There are 2 options available for this to do.

1. By linking the image to its image path from the site. This can be achieve using a module https://www.drupal.org/project/image\_link\_formatter.
2. By using download module and custom field theme formatter. In this you need to enable the download file module https://www.drupal.org/project/download\_file. And than create customize the field view using the field template.
> 0 votes

---
Tags: theming, media
---


# Question
Title: Add a meta content="noindex,nofollow" tag on a node created programmatically
Is it possible to add a meta content="noindex,nofollow" tag to the head on the page of a node created programmatically (and onl this node)? I have created the node like this:

```
function MODULENAME_install() {
  $bodytext = 'Some Text';

  $node = new stdClass();
  $node->type = "page";
  $node->title = "New title";
  $node->language = LANGUAGE_NONE;
  node_object_prepare($node);
  $node->body[$node->language][0]['value'] = $bodytext;
  $node->body[$node->language][0]['summary'] = '';
  $node->body[$node->language][0]['format'] = 'full_html';
  $node->path = array('alias' => 'new-title');
  node_save($node);
}

```

# Answer
You can use below code for adding no-follow and no-index meta for the node. Put this code in your themes template.php file.

```
function MYTHEME_html_head_alter(&$head_elements) {
  if (arg(0) == 'node' && arg(1) == 'YOUR NODE NID' && !arg(2)) {
    $head_elements['MYMODULE_meta_robots'] = array(
      '#tag' => 'meta',
      '#type' => 'html_tag',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex'
      )
    );
  }
}

```
> 4 votes

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


# Question
Title: Print selected fields in page tpl Drupal 7
For some reasons, I have to customize the display of the content node programmaticaly, mixing content from other sources.

Instead of making a `print(render($page['content']` which outputs all the content, I need to access to selected parts of the content (for instance, value of a text field, url of a PDF file, etc.). I am using this approach:

`print render( $page['content']['system_main']['nodes'][$nid]['body']['#object']->field_subtitle_product["und"][0]["value"]);`

Would it be correct or is there a more straighforward method? ( I don't want to low to node.tpl.php anyway).

Thanks!!

# Answer
> 3 votes
First, If you want to print selected field then you should to do it in `node.tpl.php` and not in `page`. There are many ways to do this :

If you just need to render the fields in default way, you can go to `Admin > Content Type > Your Content Type > Manage Display` and hide the fields you want.

If you want to do it through template files then you can use it using :

```
hide($content['field_name']);
print render($content['field_name']);

```

You can just remove `print render($content);` and write :

```
print render($content['field_name']);
print render($content['field_name2']);

```

# Answer
> 0 votes
I don't think there's anything wrong with it, so long as it's done correctly - some things to note:

* make sure the page.tpl.php is specific to the content type; this will reduce overhead and potential errors when content types don't contain that field
* this can also be done using blocks and enabling php editing if you don't want a custom tpl.
* you should use field\_view\_value and field\_get\_item or similar instead of \['und'\]\[0\]\['value'\]

---
Tags: 7, nodes
---


# Question
Title: Omega 4 Sub-Theme problem with file_get_contents(make.libraries) failed to open stream
when creating an omega 4 sub-theme using drush 6 on windows 7 and xampp and drupal 7, see attached pic,'file\_get\_contents(libraries.make) : failed to open stream : no such file or directory make.utilities.inc:471 Can anyone help?

# Answer
It's a known bug of Omega theme, so you should follow Drupal issue queue for details: Invalid or empty make file: libraries.make.

As workaround, you may to navigate to subtheme's folder (e.g. fifth\_avenue subtheme dir) and run:

```
drush make libraries.make --no-core --contrib-destination=.

```
> 0 votes

---
Tags: drush, theming
---


# Question
Title: Views exposed filter hide if less then 10 items
I want to show the exposed filter only when there are more than 10 items to filter. Any suggestion to accomplish this?

# Answer
> 1 votes
Add this to your theme's template.php file:

```
function THEME_views_pre_render(&$view){
  if ($view->name == 'VIEWNAME' && $view->current_display == 'DISPLAYID' && $view->total_rows <= 10) {
    $view->exposed_widgets = '';
  }
}

```

This will remove all of the exposed filters. If you have more than one and you only want to remove a single exposed filter, you will have to parse that filter out of the `$view->exposed_widgets` html string.

---
Tags: views
---


# Question
Title: How to render a block in php for a special node id
I would like to render a block from only one node on all node pages. But all the code I found to render blocks never takes the nid as an input. Is there a possibility that I can trick the block renderer into thinking it is on a different page?

If it is of any help: In my case I want to render the block for Opening hours from one node id on all pages. So I do not have to add the same opening hours for every node.

# Answer
Add this to your theme's template.php file:

```
function THEME_block_view_alter(&$data, $block) {
  if ($block->module == 'opening_hours' && $block->delta == 'week') {
    $node_fixed = node_load(77); // swap out 77 for your node's id
    if ($node_fixed) {
      $data['content']['#node'] = $node_fixed;
    }
  }
}

```
> 1 votes

---
Tags: nodes
---


# Question
Title: How do I know Honeypot is working on my custom module form?
I have a custom module that renders a form. `In hook_form_alter()` I have added `honeypot_add_form_protection($form, $form_state, array('honeypot'));`

Though, when I perform 'Inspect Element usnig chrome I cannot see any honeypot fields in the html of the page. So, I'm slightly confused on whether this actually work or not.

Any idera on how to test this or atleast see that the form is protected by the Honeypot module?

# Answer
> 4 votes
You can enable an option *Log blocked form submissions* on page *admin/config/content/honeypot*, set *Honeypot time limit* to, let's say, 30 seconds and try to submit your form faster than 30 seconds. Then check your log (*admin/reports/dblog*). You will see Honeypot log message if it worked.

And you probably should include some option in array:

```
  honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));

```

> Note that you can enable or disable either the honeypot field, or the time restriction on the form by including or not including the option in the array. (https://www.drupal.org/node/1232638)

---
Tags: forms, webforms, advertising
---


# Question
Title: Reducing Number of Fields in Content Type
**Context:**

I have a product content type on Drupal 7 with \>100 fields, and there are \>7000 products, all with several revisions. Our client keeps requesting that we add and remove fields, which is quite painful and takes several tries to successfully complete due to mysql having a conniption.

The go-to strategy has been to increase the RAM on the server, but we are hitting a cost wall and this bothers me as a developer since we are just deferring dealing with the problem.

**Comedy Option:**

The majority of these fields are specifications which are never related, filtered or displayed outside of the detail view. Could I **reasonably** create a JSON product\_spec field that contains all of these spec fields and write custom modules to display them on the detail/spec screens, allow editing through the API, and allow editing them on the admin interface?

Is there an existing module that does something similar? Would entitycache be a much more practical option?

# Answer
> 0 votes
This is really interesting and, whereas the suggestions in the other question are really good as pointed out by the comment above, I don't really think it's practical to give up on the Field UI for this (like mentioned in the other question).

Let me explain:

* Creating a custom field is really easy, there's a good example in Panopoly Widgets for the dashboard widget, which has a custom field for the Spotlight widget.
* Creating a custom entity isn't so bad either but creating every single field using Form API should be out of the question

The only plausible solution that I can think of would be to implement hook\_field\_storage\_info() and create a new Field API storage backend that uses a better table configuration.

If you look at field\_sql\_storage.module in core, it's a pretty concise module that provides the one field per table storage backend, I'm sure with some hacking around you could create a new backend that uses one table per entity and stores each field in a new column there (kinda like D6 CCK with cardinality 1 fields).

You would have to be constantly altering the table schema whenever new fields are added (which should be fine). This might be the place to do it: hook\_field\_storage\_create\_field().

It's pretty theoretical but I think it'll work... the beauty of this approach is that you can still use Field UI for everything as usual.

Caveat: You're gonna have to figure out how to handle complex fields or multiple cardinality (hint: more columns?)

PS - Knowing of the frequent schema changes, you wanna make sure you have backups/concurrency for peace of mind.

Good luck and if you get this working I'd like to see it! :)

# Answer
> 0 votes
Why not solve it with custom fields, grouping similar fields into one compound custom field and trying to keep a sane data model (ex: not 'all the things in one field'). There are many tutorials on how to create custom fields and it's quite easy.

# Answer
> -1 votes
I would give the Dynamic Properties module a try.

---
Tags: nodes
---


# Question
Title: Form API Submit Button for Multiple Forms
I created a module with 3 forms on it. Is there a way to only have one submit button at the very bottom of the page that will store all three values?

# Answer
Not really. Drupal form may try to redirect you after successful submit. If 3 forms try, which redirect should work? And that's only one example.

Create fourth form function. In it, call all 3 existing ones, clean up mess with submit functions, validators and redirects, and it should work. Or simply merge your forms into one, why you needed three?
> 0 votes

# Answer
You could try the multiform module. This is especially useful if the forms you have on one page are not ones you created, but are instead Drupal forms you need to have on a single page.

> This is an API module which lets you put several forms into one .
>
> The usage is very simple: there is one API function to call: multiform\_get\_form() and you can pass the form names in the attribute list.

You can use it like this:

`multiform_get_form(array('form_id', $arg1), array('form_id', $arg1, $arg2));`

https://www.drupal.org/project/multiform
> 0 votes

---
Tags: 7, forms
---