# Question
Title: Copy filefield image to different filefield field
I am upgrading an older D6 site to D7. Way back we made the mistake of creating separate image fields for different content types. So instead of just creating a field field-image and reusing it, we have a field-event-image, a field-testimonial-image and so on (and a field-image). Well, besides the excess clutter, we need to create a view that shows a flexslide that sources nodes from multiple content types and it only allows one image field. So I would like to move all the images into the field-image field. I have seen a number of potential ways to achieve this result but no luck so far. Using migrate module is probably the most elegant, but seems over my head. VBO with Rules seems good and I have seen some examples but I get stuck creating the rule.

Any suggestions to my dilemma? Thanks

# Answer
> 0 votes
I fixed it by running SQL on the database directly through phpmyadmin. First I added the destination field to the content type. Then, I went into phpmyadmin and ran this: (change your field names as appropriate.

```
INSERT field_data_field_image SELECT * FROM field_data_field_event_image;

```

and

```
INSERT field_revision_field_image SELECT * FROM field_revision_field_event_image;

```

After it ran successfully, I went in and checked the content. All good. Then I was able to delete the old field. Problem solved! Thanks.

---
Tags: rules, views
---


# Question
Title: Is it possible to have nested divs in content fields on a view?
I'm trying to create a view that displays certain content fields inside a div that are contained by other content fields.

For example. I am displaying an image, a title, a body, and a posted date.

I'd like to do something like this

```
<div class="a">
   <img src="image.jpg">
   <div class="title">
      Title
   </div>
   <div class="text">
      <div id="postdate">
         1/1/1999
      </div>
      <div id="body">
         body text
      </div>
   </div>
</div>

```

Is this possible?

# Answer
Just **exclude from display** all your fields.

Then, at the end, **create a Global text area**, where you can use tokens from your excluded fields.
> 3 votes

# Answer
exclude all the fields from display except the last field and rewrite the output of that field to apply the structure you need using tokens of the previous field.
> 1 votes

---
Tags: views, theming
---


# Question
Title: Allow only lowest taxonomy terms to assign to nodes
I have a lot of taxonomy terms that need to be categorized into multiple categories and subcategories:

```
- AAA
  - BBB
    - CCC
    - DDD
    - EEE
...

```

Is there a way how to restrict assigning higher terms to nodes (AAA, BBB) and allow to use only lowest terms (without any child terms - CCC, DDD, EEE)?

# Answer
Hierarchical Select.

> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!
> 1 votes

---
Tags: nodes, taxonomy-terms
---


# Question
Title: How can I sum up the totals of groupings in views?
I am trying to sum up my sales in my Commerce store by month.

I have created a view of completed payment transactions that is grouped by payment year (first grouping) and then payment month (second grouping). The config looks like this:

This gives output look like this:

Now what I'd like to do is sum up each month (the second grouping) to show the total sales for that month. I think I can use aggregation for this but I'm not sure how to set it up.

# Answer
> 0 votes
Most of the links I found for this kind of thing point towards Views Aggregator Plus. Apparently it allows you to "aggregate and group by column" (source).

---
Tags: views, css-js-aggregation
---


# Question
Title: Is it bad to add js and css in template_preprocess for a custom block?
If I load my page where my block is displayed as user 2 (any user besides user 1) my block displays correctly. If I reload the page my block doesn't display correctly and my js and css that was added via template\_preprocess() doesn't show up.

I verified that if I turn off Block caching the problem goes away so it tells me that I shouldn't be adding js and css in the template\_preprocess functions and add it via '#attach' but I have a function (video\_widget\_add\_js) that I am adding javascript because I am adding it in multiple places and want to reuse the code. Anyone have a good suggestion on this?

```
  <?php

  /**
   * Implements hook_block_view().
   */
  function leadership_block_view($delta = '') {
    $block = array();

    switch($delta) {
      case 'leadership_all_companies':
        $node = menu_get_object();

        $data_card_content = leadership_get_data_card_content($node);

        if (!$data_card_content) {
          $block = array(
            'subject' => '<img class="ld-block-logo" src="' . variable_get('leadership_block_logo') . '" alt="Leadership Logo" />',
            'content' => theme('leadership_allcompanies', array(
                'taxonomies' => leadership_get_taxonomies(FALSE),
                'delta' => $delta,
              )
            ),
          );
        }
        break;

    }

  }

  /**
   * Implements hook_theme().
   */
  function leadership_theme() {
    return array(
      'leadership_allcompanies' =>  array(
        'variables' => array('taxonomies' => NULL, 'delta' => NULL, 'has_data_card' => NULL),
        'template' => 'leadership-allcompanies',
      ),
    );
  }

  /**
   * Preprocess for the all companies block.
   *
   * @param array $vars
   *   An associative array containing:
   *   - taxonomies array
   *     An array that contains taxonomy objects @see taxonomy_get_tree().
   *   - delta string
   *     The block string key.
   *   - has_data_card
   *     This will only be used in the all_companies_and_data_card block. If set
   *     to FALSE then only all data that would appear in the all companies block
   *     will appear. If set to TRUE both will appear.
   */
  function template_preprocess_leadership_allcompanies(&$vars) {
    // Add js and css files.

    $js_extension = (variable_get('smg_global_is_production', false)) ? '.min.js' : '.js';

    $path = drupal_get_path('module', 'leadership');
    $video_widget_path = drupal_get_path('module', 'video_widget');
    drupal_add_css($path . '/css/all_companies_block.css');
    drupal_add_css($path . '/css/datacard.css');
    drupal_add_css($path . '/css/datacard_' . variable_get('smg_global_site') . '.css');
    drupal_add_css($video_widget_path . '/video_widget_includes/css/video_widget.css');
    drupal_add_js($video_widget_path . "/video_widget_includes/angular/app{$js_extension}");
    //drupal_add_js('sites/all/libraries/angularjs/bower_components/angular-animate/angular-animate.min.js');
    drupal_add_js($path . "/angular/js/all_companies_block{$js_extension}", array('every_page' => TRUE, 'preprocess' => TRUE));
    drupal_add_js($path . "/angular/js/datacard{$js_extension}");

    $vars['site_id'] = variable_get('smg_global_site');

    $taxonomies = $vars['taxonomies'];
    if ($taxonomies) {
      if (variable_get('smg_global_site') == 'pw') {
        // Add the parent tids,titles (Ex: Machinery, Materials, Service)
        foreach ($taxonomies as $taxonomy) {
          $categories[$taxonomy->parents[0]]['tids'][] = $taxonomy;
        }
        foreach ($categories as $tid => $category) {
          $categories[$tid]['tid'] = $tid;
          $categories[$tid]['title'] = taxonomy_term_load($tid)->name;
        }
        $vars['taxonomies'] = $categories;
      }

      // Add taxonomy list to Drupal object to be used by Angular.
      drupal_add_js(array('leadership_all_companies_block' => $taxonomies), 'setting');

      // Call the video widget registering function
      video_widget_add_js();
    }
  }

```

# Answer
Generally, yes, you should use `['#attached']` in renderable arrays to add assets in a cache-compatible way. `$block['content']` can be a renderable array if you make it an array instead of a string, so you're not too far off here. I'm not sure exactly what you're doing inside `video_widget_add_js()`, but if it's just adding a bunch of assets, then consider implementing `hook_library()` instead. Library implementations are attachable in `['#attached']`.

In your case, however, the attached assets aren't your only problem. With block caching enabled, a cache hit bypasses `hook_block_view()` completely, instead retrieving the previously compiled `$block` array from cache. Since you use `$node = menu_get_object()` in `hook_block_view()`, you probably need the block to vary by page. However, the default block cache setting is DRUPAL\_CACHE\_PER\_ROLE, which only varies by a user's role combinations.

You could set your block to cache with DRUPAL\_CACHE\_PER\_PAGE instead, but the easiest thing to do without refactoring a bunch of your code is to set your block to DRUPAL\_NO\_CACHE. DRUPAL\_CACHE\_PER\_PAGE isn't hugely efficient anyway unless you have a lot of authenticated user traffic.

To set a particular cache setting on a block, edit the `hook_block_info()` implementation:

`/**
 * Implements hook_block_info().
 */
function leadership_block_info() {
 return array(
 'leadership_all_companies' => array(
 'info' => t('Leadership block'),
 'cache' => DRUPAL_NO_CACHE,
 );
 );
}`
> 5 votes

---
Tags: 7, blocks
---


title: Image output when using scald module

text:
# Question
Title: Image output when using scald module
I'm using the scald module for image management. It's working 99% as I'd want it to - but when used with WYSIWYG (ckeditor) I'm having an annoying issue.

The images in this context need captions so I've hooked into the scald templating and changed the output to use and tags.

All fine - except when saved the WYSIWYG / scald seem to add lots of empty

tags between the figure and the figcaption.

Attempting to use the empty paragraph tag module or create my own input filter have failed as they run before scald replaces the atom reference with the actual image output.

Any suggestions on where to hook into scald to be able to influence this markup?

# Answer
> 1 votes
I've been able to resolve this without using Scald templating.

The Scald plugin for CKeditor automatically inserts the image **Title** as the caption just below the image. This text is editable in WYSIWYG if you want to replace the image **Title** with your own caption.

Below is how it looks at my site. Notice the caption just below the image. (This is without any additional CSS - it can look nicer if you add some some CSS.)

And this is the markup inserted by the Scald plugin. The caption is in the `<div>` with the class `dnd-legend-wrapper`:

```
<div class="dnd-atom-wrapper type-image context-sdl_editor_representation atom-align-right" contenteditable="false">
<div class="dnd-drop-wrapper"><!-- scald=2:sdl_editor_representation {"link":""} -->
<div class="image"><img alt="Fred Espen Benth" src="http://example.com/sites/default/files/styles/large/public/thumbnails/image/fredespenbenth.jpg?itok=TwJhh_s6" style="height:320px; width:480px" title="Fred Espen Benth" /></div>
<!-- END scald=2 --></div>

<div class="dnd-legend-wrapper" contenteditable="true">
<div class="meta"><!--copyright=2-->Fred Espen Benth. Foto: Gunhild M. Haugnes<!--END copyright=2-->.</div>
</div>
</div>

```

---
Tags: theming, wysiwyg, scald
---


title: Option sets for fields?

text:
# Question
Title: Option sets for fields?
In my content type I have a products field (entity reference) which references other content types (product content types). What I want to do is each product field has to have a specific option set, and on the node add form the user can choose a product with a specific said option. Example:

Product: Food package A Options to choose from: Set A, Set B, Set C, etc.

Product: Food package B Options to choose from: Set A, Set B, Set C, etc.

My Goal: Choose product: Food package A Choose option: Set A

I tried editable fields but what happens is the user edits the original product content. BTW I'm not using any commerce module.

Any help would be greatly appreciated!

# Answer
> 0 votes
I didn't fully understand your question. But what is get is you have multiple fields that each one is specific product say, tablet,cellphone,food and every product field has its own specific sets of options.

I recommend you to use field collection module and set the number of values to `unlimited.` By this module, define the filed collections and specify what sets every product field is free to choose.

---
Tags: entities
---


# Question
Title: Is it possible to use an Image Style in a text field?
Image Styles is a great feature in Drupal. Is it possible to apply a preset Image Style to an image that is brought into a long text type field that uses WYSIWYG in Drupal 7? That is, for use in the basic node, not in a View.

Currently, we're using the IMCE WYSIWIG bridge to insert images in the textfield, and there seems to me no way to indicate what preset Image Style to use.

# Answer
It depends on what you mean by "possible" `:-)`.

The **Scald** module (integrates with the WYSIWYG CKeditor) uses something called "contexts" that in turn makes use of the preset image styles. So it is certainly possible to do this if you use **Scald** to insert images into WYSIWYG.

**Scald** has a drag'n'drop UI that allows you to place an image (or "atom" in Scald-speak) into WYSIWYG. When you do that, you can set its legend (i.e. caption), context and alignment (see sample dialog below):

In this case, the "Context" is set to "Full page". which I have associated with the preset Image Style known as "Large 480x480".

Below, you can see the markup that is *generated* by **Scald** as a result of this, and you can see that it links to the image using the path:

```
public:://styles/large/public/thumbnails/image/fredespenbenth.jpg

```

the `styles/large` path is indeed the image cache for the preset "Large 480x480" image style.

```
<div class="dnd-atom-wrapper type-image context-sdl_editor_representation atom-align-right" contenteditable="false">
<div class="dnd-drop-wrapper"><!-- scald=2:sdl_editor_representation {"link":""} -->
<div class="image"><img alt="Fred Espen Benth" src="http://example.com/sites/default/files/styles/large/public/thumbnails/image/fredespenbenth.jpg?itok=TwJhh_s6" style="height:320px; width:480px" title="Fred Espen Benth" /></div>
<!-- END scald=2 --></div>

<div class="dnd-legend-wrapper" contenteditable="true">
<div class="meta"><!--copyright=2-->This is the caption that will appear under the image.<!--END copyright=2-->.</div>
</div>
</div>

```

Now, as you can see, **Scald** is doing this, so it must be possible.

And you can (to some extent) do the same thing *without* **Scald** by inserting similar markup "by hand" or with the help your own custom module. But **Scald** has in place additional magic to regenerate that style of the image in the image cache if it does not exist. If you do this just by inserting the markup, you can't be sure that the image exists in that style, so you have to use other means to make sure the image cache is populated with the styles you actually use. (For example sniffing for URLS pointing into the cache in `hook_preprocess_node()`, and regenerate those that are missing.)
> 1 votes

# Answer
Yes, this can be done with the module found on: https://www.drupal.org/project/image\_filter
> -1 votes

---
Tags: nodes, media, wysiwyg
---


# Question
Title: Entity Reference. Hide not user referenced terms in node form?
This is my 2nd question about my problem, the last was "Users have access to add Commerce Products into the Store and publish it. How to display to user only allowed firms in the product addition form?" I am writing my 6th module and I do not know nothing about form fields arrays. I need to display in node addition form only user referenced terms in field Firms. Taxonomy "Firms" has **field\_seller** of type Entity Reference. I add to all Firms terms users that must have access to them. How can I display to user only those terms that have reference to this user when he add node Product ? I've made this code that has only correct name (I've checked this with other funcions that was in it and worked):

```
/* Displays only terms that have Entity Reference field with current user reference */
function user_referenced_taxonomy_terms_form_node_form_alter(&$form, &$form_state, $form_id) {
  //$form['field_firm']
}

```

how to get array $form\['field\_firm'\] of terms that have reference to current user if the user role is not admin?

# Answer
> 0 votes
I solved this task with my module: This code limit radiobuttons of field\_firm on the node addition page with only those terms that have entity reference to current user. Admin have access to all. If user has no one term access field Firms hides.

```
/* BASE_FORM_ID : node_form */
/* Displays only terms that have Entity Reference field with current user reference */
//$form['field_firm']['und'][1551]= array('#access' => FALSE); //hides taxonomy term 1551

function user_referenced_taxonomy_terms_form_node_form_alter(&$form, &$form_state, $form_id) {

  global $user;
  //if current user has roles administrator or editor return
  foreach ($user->roles as $role) {
      if (($role == 'administrator') || ($role == 'editor')) return;
  }
  if (isset($form['field_firm'])) {
    $query = new EntityFieldQuery();
    $term_entities = $query
      ->entityCondition('bundle', 'firms')
      ->entityCondition('entity_type', 'taxonomy_term', '=')
      ->fieldCondition('field_seller','target_id',$user->uid) // if user has access
      ->execute();
    if ($term_entities) {
        //forming array of firms using $term_entities array
         $items = array_keys($term_entities['taxonomy_term']);
         foreach ($form['field_firm']['und']['#options'] as $key=>$value) {
             if ($key == '_none') continue;
             $delete=true;
             for ($i=0;$i<count($items);$i++) {
                 if ($key == $items[$i])  $delete = FALSE;
             }
             if ($delete) $form['field_firm']['und'][$key]= array('#access' => FALSE);
         }
    }else {
        //hide field firm if user has no access to any term
        $form['field_firm']['#access'] = FALSE;
    }
  }
}

```

---
Tags: entities
---


title: Transfer drupal 7 content types

text:
# Question
Title: Transfer drupal 7 content types
I have a Drupal install with 10 content types and 30 views being used as web app. The app uses MySQL as a database.

What I would like to do is to reuse the same app but with SQLite. Is there a way to migrate the theme, content types and views without re-building them from scratch? I am not interested in the content.

# Answer
You can export all your config using Features module: This module dumps to code several config data as content types and Views (but no content), generating modules that once enabled in another site regenerate dumped config.

One you have your config exported install a new Drupal site over SQL Lite and enable the exported modules with the config.

To 'migrate' the theme you only have to copy the theme folder to the new installed site right folder (usually /sites/all/themes/ or /sites/all/themes/custom/).
> 3 votes

# Answer
If all what you need is just moving your site to SQLite database you can use special converter scripts like mysql2sqlite.sh. Another way is using DBTNG Migrator module.
> 2 votes

---
Tags: 7, migrations
---


# Question
Title: How to display all when input argument is wrong
I create a view display a books depend on url argument (book type name) ... And when book type name is not exist in book types list ... view be empty .. how can I when the url argument is wrong, display all books?

thank you

# Answer
For contextual filters, the Views UI allows you to specify two different cases:

## Case 1: If the filter value is not passed to the URL

In the contextual filter configuration, in the "When the filter value is not in the URL" section, you need to set the "Display all results for the specified field" option.

## Case 2: If the filter value is wrong

In the contextual filter configuration, in the "When the filter value IS in the URL or a default is provided" section, you need to check the "Specify validation criteria" checkbox. Then, you can set the "Action to take if filter value does not validate" to "Display all results for the specified field".

You can see more details in the Views documentation: https://www.drupal.org/node/1578574

Hope it helps,
> 1 votes

---
Tags: 7, views
---


title: Drush alias partially working

text:
# Question
Title: Drush alias partially working
My Drush alias file is:

```
$aliases['mysite'] = array (
  'uri' => 'mysite.com',
  'root' => '/var/www/mysite',
  'path-aliases' => array(
    '%dump-dir' => '/tmp',
  ),
);

```

when I do `drush @mysite status` I get

```
 Drupal version         :  7.36
 Site URI               :  mysite.com
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  dbuser
 Database name          :  dbname
 PHP executable         :  /bin/php
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :  /home/deploy/.drush/mysite.aliases.drushrc.php
 Drupal root            :  /var/www/mysite
 Site path              :  sites/default

```

But I'm unable to run other Drush commands.

eg:

```
drush @mysite dd
You need to specify an alias or run this command within a drupal site.           [error]
Target 'root' not found.        [error]

```

OR

```
drush @mysite cc all
No Drupal site found, only 'drush' cache was cleared.                            [warning]
'all' cache was cleared.                                                         [success]

```

But `drush dd` commands works this way:

```
drush dd @mysite
/var/www/mysite

```

I tried like that, but this one doesn't work though `drush cc all @mysite`

Any ideas why is that so, the site is running perfectly.

# Answer
You're using an unstable version of Drush 7.0-dev according to drush github page. You should install Drush 6.60 or lower and try again.

Or you can also switch to a tagged release of version 7 according to the comment below by @greg\_1\_anderson:

> "7.0-dev" is HEAD of master, which is refreshed almost daily. So, the OP might be using a very recent build, or one that is over a year old. Switching to a tagged build like 7.0-rc1 would remove the uncertainty.
> 0 votes

# Answer
In `drush status` you should have the following lines right after Database credentials:

```
Database                        :  Connected
Drupal bootstrap                :  Successful

```

When you don't have it, this suggest your Drupal instance is not properly configured and `drush` has problem bootstrapping it. For example, you may check if you can connect to the database, try: `drush @mysite sqlc`.

When executing `dd` on a remote machine, Drupal needs to be able to bootstrap on the configuration level, so it can read the variables. When you don't have the proper access, you'll have the error like:

> Target 'root' not found.

See also: drush\_core\_drupal\_directory().

---

Other suggestions:

* Make sure that on your local and remote you have got the same version of `drush`.
* Other problems could include issues with specific PHP version (see: #779).
* If you've still problems, run `drush` with verbose (`-v`) or debug options (`-d`).
> 1 votes

---
Tags: 7, drush
---


title: change quicktabs default tab

text:
# Question
Title: change quicktabs default tab
according to current documentation of for change alter quicktabs should use this method in my module

```
mymoule_quicktabs_alter(&$quicktabs){
    $quicktabs->default_tab=2;
   }

```

when i print result with dsm it changed applied, but it **not** apply to visual output of quicktabs.

tell me how i can change quicktabs default tab ? tnx

# Answer
Its not done simple, by default quicktabs ordered by wieght, Quicktabs has quickly become one of my favorite Drupal modules of all time. To think that I was actually wasting time creating tabs by using jQuery plugins, and writing custom AJAX. Creating tabbed content is one of the most popular techniques used on the web today, and with Quicktabs it has never been easier to add tabs to your Drupal site - even with AJAX!

First you'll want to install Quicktabs

Once you have Quicktabs installed, there are a couple of ways to generate tabs. You can do it through the Drupal interface, or you can do it programmatically, but first, make sure you have some content that you want to show in tabs! Quicktabs works with your existing content. You can tab between views, blocks, nodes, or a mixture of these.

For this demo, we'll use Views and set up 2 displays filtered by a certain taxonomy term. We will then create a tab that displays nodes of each taxonomy term respectively. Make sure you have some taxonomy terms to choose from for each post. Then you'll want to create a view called "my\_listing", or whatever makes sense for you.

Once you have created your View, create a couple of different "page" displays. Name each display according to your taxonomy term, so if you want to tab between say "Development" and "Theming" nodes, each page display will be named respectively.

Since you're creating page views, you'll have to specify a URL for each under the Page Settings section. You can use something like "list/development" and "list/theming" respectively. This is required by page displays, but it is also good if a user for some reason does not have javascript enabled, they will still be able to see the listings, just not through AJAX.

Also, for simplicity, make "Row style" node, so we don't have to play with fields.

Under "Filters" filter on each display for that specific taxonomy term, so that each display is only displaying nodes of whichever taxonomy you choose. Save the view.

Now that you have some content to play with it's time to create some tabs. Browse to admin/build/quicktabs and click on the "New QT block tab".

By default, Quicktabs creates a block for you which you can then place anywhere in the site like a regular block, but there is also a way to output your quicktabs in code, which i'll show you further down.

In the Block Title field, give your block a meaningful title. Next is the style dropdown, where you can select between various styles of tabs. You can also select "no style" so you can theme them your own way

The next field allows you to select whether or not you want your tabs to be AJAX. In most cases you will want to use AJAX so that you only load the second view when the user requests it.

The "Hide empty tabs" will only work if you do NOT use AJAX, which is kind of unfortunate. But, an easy way to deal with this is to use the "empty text" area in your views to give the user a friendly "There is no content here" message.

The next section is where you will start creating your tabs

Let's say the view you created with the 2 page displays are for a taxonomy term "Development" and one for "Theming". Give each tab their respective title. For the Tab type, select "view". In the tab content section, select the view you created (my\_listing). Then select the display you want to show. For the Development tab, show the display that filters on Development. For the Theming tab, show the display that filters on Theming. You can also pass arguments into your Quicktabs to use with Views that accept arguments which is really cool, but I won't be covering that here.

Click save. You now have a block available for you to place anywhere on your site, that will tab between nodes of each taxonomy term! Very cool! But, what if you dont' want to use a block...what if you want a bit more control to place these tabs wherever you want? It's easy.

On your tabs listing page (admin/build/quicktabs) hover over the 'edit' link and take note of your quicktabs ID in the url. (quicktabs/1/edit). If this is your first quicktab, the ID will be 1.

Now to print out your quicktabs, all you need to do is call this function and run it through `theme("quicktabs");` like this:

```
$tabs = quicktabs_load(1); // where 1 is your quicktabs id
$mytabs = theme("quicktabs", $tabs);

return theme("my_custom_template", $mytabs);

```

Then in your custom template, just print out the mytabs variable and you should see your quicktabs!
> 2 votes

# Answer
```
mymoule_quicktabs_alter(&$quicktabs) {
  $quicktabs->default_tab=2;
}

```

This works fine.

Please check if any JS script is overwriting your default tab. Normally if other module or JS script that alters the default tab and executes after current module; you might not see the effect in front-end.
> 0 votes

# Answer
own module must be sort after quicktab module - when i added module name webmodule and there insert

webmodule\_quicktabs\_alter(&$quicktabs) { $quicktabs-\>default\_tab=2; }

everything works fine
> 0 votes

# Answer
mymoule\_quicktabs\_alter(&$quicktabs) { $quicktabs-\>default\_tab=2; return $quicktabs; }

This works fine.
> 0 votes

# Answer
The easiest is qt- = in the new version of quick tab it takes as a query string
> -1 votes

---
Tags: blocks
---


# Question
Title: How to apply focus for specific tab in quicktab
I have used quicktabs to search my channels and profiles.I have set default tab "Channels/Videos" in quicktabs setting.When a user enters the text and selects "Profile" tab the focus automatically reverts back to "Channels/Videos".What I want want is,it should remain on the option whichever is been selected("Channels/Videos" or "profile").How can i do this? I also checked by setting the default tab as"none" in quicktabs setting but when a user search for "Channels/Videos"(or "Profile") focus on tab( which is in blue color ) disappears. How can i fix this problem?

# Answer
You can alter the search form hook\_for\_alter using form id.

Add a hidden field name it 'mytab' whose by default value will be channel and on click of tab its value will be toggled between channel and profile.

So when we submit the form to search the content, it will look this way **?title=hello&mytab=channel**

Now on in your **hook\_form\_alter** inline js code to select the default tab based on the `mytab` value that you can get using `$_GET`.

Let me know if it works for you.
> 0 votes

# Answer
```
mymodule_quicktabs_alter(&$quicktabs) {
  $quicktabs->default_tab=2;
  return $quicktabs;
}

```

This works fine.
> -1 votes

---
Tags: blocks
---


title: How do I add a menu task to /node path?

text:
# Question
Title: How do I add a menu task to /node path?
I want to add a custom tab after "Edit" but can't figure out how to do so. I added a mymodule.links.task.yml file

```
entity.node.import_form:
  route_name: entity.node.import_form
  base_route: entity.node.canonical
  title: Import JSON from file

```

But I don't understand what to do next. The node form just errors out with:

> Symfony\Component\Routing\Exception\RouteNotFoundException: Route "entity.node.import\_form" does not exist. in Drupal\Core\Routing\RouteProvider-\>getRouteByName() (line 128 of /var/www/sites/datacenter.com/docroot/core/lib/Drupal/Core/Routing/RouteProvider.php).

# Answer
What you have done is to create a menu task on the route `entity.node.canonical` with the title of `Import JSON from file` which links to the route `entity.node.import_form`.

The error you are getting is because the route `entity.node.import_form` (the link of the task) doesn't exist. You have to either depend/enable the module that provides this route or create the route yourself.
> 1 votes

---
Tags: routes, 8
---


# Question
Title: Show fields from diffrent content types in same view?
Im using Drupal 7.x Merci, views, panels, chaos tools, rules, etc. I am working on a equipment checkout system, and I have a view that lists all the reservations made. In that view I would like to not only show the fields from the Content Type:Reservation, but also the picture from the Content Type:Customer. I know that I need some kind of reference field so that I get the correct picture next to the correct reservation, so they have several fields in common, Customer Name and L#. I would prefer to use L# but i'm not sure what reference I need to use (entity reference, node reference, field reference) I already have the view built displaying the reservations. Any help would be great, there are lots of questions around about this but I haven't found one that touches on this.

Thanks in advance :)

# Answer
> 0 votes
Depending in the setup, the person who makes the reservation might also be referenced via the author field in views, but I don't know how your reservation system works.

Properties of other entities can be embedded in a view via the relations in the advanced section. There has to be a common field such as an entity reference linking the two content types together, but author, tags and several other properties can be used as well.

After adding such a relation, New fields will become available in the fields, filter and sorting sections.

UPDATE

I believe there is some misunderstanding about the modules. An entity reference (or any other reference in Drupal) uses the user id (uid) not a custom field #L. So when you add such a reference to a content type, you can only find users by username (or common name if realname module is installed). Since you said you have the customer name this should not be a problem as you select the users by name, but their uid is stored in the database.

Make sure there is only one relation on the content type that is created on the desk (registration). Adding an entity reference on the user (or both content types) makes no sense; a registration is made for one or more users, user's don't own one or more registrations.

Create a view listing fields of the main content type you want to display (registration). Then add a views relationship to the user object via the entity reference field. Finally you can add all fields of the user object to your list of fields.

The only filters you will need are filters for limiting the set of registrations (you could add contextual filters to list registrations per user), but I'd leave out all registrations to start with. You can always add them later.

---
Tags: views, entities
---


# Question
Title: What's the best way to create variables that are available to every single URL on my site, based on node id or taxonomy id?
On Drupal site A we have a bunch of links to non-Drupal site B. For marketing and tracking purposes all these links have a different URL variable appended to them, so that when a user registers on site B we can determine where on site A they came from.

At the moment I use **page.tpl.php** to create the variable (`$forceCode`) but it now transpires I need this variable to be available to **node.tpl.php** too, and I feel like there must be a less hacky and more universal way of doing this, probably using a preprocess function in **template.php** that right now seems beyond my comprehension level.

**PLAIN LANGUAGE EXPLANATION**

`$specialPages` is an array of node IDs that need a special code.
`$specialFolders` is an array of taxonomy IDs that need a special code.

* If the current node ID matches any in the `nid` array, I set the variable accordingly.
* If not then I get the category (taxonomy) of the current node, or if the current page is a taxonomy term itself then use its own `tid`.
    + Then using this taxonomy ID I get all other `tid`s that are parents of that `tid`.
    + Then I look for matches of any of these taxonomy IDs in my array of special `tid`s in order to set the variable.
* If the current page has not matched any of my special nodes or taxonomies, the variable remains its default value.

**ACTUAL CODE**

```
// we later restrict our parent taxonomy search to certain types but it's not strictly necessary
$contentTypes = array("article","advpoll","event");

$specialFolders = array(
    276 => "events",
    292 => "free-dating",
    498 => "date-explorer"
);
$specialPages = array(
    22 => "reviews",
    86 => "texting"
);

$forceCode = "default";

// check for specific page first
if (@array_key_exists($node->nid,$specialPages)){
    $forceCode = $specialPages[$node->nid];
} else {
    // there was no entry for this nid, let's check parent terms
    $parentTerms = array();
    $hasParents = false;
    if (arg(0) == "taxonomy") $hasParents = arg(2);
    if (@in_array($node->type,$contentTypes)) {
        $category = field_view_field('node', node_load($node->nid), 'field_category');
        $hasParents = $category['#items'][0]['tid'];
    }
    if ($hasParents !== false) {
        $parents = taxonomy_get_parents_all($hasParents);
        foreach ($parents as $term){
            $parentTerms[] = $term->tid;
        }
    }

    foreach ($parentTerms as $tid){
        if (array_key_exists($tid,$specialFolders)){
            $forceCode = $specialFolders[$tid];
            continue;
        }
    }
}

```

# Answer
> 0 votes
I've found a very satisfactory solution using `function matchtheme_preprocess(&$variables, $hook)` which will always supply variables to page and node templates.

The more complicated bit was finding an appropriate way to get this function to collect the data I need (nid or tid) properly regardless of whether it was the page or node template making the call.

Essentially (this is the cut down version) I just did this:

```
if ($hook == "page"){
    // supplies variables to page.tpl.php
    // the page template can cover anything, including a node and taxonomy
    if (arg(0) == "node"){
        $nidToCheck = arg(1);
    } else if (arg(0) == "taxonomy"){
        // already a taxonomy page, the term id is the category
        $hasParents = arg(2);
    }
} else if ($hook == "node"){
    // supplies variables to node.tpl.php
    $nidToCheck = $variables['elements']['#node']->nid;
}

```

From there `if ($nidToCheck)` allows me to use the `nid` to generate `$hasParents` for nodes, and then I can move on handling all nodes and taxonomy terms to do what I want (all this bit is essentially the same as in my question).

Finally I feed back to the template an array of variables in much the same way as they were set before.

So glad to have this sorted as it caused quite a headache. Would love to hear whether or not this is an efficient or clever way of dealing with it. The most obvious issue to me is that the array of variables (and of course the whole function) will get run twice on node pages - once for the page template and once for the node template - which is a touch inefficent. I guess I could contain the whole thing in an `if (!isset...`

---
Tags: nodes, taxonomy-terms, theming, configuration
---


# Question
Title: How to access services_views the correct way?
I am trying to fetch some views with the services\_views module. Sadly enough I keep getting the response: "404: Not found: Display on view my\_view\_name could not be found".

I am using Views 3 and I defined for test a view with a 'page' display id. (default display id is not a "default" anymore)

I know that I have to pass the display\_id argument but simply can't make it work.

Here is the calls I am trying to use:

```
http://www.mywebsite.com/rest/views/my_view_name.json?display_id="page"
http://www.mywebsite.com/rest/views/my_view_name.json?display_id=page
http://www.mywebsite.com/rest/views/my_view_name.json?parameters[display_id]="page"
http://www.mywebsite.com/rest/views/my_view_name.json?args[display_id]="page"

```

In the resource definition for the service it is clear that display\_id has to be passed as an argument.

```
'args' => array(
  'view_name' => array(
    'name' => 'view_name',
    'type' => 'string',
    'description' => 'The name of the view to get.',
    'source' => array('path' => '0'),
    'optional' => FALSE,
  ),
  'display_id' => array(
    'name' => 'display_id',
    'type' => 'string',
    'description' => 'The display ID of the view to get.',
    'source' => 'param',
    'optional' => TRUE,
    'default value' => 'default',
  ),...

```

Is there anyone who managed to make this work?

Thank you.

# Answer
On a Drupal.org issue page for this module, someone suggests the following for the 7.x version.

```
The arguments are passed in the usual url format, for example:
http://example.com/my_endpoint/views/view_name?display_id=default&args=123&offset=0&limit=10&return_type=FALSE

Multiple arguments can be used like this:
http://example.com/my_endpoint/views/view_name?display_id=default&args[0]=abc&args[1]=123&offset=0&limit=10&return_type=FALSE

```

I've been trying to get this working on 6.x but haven't succeeded yet.
> 1 votes

# Answer
If you have Firefox installed, or Firebug you can look at the HTML source to get the display\_id. See this screen shot (and please ignore my page argument!):
> 1 votes

# Answer
I faced the same issue with services\_views to pass arguments to a view called by services request and I solved it by applying a patch in the module without that it won't work.

Here is a diff patch from my project

```
diff --git a/sites/all/modules/services_views/services_views.moduleb/sites/all/modules/services_views/services_views.module
index 9ce8080..65dd92e 100755
--- a/sites/all/modules/services_views/services_views.module
+++ b/sites/all/modules/services_views/services_views.module
@@ -182,6 +182,10 @@ function services_views_views_plugins() {
 function services_views_services_request_preprocess_alter($controller, &$args, $options) {
   if (isset($controller['view info'])) {
     array_unshift($args, $controller['view info']);
+    $args[0]['args'] = array();
+     if (!empty($_GET['args'])) {
+       $args[0]['args'] = $_GET['args'];
+     }
   }
 }

diff --git a/sites/all/modules/services_views/services_views.resource.inc b/sites/all/modules/services_views/services_views.resource.inc
index eb9fbb4..aae2975 100755
--- a/sites/all/modules/services_views/services_views.resource.inc
+++ b/sites/all/modules/services_views/services_views.resource.inc
@@ -111,10 +111,11 @@ function services_views_execute_view($view_info, $view = NULL, $display_id = NUL
     $view_name = $view_info['view_name'];
     $display_id = $view_info['display_id'];

-    $args = array();
+    $args = $view_info['args'];

     $view = views_get_view($view_name);
     $view->set_arguments($args);
+    $view->execute_display($display_id, $args);
   }

```

I don't remember the link to the patch but that may helps see services views args issues

If you created a service display for the view you would see it as a resource it self.

Hope that helps
> 1 votes

# Answer
Chances are you want `display_id=page_1`. The `display_id` parameter must be the **internal** id of the display. AFAIK the default display always has id 'default'.

The id's of any additional page displays you create are not visible in the Drupal 6 UI, but you can find them out by doing an export on your view and looking at the resulting code.

Each display is created with a call to `$view->new_display()` where the third parameter is the id (see views\_db\_object::new\_display).
> 0 votes

---
Tags: 7, views, services
---


# Question
Title: Views: attachment inherits exposed filters when set to No
I created a page with an attachment to it. Its a Glossary for the Username.

And here is my attachment setting:

i Have exposed filters on the page where it is attached to:

And the Filters works together: When i write something to the name it searches it and when i click on the glossary it retains the name's search value. I don't want that.

If i click on the Glossary i oly want that search, any other filters should reset. How do i achive that?

# Answer
You can't do that by default with views settings. Filters are meant to stay upon adding / removing one of them, because otherwise you can't search items combining them. You can add a "Reset" button form the "Advanced" block of the view UI (see screenshot).

If you want this behavior to be exactly as you describe, I think you'll need write up a plugin for the filters yourself, or alter the default ones.
> 0 votes

---
Tags: views
---


# Question
Title: How to create fields group as accordions?
Hello Drupal community,

I am trying to create a group of fields with an accordion, so that it can be visible/unvisible with a simple clic on the title of the field's group.

Does anyone know how to do it ? Or know a module that does it ?

# Answer
> 4 votes
The Field Group module is great for that usage.

> Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.

---
Tags: entities, nodes, navigation
---


# Question
Title: Drush fails "unable to copy" to drush-backups?
When I run $ drush pm-update I receive an "Unable to copy" error.

> Unable to copy /mnt/hd0/vhosts/yourwebsite.com/drupal-7.36 to /home/ec2-user/drush-backups/opencall/20150422140414/drupal. \[error\] Unable to move /mnt/hd0/vhosts/yourwebsite.com/drupal-7.36 to /home/ec2-user/drush-backups/opencall/20150422140414/drupal. \[error\] Failed to backup project directory /mnt/hd0/vhosts/yourwebsite.com/drupal-7.36 to

Any thoughts? I'm sure it will run if I use sudo but that has other undesirable consequences.

# Answer
> 0 votes
Think I've solved it.

Looks like someone previously ran Drush in the sudo environment and that had the effect of setting permissions to 6226 all over the place.

Updated manually and fixed permissions as I went.

---
Tags: drush
---


# Question
Title: drupal_http_request with basic authorization receives 401 response
I am trying to use drupal\_http\_request to connect to a remote rest-based webservice that uses http basic authorization. The following curl command works every time from a command line, and I'm trying to figure out how to do the same the "drupal 7 way".

```
    curl 'https://XXXXXXXX/login' -H 'Authorization: Basic XXXXXXXX==' \
      -H 'Content-Type: application/x-www-form-urlencoded' \
      --data 'username=XXXXXXXX&password=XXXXXXXX'

```

Here is the code I am using in Drupal

```
    class XXXXXX {
      function login($username='', $password='') {
        // construct url - returns https://XXXXXXXX/login
        $url = $this->constructLoginUrl();

        $data = array(
          'username' => $username,
          'password' => $password
        );

        $headers = array(
          'Authorization' => "Basic XXXXXXXX==",
          'Content-Type'  => "application/x-www-form-urlencoded"
        );

        $response = drupal_http_request( $url, $headers, 'POST', http_build_query( $data )

        return $response;
      }
    }

```

When I run the curl request, I get a json\_encoded response. When I run the second bit of code, I get a 401 unauthorized error from the other server. So, my intent is to make the Drupal request work exactly the same as the curl request above. Is there something I should be doing differently?

# Answer
If you're using Drupal 7, then I'm fairly certain you're supposed to put everything after the URL into a single options array instead of positional arguments. This was done so you can pass some arguments without passing all of the preceding ones.

https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_http\_request/7

```
drupal_http_request($url, array(
  'headers' => $headers,
  'method' => 'POST',
  'data' => http_build_query($data)
));

```

should work.
> 4 votes

---
Tags: users, services
---


# Question
Title: How can the Feeds module fetch a file from a dynamic URL?
The feeds module does fine importing a source file (CSV, in my case) from an external URL. However, I'm trying to schedule Feeds to pull in a report every X days. I need Feeds to fetch at a dynamic URL, say:
`www.example.com/report/%start-date%/%end-date%`

I'm guessing this would use the Token module, but aside from that I'm not sure what to do.

# Answer
As I know Feeds doesn't have something like that, its maybe a feature that you can propose on they issue list.

A workaround its to create a small module that will work as a proxy for your dynamic address.

You will have something like that :

```
<?php

function proxy_menu() {
  $items = array();
  $items['proxy-url'] = array(
    'title' => 'Proxy for danymic url',
    'page callback' => 'proxy_get_contents',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );
  return  $items;
}

function proxy_get_contents() {
  $url = 'http://www.example.com/report/%start-date%/%end-date%';
  $request = drupal_http_request($url);
  if ($request->code == 301 || $request->code == 304) {
    return $request->data;
  }
}

```
> 1 votes

# Answer
You can extend the FeedsHTTPFetcher class and register your plugin with hook\_feeds\_plugins(). Then override the fetch method to handle your dynamic URL that's stored in $source\_config\['source'\].
> 0 votes

---
Tags: uri, feeds
---


# Question
Title: Fatal error: Call to undefined function system_run_automated_cron()
I migrated my database from oracle to mysql and when linking it to my drupal the following error:

```
Fatal error: Call to undefined function system_run_automated_cron() in /var/www/drupal/includes/common.inc on line 2732

Call Stack
#   Time    Memory  Function    Location
1   0.0000  241712  {main}( )   .../index.php:0
2   0.1117  1842704 menu_execute_active_handler( )  .../index.php:21
3   0.1120  1844088 drupal_deliver_page( )  .../menu.inc:532
4   0.1123  1845064 drupal_deliver_html_page( ) .../common.inc:2589
5   0.1213  1858496 drupal_page_footer( )   .../common.inc:2705

```

Someone could help me solve this problem?

# Answer
For some reason it hasn't defined `system_run_automated_cron()` in the core system module. It's just a matter of figuring out why. A couple of things to check are:

1. Since you moved the DB over, did all the tables get created correctly? Check for the `system` table for a row entry with the `name` column set to "system". Is the `status` column set to 1?
2. Does modules/system/system.module exist and is executable by the webserver?
> 0 votes

---
Tags: 7, migrations, database
---


# Question
Title: Profile 2 different types with single edit form
I am using the profile2 module to create different types of information for the user. One of these profile types are filled in on the registration page.

What I am trying to accomplish is combining the registration form profile with another profile so that they can be edited on the same form page.

For example: The fields of Profile-Registration and Profile-Info must all be editable on www.website.com/form/%user/edit. These fields are rendered with views, and are working perfectly. It is just the editing I am trying to figure out. I am not sure how to go about achieving this.

# Answer
> 0 votes
It could be accomplished using Panels:

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

and Profile2 Panels Module:

> Page Manager (Panels) support for Profile2.
>
> With this module you can take over Profile2 paths with Page Manager. Now it is possible to theme your Profile2 edit and view pages with Panels.

If you're not familiar with panels, there are numerous resources and tutorials out there

---
Tags: forms, users
---


# Question
Title: Easy way to get this custom module to work with multiple Nodes (NID's)
Topsitemaker hooked me up with this custom module that works great with one node when I enable it. My issue is I need it to work across multiple nid's. The field name and cid on all the nid's will stay the same, the only thing that will change will be the nid. I have been trying without success to get this to work. In this example it works for nid 4, but if the module is enabled, it will return the error for the same field on other nid's. Is there an easy way to get this module to work with several nid's?

```
'<?php

/**
 * Implements hook_form_alter().
 */
function sample_form_alter(&$form, &$form_state, $form_id) {
  // Make sure that we are selecting the webform forms.
  if (substr($form_id, 0, 20) == 'webform_client_form_') {
    $form['#validate'][] = 'sample_webform_validate';
  }
}

/**
 * Sample validation callback.
 */
function sample_webform_validate($form, &$form_state) {
  // Replace this with the name of your field, cid (webform component ID) and
  // nid.
  $field_name = 'application_name_director_name_manager_name';
  $cid = 10;
  $nid = 4;
  // Check if this is a duplicate.
  $is_duplicate = db_select('webform_submitted_data', 'd')
    ->fields('d')
    ->condition('nid', $nid)
    ->condition('cid', $cid)
    ->condition('data', $form_state['values']['submitted'][$field_name])
    ->execute()
    ->fetchObject();
  if ($is_duplicate) {
    form_set_error($field_name, t('YOU HAVE ALREADY SUBMITTED FOR THAT APPLICATION, PLEASE SELECT A NEW APPLICATION.'));
  }
}

/**
 * Implements hook_form_alter().
 */
function sample_form_alter2(&$form, &$form_state, $form_id) {
  // Make sure that we are selecting the webform forms.
  if (substr($form_id, 0, 20) == 'webform_client_form_') {
    $form['#validate'][] = 'sample_webform_validate';
  }
}

```

# Answer
Would have been good if you explained what the module does so we don't have to read through the code to understand the module.

I am going to assume you mean the nid condition in the query.

The condition function of the query object defaults to 'IN' if you send it an array.
eg.

```
$nid = array(4, 5, 6);

```

and then:

```
->condition('nid', $nid)

```

will check nids 4, 5 and 6.
If you want to check all submitted webforms, just remove the nid condition.
> 1 votes

---
Tags: webforms
---


title: Flood for node add

text:
# Question
Title: Flood for node add
I've been noticing in my site logs that I'm getting a lot of notices of

> access denied 2015-04-22 15:20 node/add Anonymous (not verified)

Most of which are coming from a set of IPs, and in quick succession (we're talking milliseconds). Clearly, these are bots that are trying to add their spam to my site.

Is there anything out there I can use to track and block users if they try to illegally add nodes? I have become familiar with D7's flood table after a series of bruit force attacks. So I feel like it should be possible to do something similar to that with access denied errors for node/add. The question is, has anyone every done that? Or is that something that would require a custom module?

The ideal functionality of this solution would to be ban (ether permanently or temporarily) an IP after x attempts resulting in access denied in x time period. Probably something like 5 access denied notices in a second or so.

# Answer
Surest way I know is to block them even before they hit your Drupal. They only work if you have cooperation of sysadmin, but they are fast and pretty reliable.

**mod\_qos** \- not a protection per se, but may be used to ensure that requests to node/add will not slow down other parts of your site. That's the way I would go in your situation, probably.

**ModSecurity** \- catch-all security module with thousands of rules available on the Internet. One of them here; sadly it's copyrighted, but you can find examples with Google or implement the same logic using Mod's own documentation, if needed.

Directly in Drupal - I wouldn't even try. CPU and database usage to store IP addresses and connection count, compare them at each request etc is not worth what you can save in bandwidth. Just make 403 page a lightweight one.
> 2 votes

---
Tags: 7
---


# Question
Title: Rules governing views-based free text search
I have a search feature that uses Views. There is a search box 'filter' that's just a text box which enables users to input text to search the database. Pretty standard stuff.

I'm curious to know however if there are any rules governing how this search functions?

(Ie. if I enter one word, fine it searches on that term. However if I enter two terms I notice it returns no results, even if I know both terms are in a node and in that exact order!). But if I put two or (more?) words in double quotes " " it seems to return items that have both of those words, although not in that sequence necessarily.

Anyway, I'm just wondering if anyone knows if there is a list of rules governing a Views-based search text? thanks.

Note: my search filter is based off 'search: search terms'.

# Answer
> 1 votes
The rules controlling exposed text field filters are various SQL operators. To give you a good indication of what's happening, navigate to **admin/structure/views/settings** and enable `Show the SQL query` option for the Views UI then preview various views with different operators. As you enter different text, you can see the SQL keywords used to filter the view.

For `Search: Search terms` filter its based off the core Search index. The search module crawls node content, breaks it into text tokens, weights the score according to your settings (see **admin/config/search/settings**), and builds an index for terms to content.

In terms of fuzzy search technology Drupal's is pretty basic, but it works most of the time. If you're looking for more robust search options there are more advanced solutions out there (Google CSE, Apache Solr, etc.).

---
Tags: views
---


# Question
Title: Displaying alternate text for a taxonomy term in node
I have a taxonomy term called 'price'. I'd like it to display on the node page if it exists. But I don't want the taxonomy value to appear on the node page, I want the label to appear 'Price:' followed by hard-coded text that says 'see website.'.

Is this possible, and if so, how?

I don't want to use String Overrides because I'm using the value for the taxonomy term elsewhere. Perhaps some sort of code-based method (no pun intended) would work better :)

# Answer
You can override the display your theme **node.tpl.php** template. Place something like this in your **template.php**...

```
function MYTHEME_preprocess_node(&$variables) {
   $variables['price_display'] = '';
   if(isset($variables['node']->field_terms[LANGUAGE_NONE]) && is_array(($variables['node']->field_terms[LANGUAGE_NONE]))) {
     foreach($variables['node']->field_terms[LANGUAGE_NONE] as $tag) {
        if(isset($tag['taxonomy_term']) && $tag['taxonomy_term']->name == 'price') {
          $variables['price_display'] = 'see website';
          break;
        }
      }
    }
  }
}

```

At this point you should have the variable `$price_display` available to print out in **node.tpl.php**.
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: What's the class or id of the autocomplete suggestions pane?
I'm doing a form with a fairly standard autocomplete\_path textfield, like:

```
$form['the_field'] = array(
    '#title' => t('A title'),
    '#type' => 'textfield',
    '#autocomplete_path' => "path/to/autocomplete",
    '#description' => "Some description."
);

```

It's working fine, but I want to do some styling of the suggestions that show up in response to the user's type-in. I'm trying to track down the id or class of this pane so I can add some css or whatever, but I can't find it -- the various browser inspectors keep closing when I try to look at the pane. Does anybody know what this is? Thanks!

# Answer
The element's id attribute is `autocomplete`.
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: How do I interact with $title, $breadcrumbs, and $action_links within a process or preprocess function?
I'm using a Bootstrap subtheme, with a custom page.tpl.php override. Within the template file, I see there are variables for $title, $breadcrumbs, and $action\_links.

If I wanted to access these inside of a preprocess or process function, let's say to modify the title based on whether or not there is content in a given region, how would I do that?

They don't seem to be passed along in $variables like the rest of the page content. $variables\['title'\] is not present. Would I use API functions such as `drupal_set_title()`?

# Answer
> 4 votes
This is how I manipulate breadcrumbs in page preprocess function. You can actually do this somewhere else, where you think it fits according to your needs.

```
/**
 * Implements hook_preprocess_page().
 */
function extremes_preprocess_page(&$variables) {
  // You can use preprocess hooks to modify the variables before they are passed
  // to the theme function or template file.

  //define breadcrumbs array
  $breadcrumb = array();
  $breadcrumb[] = l('SS','<front>');//add homepage first
  //if we are on one of my dynamic pages, we do this
  if (arg(0) == 'node' && is_numeric(arg(1)) && !empty($variables['node']) && _is_dynamic_type($variables['node']->type)) {
    if (!empty($variables['node']->field_term_reference)) {//we are gonna depend on a term ref field
      //get all parent terms
      $parents = array_reverse(taxonomy_get_parents_all($variables['node']->field_term_reference[LANGUAGE_NONE][0]['target_id']));
      //and add them to breadcrumb array
      foreach ($parents as $parent) {
        $breadcrumb[] = l($parent->name, 'taxonomy/term/' . $parent->tid);
      }
    }
    //set the breadcrumb
    drupal_set_breadcrumb($breadcrumb);
  }
  //if we are on a term listing page
  else if (arg(0) == 'taxonomy' && is_numeric(arg(2))) {//you can also check here, which vocabulary you want
    //easier this time
    $parents = array_reverse(taxonomy_get_parents_all(arg(2)));
    foreach ($parents as $parent) {
      $breadcrumb[] = l($parent->name, 'taxonomy/term/' . $parent->tid);
    }
    if (arg(3) && $type = taxonomy_term_machine_name_load(arg(3), 'vocab_name')) {
      $breadcrumb[] = l($type->name, request_path());
    }
    drupal_set_breadcrumb($breadcrumb);
  }

}

```

This sample uses taxonomy\_machine\_name.module which uses the same system with pathauto and is very useful for loading taxonomy terms from url if you set up correctly.

For title, you can go with drupal\_set\_title() and for action links hook\_menu\_local\_tasks\_alter().

---
Tags: theming
---


# Question
Title: How to remove the Destination parameter from an URL in Drupal 7?
I have a blog posts, and when an anonymous user visits it and and clicks the link "Login" or "Register" to post comment (under blog entry), then its url looks like this:

> **http://example.com/user/login?destination=node/55%23comment-form**

But I don't want that parameter of `destination` here. I just want a simple link like so:

> **http://example.com/user/login**

Any suggestions?

# Answer
> 4 votes
Finally I got the solution by using `hook_url_outbound_alter` in my theme template. I tested it successfully.

```
function moon_url_outbound_alter(&$path, &$options, $original_path) {
 // here "moon" is my theme, use your own.
  switch ($path) {
  case 'user/login':
  unset( $options['query']['destination'] );
  break;
 }
}

```

# Answer
> 1 votes
you could create your own block to easily accomplish this:

* create a new block allowing Full HTML, then insert your own link to login / register

> ```
> <a href="/login">Sign In</a> / <a href="/register">Register</a> to post comments
>
> ```

* limit it's visibility to the content types you want, in the placement you want, and only show for anonymous users
* use some css (or a preprocess function override if you want to get fancy) to hide the existing element

# Answer
> 0 votes
Would the Login Destination module help?

---
Tags: 7, redirection
---


# Question
Title: Removal of all markup and overall customization
So, hey everyone, I've picked Drupal for my newest project, and after checking out the code and a couple of case studies. I think that it's a perfect fit, but I have some concerns about the markup and customization.

I like to write my own markup, and hardcode things like menu items, remove unnecessary clutter, most JS, and really just give the website a life of its own.

What I'm really asking is if any of you had done (or attempted to do) a similar thing and if it's possible to remove absolutely all of the markup and JS (I don't really need any JS) Drupal adds to the frontend without breaking things to hell?

I'd appreciate any kind of help or guidance.

# Answer
> 1 votes
you can customize drupal as deeply and drastically as you please. typically that requires more intimate knowledge of how drupal works.

For alot of `field` based modifications the Display Suite module allows per-field `HTML Reset` to customize the HTML outputted per field. A lighter weight approach to the same idea of "resetting" how drupal outputs a field is the Fences module.

With regards to JS there is hook\_js\_alter which you may use the remove/alter what javascript files are loaded on the page.

All the HTML for the page can be tweaked from the `html.tpl.php` file used by your installed theme (or the base core supplied html.tpl file).

Have I done allll of these?! No, but I have used hook\_js\_alter to conditionally include JS on some pages via a module. I have for example removed all sidebars and unset I think most of the CSS found in `<head>` by conditionally supplying my own template file to a menu path via hook\_menu:

Load custom template from MENU\_CALLBACK

So there are *tons* of utilities to do this in Drupal. How these utilities play with 3rd party modules you want to leverage on your site ... or just how much *custom work* you want to do on your own website -- I leave as an exercise for you.

---
Tags: theming
---


title: Why is drupal resizing my images?

text:
# Question
Title: Why is drupal resizing my images?
In drupal I'm displaying a view in a block. I'm stripping out all the html and rewriting the results as this

```
<li><a href="#">[field_button_image]</a></li>

```

On the preview it looks okay, but in the block that contains the view it renders the image like this

```
<img typeof="foaf:Image" src="image/image.png" width="200" height="240" alt="">

```

The image is distorted because of the width and height styling that is added in the tag. Where is this coming from? And is it possible to disable it?

# Answer
> 2 votes
Check your content type. what is default image type in manage field display. set it Original image. hope this help!

# Answer
> 0 votes
The display setting of this field for the particular content type might be different from the original.

# Answer
> 0 votes
I suggest to have a look in to your :

* block.tpl templates
* Or maybe a filter in the block or the user permissions
* Display mode of the node

---
Tags: views, media
---


title: configuration views

text:
# Question
Title: configuration views
In my body field of view, I want to restrict the text entered by the user to a specific number of lines or size. How can I apply this condition?Is there any way to do this by configure that field?

# Answer
> 5 votes
1. Go to your view and click on the field you want to restrict the text to max length.
2. Click on the "REWRITE RESULTS" and then tick "Trim this field to a maximum length" checkbox
3. Enter Maximum length of characters you want to display.

# Answer
> 1 votes
Check out the maxlength module...

> Maxlength allows you to set maximum length of any field on any form making use of the form API. This includes fields created using the UI. (Example: any text field on a node) In D6 Maxlength allows you to set maximum lengths to the body, title and CCK textfields of any content type (node).
>
> When the maximum length is enforced for a field, while editing content of that type some Java Script will countdown how many characters are left, also if the Javascript is turned off, it falls back to form API validation.

---
Tags: 7, views
---


# Question
Title: How can we create a search form to display a specific node
I need to create a result publishing system in drupal.

there must be a search page to enter the student register number.

when the user enter the register number it should take it to a single specific node.

here the register number is a nodeid

so when a user enter the node id and hit show button, it should display that specific node.

which method is best.

i think with views we can do this.

but how

thanks

# Answer
> 3 votes
Make an exposed filter (with autocomplete) of the register number in your view (showing all these desired nodes), enable it's exposed filter block (Advanced \> Exposed form in block : Yes)

Now place this block where ever you want, hit apply, you should be taken to the views page, only showing one result. (Make sure the full rendered node entity is shown)

---
Tags: views
---


title: Link to View page in TPL file?

text:
# Question
Title: Link to View page in TPL file?
Is it possible in a TPL to create a link to a View page? Rather than hard code the link I would like it to update if the URL of the view page changes.

# Answer
> 0 votes
If the Page display name of the view is `page`, then it prints the path

```
$view = views_get_view($view_name, TRUE);
print $view->display['page']->display_options['path'];

```

# Answer
> 0 votes
Use views\_get\_view to get **$view** object.

Using view object you can find view path. It expects view name, which would obviously remain intact in your case.

---
Tags: theming
---


title: Destroy Superfish plugin

text:
# Question
Title: Destroy Superfish plugin
I have the Superfish module on my site that my main navigation uses. The site I am building is responsive so I'd like to destroy Superfish when the viewport is smaller than a specific size.

I see that superfish has a destroy method: `example.superfish('destroy');`

How can I use this method on my nav menu in Drupal? I'm assuming I need to do something like...

```
Drupal.behaviors.superfish {something here}

```

# Answer
I have the same issue and I think this is not possible: The `destroy()` method was implemented in the Superfish jQuery plugin since version 1.7, but the Superfish module uses version 1.4.8 of Superfish jQuery plugin.
> 1 votes

---
Tags: 7, javascript, navigation
---


# Question
Title: How to Display Image after submitting webform in the confirmation message page
I have added field as file in webform so that we can add image in this file field. Now i want to display next page after submitting image file by using following code

\[submission:values:image\_file\]

but I cant able to display the image in the confirmation page. how to display the image in the next page

# Answer
Instead of it you can directly try to add image in ***Confirmation message***. You can find that under form settings in webform.

like this : `<img src="[submission:values:image_key]"/>`
> 0 votes

---
Tags: webforms
---


# Question
Title: Creating custom cron jobs in the same module
I have Drupal 7 installation with Feed Import module enabled (not the same as Feeds module!). From this module I need to import data from several xml feeds with a different schedule. For example feed A should be imported once a day, but feed B - once a week.

I have done research and suggestions are that Elysia Cron or Ultimate Cron should help to do this. However I can't figure out what needs to be done to actually achieve that different feeds can be imported on different times.

If I take Ultimate Cron case as an example, then using their API ultimate\_cron.api.php https://www.drupal.org/project/ultimate\_cron I have found following suggestion:

I create a hook in Feed Import module, and define a new cron task (to import feed which is already defined in Feed Import by name "test API feed RAW"). Code looks like this:

```
function feed_import_base_cronapi() {
  $items = array();

  $items['test_api_feed_raw_cron'] = array(
    'title' => t('test API feed RAW')
  );

  return $items;
}

```

However when I go to Cron page in administrative layout and manually execute newly created task, nothing happens. It shows that cron task has been executed successfully, but no data is imported.

It seems that this newly created task is not actually linked with the feed that is defined in Feed Import module. Or that it is not triggering import of that feed.

What am I missing and doing wrong here? I'm not so strong with php and module development, any help will be appreciated.

I have already googled and looked for various solutions, but nothing works. I really feels like I'm missing something very basic and obvious. But of course it could be also opposite and I'm trying to achieve something really complicated..

# Answer
Found a solution with a help from a colleague. Will post it here if someone would have need for it some day.

I'm missing a callback function here that triggers the actual feed import. And also I changed from Ultimate Cron to Elysia cron. (not sure if that actually makes a difference here though)

the actual function that triggers feed import is from feed\_import\_base.module

```
_feed_import_base_process_feed($feed);

```
> 1 votes

---
Tags: cron, importing-exporting
---


# Question
Title: Complex order form presented as series of linked screens
\[Somewhat new to Drupal Commerce and Webform; trying my best to construct this question in a clear way\]: The project involves order forms for a combination of fee-charged workshops and also a series of no-fee workshops where the person needs to make 2 choices among 6 options but must rank them by preference (in case they can't get their top choice). So there are several kinds of choices the person needs to specify. Then the form needs to collect a wide variety of info, not just basic contact info. Finally it needs to collect payment for the items requiring it.

I already have a Webformbased structure that does all these things. (Although maybe not very efficiently.) It all exists on one page, using collapsible fieldsets to keep the initial view of the page simple and to have everything in one place. It makes sense to me, but for the new user I think it may be confusing.

I am thinking, it would be "better UX" if the various parts of this ordering process were divided into smaller chunks. I am thinking, either pages or maybe modal windows that are clearly and boldly identified as Step 1, Step 2, etc. and with the option to go back if desired. The results from each page or modal window would of course need to be compiled as part of the same order.

Is there a path to this sort of order form structure via existing modules, or is this a custom code project?

# Answer
It was a lack of useful earlier search results that led to posting the question. But often the query just needs the right search term. In this case, it's exactly "multistep" or "multi-step." That finds this, which along with the ensuing discussion and comments, answers the question quite well: https://www.drupal.org/node/324779

So, the capability was already there in Webforms, I just hadn't seen how to use it.
> 0 votes

---
Tags: webforms, commerce
---


# Question
Title: Images placed in blocks do not show up on certain pages
I hope this is not a silly question. I have created some links to social media using images inside custom blocks. The images show up on every single page on my local testing server, but after uploading to my production server, I notice that on pages where I use URL aliases that are not directly attached to the site url, the images don't show up. For example if I the page address is www.thebeat99.com/sandbox/competitions, the images show up just fine. If the page address is www.thebeat99.com/sandbox/profile/dami, the images don't show up. I have tried adding a base url in the settings.php file but it does not work either.

This is an example of the html I use to embed the images:

```
<div class="beaticon" id="fbicon">
  <a href="http://www.facebook.com/thebeat999fm">
    <img alt="Facebook" height="32" src="sites/default/files/buttons/fbicon.png" width="15" />
  </a>
</div>

```

# Answer
> 0 votes
Add "/sandbox/" before sites like below (src="/sandbox/sites/default/files/buttons/fbicon.png")

```
<div class="beaticon" id="fbicon">
    <a href="http://www.facebook.com/thebeat999fm">
        <img alt="Facebook" height="32" src="/sandbox/sites/default/files/buttons/fbicon.png" width="15" />
    </a>
</div>

```

Or add "/" before sites as src="/sites/default/files/buttons/fbicon.png" and set your base url to http://www.thebeat99.com/sandbox

---
Tags: blocks, media
---


# Question
Title: How to prevent required field validation in validation function?
**Issue:** When create a node and node publish check box is checked, all validation should work (it's working fine). but when create a node and node publish check box is not checked , then all validation should skip.

```
function mymodule_form_alter(&$form, &$form_state) {
   array_unshift($form['#validate'], 'mymodule_reqursive_unrequired');
}

function mymodule_reqursive_unrequired(&$form, &$form_state) {
    // print_r($form);die;
    $form['actions_copy']['submit']['#limit_validation_errors'] = array();
    $form['actions']['submit']['#limit_validation_errors'] = array();

    $form['title']['#required'] = FALSE;
    $blog_images = $form['field_image_blog'][LANGUAGE_NONE];
    $form['field_page_title'][LANGUAGE_NONE][0]['#required'] = FALSE;
    foreach($blog_images as $image_k => $blog_image) {
      $form['field_image_blog'][LANGUAGE_NONE][$image_k]['#required'] = FALSE;
    }
    // print_r($form);die;
}

```

Any suggestion ?

# Answer
After a lot of debugging and search i get the solution.

```
function mymodule_reqursive_unrequired(&$form, &$form_state) {
    // print_r($form);die;
   if(!$form_state['values']['status']) {
     drupal_static('form_set_error', NULL, TRUE);
     drupal_get_messages();
   }
    // print_r($form);die;
}

```

for reference check it
> 0 votes

---
Tags: forms
---


# Question
Title: Is it possible to wrap the fields of a view inside a <nav> and </nav>?
**UPDATE:** Colin is right but I'd like to go over what I did to accomplish this. I added a views-view.tpl.php template and where it said

```
<?php print $rows; ?>

```

I wrapped it like this

```
<nav id="menu"><ul>
    <?php print $rows; ?>
</ul></nav>

```

I also wanted to prevent each row from being wrapped in a view so I also added a views-view-unformatted.tpl.php template and replaced

```
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
</div>

```

with just

```
<?php print $row; ?>

```

---

I'm trying to have a view that starts with a

```
<nav id="menu"><ul>

```

then contains all the content of my view like so

```
<li>image</li>
<li>image</li>
<li>image</li>

```

and then ends with

```
</ul></nav>

```

However I'm having a lot of trouble. Header and footer does not work because it starts and closes it in it's own div. I tried hiding all the contents and doing a global text field like so

```
<nav id="menu">
    <ul>
        <li>[image]</li>
    </ul>
</nav>

```

However that gives each item it's own nav and closes it right after each one.

Is wrapping the entire comments in the and tags possible in drupal?

# Answer
You will need to add a View template to your theme, take a look at Views template files to give you an idea of how to accomplish this
> 1 votes

---
Tags: views
---


# Question
Title: Putting sent private messages into a block
I used this tip to put private the Drupal 7 private messages into blocks, in order to put those blocks on a quicktabs block:

```
<?php
/**
 * Implements hook_block_info().
 */
function MYMODULE_block_info() {
  $blocks = array();
  $blocks['messages_list'] = array(
    'info' => t('Messages List'),
    'cache' => DRUPAL_NO_CACHE,
  );
  $blocks['messages_sent'] = array(
    'info' => t('Sent Messages'),
    'cache' => DRUPAL_NO_CACHE,
  );
  $blocks['new_message'] = array(
    'info' => t('New Private Message'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
require_once('sites/all/modules/privatemsg/privatemsg.pages.inc');
function MYMODULE_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'messages_list':
      global $user;
      $block['subject'] = t('Private Messages List');
      $block['content'] =
        drupal_get_form('privatemsg_list', 'list', $user);
      break;

    case 'messages_list':
      global $user;
      $block['subject'] = t('Private Sent Messages');
      $block['content'] =
        drupal_get_form('privatemsg_list', 'sent', $user);
      break;
    case 'new_message':
      $block['subject'] = t('New Private Message');
      $block['content'] = drupal_get_form('privatemsg_new');
      break;
  }
  return $block;
} ?>

```

It works quite well, but I have the following issues:

1. Tab 1 (Inbox): Why I can't delete messages on the message list, or change their status.
2. Tab 2 (Sent messages): How do I see the sent messages list? Is there a separate form?
3. Tab 3 (New message): After sending a new message, how to I redirect the user back to the messages list?
4. How to avoid needing to include sites/all/modules/privatemsg/privatemsg.pages.inc (If I want to put this block on a non-standard URL, not starting with '/messages', I get an error that a function in that file is not found.

Notes (EDITED):

Drupal 7 Privatemsg views integration module is stuck (you can see the latest patch here). Forms integration works, somewhat.

Alternate approachers:

* Edit it with the data module (which allows to make a view on any table) + VBO. IF they work together.
* Recreate the whole solution with Views + VBO.

Please advise

Thanks

Amnon

# Answer
> 1 votes
No need to use quicktabs. The tabs functionality is inherent if you use the privatemsg\_filter addon module - inbox, sent messages and all mail are exposed as three tabs.

It was only needed to add a 4th tab with the option to send a new private message.

The tab already existed as a page, so adding it was simple using hook\_menu\_alter().

So the final code is:

```
<?php
function MYMODULE_menu_alter(&$items) {
  // Make the privatemsg new link a tab
  $items['messages/new']['type'] = MENU_LOCAL_TASK;
}
?>

```

# Answer
> 0 votes
You could use that sandbox project enter link description here to create the block you want

---
Tags: 7, privatemsg
---


# Question
Title: Services 3 - updating a custom field in a user account
I'm using Postman in Chrome to test my services. I'm sucessfully able to create user accounts using the following:

**Headers:**

* Content-Type /application/x-www-form-urlencoded
* X-CSRF-Token 84t\_NqiZcxiK42Obcy4aIpT7oxhar4DJvf7hIvRSxJE

**x-www-form-urlencoded data**

* Name = testname1
* mail = testmail1@localhost.com
* pass = pass

This works, but to update a custom field, nothing seems to work. My field is a text field with the machine name field\_test\_text, I've tried adding the value

* field\_test\_text\[und\]\[0\]\[value\] = TEST

But this doesn't work, however the user is still created.

# Answer
> 2 votes
Switch between different content types and test, for example, application/json works perfectly for me. You need to do the following steps:

1. Request CSRF token /services/session/token (sample request below)

```

request.get({url:'https://serveraddress/services/session/token'}, function(error, response, body) {
if(!error && response.statusCode == 200) {
  console.log('CSRF Token obtained : ' + body);
} else {
  console.log('Failed to retrieve CSRF token.');
}
```
2. Make use of the obtained CSRF token to perform authentication (if needed), sample below

```

// Set the headers
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRF-Token' : token
};

// Configure the request
var options = {
  url: 'https://serveraddress/servicesendpoint/user/login.json',
  method: 'POST',
  headers: headers,
  body: 'username=yourusername&password=yourpassword'
};``

// Start the request
request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
      var jsonBody = JSON.parse(body);
      console.log('Authentication succeeded, cookie value is : ' + body);
      console.log('SESSID : ' + jsonBody.sessid);
      console.log('SESSION_NAME : ' + jsonBody.session_name);
      console.log('Token : ' + jsonBody.token);
    } else {
      console.log('Authentication failed. Error is : ' + error);
      console.log('Authentication failed. Body is  : ' + body);
      console.log('Authentication failed. Response is : ' + JSON.stringify(response));
    }
});

```
3. Now that you have SESSION NAME & SESSION ID, you can proceed with updating a node. See sample below.

```

//set headers
  var headers = {
              'X-CSRF-Token' : authResult.token,
              'Content-Type': 'application/json',
              'Cookie' : authResult.session_name + '=' + authResult.sessid
            };

  // Configure the request
              var options = {
                  url: 'https://serveraddress/serviceendpoint/node/' + user.result.nid,
                  method: 'PUT',
                  headers: headers,
                  json: data
              };

  request(options, function (error, response, body) {
            if(!error) {
                console.log('Drupal node is updated successfully!');
                console.log(body);
            } else {
              console.log('Updating Drupal node failed! Error status : ' + response.statusCode);
              console.log('Updating Drupal node failed! Error body : ' + JSON.stringify(body));
            }
          });

```

If you notice above, I am console logging all the errors that is returned from the Services, so that I have something to Google and figure out.

For those who wish to know how to upload a file and associate them to a node. Assuming that Service Endpoint is configured to accept file uploads. You will need a sample request as below:

```

     //data
     var data = {
       "uid":"1",
       "filesize":fileSizeInBytes,
       "filename":user.firstName + '_' + user.lastName,
       "file": base64Image
     };

 var options = {
       url: 'https://serveraddress/servicesendpoint/file',
       method: 'POST',
       headers: headers,
       json: data
     };
request(options, function(error, response, body) {
       if(!error) {
         //photo is uploaded, returning fid
         console.log('Publishing Image to Drpual succeeded. FID is : ' + body.fid);
       } else {
         console.log('Publishing Image to Drpual failed. Response is : ' + JSON.stringify(response));
         console.log('Publishing Image to Drpual failed. Body is : ' + JSON.stringify(body));
       }
     });

```

Attach the returned FID to the request that is supposed to update the node.

Sample JSON to update a field of a content type would look like this:

```

data = {
      "body": {
          "und": [
              {
                  "value": user.profile,
                  "format": "full_html"
              }
          ]
      },
      "field_member_position": {
          "und": [
              {
                  "value": user.title
              }
          ]
      },
      "field_member_photo" : {
        "und" : [
          {
            "fid" : fid
          }
        ]
      }
    };
  }

```

Hope above help those struggling with using Services 3. The code is written in Express JS 4 and I have used the request NPM module.

A simple checklist for Services 3 would be:

1. Configure the module (request content type, as well as allow CRUD on nodes/files as per your need)
2. Make sure you are hitting the correct URL to get token, authenticate and update node, upload file
3. Watch for famous errors such as Not Acceptable Content type, Trying to Authenticate as anonymous user, A particular field is required (username/password), others

4. When trying to update a custom field, it is more useful to SEE that particular node's structure via DEVEL and then accordingly structure your JSON data.

---
Tags: users, services, files
---


title: Questions and answers module Drupal 6

text:
# Question
Title: Questions and answers module Drupal 6
Are there any modules for questions and answers website in Drupal 6? I want it to have theme.

# Answer
The Answers module should do the trick:

> Answers provides a question & answer service. Users can post questions and other users can answer them.
>
> ...
>
> The displays are based on standard CCK node displays and Views, so can be themed in the typical ways.
> 1 votes

# Answer
Some suggestions that might possibly help:

* There's a Drupal **distribution** for it ... (not just a 'module'), i.e ArrayShift. Quote from its project page:

> A question/answer site built to emulate the core functionality of the StackOverflow.com site and the StackExchange platform.
* There is a Drupal **theme** for it, i.e the ArrayShift Theme. Here is a screenshot (from its project pages):

**Note**: Refer to my answer in https://drupal.stackexchange.com/questions/11566/module-for-creating-a-site-similar-to-stack-exchange-sites/154288#154288 for more details about a roadmap for future releases of this ArrayShift.

Disclosure: I'm the (new) maintainer of this distribution,
I hope this does not violate the site's policy on self-promotion.
> 0 votes

---
Tags: 6
---


# Question
Title: Uploading Image to s3 turns to horizontal always
I am using s3fs module to put images on s3bucket using image field in any content type.

When I take a verticle picture, upload it to the s3bucket, it turns to horizontal. On local file system, it works fine, but not on s3. Any idea what could be the reason?

# Answer
> 2 votes
Without knowing the origin of your images nor the s3f module I'm rather guessing your problem consists of the two following parts:

* the EXIF data of your images probably contains information that says 'this image should be displayed horizontally
* the s3fs module or actually drupal's image module respects the information about the image orientation – but that's different from your expectation (could also be that the problem is that the info about the orientation is ***not*** respected)

According to this I would suggest you try either (or both) of the following:

* try to strip the EXIF data in case you don't need it, for example by saving "websafe" from Photoshop or the like
* Try to 'teach' drupal the correct exif orientation – for example by using the EXIF Orientation module.

# Answer
> 0 votes
A possible cause for this is mishandling/misreading of the exif data within an image. http://en.wikipedia.org/wiki/Exchangeable\_image\_file\_format

---
Tags: media
---


# Question
Title: is it possible to declare an user group for the remote user in aliases.drushrc.php
I have a different user group for apache on my remote server clould i specify a group for drush sync like remote-user user adds the user or in some similar way ?

# Answer
No; in unix, the group ownership is attached to the user. Use `usermod -a -G` to add the desired group permanently to your remote user. See man usermod for more information.
> 1 votes

---
Tags: drush
---


# Question
Title: Execute drush command against against multiple groups
We have a large set of Drupal instances, and we use Drush alias groups to group them logically. For example, we have a group "dev" for all sites "in development", and, for example, another called "7\_36" for all on Drupal core 7.36.

I can currently run commands against all sites in a single group (`drush @dev status`), but is it possible to run a command against all sites which are in both groups? For example, I'd like to run a command against all sites found both in @dev and in @7\_36.

Is this possible?

# Answer
> 5 votes
You can create a new alias group that is the combination of the two (by hand):

```
$aliases['newCombinedGroup'] = array(
  'site-list' => array(
    // Dev group 1 sites
    'site1',
    'site2',
    'site3',
    // 7_36 group 2 sites
    'site6',
    'site7',
    'site8',
  ),
);

```

This is discussed in this other thread: How to use Drush's concurrent execution capability?

Another option as pointed out by the maintainer of Drush here: https://drupal.stackexchange.com/a/134472/3279

is to *compose* your alias group site names for example from a PHP array of site names, then build your alias entries programmatically by looping through these site names and filling out the contents of the drush alias itself.

So something like:

```
// This is untested example code.
$sites_in_dev = array('site-dev-1', 'site-dev-2');
$sites_in_736 = array('site-1', 'site-2');

$aliases['newCombinedGroup'] = array(
  'site-list' => $sites_in_dev + $sites_in_736;
);
$aliases['@dev'] = array('site-list' => $sites_in_dev);
$aliases['@7_36'] = array('site-list' => $sites_in_736);

foreach ($sites_in_dev as $sitename) {
  if ($sitename == 'site-dev-1') {
    $aliases['Dev1'] = array( /* ... */ );
  }
  if ($sitename == 'site-dev-1') {
    $aliases['Dev2'] = array( /* ... */ );
  }
}

foreach ($sites_in_736 as $site) {
  // ... etc ...
}

```

.... You get the idea. Also I would refrain from using `@7_36` as an alias name. In general PHP variables shouldn't start with numbers -- and while an alias isn't a php variable persay you're playing with fire by giving it a name that would be an invalid php variable name; when evaluated now and in future versions of Drush ... who knows how that will behave.

---
Tags: drush
---


# Question
Title: I'm looking for a Drupal Commerce Shipping in-cart estimate
I am working on a Drupal Commerce site, we are trying to add a feature in the cart that would allow the user to input their zip/postal code or country and receive an estimate on shipping, before proceeding through the checkout. I'm new to Drupal Commerce, so maybe this functionality already exists?

a shove in the right direction would be greatly appreciated. Thanks.

# Answer
link- https://drupal.org/project/commerce\_shipping Commerce Shipping provides a shipping rate calculation system for Drupal Commerce , integrating shipping service selection into both the checkout form and order edit form. This module is a framework that is meant to be used in conjunction with shipping method modules like Commerce Flat Rate , Commerce UPS , and others. Shipping service availability and rate calculation is handled in the user interface through Rules and is backed up by an API that gives you a high level of flexibility to implement simple or complex shipping scenarios.
> 1 votes

# Answer
yes - use commerce\_shipping

add in the `Shopping cart form (Commerce Order)` view, and `Shopping cart block (Commerce Order)` view - if used, the *Commerce Order: Order total* to the footer, as the line item summary does not display the shipping line item .., rearrange the order, like this:

and hide the total in the *Commerce Line Item: Line item summary* (makes only sense in block view ;), in the cart view just remove the line item summary), like this:

then - create a shipping rule and add the following event:

* After adding a product to the cart
* After removing a product from the cart
* After updating an existing commerce line item

(the default event is needed when the user changes it on the shipping step, or where you configured the shipping service in the checkout settings - if you remove the default event the rule will no longer show up in the shipping calculations rules, but only on the general rules UI)

setup your condition, fe:

* Total product quantity comparison

and choose the action:

* Apply shipping rate to an order

now, if desired, you can gracefully disable the shipping service in the checkout settings.

**and don't forget to make a rule for every case, even the 'inital' one.**
> 0 votes

---
Tags: commerce
---


# Question
Title: sites/subDomain/libraries doesn't load the library files
My website has two sub-domains, I need to install `imageFlow` library in both of these sub-domains but for some reasons I need to replace default images of `imageFlow` (I mean `slider.png`, `button_play.png` and `button_pause.png`) library in `sub-domian1` with some images and in `sub-dmoin2` some other pictures. To do so I created folders `sub-domain1/libraries` and `sub-domain2/libraries` and I copied the modified version of the `imageFlow` in there. But unfortunately it doesn't work and `imageFlow` is not loaded. If copy the `imageFlow` library in `sites/all` it works well but in this way the same version will loaded for all sites.

# Answer
I think you would want to keep the imageFlow library itself in the sites/all/libraries folder, then to adjust the images for each site, modify your *theme* to override the default css and images of the imageFlow library. You could do this by copying the imageflow.css stylesheet into your theme, including it, then modifying it to point to custom images instead of the imageflow default images.

This would be a little bit more standard approach than changing the imageFlow source files.
> 1 votes

---
Tags: 7, subsites, theming
---


# Question
Title: How to avoid Exif data rotating images automatically during approval selection?
I've been doing some digging, but so far with no results. I'm currently looking for a way of forcing or letting the admin to dictate the orientation of an image. I came across an issue where some user uploaded content looked correct upon initial upload, but when the admin began the approval process, the files hidden orientation data changed it from a vertical to a horizontal orientation. Now mind you I know that I could simply re-save that file, pull down the submitted post data and re-upload with the correct image, but I'm trying to be as efficient as possible in the event someone outside myself is administrating the content one day.

Has anyone come across a module that could help force orientation away from EXIF content or other data?

Thanks in advance!

# Answer
Once you've set up ImageMagick you can start using it in a file hook to process your images on upload.

Some good hooks to look at would be:

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_file\_presave/7

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_file\_insert/7

Watch for an image being uploaded, read exif data with imagemagick, adjust accordingly.
> 0 votes

# Answer
We had this issue and put up a module that fixes orientation based on EXIF data. Link to project https://www.drupal.org/project/exif\_orientation

No need for ImageMagick.
> 0 votes

---
Tags: webforms, media
---