title: Page with Arguments

text:
# Question
Title: Page with Arguments
I have a basic page named as news.

Now i have created a two blocks from view in page news

**Block 1 is block of taxonomy**

**Block 2 is having Contextual Filter with term id**

I have assigned these block to news page as

**news**

**news/\***

Now when i am accessing

example.com/news only Block 1 is coming which is fine

when i am accessing

example.com/news/1

Block1 is coming and an error

**Requested page could not found**

I want block 2

How to do this

Please

Thanks

# Answer
> 0 votes
Block views don't automatically pull in contextual filter values from the URL.

So to make it work you need to configure the "When the filter value is NOT available" setting to be "Provide default value".

Then you get some more options appearing below, where in the "Type" field you can select "Taxonomy term ID from URL".

Then configure the other settings as required.

**\[EDIT\]**
Note that term ID from URL only works from either a node page (node/NID) or a taxonomy term page (taxonomy/term/TID) or an aliased path for one of the pages.

If you want o do it with some other random page use the "Raw value from URL" option for the "When the filter value is NOT available" setting, then select the position in the URL that your parameter is (in your case 2).

---
Tags: views, 7, theming, uri
---


# Question
Title: How to theme a link in a D7 render array?
I'm trying this:

> ```
>         $content[] = array(
>           '#theme' => 'link',
>           '#text' => $row->title,
>           '#path' => $base_path . 'node/' . $row->nid,
>           '#attributes' => array('attributes' => array('title' => $row->title)),
>           '#prefix' => '<h3>',
>           '#suffix' => '</h3>',
>         );
>
> ```

but Drupal is complaining that "Arg 1 passed to drupal\_attributes() must be an array, null given" My array looks fine? ...or does it xD

Here is the API doc I'm looking at

# Answer
The `theme_link()` function behaves a bit like the `l()` function; the attributes array needs to be inside an `#options` property:

```
$link = array(
  '#theme' => 'link',
  '#text' => $row->title,
  '#path' => $base_path . 'node/' . $row->nid,
  '#options' => array('attributes' => array('title' => $row->title)),
  '#prefix' => '<h3>',
  '#suffix' => '</h3>'
);

echo render($link);

```
> 8 votes

# Answer
Wanted to edit Clive post, but got rejected :(

---

As Andy pointed out, it's not recommended to use theme\_link instead of l(). Using `drupal_pre_render_link()` is cleaner for renderable array.

```
 $link = array(
  '#type'  => 'link',
  '#title' => $row->title,
  '#href'  => 'node/' . $row->nid,
);

```

You can also go for the "easy-quick-fix" solution with #markup (But don't)

```
$link = array(
  '#markup' => l($row->title, 'node/' . $row->nid),
);

```
> 4 votes

# Answer
I think your code should read

```
'#attributes' => array('title' => $row->title),

```

The wording of the doc in common.inc seems a little unclear, but see the doc for drupal\_attributes() for an example.
> 1 votes

---
Tags: theming
---


# Question
Title: How to filter by two fields using a single exposed filter in Views?
I have a view listing nodes. I added 2 exposed filters. One is **Content: title** and the other is **Content:Body**. Then I have 2 input fields to enter some keyword to do searchs.

I need to have **just one** field and do the search in both fields: title and body. Can I do this?

# Answer
> 16 votes
I think you could either:

* Use the *Global: Combine fields filter* which allows you to choose two fields (out of those already added to the display as a normal field) to filter on. The filter can be exposed, its operator changed, etc. like normal. Views warns *This filter doesn't work for very special field handlers.*
* Use the *Search: Search Terms* filter. This uses search.module's data to do the query (check out the *search index* build mode).

# Answer
> 1 votes
Yes, use the search terms that works.

It search both title and the body and display the result.

---
Tags: views
---


title: Conditional image style in Views

text:
# Question
Title: Conditional image style in Views
How can I apply different image style to an image field in Views, based on the condition of some other field of the same content type? I need to print the image with some frame, if some field (checkbox) is true, and with other style if the field is false. Any ideas?

Thanks

# Answer
Add the image field twice(!) to the fields list. Use the frame style on the first image and the no-frame style on the second. Exclude both fields from display and place them before the checkbox.

Next, rewrite the output of the checkbox field to use \[field\_image\] if the checkbox is checked (normal rewrite) and \[field\_image\_1\] if it is not (no result behaviour, Treat 0 as empty).
> 4 votes

---
Tags: views, media
---


# Question
Title: Where can I save a CSV file that I construct dynamically to make it available for download?
I dynamically construct a CSV file following that method:

```
$fp = fopen('export.csv', 'w');
foreach ($export as $fields) {
  fputcsv($fp, $fields);
}
fclose($fp);

```

A file 'export.csv' appears in the very root of my Drupal directory.

I display a link to a page, allowing user to download that CSV file:

```
drupal_set_message(l('Export to CSV', 'export-csv'));

```

In the page callback function, I make the file downloadable like this:

```
function grap_contact_export_csv_page() {
  header("Cache-Control: public");
  header("Content-Type: application/octet-stream");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=\"grape-export.csv\";" );
  header("Content-Transfer-Encoding: binary");
  $fp = fopen('export.csv', 'r') or die('Cannot access the file');
  echo fread($fp, filesize('export.csv'));
  fclose($fp);
  drupal_exit();
}

```

That works well.

What disturbs me is the location of the file. Of course, I know that I should not save it there. My question is: Where is the optimal location to save that kind of files? In the custom module's directory? In `sites/default/files`? **What is the best practice?**

# Answer
> 3 votes
The best practice is to use Drupal functions, not direct PHP functions, if there is Drupal API available. Particularly, here you may be interested in `file_save_data` and `file_unmanaged_save_data`.

If you want file available for short time, unmanaged file may be the way to go. But if you want periodic exports, archiving of prepared files, automatic clean-up etc, Managed is the way to go. If in doubt, try managed.

Examples for Developers offers a pretty good file\_example.module, read it, play with it, and come back with more specific question.

# Answer
> 1 votes
You don't need to save the file.

```
drupal_add_http_header('Content-Type', 'text/csv; utf-8');
drupal_add_http_header('Content-Disposition', 'attachment; filename = file_name.csv');

// print directly to stdout
$fp = fopen('php://output', 'w');
foreach ($export as $fields) {
  fputcsv($fp, $fields);
}
fclose($fp);

drupal_exit();

```

---
Tags: 7, importing-exporting, files
---


title: can't remove js from page

text:
# Question
Title: can't remove js from page
I've looked at this post https://stackoverflow.com/questions/9578013/how-to-unset-a-js-file-from-a-drupal6-installation-doesn%C2%B4t-work-with-remove-sc and this one How can I remove Javascript files?

and I've tried to duplicated it, but it wont work. I am trying to unset the regular jquery version. I've added this inside my phptemplate\_preprocess\_page function:

```
$js = drupal_add_js();
  unset($js['core']['misc/jquery.js']);
  $vars['scripts'] = $js;

```

when I print out $vars, it looks like it worked, but the original jquery is still included!

# Answer
> 0 votes
I finally found out what my issue was. I was #4 from coreyp\_1's answer above: in the process of finding a solution, I had tried installing the jquery multi module, which didn't do the trick. This module was overrideing my work. When I disabled it, my code now worked.

# Answer
> 0 votes
I can think of 4 things to check in this case, in order of likelihood:

1. What does the preprocess function stub look like? Are you using the variable `&$vars` there, too, or are you using `&$variables` instead (which is how it appears in the documentation)? They, of course, have to match.
2. Have you cleared your cache? D6 was bad about sometimes needing the cache to be cleared twice.
3. Is the function actually running? If not, then there may be a problem with the function name that it is not being recognized, or that the cache has not been cleared (which should be taken care of by checking #2).
4. Is something messing with the variable afterwards that is inadvertently re-adding the core js file?

---
Tags: 6, javascript
---


title: Users logouts from time to time

text:
# Question
Title: Users logouts from time to time
I only want users to logout if they visit the "logout" page. For this I set this in my settings file:

```
ini_set('session.gc_maxlifetime', 0);
ini_set('session.cookie_lifetime', 0);

```

But users are still disconnecting from site from time to time and I don't know why. Is there a better way to tell site to not log out users? What is causing users to be disconnected?

**EDIT:** I have users that launch site from browser and that launch site through mobile application by rest service(services module). Both types of users are disconnects. I not sure but sometimes when I save some views user is logging out and I recieve message that you have no access.

**UPDATE:** this part of code `ini_set('session.gc_maxlifetime', 0);` logs out user. I thought that if it set to 0 it means that user has never been loging out until he not push on logout.

# Answer
**Is there a better way to control user's login sessions?** *Yes.*

There's a great module (beta since 2012, 1,000+ active sites used it as of October 1, 2014): https://www.drupal.org/project/persistent\_login

From the module page:

> The Persistent Login module provides the familiar "Remember Me" option in the user login form. Additional security is provided by using two tokens (one long-running, one per access) that allow the detection of unauthorized token use.
>
> Persistent Login is independent of the PHP session settings and is more secure (and user-friendly) than simply setting a long PHP session lifetime. For a detailed discussion of the design and security of Persistent Login, see Improved Persistent Login Cookie Best Practice.

**What is causing the users to be disconnected?** *Depends.*

As Mołot pointed out, there are literally dozens of things that could be happening. For example, we could be talking about multiple browsers, multiple devices, or someone who regularly clears out their cookies and internet history. Most of these situations are out of your control. The standard Drupal session cookie usually keeps me logged in over the course of a day or two without having to re-login. If someone is getting logged off in the same 24 hours span, something is happening.
> 0 votes

---
Tags: sessions, users
---


# Question
Title: Exposed Filters Search : remove parameters from URL
i need to create something like a landing page search block (using views exposed filters) that links to a new search page. I have problems with my current set up and I am trying to avoid any code tweaks.

My current exposed block sends the results to a result page. However, the parameters are passed in the URL. instead of seeing mysite.com/results one sees mysite.com/results?taxonomy\_vocabulary\_3\_tid=blue. How can configure so that the user only sees the main url.

Also, My search box is not showing up on the results page. Is there a way to configure so that the results page allows you to submit another search. I would think that would be a pretty standard set up.

Thanks!

# Answer
> 1 votes
Looks like there is a module that changes the views arguments from a GET to a POST.

Views ExPost

# Answer
> 0 votes
> How can configure so that the user only sees the main url?

First of all, I'm not sure this is advisable. GET parameters are designed to reflect the page content and users expect that if they bookmark this page, they will get those results. If you don't like the ugly "taxonomy\_vocabulary\_3\_tid" then you can change the machine name in the exposed form settings to something closer to reality, perhaps "?color=blue" ?

Note, if you really wanted your url to magically not have parameters, you *might* be able to tweak the variables the form sends as a POST variables and write a custom module that circumvents these and passes them on from Views. But this is not recommended.

> Is there a way to configure so that the results page allows you to submit another search.

Sure there is. I just checked and found that this is default function of "input required" contextual filters.

---

---

And this is a result of the following settings:

---
Tags: views
---


# Question
Title: Link to create new node with taxonomy term from url already selected?
I need to make a link to create a new node. I need this link to appear on taxonomy term pages so I was going to put it in a block. Nodes can be tagged with taxonomy terms.

How can I make it so the create node form has the term (from the page the link was on) already selected? So if you were on mysite.com/term/1 and and clicked the create node link, the node would have term 1 already selected.

Ive found this module but its in dev for D7 so there another way? http://drupal.org/project/prepopulate

Thanks

# Answer
> -1 votes
I think the Prepopulate module is in fact safe. It has a large number of sites using it and was mentioned in a mustardseed media screencast. http://drupal.org/project/prepopulate

# Answer
> 0 votes
Yes, you need to download and enable the Prepopulate module.

The syntax you use to prepopulate taxonomy terms with D7 is (AFAIK) not documented anywhere and the syntax it is also radically different from the syntax used in D6 that is demoed in a number of screencasts of the Preopulate module. In D7 taxonomy terms are fields. If you read the source code, you'll find that you prepopulate taxonomy terms as would prepopulate other field.

I.e. if your taxonomy term field is `field_tags` and you want to prepopulate with the term "myterm", you use the following syntax (with clean URLs):
`/node/add/article?edit[field_tags][und]=myterm`.

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


title: related products in blog post

text:
# Question
Title: related products in blog post
I'm building my first drupal commerce with commerce-kickstart 2 on drupal7. My client asked my to add a feature that associate products and blog posts.

At first I thought the best way was to add "product-reference" to the blog-post content type, this way the non-technical user could easily select 0 to n products to the post as "suggested" or "correlated" products, but when I added the product-reference field the whole blog-post content-type became a "product display" and the template file for the view was the wrong one.

Then I though of creating a block with a query for the products but I don't want the client to have to deal with this level of complexity.

I thought about writing the logic inside the product display template file but it doesn't feel like a good practice.

I searched for modules but I didn't find what I was looking for (maybe because I'm noobie to drupal I don't know yet how the search efficiently)

Are there any modules that can help with this?

thx

# Answer
> 2 votes
So this is an important question for Drupal Commerce: *What is the best practice way of creating a related products block per content type?*

Fortunately, there's a simple answer. Just add an entity reference field that references the product displays:

1. Add an entity reference field called "Related Products" on your blog content type.
2. Configure this field to only show the product displays (not product entities).
3. Hide this field on the "Manage Display" tab.
4. Create a view block that targets your blog content type.

1. Edit the view and add a contextual filter for "Node ID" and provide the default value to come from the URL. This will allow the block to bring in the node you are viewing if you are viewing your blog post.
2. Add a relationship on the "Related Products" field you added to your blog content type and rename it "Related Products" and require that relationship.
3. Add a field, it should be your product reference field for your product display. For me, it's called "Product" but it could be called something different depending on your setup. **NOTE** Make sure you set it up to use your new relationship.
4. Modify the title to use your new relationship.
5. Set the View Block to display in a sidebar or some region that is available on blog posts.

And BAM! there you have it! A step-by-step to show off related projects in a block on your blog posts.

---
Tags: 7, commerce
---


# Question
Title: how do you restrict directory path to role?
How would you go about restricting a specific directory path to a role?

www.example.com/example1/example3/example4

How do you restrict role access to the directory example1 so that example3 and 4 are restricted automatically?

Thanks!

# Answer
> 1 votes
A google search did the job:

https://www.drupal.org/project/path\_access

The module will enable you to restrict access to certain paths per role. Each role has a page of either ACCESS ONLY or CANNOT ACCESS paths. Easy to set bunch permissions if you play with many roles at once.

# Answer
> 2 votes
This depends on what that path is? Drupal has many kinds of paths and default permissions out of the box. If this was a Book hierarchy default permissions exist for books. The same for Taxonomy terms and other types of content. If this was a Views based path, you could configure Access rules in your view.

Without any 3rd party module support I would look at hook\_menu if you are defining these paths yourself or hook\_menu\_alter if they are provided by another module.

Drupal Roles are not a reliable way to deem access to content -- I would alter the `access callback` for this path to use `user_access` permission values and create a custom permission such as `view my custom site area` and give that permission to desired roles. Then I would an `access arguments` of `view my custom site area` so the `user_access` check works on those paths.

The Workbench Access module can do what you're asking if you define the Access rules using the `Menu Scheme` and not Taxonomies, but this module only works for `Nodes` last I checked.

> Workbench Access provide the hierarchical permissions across "Sections" of your web site. You can use menus, taxonomy, or create your own hierarchical structure for controlling access to a piece of content.

---
Tags: users, uri, files
---


title: how to export and import nodes in bulk?

text:
# Question
Title: how to export and import nodes in bulk?
is there any way to export and import nodes programmatically...? While import if the node already exists then it should be updated without creating a new node.

# Answer
> 0 votes
Try the Node Export module

> This module allows users to export nodes and then import it into another Drupal installation, or on the same site.
>
> Using this module you can save yourself a lot of time setting up new websites that have similar nodes to websites you've already made, migrating nodes to new Drupal versions, or between development/staging/production sites.
>
> You will need the same content types for the imports to work (unless using Feeds to import), and ideally relevant compatibility with fields, and modules

# Answer
> 0 votes
You'll most likely want to use

I haven't used either myself, so I can't be of much more help. But I believe they can both be used to import data, and update nodes if they already exist.

---
Tags: nodes
---


# Question
Title: Slideshow showing 3 slides (prev - active - next)
I am trying to accomplish the following:

I have a content type that contains title, img and body.

i want to show the nodes in a slideshow, like for example flexslider.

Nothing special so far.

i now want to show 3 slides at once, the 3 slides cover 100% width, where the 1st slide is the previous slide, the middle one is the active slide and the 3rd one is the next slide. (The 1st and 3rd slide have some opacity on them to mark the active slide)

i have tried to do this with flexslider, jcarousel and jquery cycle but without aky success.

I managed to show 3 slides at once, but then i cannot navigate through the slides.

Any suggestions on how you guys would approach this would be very welcome!

Thanks in advance!

Edit:

After some more research i created 3 flexsliders (each in their own content pane) that i put into one page manager page. I then floated them next to each other.

I configred each flex slider to skip 0,1 and 2 slides accordingly.

I now still have the remaining issue of controlling the 3 slideshows through one next and previous buttons.

Any suggestions for this would be very welcome!

# Answer
Edit2:

I found the solution by studying the flexslider module. You can manipulate sliders by #ID with the following commands:

```
(function ($) {
$(document).ready(function(){
$(".page-about-livio #flexslider-2 .flex-next").click(function() {
    $('#flexslider-1').flexslider("next");  //Go to next slide
    $('#flexslider-3').flexslider("next");
});
$(".page-about-livio #flexslider-2 .flex-prev").click(function() {
    $('#flexslider-1').flexslider("prev");  //Go to next slide
    $('#flexslider-3').flexslider("prev");
});
});
})(jQuery);

```
> 0 votes

---
Tags: javascript, views
---


# Question
Title: Responsive Grid View appearing in single column
I'm trying to create a responsive views grid. I installed the the Views Responsive Grid module. The problem is when I select that option the images appear in a single column instead of appearing in the specified columns. How do I fix this?

# Answer
You need to apply some css rules to the output. Basically, assuming each div of the grid has a `views-content` class, give that class a `float:left` and some margin. Or if you use a responsive theme already, set the correct classes to the output in Views UI...

As per the Views Responsive Grid:

> In order for the columns to work you'll need to specify the class name of your columns. For example, if your theme utilizes a grid, like Twitter Bootstrap does, you would specify "span3" as the column class(making sure to use the correct span size). This will make sure your column adhere to the grid in your Bootstrap based theme.
> 4 votes

---
Tags: views, theming
---


# Question
Title: Reverting/updating "FILE_DISPLAY" in Features
My site is running Drupal v7.30 and Features v7.x-2.2. I can't revert or update `file_display` components in features. There are additional definitions under the Default column that appear to be define by the Media (7.x-2.0-alpha3) module in `hook_file_default_displays_alter()`. How do I go about properly keeping my features not in a perpetual `Overridden` state?

# Answer
There is a bug with media and the media modules.

There is some patches already that you could try

https://www.drupal.org/node/2104193
> 0 votes

---
Tags: 7, features, media
---


# Question
Title: Strange Issue with displaying information of the current term
I have built a series of views to build a Drupal Commerce display for products based on the Taxonomy terms of those products. These terms have a hierarchy. There are nearly 40,000 products being imported through Commerce Feeds, the taxonomy terms are attached to the products during the import.

Currently I have a series of 3 views working together to achieve what I want and am attempting to build a fourth view that I am having a strange problem with. View http://cde.gttechlife.com/products for reference.

View 1(Product Taxonomy Children) pulls in all Taxonomy terms based on the Parent Term context in the URL. (Term Alias is the name displayed, Product Code for Image pulls in an image based on product code) It pulls that in through Term Name converted to ID and turns term name spaces into dashes. See Below:

View 2((Top Level Products) Pulls in all Taxonomy Terms that do not have Parents and displays them. View 2 is attached to view 1 if View 1 has no results based on the Contextual URL, this is the only time view 2 is displayed. So no contextual filter on the URL it displays all terms with no parents.

If View 2 DOES have a contextual URl, there it displays a no results attachment View 3. View 3 pulls in all products with that Term Name in the URL.

All of these views work exactly as needed. But I want to add another view. I want View 4 to also be pulled into view 2 with view 3. View 4 (Taxonomy Description). View 4 pulls in the Taxonomy Term Description and the custom field Category Alias, and Product image of the current term in the URL. Oddly enough this ONLY works for contexts with no dashes. Just like the other Views I made sure to check "Transform dashes in URL to spaces in term name filter values" but for some odd reason it still only works for one word terms. For example (cde.gttechlife.com/products/vibratite) works fine but (cde.gttechlife.com/products/Gasket-Flange-Sealant) does not. It seems like such a simple problem to have but I have hit a wall looking for the solution. Any help would be appreciated.

Also trying to figure out the best way to get the Breadcrumbs to reflect the parent terms and even ideally in the url, but I still have some effort to put in on that end. Have been using the Crumbs module thinking I will be able to do what I need if I put in the time. But the problem stated above has me stumped because I can't think of why it wouldn't work correctly.

# Answer
> 0 votes
If the contextual id is working on the 3rd view, then you should set the validation criteria to convert the term to an id:

That *might* fix the "inherit filters" of your views footer.

**EDIT:** An answer to your second question about reflecting your architecture in the url structure and breadcrumbs.

I have made two videos where I've concocted two different ways to make a Drupal Commerce Catalog using hierarchical taxonomy (either with one vocabulary or multiple vocabularies). Both of these ways of using Views and Taxonomy creates urls that reflect where you are. I'd bet with a little creativity you could make views create a breadcrumb as well.

1. Hierarchical Views Catalog using Taxonomy
2. Multi-vocabulary Hierarchy Views Catalog

Hope that helps!

---
Tags: commerce, taxonomy-terms, views
---


# Question
Title: How do I hide the page title in Drupal 7?
I'm a site administrator for my university and I'm using Drupal through their servers, but I can't figure out how to hide the page title from the screen. I can't install modules because I'm not on their lab computer (using my personal laptop and I don't have the permission to) and I don't see anything that I can uncheck that says "Automatically update Menu Title". Is there a way to work around this? Or does this mean I have to use my school's lab computers?

# Answer
You can update the template for the Content type or that specific node.

I tend to use CSS to hide the page element if it is only one page title/node I am trying to hide.
> 1 votes

# Answer
If you can't install modules, can't access templates and can't access css, and that functionality is not already built into the site - then it is not possible to do this by just using the admin GUI.

This is a trivial task if you've access to templates and/or css. But to do it using the admin GUI, you need to first write and install a small module that adds a checkbox to do this to the admin GUI.
> 1 votes

---
Tags: 7
---


# Question
Title: How to add custom views display formats to a view?
I have a project in which some views have different displays. I want to create similar displays for other views, see in the image. Can I reuse them or I will have to do custom coding again for each view?

# Answer
further to what @Danny Englander says, you can find the export option for a view to the right of the display list:
> 1 votes

---
Tags: views
---


# Question
Title: Update pagination after hook_apachesolr_process_results()
Apache Solr Search Version: 6.x-2.x-dev

I am using hook\_apachesolr\_process\_results() to modify results of search. This returns fewer results than are indicated by displayed filters. Pagination is also configured for original search results, not those modified by hook.

My question is: Is there a way to modify the pagination due to modified results totals without deleting the excluded nodes from the index?

For example, if I execute search A, my pagination is set for a total of 100 results on 10 pages listing 10 results per page.

When the results of this search are modified by hook\_apachesolr\_process\_results(), I now actually have only 15 results. But, my pagination is still set for 100 results.

I want to know how to reset the pagination for a total 15 results.

Thanks for any assistance anyone can provide.

# Answer
> 0 votes
Instead of using hook\_apachesolr\_process\_results() I figured it was better to use hook\_apachesolr\_update\_index instead.

Following the guidance here: http://www.phase2technology.com/blog/filtering-apache-solr-search-results-based-on-dynamic-fields/

I am now able to create a filter using hook\_apachesolr\_modify\_query that will return the correct results and pagination.

---
Tags: search
---


title: site contact form not working

text:
# Question
Title: site contact form not working
My hosted site's contact form is not working. I have checked all the obvious things like:

* correct site email address.
* permissions
* spam box

It is working on the local development machine. I contacted the hosting company various times with no luck.

I have also dropped a PHP mail script into the root and calling it directly works. So PHP's mail function works, just not my contact form.

So my question now is, what alternatives can I explore, bar getting the co-operation of the hosting company, to fix this.

# Answer
Since your question is about what alternatives you could use, have you tried the PHPMailer library? Here it is: https://github.com/PHPMailer/PHPMailer

Another alternative could be the Mandrill API. You could add a custom submission handler to your contact form, and in that, make your API call to Mandrill.

Just for sake of completeness, here's how I would approach it (using the Mandrill PHP wrapper):

```
//mymodule.module

require DRUPAL_ROOT . "/Mandrill.php";

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

  if($form_id == "my_contact_form"){
    $form['#submit'][] = "mymodule_api_submit";
  }
}

function mymodule_api_submit(&$form, &$form_state){
  $mandrill = new Mandrill("PUT_AN_API_KEY_HERE");
  $message = array(
  'subject' => 'Test message',
  'from_email' => 'you@yourdomain.com',
  'text' => 'Message!',
  'to' => array(array('email' => 'email@domain', 'name' => 'TheirName')),);

  $mandrill->messages->send( $message );
}

```

I hope this helps.
> 1 votes

---
Tags: emails
---


title: Problems with file type field of node

text:
# Question
Title: Problems with file type field of node
I have created some custom page on frontend for particular type of node modyfications. Here's my page callback:

```
function vintranet_talk_edit_entry_page_callback($sNid) {
    module_load_include('inc', 'node', 'node.pages');

    $oNode = node_load($sNid);

    return drupal_get_form('page_node_form', $oNode);
}

```

My node has one field with file attachments.

Config:

```
'vintranet_talk_attachments' => array(
    'field_name'     => 'vintranet_talk_attachments',
    'label'          => t('Attachments'),
    'type'           => 'file',
    'cardinality'    => -1,
),

```

Instance:

```
'vintranet_talk_attachments' => array(
    'field_name'     => 'vintranet_talk_attachments',
    'label'          => t('Attachments'),
    'entity_type'    => 'node',
    'bundle'         => 'intranet_talk_page',
    'widget'         => array(
        'type' => 'file_mfw',
    ),
    'settings'       => array(
        'max_filesize'       => 10,
        'file_directory'     => 'intranet/talk',
        'file_extensions'    => 'jpg, png, gif, pdf, zip, doc, rtf, xdoc, rar',
        'description_field'  => 1,
    ),
    'display'        => array(
        'default' => array(
            'type' => 'file_table',
        ),
    ),
),

```

My first problem is, when I want to upload JPG file after module installation, system sends me this message:

So ok... I'm going to check that particular field settings in Structure and I see this:

Why the hell it is saved like this?!

Okaaaaay.... so I'm changing this form field value on `jpg, png, gif, pdf, zip, doc, rtf, xdoc, rar`, saving and trying to upload the image one more time...

....clickin "Upload" button.... aaaaandd....

....yup.... that's my 2nd problem :/. Have no idea why it's not working. On the backend, in other hand, the "Upload" button works perfectly. Am I missing something?

(working on Drupal 7.31 version)

# Answer
Answer for my problems:

```
function hook_menu_alter(&$aItems) {
    $sNodePath = drupal_get_path('module', 'node');

    $aItems['file/ajax']['file path']    = $sNodePath;
    $aItems['file/ajax']['file']         = 'node.pages.inc';
    $aItems['system/ajax']['file path']  = $sNodePath;
    $aItems['system/ajax']['file']       = 'node.pages.inc';
}

```
> 0 votes

---
Tags: entities, nodes, files, i18n-l10n
---


# Question
Title: Entity metadata wrapper + entity reference + translation
I have two node types: 'festival', which can be translated and 'event', which untranslatable. Event has multivalued field reference to Festival, so that one Event referenced to all translated festival instances. Now I need to load Festival title depending on current user language.

```
global $language;
$fest_title = $emw_event->language($language->language)->field_fest_reference->value();

```

returns an array of all festivals ignoring language parameter.

How to get language-specific title?

# Answer
> 0 votes
```
global $language;
$fests = $emw_event->field_fest_reference->value();
foreach ($fests as $fest) {
  if ($fest->language == $language->language) $fest_title = $fest->title;
}

```

---
Tags: 7, entities
---


# Question
Title: Create drupal content programmatically with custom entity ( assets )
I am using asset module : https://www.drupal.org/project/asset

I creates a new entity type = asset. I get a form where I can add ( document, image, video..).

How can I, from a custom module add a content of asset ? I think that I cannot do it the way we creat nodes ... like :

```
$node = new stdClass();
$node->type = "asset";
node_object_prepare($node);
....

```

Please help

thank you

# Answer
this is the right code:

```
function create_assets(){

$asset = entity_create('asset' , array('type' =>'image'));
$asset->title = 'image publication';
//$asset->field_asset_image = array(LANGUAGE_NONE => array(0 => array('value' => get_external_image("http://cdn.sstatic.net/drupal/img/logo.png"))));
$asset->field_alt["und"][0]["value"] = "alt image publication";
//$asset->save();
entity_save('asset', $asset);
}

```
> 0 votes

# Answer
I think you can try to use core and EntityAPI methods for this task like this:

```
$asset = entity_get_controller('asset');
$asset->type = 'MY_TYPE';
$asset->... = '...';
....

$asset->save();

```
> 0 votes

---
Tags: media
---


title: Site name\logo in a panel pane?

text:
# Question
Title: Site name\logo in a panel pane?
I want the site's name\logo to appear in a column in a Panels pane (instead of it's regular appearance in the header region). is there any way to achieve this without programing?

# Answer
> 0 votes
Yes.

Go to the pane where you want the logo or site name. Click on the 'Add content' gear wheel and then you'll find the site name and logo under the 'Page elements' section.

---
Tags: panels
---


# Question
Title: Show item as local task but hide if argument is not provided
I have three tabs and third have wildcard in path. I added access callback for this menu item that checks if no argument then close access. The tab not shows afte that but ther is error "Notice: Undefined offset: 1 in \_menu\_translate()". So how correctly hhide this tab?

Access callback that I wrote:

```
/**
 * System log view access callback.
 */
function ebanq_custom_system_log_view_access($log_id) {
    return is_numeric($log_id) && user_access('access content');
}

```

# Answer
> 0 votes
I solve this by argument load function, but I don't think it is correct to do like this.

```
// Menu item change
//....
'system-log/%ebanq_custom_log_id/view' => array(
//....

/**
 * Implements hook_load().
 */
function ebanq_custom_log_id_load($arg) {
    if (!is_numeric($arg)) {
        return FALSE;
    }
    return $arg;
}

```

---
Tags: routes
---


# Question
Title: Field settings are not being exported with Features
I have a product content type that has a product reference field. Under the Product types that can be referenced section there is a list of product types that can be referenced. I have selected one of these. When exporting/importing this content type, the field settings (eg. the selected referenced product) are not exported. How could i export this without selecting the referenced product manually.

# Answer
The setting got exported but could not be set, because it was referencing an nonexistent product type.

On the old site i had a Recurring Product type w. a "recurring\_product" machine name. I wanted to export the display for this. On the new site only a "recurring" product type existed and therefore could not match the setting.
> 0 votes

---
Tags: commerce, features
---


# Question
Title: Don't show a field if it is not filled in
What is the best way to don't show up a field if it is not filled in.

I have a content-type for the homepage: (Machine name: home\_pagina).

There is a field for my client to give a warning-message if necessary: (Machine name: field\_aandachts\_tekst).

The warning message has to show up in a colored box/div. But if the field is not filled in, the box/div should not show up.

I tried to achieve this with a field-template....

I already have a "field.tpl.php" created. So i thought if a create a special field template for the field (field\_aandachts\_tekst) i could put the colored box/div in there. And if the field is not filled in the box/div would not show up also.

But it seems that the field-template for the (field\_aandachts\_tekst) is not used...

My template for controlling the view of the (field\_aandachts\_tekst) is called:

field--field-aandachts-tekst.php

but it seems this template is not used... (instead it uses: "field.tpl.php")

The code in my "node--home\_pagina.tpl.php" looks like this:

print render($content\['field\_aandachts\_tekst'\]); surrounded with php-tag ofcourse

Any tips or suggestions are good!

Thanks, Kristof

# Answer
Okay dear readers,

I find the solution/problem:

I forgot the extension .tpl in my template name. Stupid of me. Everything is working fine now.

Thanks for reading!

kristof
> 0 votes

---
Tags: theming
---


# Question
Title: Display name of Content Type instead of node Title in Views
I have multiple different content types: *Part A*, *Part B*, *Part C*, etc.

What I need, is to display "Part A" in Views, instead of the title of the content. I also need to link to the content.

Is there an easy way to do this? It seems like such a simple thing, but I've found nothing on Google.

I'm thinking of using the Automatic Node Titles module to replace the title with "Part A (username - date)", so is this the best way?

# Answer
> 0 votes
It's simple. Go to your view. Add field \>\> Content: Type

Then in the field settings, check 'Link this field to the original piece of content'

That's it. You will find content type in each row. and if you click on it goes to node content page.

---
Tags: 7, views, nodes
---


title: How to use drush site-lists alias?

text:
# Question
Title: How to use drush site-lists alias?
I several folders containing symlinks to my drupal sites. I'd like to use this folder structure to create an alias so I can run commands on each group of sites.

I'm trying to do what "drush @sites status" will do, but on a smaller subset.

I wrote the following based on the docs

```
// List the instances from the OU instances folder
$full_path = "/opt/drupal/sites/instances";
if ($handle = opendir("$full_path")) {
    while (false !== ($file = readdir($handle))) {
        if(is_dir($full_path."/".$file)) {
          if ($file != '.' && $file != '..')
            $instances[] = $file;
        }
    }
}

// Turn them into aliases so we just have to type @instance
foreach ($instances as $instance) {

    $site_list = [];

    // Look at each instance
    $site_paths = $full_path . "/" . $instance;

    if ($file_handle = opendir("$site_paths")) {
      // List out the folders in this instance
      while (false !== ($site_folder = readdir($file_handle))) {

        if(is_dir($site_paths."/".$site_folder)) {
          // If the folder represents a drupal site
          if ($site_folder != '.' && $site_folder != '..')
            // Add it to this instances list
            $site_list[] = '@' . $site_folder;
        }
      }
    }

   $aliases[$instance] = array(
            'site-list' => $site_list,
        );
}
print_r($aliases);

```

The cheeky print\_r on the end shows my array as

```
 [partnership] => Array
        (
            [site-list] => Array
                (
                    [0] => @www.1.co.uk
                    [1] => @www.2.org
                    [2] => @www.3.org.uk
                    [3] => @www.4.org
                    [4] => @www.5.eu
                    [5] => @www.6.net
                    [6] => @www.7.com
                    [7] => @www.8-ri-2020.eu
                    [8] => @www.9.edu
                    [9] => @www.10.ac.uk
                    [10] => @www.11.org
                    [11] => @www.12.ac.uk
                    [12] => @www.13.co.uk
                    [13] => @www.14.org.uk
                    [14] => @www.15.ac.uk
                )

        )

```

I've changed the names to protect the innocent, but they are valid aliases.

When I run "drush @partnership status" I get

```
drush @partnership status
You are about to execute 'status' non-interactively (--yes forced) on all of the following targets:
Continue?  (y/n): y
Invalid argument supplied for foreach() backend.inc:661

```

How do I get drush to actually run through this alias list telling me the status of each site?

# Answer
> 0 votes
I found that one of my colleges had written an invalid file in the drush folder. I was writing mine in my ~/.drush folder.

The result was it would run his code, then my code, leaving a big mess that drush could only partially understand

I fixed the incorrect file and the code I posted in the question started working. I can now run drush commands against a site-list.

---
Tags: drush
---


title: Text only rotating banner

text:
# Question
Title: Text only rotating banner
Is there any module for drupal 6 I can use to create a rotating banner with no images for drupal 6 site

Thanks

Colin

# Answer
> 1 votes
Try the Marquee Block module

> Provides a jQuery-based scrolling marquee block that can be customized with your own text or HTML. Configure speed, scroll direction and scroll behavior easily on the Block setup page.

Image from module page:

Or else if you want to do it so simple. just create a block and use `<marquee>` in your custom block ;)

---
Tags: 6, blocks, media
---


# Question
Title: Remove wrapping div from field type radios (Drupal 7)
I am trying my hand at theming form output and am stuck on radios. I am attempting to remove the div that wraps a set of radios,

```
div.form-item > div.form-radios > div.form-type-radio > input[type="radio"]+label
                ^^^^^^^^^^^^^^^ <- Remove that

```

I have a sample form:

```
function no_name_form($form, &$form_submit) {
    $form['radios'] = array(
        '#type'    => 'radios',
        '#title'   =>'Question text',
        '#options' => array(
            '1' => t('yes'),
            '0' => t('no')
        ),
        '#theme'   => 'no_name_radios',
    );
    return $form;
}

```

and I register the theme functions for both the radios group and individual radio buttons:

```
function no_name_theme($existing, $type, $theme, $path) {
    return array(
        'no_name_radios' => array(
            'arguments' => array('element' => NULL),
        ),
        'no_name_radio' => array(
            'arguments' => array('element' => NULL),
        ),
    );
}

```

Then I define the theme functions:

```
function theme_no_name_radios($variables) {
    $element = $variables['element'];
    $attributes = array();
    if (isset($element['#id'])) {
        $attributes['id'] = $element['#id'];
    }
    $attributes['class'] = 'form-radios test';
    if (!empty($element['#attributes']['class'])) {
        $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
    }
    if (isset($element['#attributes']['title'])) {
        $attributes['title'] = $element['#attributes']['title'];
    }
    return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
}

function theme_no_name_radio($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'radio';
  element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

  if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-radio'));

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

```

When I use even the stock code from Drupal 7 to build the theme functions, the radios come out blank, and at this point none of the code has changed.

Ultimately, I want to end up with this:

```
div.form-item div.form-type-radio > input[type="radio"]+label

```

I am not sure where I went wrong.

# Answer
> 2 votes
The `div.form-radios` is set by the theme wrapper of the radios. Use this code to prevent the theme wrapper from adding the additional div:

```
function no_name_form($form, &$form_submit) {
  $form['radios'] = array(
    '#type'    => 'radios',
    '#title'   =>'Question text',
    '#options' => array(
        '1' => t('yes'),
        '0' => t('no')
    ),
    '#theme'   => 'no_name_radios',
    '#theme_wrappers' => array(),
  );
  return $form;
}

```

---
Tags: 7, theming
---


title: Endpoint services with url alias name

text:
# Question
Title: Endpoint services with url alias name
Is it possible the to view xml/json format data with url alias name instead of endpoint\_path/node/1 or endpoint\_path/node/2

# Answer
> 0 votes
Try the Services node resource extension module

> Extends functionality for the node resource available through services module.
>
> Additional Resources:
>
> -lookup - provides a resource to request a node through the url alias.
>
> -POST data = \[ 'alias' =\> the url alias. \]

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


title: Hide a user in People List

text:
# Question
Title: Hide a user in People List
I have a super user(user 1) that I want to hide in people list (mysite.com/admin/people).

Is there anyway to filter it out? I couldn't find a hook unless I just missed it. I know I could create my own view and easily filter it but then I loose the bulk operation which I need to keep.

EDIT: here is the "why". I'm building an intranet system with drupal. User 1 is the super user that I want to keep for myself to be able modify advanced features of the intranet. I have created another "admin" roles that can manage content, users, roles, etc. I have a few dozen modules installed, but the ones applicable per this issue is user protect, workbench, and permissions lock.

There is a bug in user protect that allows my admin to delete the user1 account via the bulk operations on the people page, so I want to just hide it altogether.

# Answer
Put this in a custom module and it will effectively remove User 1 from the People list, but only there.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  unset($form['accounts']['#options'][1]);
}

```

But as Free Radical pointed out, if you say why there might be better solutions.

Cheers,
> 3 votes

# Answer
The User One module insert automatically superaddmin hidden

> * User one account is protected from viewing and editing. Users -- even with 'Administer users' permission -- will be denied access.
> * User one account is hidden from user listing page, admin/people.
> * User one account is hidden from user lists such as in blocks, Who's New and Who's Online. User One provides its own version of Who's
> Online block for correct count of logged in users besides hiding user one.
> * User One exposes Drupal's built-in values to change otherwise inaccessible such as number of allowed login attempts and time window to remember such login attempts.
> * While Drupal temporarily deny login after multiple failed logins, User One goes one step further to allow permanently block such IPs
> automatically and notify the site admin.
> 1 votes

# Answer
IF all else fails, you can hack core:

modules/user/user.admin.inc

change part of function user\_admin\_account()

```
if($account->uid != 1) // add if statement
{
  $options[$account->uid] = array(
  'username' => theme('username', array('account' => $account)),
  'status' =>  $status[$account->status],
  'roles' => theme('item_list', array('items' => $users_roles)),
  'member_for' => format_interval(REQUEST_TIME - $account->created),
  'access' =>  $account->access ? t('@time ago', array('@time' =>     format_interval(REQUEST_TIME - $account->access))) : t('never'),
  'operations' => array('data' => array('#type' => 'link', '#title' => t('edit'), '#href' => "user/$account->uid/edit", '#options' => array('query' => $destination))),
  );
}

```
> 0 votes

# Answer
Taking inspiration from `user_filter_form` and `user_filter_form_submit` functions in *user.admin.inc* :

From a custom module's init hook, add a filter for `user_overview_filter` if current page is admin/people. Set into sesssion variable like this:

`$_SESSION['user_overview_filter'][] = array('filter_name_maybe_username', 'superadmin');`

You might also want to use label 'Filter' instead of 'Reset' if the only filter available is your custom filter. Similar logic can be applied for VBO form.

Let me know if it helps.
> 0 votes

# Answer
Hiding admin user is not enough.because by this url (user/1/edit) it would be accessible.you should change access permission by calling hook\_menu\_alter here is a simple code for you : now it dose not important if others can see admin on people page.because they cannot edit it.

tips: change MODULENAME with name of your module.

```
/**
 * Impelement hook_menu_alter
 * @param array $items
 */
function MODULENAME_menu_alter(&$items) {
    $items['user/%user/edit']['access callback'] = 'MODULENAME_change_premission';
}

function MODULENAME_change_premission($account) {
    global $user;
    //check if account is admin and person trying to edit is not admin
    if ($account->uid == 1 && $user->uid != 1) {
        return FALSE;
    } else {
    // return default access premission
        return user_edit_access($account);
    }
}

```
> 0 votes

---
Tags: users, hooks
---


title: Empty Field Notification View?

text:
# Question
Title: Empty Field Notification View?
My website has a content type with about 15 fields. Now I don't have all the data to fill the fields all the time. I've got close to 1000 entries in this content type.

Is there any module that can work as a Notifier. Ex: I've chosen to have Content Type A selected and the module tells me how many Entries that are not 100% filled and what fields are missing. ?

# Answer
> 0 votes
Try any one of the module as per your requirement.

Content Complete

> Content Complete is a CCK extension module that allows to tag CCK fields needed for completion (CCK Complete). The module checks the tagged fields against the content provided for those content types, and computes a complete percentage that can be shown to the user.

Field Complete

> In some situations you want to mark an entity field to indicate it should be completed but not enforce its completion at that time. This module extends the choice between Required and Not required to "desirable" completion.
>
> This module overcomes the problems with the (otherwise excellent) Content Complete module which cannot cope with field collections or fields that link to other entities.

Hope the following links give you clear ideas on how to use Content Complete module.

Measure node completion in Drupal, part 1

Measure node completion in Drupal, part 2

---
Tags: views, 7, notifications
---


# Question
Title: Use Ajax on Exposed Filter of a View but NOT on the pager of that View
I'm experimenting with a "page" view, and would like to submit the view's exposed filters via Ajax, but not the same views pager.(I currently have a checkbox "has taxonomy term" filter that has been enhanced by the BEF module.)

Currently if I select "Use Ajax: Yes" in the "Advanced" column of the views settings, both the pager and exposed filter are submitted via Ajax. Is there a way to make it so that only the exposed filter submits via Ajax, and the pager reloads the page with the default "?page=X' GET parameter?

I was thinking I could leave "Use Ajax: No" in the view settings, and then somehow add the ajax functionality to the exposed form, via some hook. (form\_alter?) Or maybe add some inline javascript which disables the ajax functionality of the pager? (which isn't even a form.)

Hoping someone could point me in the right path. (Using Drupal 7 and Views 3)

# Answer
> 3 votes
I'm sure you've found a solution / workaround for this by now, but this thread came up while I was faced with the same issue, so I figured I'd share the solution that worked for me.

All I did was simply remove Drupal's AJAX event handler from the pager links using jQuery's unbind method, e.g.:

```
$('.pager a').unbind();

```

With the event handlers removed, the pagination links fall back on the HREF URLs contained within the anchor tags.

# Answer
> 1 votes
I don't think what you're describing will be easy, due to the nature of the ajax function.

just thinking outloud (in type?) here: leave ajax on, limit results to 25. add an offset filter to the contextual filters, the default being "0". use a custom paging function (custom footer in view? template?) and generate links with the offset (and your form values?) for use by your contextual filters.

---
Tags: ajax, views
---


# Question
Title: Entity reference for feed imports not working on some referenced nodes
I've posted this problem on drupal.org but I feel that it's so cryptic that maybe it deserves a larger audience.

For some reason, when I'm trying to import users that are associated with group nodes some imported users do not have any referenced group nodes associated.

I've noticed that the group nodes that cannot be referenced are only nodes that have been imported via a previous feeds import. Despite this, users that are created through the user creation form CAN be associated with the group nodes that do not work through the feeds import process.

There are two php warnings that occur when an entity reference cannot be created through the feeds process:

**Warning: array\_keys() expects parameter 1 to be array, boolean given in entityreference\_feeds\_set\_target() (line 132 of /home/angelo/dev/client/profiles/openatrium/modules/contrib/entityreference/entityreference.feeds.inc).**

**Warning: reset() expects parameter 1 to be array, null given in entityreference\_feeds\_set\_target() (line 134 of /home/angelo/dev/client/profiles/openatrium/modules/contrib/entityreference/entityreference.feeds.inc).**

This implies that for some reason 127: $handler-\>getReferencableEntities($value, '=') isn't returning what it's supposed to and I'm not too sure why.

Has anyone else run into this issue?

# Answer
Fixed. It turns out there were erroneous microsoft nbsp characters in the feed CSV that looked exactly like spaces. This resulted in the referenced entity not being found.

Removing these characters made the feed work correctly.
> 0 votes

---
Tags: entities, feeds
---


title: Translate Forums page title

text:
# Question
Title: Translate Forums page title
I've tried with `preprocess_page`, `preprocess_forums` even changing `drupal_set_title` directly in forum.module but i can't get change that ugly page title "forums".

Any idea?

# Answer
> 1 votes
Try to change the name of the (taxonomy) vocabulary that holds the names of the forums and groups.

---
Tags: 7, theming, nodes
---


# Question
Title: Multiple content types from Views module, not old nodes from one of them
I use the famous Views module to show nodes of different content types. One of these content types has a field called "final date". If a node has an old date, smaller than today's date, I want it to disappear from the start page so it's always up to date. How do I solve this problem?

# Answer
To filter out content that has a "final date" that is in the past, you can set up a filter as follows on the view for this content type.

Filter on "final date" "is greater than or equal to" an offset date of "+0 minutes".

Screenshot below shows the final setting (in the screenshot example I used the "Post date" as the date field to filter on, but in your case it should be "Final date.")

Alternately, you could look at the Scheduler module and instead of using a "Final date" field, schedule these nodes to unpublish at a certain date. Depends on your use case.
> 1 votes

# Answer
Why not have this view return a set limit of records and sort DESC on the `final date` field?
> 0 votes

---
Tags: views, nodes, datetime
---


# Question
Title: Alter html output of a term reference form field
On my node edit form a term reference field is rendered with the following html output:

```
<div class="form-item form-type-radio form-item-field-trainingstype-und">
  <input type="radio" id="edit-field-trainingstype-und-12" name="field_trainingstype[und]" value="12" class="form-radio">
  <label class="option" for="edit-field-trainingstype-und-12">External </label>
</div>

```

As you can see the value attribute is set to 12 which is the term id of that particular item. Now I would like to replace 12 with the term name, **External**.

So it would look like:

```
<div class="form-item form-type-radio form-item-field-trainingstype-und">
  <input type="radio" id="edit-field-trainingstype-und-12" name="field_trainingstype[und]" value="External" class="form-radio">
  <label class="option" for="edit-field-trainingstype-und-12">External </label>
</div>

```

I am unsure which function to use to target this particular field. I was looking at theme\_checkbox() and theme\_form\_element() but I am uncertain how to proceed and if these are the right functions for the job.

**UPDATE:** So I would like to show another field based on the option chosen for the field\_trainingstype. In a hook\_form\_alter I am now doing this:

```
$form['field_organisaton']['#states'] = array(
  'visible' => array(
    ':input[name="field_trainingstype[und]"]' => array('value' => '12'),
  ),
);

```

But I would like to trigger this by term name External because the term id might differ per environment.

# Answer
Doing it that way round will cause problems with the form submission; the value for a term reference field needs to be an integer and throwing a string at it will undoubtedly upset things. You could massage values back into place in a validate function but it seems a bit...messy.

The alternative would be to load the taxonomy term up in the form, so you can use the ID from there:

```
$terms = taxonomy_get_term_by_name('External', 'vocab_machine_name');
$term = array_shift($terms);
$form['field_organisaton']['#states'] = array(
  'visible' => array(
    ':input[name="field_trainingstype[und]"]' => array('value' => $term->tid),
  ),
);

```

That should make it reusable across different environments (provided the vocab only has one term with the name "External").
> 2 votes

---
Tags: theming, entities
---


# Question
Title: hook_form_alter Save $form['account']['field_first_name'] into $form['profile']['field_first_name']
Hi I'm trying to save a field into another field in the same form when the form is submitted.

I've tried using hook\_form\_alter and checked for `count($form_state['input']) > 0` to save $form\['account'\]\['field\_first\_name'\] into $form\['profile'\]\['field\_first\_name'\]

I know you may say that I can use the profile2 module. I'm already using that. I just need to figure out how to save one field value into another field when a form is submitted.

Any help would be greatly appreciated.

# Answer
Got it! In my hook\_form\_alter function I added `$form['#submit'][]='my_submit';`

Then I created the `my_submit()` function.

```
function my_submit($form, &$form_state) {
  if (count($form_state['input']) > 0) {
    form_state_values_clean($form_state);
    $form_state['values']['profile']['field_first_name'] = $form_state['values']['field_first_name'];
    $form_state['values']['profile']['field_last_name'] = $form_state['values']['field_last_name'];
    $form_state['values']['profile']['field_groups'] = $form_state['values']['field_groups'];

    unset($form_state['values']['field_first_name']);
    unset($form_state['values']['field_last_name']);
    unset($form_state['values']['field_groups']);
  }
}

```

The important parts of the function above to notice are `form_state_values_clean($form_state);` then I access the values through `$form_state['values']` array.

Hope this helps someone else looking to do the same functionality.
> 1 votes

---
Tags: forms, users
---


title: Mucho Menu is Not Displaying D7

text:
# Question
Title: Mucho Menu is Not Displaying D7
I am using Drupal-7. I am trying to build a Fly out menu that have images, content blocks.

I am using the MuchoMenu to create top menu into my site.

I wanted to create Flyout menu same like displayed in Mucho Menu with image block.

I have created Main MuchoMenu, Mini Panels, Content Types to display images and content blocks.

But, my Menu Items are not displaying into my website. Do I have to add anything into my page.tpl.php or page--front.tpl.php pages? I have added Main MuchoMenu block into "Main Menu" Region.

In both page.tpl.php and page--front.tpl.php files, I have added this into menu section:

```
<div id="nav_wrapper" class="nav_wrapper">
        <?php if ($main_menu): ?>
          <div id="main-menu" class="nav">
            <?php print theme('links__system_main_menu', array(
              'links' => $main_menu,
              'attributes' => array(
                'id' => 'main-menu-links',
                'class' => array('links', 'clearfix'),
              ),
              'heading' => array(
                'text' => t(''),
                'level' => 'h2',
                'class' => array('element-invisible'),
              ),
            )); ?>
          </div> <!-- /#main-menu -->
        <?php endif; ?>

    <?php if ($secondary_menu): ?>
      <div id="secondary-menu" class="nav">
        <?php print theme('links__system_secondary_menu', array(
          'links' => $secondary_menu,
          'attributes' => array(
            'id' => 'secondary-menu-links',
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            'text' => t(''),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>
      </div> <!-- /#secondary-menu -->
 </div>  <!-- End of nav_wrapper  -->
    <?php endif; ?>

```

Please let me know as I am new to Drupal.

Thanks!

# Answer
Thanks for editing @Krishna Mohan.

I have changed module from MuchoMenu to "TB Mega Menu". TB Mega Menu allows us to create block into drop down menu.

And, I think "to display custom menu" need to print block into that region.

So, Define region into .info file and print that block into page.tpl.php file.

So, in page.tpl.php replace code with this:

```
<div id="nav_wrapper" class="nav_wrapper">
          <div id="main-menu" class="nav">

             <?php print render($page['top_menu']); ?>

          </div> <!-- /#main-menu -->
</div>  <!-- End of nav_wrapper  -->

```

I am new to drupal, so I might be wrong.

Thanks!
> 0 votes

---
Tags: 7, routes, navigation
---


title: feed from view doesnt work

text:
# Question
Title: feed from view doesnt work
I made a view which works fine in the page view, but clicking on the feed icon or going directly to the path for the feed gives a http 500 internal server error on IE 11.

And on firefox it simply has a blank white page.

Why arent the feeds working?

# Answer
> 0 votes
I had to enable the RDF module and now it works.

---
Tags: views, feeds
---


# Question
Title: How do you run custom functions after Migrate class finishes an import?
I have migrate classes to import useres, taxonomy, content, etc. Some of these are being imported from a CSV source and need to be organized a little better either before or after an import.

How can I run custom functions before and after an import with the Migrate module?

# Answer
> 5 votes
For what you're asking (running a function prior to or after a single Migration) see the documentation for Less Commonly Implemented Migration Methods. They include:

* **`function preImport()`**
* **`function postImport()`**
* `function preRollback()`
* `function postRollback()`

Note this caveat from the documentation:

> NOTE: If you are running your migrations through the web UI, which chunks the work into batches, if a given migration takes long enough to be broken into separate batches, these functions will be called for each batch. They are called each time the migration is invoked, not just the first (or last, in the complete case).

If you don't like that behavior, then in your `preImport()` or `postImport()` simply use a static variable to see if your custom logic has already run once. Lullabot Posted a good blog entry on using `drupal_static` back in 2011 on this subject.

With regards to per-record migration completion (like moving 1 song from legacy data store to drupal -- 1 "row" of a migration) take a look at the documentation for Commonly Implemented Migration Methods. They include:

* `function prepareRow($row)`
* `function prepare($entity, stdClass $row)`
* `function complete($entity, stdClass $row)`
* `function createStub()`

# Answer
> 0 votes
I found this especially useful for turning ON and OFF patterns for Path Auto settings with a simple `variable_set('pathauto_node_MYTYPE_pattern')` when migrating existing aliases into a new site.

---
Tags: migrations
---


# Question
Title: How do I add an additional submit handler in commerce checkout form?
How do I add an additional submit handler? I have tried this but it did not work.

```
function c_coupon_form_alter(&$form, $form_state, $form_id) {
  drupal_set_message($form_id);
  switch($form_id) {
     case 'commerce_checkout_form_review':
      drupal_set_message($form_id . '_form submit');
      $form['#submit'][] = 'c_coupon_review_submit';
  }
}

function c_coupon_review_submit($form, &$form_state) {
  drupal_set_message('submitted');
}

```

# Answer
> 15 votes
What you are doing is correct.

The problem is that Drupal Commerce has defined the submit action on the buttons that is clicked, which will be used instead of the submit handlers defined on the form itself. So you need to add your submit handlers to the buttons (Cancel, Continue) that you want to use your submit function.

```
$form['buttons']['continue']['#submit'][]='c_coupon_review_submit';

```

# Answer
> 7 votes
To quickly answer Ahmad's refined question - how to add his custom submit function BEFORE other submit functions:

```
if ( empty($form['buttons']['continue']['#submit']) ) {
    $form['buttons']['continue']['#submit'] = array(); // just in case
}
array_unshift($form['buttons']['continue']['#submit'],'c_coupon_review_submit');

```

# Answer
> 1 votes
Use the following code to add extra submit handler to a form. It worked for me:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
        if ($form_id == 'xyz') {
            $form['#submit'][] = 'webform_extra_submit_test';
        }
    }

function webform_extra_submit_test($form, &$form_state) {
    global $user;
    $user_id = $user->uid;
    // do code here $form_state['values'] etc...
}

```

---
Tags: commerce, forms
---


# Question
Title: views - get teasers of "related nodes" referenced in entity fields on current node
I have a content type 'Article' which has a custom field of 'related articles'. This field uses the Entity Reference module and allows an admin to specify up to 4 related articles (nodes) to be shown on that page.

I'm trying to create a view block to display the teasers of those related articles on the page.

I'm struggling to set-up the view.

So far I've got it as:

The plan is that this view will be attached to an existing view which just shows the latest articles.

The view at the moment doesn't seem to be referencing the entity field (Related Articles) or showing those items...

Probably missing something obvious but would appreciate any pointers.

# Answer
> 1 votes
Don't use an Entity Reference relationship for this, but rather, change your Show: to "Fields" and add the referenced entity field. Then you will be able to set the "Formatter" to "Rendered entity", and the "View mode" to "Teaser".

You may need to add a contextual filter or set this up as an attachment display rather than a block.

I can post a few screen shots if my answer isn't clear.

---
Tags: views, entities
---


# Question
Title: On click of checkbox send email to selected recipients using module
```
 <script type="text/javascript">
 function send_email(){
 var persons_names;
 persons_names = $('#send_mail_persons input:checked');
 var persons_names_Str='',coma='';
 if(persons_names.length != 0){
 persons_names.each(function(){
     persons_names_Str += coma+$(this).val();
     coma = ',';
 })
 }
 alert(persons_names_Str);
 //    console.log(" persons_names_Str: "+persons_names_Str);
 ajax_call_to_send_values_to(persons_names_Str);
 }

 function ajax_call_to_send_values_to(persons_names_Str){
 $.ajax({
              url: 'http://<?php echo $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];?  >',
            type: 'POST',
              data: { persons_names_Str: persons_names_Str
                       },
              success: function(data, textStatus, xhr) {

              },
            //called when successful

              error: function(xhr, textStatus, errorThrown) {
            //called when there is an error
                  }
    });
 }
 </script>

 <?php
 if( isset($_POST['persons_names_Str']) && !empty($_POST['persons_names_Str']) )
  {
 $list = $_POST['persons_names_Str'];
 //print_r($list);
 //$to_arr = explode(",", $list);
 //$to = array_filter($to_arr);
 //echo $to;
 //print_r($to);
 $to = $list;
 $subject = "Test Subject";
 $body = "This is temporary email from Lawandmoney. ";
 $headers = "From: no-reply@lawandmoney.com\r\n" .
 "X-Mailer: php";

 $to =  "no-reply@lawandmoney.com";
 $headerFields = array('BCC: '.$list.', "From: no-reply@lawandmoney.com" ."X-Mailer:    php"');
 if (mail($to, $subject, $body, implode("\r\n", $headerFields))) {
 //if (mail($to, $subject, $body, $headers)) {
  echo("<p>Message sent successfully! our lawyer will contact you as soon as   possible</p>");
  } else {
  echo("<p>Message delivery failed...</p>");
  }
  exit();
  }

  ?>

  <div id="send_mail_persons">
  <?php
   $sql = "SELECT * FROM lawyer_details WHERE city LIKE :city AND speciality LIKE   :speciality";
   $result = db_query($sql,array(':city' => '%'.  db_like($_SESSION['selected_county']).'%' , ':speciality' =>  '%'.db_like($_SESSION['lawarea']).'%'));

 $rows_count=$result->rowCount();

 if($result && $rows_count>0)
 {
 while($row = $result->fetchAssoc())
 {
  ?>
  <div class="result">
   <div class="resultPadder">
       <div class="resultLeft">
          <div id="fav">
         <div><input type="checkbox" name="checkbox[]" id="email1" value=<?php echo  $row['email_id'];?> /><a class="b ui-link" href="" onclick=""><?php echo  $row['first_name'].' '.$row['middle_name'].' '.$row['last_name'];?></a>
          </div>
       <div class="p-t-2"><?php echo $row['street_address'];?></div>
       </div>
       </div>
  <div class="resultRight">

 </div></div><div class="clear"></div>

 <?php

  }
  }
 else
  {
 echo "No Result Found";
 }
 ?>
 <a href="javascript:void(0);"  onClick="javascript:send_email();"><span>Send  Email</span></a>

 </div>
 </div>
 <div>

```

only just add jquery file in head section.

# Answer
> 0 votes
```
 <script type="text/javascript">
 function send_email(){
 var persons_names;
 persons_names = $('#send_mail_persons input:checked');
 var persons_names_Str='',coma='';
 if(persons_names.length != 0){
 persons_names.each(function(){
     persons_names_Str += coma+$(this).val();
     coma = ',';
 })
 }
 alert(persons_names_Str);
 //    console.log(" persons_names_Str: "+persons_names_Str);
 ajax_call_to_send_values_to(persons_names_Str);
 }

 function ajax_call_to_send_values_to(persons_names_Str){
 $.ajax({
              url: 'http://<?php echo $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];? >',
            type: 'POST',
              data: { persons_names_Str: persons_names_Str
                       },
              success: function(data, textStatus, xhr) {

              },
            //called when successful

              error: function(xhr, textStatus, errorThrown) {
            //called when there is an error
                  }
    });
 }
 </script>

 <?php
 if( isset($_POST['persons_names_Str']) && !empty($_POST['persons_names_Str']) )
  {
 $list = $_POST['persons_names_Str'];
 //print_r($list);
 //$to_arr = explode(",", $list);
 //$to = array_filter($to_arr);
 //echo $to;
 //print_r($to);
 $to = $list;
 $subject = "Test Subject";
 $body = "This is temporary email from Lawandmoney. ";
 $headers = "From: no-reply@lawandmoney.com\r\n" .
 "X-Mailer: php";

 $to =  "no-reply@lawandmoney.com";
 $headerFields = array('BCC: '.$list.', "From: no-reply@lawandmoney.com" ."X-Mailer:    php"');
 if (mail($to, $subject, $body, implode("\r\n", $headerFields))) {
 //if (mail($to, $subject, $body, $headers)) {
  echo("<p>Message sent successfully! our lawyer will contact you as soon as   possible</p>");
  } else {
  echo("<p>Message delivery failed...</p>");
  }
  exit();
  }

  ?>

  <div id="send_mail_persons">
  <?php
   $sql = "SELECT * FROM lawyer_details WHERE city LIKE :city AND speciality LIKE   :speciality";
   $result = db_query($sql,array(':city' => '%'.  db_like($_SESSION['selected_county']).'%' , ':speciality' =>  '%'.db_like($_SESSION['lawarea']).'%'));

 $rows_count=$result->rowCount();

 if($result && $rows_count>0)
 {
 while($row = $result->fetchAssoc())
 {
  ?>
  <div class="result">
   <div class="resultPadder">
       <div class="resultLeft">
          <div id="fav">
         <div><input type="checkbox" name="checkbox[]" id="email1" value=<?php echo  $row['email_id'];?> /><a class="b ui-link" href="" onclick=""><?php echo  $row['first_name'].' '.$row['middle_name'].' '.$row['last_name'];?></a>
          </div>
       <div class="p-t-2"><?php echo $row['street_address'];?></div>
       </div>
       </div>
  <div class="resultRight">

 </div></div><div class="clear"></div>

 <?php

  }
  }
 else
  {
 echo "No Result Found";
 }
 ?>
 <a href="javascript:void(0);"  onClick="javascript:send_email();"><span>Send  Email</span></a>

 </div>
 </div>
 <div>

```

only just add jquery file in head section.

# Answer
> 1 votes
"to" parameter in drupal\_mail is a string. You can have as many receipent as you like in the the emails "to" string, provided they are separated by commas (","). You can do like this

```
$to  = 'one@email.com, two@email.com, three@email.com';
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'test'), $from = NULL, $send = TRUE);

```

You may check the documentation of drupal\_mail.

---
Tags: views
---


title: Flexslider - on touch

text:
# Question
Title: Flexslider - on touch
I am using Flexslider module in drupal 7 . when i checked my website on mobile. i am not use slider by touch

Is there is any setting for flexslider.

Thanks

# Answer
> 0 votes
You need to enable touch for that. Follow this path for flexslider setting `$base_url/admin/config/media/flexslider/list/default/edit`.

You will see screen such as You need to check Touch in Navigation and Control Settings & save.

Don't forget to clear cache :)

---
Tags: views, 7, theming
---


title: View mode theme name priority

text:
# Question
Title: View mode theme name priority
I have a theme set for view mode 'Teaser'. The theme name for this is named like this: node--teaser.tpl.php. So far so good.

Then I created content type 'something' and I would like to create a Teaser theme specific for my new content type 'something'. I have thus named my custom Teaser theme as node--something--teaser.tpl.php. I was expecting this more specific theme name to override theme node--teaser.tpl.php (broader, less specific), but it doesn't work that way. node--teaser.tpl.php has priority over node--something--teaser.tpl.php. Is this really the expected behavior for theme names priority? I would expect the more specific to 'beat' the less specific broader name.

Is it possible to force the more specific theme in template.php function theme\_preprocess\_node?

# Answer
This page Drupal 7 Template (Theme Hook) Suggestions explains the topic.

**To investigate for yourself:**

Install Devel module. Add this bit of code to your theme's template.php file (check if the function does not already exist):

```
function MYTHEME_preprocess_node(&$variables) {
  dpm($variables);
}

```

Then inspect the theme\_hook\_suggestions key. It will look something like this:

This show the suggestions available. To convert it to a tpl.php file just convert underscores to hyphens and add the extension tpl.php.

You can also create your own suggestions by adding this code into preprocess\_node:

```
if ($variables['type'] == 'article' && $variables['view_mode'] == 'teaser') {
  $variables['theme_hook_suggestions'][] = 'node__article__teaser";
}

```

Here I am checking for the view mode teaser and adding a theme suggestions based on that. You can check for other conditions as well and add your own suggestions as you please.

Some themes add their own suggestions so always inspect it with dpm() first.
> 1 votes

---
Tags: 7, theming, entities
---


title: Submit few forms in Drupal 7

text:
# Question
Title: Submit few forms in Drupal 7
I try to add Poll-voting to my website, on page I addet 5 votings forms, I try to make submission of all 5 forms by one click instead of 5 clicking. I wrote this script :

```
 <script language="javascript" type="text/javascript">
      function submitDetailsForm() {
           $('#poll-view-voting').submit();
       }
 </script>

```

But this code submit first form only(the forms has one id). Console.log retrieve this:

```
[form#poll-view-voting, context: document, selector: "#poll-view-voting", init:  function, jquery: "1.4.2", size: function…]
0: form#poll-view-voting
context: documentlength: 1
selector: "#poll-view-voting"
__proto__: Object[0]

```

How i can solve this issue, help please. I am new in Drupal 7 and JS.

# Answer
> 0 votes
Use **Advanced Poll** module. I think this may help you to solve your query.

---
Tags: forms, javascript, polls
---


title: Perform action on logout,

text:
# Question
Title: Perform action on logout,
I would like to add javascript on logout. I tried using hook\_user\_logout but the javascript doesn't get added.

Even adding something as simple as drupal\_set\_message doesn't result in a message being displayed.

I know the hook is firing because I can add a watchdog message in the hook and see it in the logs. The watchdog message is about the only thing I tried that DID work. Curious about other options that may or may not have results, I tried looking at Actions and Triggers and Rules. I basically decided to try to do something simple on logout, like add a message. But even those modules don't work! I was actually really suprised when Rules didn't work.

I can add messages and do actions elsewhere. Has anyone else had problems with hook\_user\_logout? And does anyone know if it is possible to add javascript with that hook?

Is this some sort of problem involving drupal\_goto? Hmmm. I am on the verge of just adding JQuery to every page to check every link to see if it is a logout link and then adding a click event. It will work for my purposes, but it is such a hack. I would prefer not to.

# Answer
> Even adding something as simple as drupal\_set\_message doesn't result in a message being displayed.

That's the expected behaviour - in the logout hook, you're still inside the authenticated user's session. Once they're logged out, you're not any more. So messages intended for that user are no longer there, because that session has been destroyed.

You should implement a logout/token expiry resource in your API, and invoke that in the logout hook. Then you don't need to remove the token held in local storage, as it will not be valid any more.
> 2 votes

---
Tags: hooks, rules, javascript, actions, users
---


title: Stage file proxy - website under shield

text:
# Question
Title: Stage file proxy - website under shield
I want to retrieve some images from my website to my local Drupal website but my website is under .htaccess password protect so I need to enter a username and password to login. I know the password and username but when I try to get the images through stage file proxy it doesn't work and it's probably because the website is under shield. What should I add in my settings.php file in order for stage file proxy to go through the shield?

# Answer
See module's INSTALL.txt file:

> If the site is using HTTP Basic Authentication (the browser popup for username and password) you can embed those in the url. Be sure to URL encode any special characters:
>
> For example, setting a user name of "myusername" and password as, "letme&in" the configuration would be the following:
>
> $conf\['stage\_file\_proxy\_origin'\] = 'http://myusername:letme%26in@example.com';

Another way, if you have a static IP, is to bypass the Apache auth for certain IP addresses.
> 4 votes

---
Tags: 7
---


# Question
Title: how can I resize user's picture with css
Can someone please help with the above question, I want to display \[current:user-picture\] using token, which has a initial size of 100x100 and resize it to 20x20 with css. But its not working. I'D TRiED TO...
1. Change the image style to 20x20 but its thesame everywhere I use the token
2. «Span class='image-resize'»\[current:user-picture\]«/span».
help me out. If you can suggest another ways to resize the picture.

# Answer
> 2 votes
It is possible to resize an image using CSS but you'll need to make sure you're targeting the img element rather than the span. See this Codepen.

As an alternative you could try using ImageCache Token but there is presently only a dev release and may not be that stable:

Create a new image style, admin/config/media/image-styles/add, to resize the image and then install and enable ImageCache Token to provide you with a token for that image style.

---
Tags: 7, theming, tokens
---


title: Open Atrium: Customizing user badge

text:
# Question
Title: Open Atrium: Customizing user badge
In the Default installation of Open Atrium, Under the navigation bar, on the right side you will see User Badge. For Anonymous user it shows Login text with link and for the authenticated user it shows Username text with image and link and sub menu shows Dashboard, Edit Profile & Logout (all with their associated links respectively).

I want to customize the user badge when user is logged in. I want to add/delete option under the drop-down. Is there any ways to do so?

# Answer
> 1 votes
check the hook

```
function hook_preprocess_oa_user_badge(&$vars) {
  if (user_access('YOUR PERMISSION')) {
    $vars['links']['#links']['YOUR BUNDLE'] = array(
      'title' => t('ITEM TITLE'),
      'href' => 'ITEM URL',
    );
  }
}

```

# Answer
> 0 votes
In oa\_dashboard.module:

```
function template_preprocess_oa_user_badge(&$vars)

```

In oa\_users.module:

```
function oa_users_build_user_details($user, $image_style = 'oa_small_thumbnail')

```

---
Tags: theming, distributions
---


# Question
Title: Display taxonomy term description within the content page
I've a content type with some fields, one of the field is associated with a taxonomy and it has some terms (each term has its own description). Here, when I input the field with the terms and submit the content. The content page appears as:

```
[title] : title of the content.

[field1] :

[field2] :

[taxonomy] : [term1]

             [term2]

             [term3]

```

The content page is viewed with all the fields and taxonomy terms with an anchor/link. I would also like to include the description in its display as

```
[term1] : [description]

[term2] : [description]

[term3] : [description]

```

Any Ideas on how to get this done.

# Answer
> 3 votes
You can do this with the display suite module. Install and enable the ds module. Then you will have a new 'Rendered taxonomy term' formatter. Go to the 'manage display' option for the content type you created. Just select the 'Rendered Taxonomy Term' for the format for your taxonomy field and you will get the description displayed.

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


# Question
Title: Using migrate with a multi-page / paginated source
I have a working module pulling a JSON feed into Drupal using the Migrate module. However, the feed is paginated, and I am only getting the first page of results (ordered DESC on creation, so giving the latest items).

I need to go back through all pages and get all/any changed items, but I can't see how to tell Migrate to iterate through the pages.

# Answer
I would do a 2 step process -- I'm not sure there is a better way using solely migrate.

Use drupal cron and a Queue to fetch all pagination results to a folder containing all the files with json data. Then use your migration(s) to process the data. Drupal has built-in cron and queue APIs; but you could just use a Linux system cron, bash or CuRL if you like.
> 2 votes

# Answer
You can parse paginated sources with migrate but it takes a little work overriding `MigrateListJSON` \- you may want to ignore the `$jsonContainer` part - that's just because the result set in our service is in a container (hence this class is abstract).

```
abstract class BSBaseMigrateListJSON extends MigrateListJSON {
  /**
   * String containing the JSON container name.
   */
  protected $jsonContainer;

  /**
   * Contains the default limit for pagination of the service.
   */
  protected $serviceLimit = 50;

  /**
   * Return an array of the IDs found in the list URL.
   */
  public function getIdList() {
    migrate_instrument_start("Retrieve $this->listUrl");
    $data = $this->getTree();
    migrate_instrument_stop("Retrieve $this->listUrl");
    if ($data) {
      return $this->getIDsFromJSON($data);
    }
    Migration::displayMessage(t('Loading of !listurl failed:', array('!listurl' => $this->listUrl)));
    return NULL;
  }

  /**
   * Returns the amount of items to be processed.
   */
  public function computeCount() {
    if ($data = $this->getTree()) {
      return count($data[$this->jsonContainer]);
    }
    // Else fail and return N/A results.
    return NULL;
  }

  /**
   * Returns an array of crids.
   */
  protected function getIDsFromJSON(array $data) {
    $ids = array();
    foreach ($data[$this->jsonContainer] as $item) {
      $ids[] = $item['id'];
    }
    return $ids;
  }

  /**
   * Returns the list URL decoded JSON response.
   */
  protected function getTree() {
    $items = array();
    $offset = 0;

    do {
      $url = $this->rebuildUrl($offset);
      $json = $this->getTreeData($url);
      $data = drupal_json_decode($json);
      $items = array_merge($items, $data[$this->jsonContainer]);
      $offset += $this->serviceLimit;
    }
    while ($data['moreResources'] == TRUE);

    // Return data if any is present.
    if (!empty($data)) {
      $data[$this->jsonContainer] = $items;
      // @todo Consider whether just returning $items is feasible.
      return $data;
    }

    Migration::displayMessage(t('Loading of !listurl failed:', array('!listurl' => $this->listUrl)));
    return NULL;
  }

  /**
   * Returns a constructed url with offset if required.
   */
  private function rebuildUrl($offset = 0) {
    $url_parts = parse_url($this->listUrl);

    // Build the query parameters.
    if (isset($url_parts['query'])) {
      parse_str($url_parts['query'], $url_parts['qparts']);
      foreach ($url_parts['qparts'] as $key => $value) {
        if ($value === '') {
          $url_parts['qparts'][$key] = NULL;
        }
        elseif ($key === 'q') {
          $url_parts['path'] = $value;
          unset($url_parts['qparts']['q']);
        }
      }
    }

    // If the offset is zero then we can simply return the original list URL.
    if ($offset == 0) {
      // Handles overriding the service limit if there's already a limit set in
      // the list URL.
      if (!empty($url_parts['qparts']['limit'])) {
        $this->serviceLimit = $url_parts['qparts']['limit'];
      }
      return $this->listUrl;
    }

    // Add the offset to the query parameters.
    $url_parts['qparts']['offset'] = $offset;

    // Build parameters to pass to the url function.
    $url_params = array(
      'path' => $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'],
      'options' => array(
        'query' => isset($url_parts['qparts']) ? $url_parts['qparts'] : NULL,
        'fragment' => isset($url_parts['fragment']) ? $url_parts['fragment'] : NULL,
        'external' => TRUE,
        'https' => (bool) $url_parts['scheme'] == 'https',
      ),
    );

    return url($url_params['path'], $url_params['options']);
  }

  /**
   * Returns the data from the given list URL.
   */
  private function getTreeData($list_url) {
    if (empty($this->httpOptions)) {
      return file_get_contents($list_url);
    }
    $response = drupal_http_request($list_url, $this->httpOptions);
    if (!empty($response->data)) {
      return $response->data;
    }
  }
}

```

This code probably won't work as-is for you as it's specific for our service, you'll most definitely need to change this line: `while ($data['moreResources'] == TRUE);` and anything to do with `offset` depending on how your service works but it's a start for how to proceed.
> 3 votes

---
Tags: 7, migrations, paging
---


# Question
Title: How to allow more roles can add users in Drupal 7?
I have created Four Roles – A, B, C, D

Home » Administration » Configuration » People – I have set visitors can create an account. A, B, C roles could register from my front end site. And I want that My C role users could create A and D role accounts. I have assigned permissions “Administer users” and “View user profiles” to my C role user. Now my C role user can view link “admin/people”. Here I want to control “Show only users where” and “Update options” form. Just like - “Show only users where” form shows only two roles A and D and other relevant thinks

Please give me some advice...

My English is not good... Sorry for it

# Answer
You can do this using Views and Views\_bulk\_update module. First, install both these modules. Don't forget to enable views\_ui module also.

Then go to Structure-\>Views. Create a new view with page-display and fetching user's data.

Now, add the relevant fields there, like user-name, email etc. Now, in the filter section, add a filter of "role" and expose it. You can add more filters and expose them.

Also, add fields regarding bulk operations and select the operations you wish to perform e.g. changing email, deleting user.

Now, give this page a "path" in the page-setting section.

Finally, save this view and go to the path you gave it. It should be up and running.

PS: If you couldn't comprehend above, you will need to learn views module. It's a very powerful module and needs some time to grasp. See some videos on youtube to learn it. For your simple purpose, it would take an hour or so to learn.
> 1 votes

---
Tags: users
---


title: How to make a menu like this one?

text:
# Question
Title: How to make a menu like this one?
This menu looks really nice. Im trying to do one similar. Any suggestions on how to start and what modules should I use.

# Answer
> 1 votes
There is a module for that. Its called TB Mega Menu. It allows you to add markup and stuff to a menu. It's pretty robust, if this is not what you are looking for then you will need to look into a custom solution such as a module or using views.

# Answer
> 1 votes
First, you could use modules like TBMegaMenu as chadpeppers already suggested. It's really robust and stable. If you are willing to pay, you could also go for MD-Megamenu.

Second, you could go the manual way by adding theme menu functions in your theme's template.php file. Drupal core provide functions like theme\_menu\_tree and theme\_menu\_link.

There is also another unique approach using menu\_views module. If your theme supports dropdown menu, then just install menu\_views module. Then create a view containing the list of your items. Now, add a new menu item and set its menu-item-type to views. You will get a list of available views. Select your view, and save the menu item. Now move this menu item under another menu i.e. make it a child of another item. Save the menu.

Now, when you will click the parent item of that views-menu item, you will see the view in the dropdown. This view can be styles as you wish using the various display options available. Possibilities are immense if you are comfortable with views.

---
Tags: routes, navigation
---


# Question
Title: How to open a new form in a block without reloading whole page?
I am using Webform with ajax mode. I have added the Webform in block so as only the block is refreshed instead of whole page, it's working fine.

All I want to do is open new form after getting confirmation message without reloading whole page.

How can I do so?

# Answer
You need to set the "Redirection Location" to "No redirect (reload current page)" in actual webform settings *(/node/x/configure)*. This will show the confirmation message in block without reloading and provide a link "Go back to form" which will reload your form by ajax.
> 1 votes

---
Tags: 7, ajax, webforms, javascript
---


# Question
Title: Use an existing Drupal site to create a new site
Today I tried to copy a existing Drupal site for creating a new one on a other domain-name.

The problem: the new website still uses the old DB. So if I create a new user for example, this user also show up in the other (first) website. The same thing for deleting content.

What did I do:

1. Created a new DB for the new website.
2. Backup the DB form the old website and find/replace the domainname to the new domain-name is the sql-file.
3. Import the SQL into the new DB
4. Copy the website-drupal folders from the old website - change the setting-file in map DEFAULT with the new DB info. (so it connects to the new DB - after that i FTP the files to the new host.

When I visit the new domain-name a copy of the website showed up and I could login. The first thing I wanted to do was delete all content and users. But seems to be the actions I do in the new website also happens in the old website.

I did a search on Google and find out I did have to change some info in SQL-file. First time I did not do that so I did everything again... so also with step 2)

But the new website seems to be still connecting to the old website. I erased the DB of the new site and the website is still working. So it makes still contact with the OLD DB.

So changing the settings-file and SQL file was not enough.

What did I do wrong??

Any tips, links are welcome!

# Answer
Hmmmm, you that settings.php should be the ticket, but to really trouble shoot it, it would be easier to see the code. But because that contains your DB connection, that's not something that you should be sharing with others. However, if your having troubles, you could always try going about this a different way.

You could start with a blank db, and toss your settings.php file. That will cause Drupal to think it isn't installed yet, and will take you through the install process. Once your done with that and have a clean Drupal site running on a clean DB, then you can dump your data from your old site into the new DB, which should transfer your data over, but you'll have a fresh settings.php file. That might be easier way to go about it.
> 0 votes

---
Tags: database
---


# Question
Title: Css class for Custom Content type fields
I'm using seven theme for creating a basic pages. In that created more content types including title and body as shown in figure.

The page appear like this.

Is it possible to add css class/styles for arranging beautiful manner. Like add custom css class for channel and language ..... How can I do this please? Thanks!

# Answer
> 1 votes
You can use the Display Suite module to control the wrappers of each field or add classes:

Drupal adds a lot of classes already, so you can probably look at the existing markup that Drupal is outputting and style it based on the classes that are already there.

---
Tags: views, 7, nodes
---