# Question
Title: Enumerate content in custom view template
I am very new in Drupal. I am using Drupal 7. I would like to create a custom rendering for a view I have created. Thanks to many posts found on the internet I have already done the following steps:

1. Created a content type with Title and URL (it simulate a link list)
2. Added 4 items of this content type
3. Created a view which return items of my content type unsorted
4. Thanks to the Theme Information link I have created a template named `views-view--xxxx--page.tpl.php` where xxxx is the name of my view.
5. I have added the following code to the TPL file

> ```
> <article id="node-123456">
>     <header>
>         <h1>Sample Title</h1>
>     </header>
>     <div class="content">
>     </div>
>     <footer> </footer>
> </article>
>
> ```

And this works perfectly because I am seeing the `Sample Title` text when navigating on the page. I want now to enumerate the list of content item produced by the view but I dont know how to enumerate them. I have tried with

```
<ul>
<?php foreach ($rows as $id => $row): ?>
    <li><?php print $view->render_field('field_url', $id);?></li>
<?php endforeach; ?>
</ul>

```

# Answer
> 0 votes
Welcome to Drupal!

Use row level templating in template suggestion and follow exactly the same markup so your code should look like the following

```
<article id="">
    <header>
        <h1><?php print $fields['title']->content; ?></h1>
    </header>
    <div class="content">
    </div>
    <footer> </footer>
</article>

```

It will follow the same markup for each row.

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


# Question
Title: Display child terms in term taxonomy page
I have a vocabulary named "Catagory" with a term tree structure including parent and child taxonomy terms.

In every term's page I want to display all the child terms for that current term. Terms are using alias. As far as I understand it can be acheived with views, but how?

Thanks!

# Answer
* Set up a new view of type "taxonomy terms"
* Give the view a "block" display (not a page)
* In the "advanced" section of the view (on the right) you can set up a "contextual filter" based on "parent term".
* The trick to making this work with a block is to select the "Provide default value" option and select "raw value from url" "path component 3". This will send in the id of the parent term from the url (works even though your term is aliased).
* Go to admin-\>blocks and put that block in the "footer" region; set it to only appear at the url taxonomy/term/\* (this will work even though your term is aliased).
> 3 votes

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


# Question
Title: Update drupal modules without updating core in one drush command
Is there a way to update all contrib modules without updating core in one drush command. For example:

`drush up` updates all modules and core. Is there a way to ignore core and just update the modules without having to list out each module name?

# Answer
You can use the `--no-core` flag.

```
drush upc --no-core

```

https://drushcommands.com/drush-8x/pm/pm-updatecode/
> 16 votes

---
Tags: 7, drush
---


# Question
Title: How to output every second grouping in views?
I have a view that outputs a list of nodes and their taxonomy terms. I use taxonomy field as grouping field. So I get:

```
Tax1 (article1, article2, article3 )
Tax2 (article4, article5, article6 )
Tax3 (article7, article8, article9 )

```

etc.

View makes markup for each group like this:

```
<div class="view-grouping">
<div class="view-grouping-header">
<div class="view-grouping-content">
<div class="views-row views-row-1"></div>
<div class="views-row views-row-2"></div>
<div class="views-row views-row-3"></div>
</div></div>

```

Question:

How is it possible to output every second grouping?

I would like to have 2 columns with 2 views, first view would output every second grouping and second view would show other groupings.

I'm using Views 3.

# Answer
> 1 votes
This seems like a good use-case for a theme override.

If you click the "advanced" section in the view and click "Theme Information" at the bottom, you'll get a list of theme names. Click on "Style output" and copy the code, and paste it into a file in your theme folder with the most specific name possible (at the end of the list starting with "views-view-unformatted.tpl.php").

Not sure if there's a more elegant way to get a row count (it doesn't seem to be an available tpl variable) but you can DIY like so:

```
  <?php function count_this_view() {
    static $count = 0;
    return $count++;
  }?>

```

Then wrap your tpl in a conditional like

```
  <php if (count_this_view() % 2) :?>

```

---
Tags: 7, views
---


# Question
Title: How to rsync files between two remotes which share the same host?
I've two remotes: `@remote.dev` and `@remote.test`.

I'm trying to rsync between these two remote Drupal instances by:

```
$ drush -vy rsync @remote.dev @remote.test

```

But rsync complains that:

> The source and destination cannot both be remote.

Both remotes are on the same machine, but they're using different path.

Is there any workaround?

# Answer
Normally you can't use two remotes for rsync, but because these two instances are on the same host you may use `drush dd` to return the filesystem path and use it as a source.

In example (syncing webroot):

```
$ drush -vy @remote.test rsync `drush dd @remote.dev` @self

```

or syncing just files folder:

```
$ drush -vy @remote.test rsync `drush dd @remote.dev:%files` @self:%files

```

This will work if you're using the same credentials for both.
> 2 votes

---
Tags: drush, deployment
---


# Question
Title: Defining the primary address of a CiviCRM contact
I have a webform with CiviCRM fields on it (webform 7.x.4.1, civicrm\_webform 7.x-4.9).

I have configured 2 addresses fieldset, one for work address and one for home address. I find it non intuitive to let the user choose the location for each address and set the first one as the primary. So i have instead defined one field that let the user choose which one is its primary address (simple select field with Home or Work value).

Now, i need to synchronize this with CiviCRM after the form is submitted. I use hook\_webform\_submission\_insert and hook\_webform\_submission\_update.

My question is : what is the best way to define which address is the primary for a contact (the address are already saved in the database). Api ? other ?

Alternative question : maybe there is another (more simple) way to do the same thing ?

# Answer
Webform-CiviCRM will always set the first address as "primary".

You don't need to expose the location-type field if you don't want to - you can set it on the backend form. This has the downside of forcing the location type of the primary address to change to whatever you've set the first address to.

Here is a solution that will solve your problem for both creating and updating contacts, and you don't need to resort to custom code and hooks:

* Set the location-type field for both addresses to be exposed (user select)
* Change both location-type webform fields to type "hidden"
* Set the default value for the first one to be "home" and the other "work"

Now when the user updates their address, the location type will not be changed (your default values will be overwritten by the existing data). But when creating new addresses you'll be setting sensible defaults.
> 5 votes

---
Tags: webforms, civicrm
---


# Question
Title: Why my site is blocked by too many connection errors?
I've created a simple website with a few pages on my local computer. I have Drupal installed in my XAMPP directory, so the directory looks like this: `c:\xampp\htdocs\drupal\<all the drupal files sit here>`.

I've signed up for a domain and I'm trying to upload my Drupal site to the web hosting company to go live.

I searched for many sites for step-by-step instructions how to do it. This is what I got and this is what I did:

1. Backup my drupal database on my computer.
2. Create a new blank database on the host.
3. Upload my local files on my computer to the host (I assume I need to upload all the files inside the Drupal directory, is that correct?)
4. Import my backed up database to the host.
5. Change the `settings.php` in the host. Is that the only file and place I need to change?

This is what I changed:

```
$databases = array (
'default' =>
  array (
    'default' =>
    array (
    'database' => 'yyyyy_xxx',   <== Can I use a different database name than the one I use on my localhost?
    'username' => 'yyyyy_xxx',   <== Can I use a different username than the one I use on my localhost?
    'password' => '12345',       <== Can I use a different password than the one I use on my localhost?
    'host' => '<www.my new site's domain name.com>',    <== Should I be using my new site's domain name here or localhost since all the files are sitting at the web hosting company's server?
    'port' => '',
    'driver' => 'mysql',
    'prefix' => '',
   ),
 ),
);

```
6. When refreshed my webpage and I've got the following error:

```
Error:
The website encountered an unexpected error. Please try again later.
Error message:
PDOException: SQLSTATE[HY000] [1129] Host 'box373.bluehost.com' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts' in lock_may_be_available() (line 167 of /home3/<my website>/public_html/includes/lock.inc).

```

I've logged into my account on the hosting company using Putty and went to `public_html/` and entered `mysqladmin flush-hosts`. Now I've got the error:

```
mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'xxx'@'localhost' (using password: NO)'

```

The `xxx` is the database name I used on my localhost. The new database name on the host is `yyyy_xxx`. Is it still referring to my localhost database even though I've changed the settings in settings.php file on the host?

I would appreciate if somebody can help me and give me some insights how to fix this problem.

Is this the correct procedure to upload files to the host for my website to go live? Besides `settings.php` file, are there any other files I need to change? How do I unblock `mysqladmin` using `flush-hosts`? Some websites suggest to include username and password to login to `mysqladmin`. I've entered `mysqladmin -uyyyy_xxx -p12345 flush-hosts` and I got the following error:

```
mysqladmin: refresh failed; error: 'Access denied; you need (at least one of) the RELOAD privilege(s) for this operation'

```

How do I prevent this problem to happen again? I just uploaded a few files to the host and I got this problem. In the future, I am going to upload the complete website to the host with way more files. I would like to find out the correct way to launch a Drupal website.

# Answer
MySQL blocks clients which error made while connecting to protect MySQL from malformed client.

So first, you need to find what sort of error it is.

In example by checking MySQL error log in data directory (typically **hostname.err**) or if you've drush installed, by `drush watchdog-show`.

You may also increase `max_connect_errors` (what is current value?) maximum value depends on architecture (check Manual).

But this is not real solution if error is frequently occurred.

`FLUSH HOSTS` can help you to eliminate blocked host. E.g.

```
mysql> FLUSH HOSTS;

```

Source: Why MySQL connection is blocked of many connection errors?

Please note that to use `mysqladmin` properly, you need to have access to `root` account. If you don't have it, use `FLUSH HOSTS` command as above.
> 1 votes

---
Tags: 7, migrations
---


# Question
Title: Block with the same function as page of Taxonomy term view
Is there any way to replicate as block which displays all nodes associated with the end of the url, like page view ( Taxonomy term view -A view to emulate Drupal core's handling of taxonomy/term.) but in a block. Example in url news/term1 the block should be able to show all nodes with the term term1.

Thank

# Answer
* Set up a new view of type "node"
* Give the view a "block" display (not a page)
* In the "advanced" section of the view (on the right) create a relationship to "taxonomy term"
* you can set up a "contextual filter" based on "taxonomy term".
* The trick to making this work with a block is to select the "Provide default value" option and select "raw value from url" "path component 3". This will send in the id of the parent term from the url (works even though your term is aliased).
* Go to admin-\>blocks and put that block in the "footer" region; set it to only appear at the url taxonomy/term/\* (this will work even though your term is aliased).
> 3 votes

---
Tags: taxonomy-terms
---


# Question
Title: Retrieve a list of values from a lookup table using db_select
I have a "jobs" table where each job can have multiple specialties. So I have a specialties table with a list of all available specialties and I have a lookup table that just has a job\_number and a specialty\_code in it so each job can be attached to multiple specialties. What I am trying to figure out is when I do a db\_select, how can I have the job record print out once, but have a list of it's specialties print out also as part of that record? Here is what I have right now for my query:

```
$query = db_select("jobs", "j");
$query->fields('j');
$query->join('job_specialties', 'js', 'j.job_number = js.job_number');
$query->join('specialties', 's', 's.specialty_code = js.specialty_code');
$result = $query->distinct()->execute();

```

This gives me the correct records, but I want to display the list of specialties each job is attached to and that's where I'm not sure how to do that. Is there even a way using the database API to do that?

Essentially I would want to be able to display the records something like this. This is only one record, but you get the idea.

```
<table>
  <thead>
    <tr>
      <th>Job Number</th>
      <th>Title</th>
      <th>Location</th>
      <th>Specialty</th>
    </tr>
  </thead>
  <tr>
    <td>12345</td>
    <td>Some Cool Job</td>
    <td>California</td>
    <td>SQL<br>HTML5<br>JavaScript</td>
  </tr>
</table>

```

# Answer
Add more fields to your query from the other tables that you have joined to:

```
$query->fields('js');
$query->fields('s');

```

Use hook\_menu() to create your page if you want a custom one, then render it in PHP (I'm guessing at your result variable):

```
<table>
  <thead>
    <tr>
       ....
    </tr>
    <tr>
      <th><?php>$result['job_number']<?></th>
      .....
 </table>

```
> 0 votes

---
Tags: database
---


# Question
Title: Output tabs and content in different regions?
The default behaviour of Quicktabs is to make accessible a block containing the tabs and the linked content. That doesn't meet my requirements, unfortunately.

Is there any way of theming Quicktabs module (7.x-3.2) in such a way, that the tabs are output in one region (eg. right sidebar in `page--nodetype.tpl.php`) and the linked content is displayed in the main content region? Or is it stretching the concept of tabs too far?

# Answer
> 3 votes
I am also trying to achieve the same result. I found this patch for an older version of quicktabs that never really got off the ground I guess.

http://drupal.org/node/1085116

I think it would be an appropriate feature.

EDIT:

Using a few ideas from the patch above, I have come up with a quick mod that splits the block into two blocks for each tab instance. Just edit your quicktabs.module as follows.

Simply add a second block definition:

```
function quicktabs_block_info() {
  $blocks = array();
  foreach (quicktabs_load_multiple() as $qt_name => $quicktabs) {
    $blocks[$qt_name]['info'] = $quicktabs->title;
    $blocks[$qt_name . '_qt_content']['info'] = $quicktabs->title . ' - Content';
  }
  return $blocks;
}

```

Then alter the block\_view function as such:

```
function quicktabs_block_view($delta = '') {
  $block = array();

  // Check if it is the content block or not
  substr($delta, -11) == '_qt_content' ? $content_tab = 1 : $content_tab = 0;
  if($content_tab) {
    $delta = substr($delta,0, strrpos($delta, '_qt_content'));
  }

  if ($qt = quicktabs_build_quicktabs($delta)) {
    if (isset($qt['content']) && !empty($qt['content'])) {
      $block['content'] = $qt['content'];
      $block['content']['#contextual_links']['quicktabs'] = array('admin/structure/quicktabs/manage', array($delta));
      $block['subject'] = check_plain($qt['#title']);
      // remove either the tabs or content depending on the block
      if($content_tab){
        unset($block['content']['content']['tabs']);
      }else{
        unset($block['content']['content']['container']);
      }
    }
  }
  return $block;
}

```

It isn't the most elegant mod, but it does the job with little changes. All you have to do is add the original block (tabs) and the new contant block to wherever you want.

# Answer
> 2 votes
A bit late, but I'm happy to announce that, thanks to the great suggestion here by MWay, we've created a contributed module called Quicktabs XT with some nice out-of-the-box (pun slightly intended) features such as controlling which Quicktabs should have a separated navigation through the GUI.

This saves you from having to hack the Quicktabs module, and allows you to receive updates to Quicktabs and the new Quicktabs XT module.

You can download it here:

https://www.drupal.org/project/quicktabs-xt

---
Tags: 7, theming, blocks
---


# Question
Title: What is the best way to tell anonymous users apart?
My company wishes to split their website so that anonymous users are given slightly different sites based on a question when they first visit.

I intend to use a cookie to store the answer to the question between sessions, but I'm wondering what the best way is to use that answer once the user is browsing the site? I intend to use page manager to handle the context but I'm still trying to determine where it should be stored:

* Cookies can be turned off by the user, or the IT department, much of our target audience have policies restricting or outright banning cookies
* Session variables seem to be the way to go, unless:
* Does the Global $user variable store different information for each anonymous visitor?

Are there downfalls in either of the latter two options? Have I missed any options?

# Answer
> 7 votes
> Session variables seem to be the way to go

Don't forget that session variables rely on cookies

> Have I missed any options?

---
Tags: sessions, cookies, chaos-tool-suite
---


# Question
Title: Why my first tab is missing for local menu tasks defined by hook_menu()?
I am learning how to use hook\_menu(). I am at a point where I have a question and not figure it out. I have a local task button inline with View and Edit and I want 4 sub-local\_task buttons. See chart below.

```
View | Edit | **Outcomes** |

*Outcomes Viewer* | Add New User | Add Bulk Ghost | Registration Report

```

However, the first button(*Outcomes Viewer*) is missing and I cannot figure out how to get it to show up. Below is the menu code within the function. The *Outcomes Viewer* is a view. I am mixing this with some custom code and views as well. (\*Drupal 7, Views 3)

```
$items['node/%node/ecg-outcomes'] = array(
    'title' => 'Outcomes',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 50,
  );
  $items['node/%node/ecg-outcomes/'] = array(
    'title' => 'Outcomes Viewer',
    'access arguments' => array(1),
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => -10,
  );
  $items['node/%node/ecg-outcomes/add-bulk-ghost'] = array(
    'title' => 'Add Bulk Ghost',
    'page callback' => 'entity_ghost_participant_report',
    'page arguments' => array(1),
    'access callback' => 'entity_ghost_participant_access_report_tab',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'file' => 'entity_ghost_participant.reports.inc',
    'weight' => 11,
  );
  $items['node/%node/ecg-outcomes/add-new-user'] = array(
    'title' => 'Add New User',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 14,
  );

```

# Answer
You need 3 menu items and 2 view pages. The parent menu and the default menu will share some configuration.

```
  $items['node/%node/ecg-outcomes/add-new-user'] = array(
    'title' => 'Add New User',
    'page callback' => 'SOME CALLBACK',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => -9,
  );
  $items['node/%node/ecg-outcomes/add-bulk-ghost'] = array(
    'title' => 'Add bulk',
    'page callback' => 'SOME CALLBACK',
    'access arguments' => array(1),
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK ,
    'weight' => -8,
  );
  $items['node/%node/ecg-outcomes/registration-report'] = array(
    'title' => 'Registration Report',
    'page callback' => 'SOME CALLBACK',
    'access arguments' => array(1),
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK ,
    'weight' => -7,
  );

  return $items;

```

As the outcome-viewer is set up as a view and you want it as the default menu tab, you need to set up two almost identical pages in your view as follows:

**View Page 1:**

```
Path: node/%/ecg-outcomes
Menu: Type : Menu tab, Title : Outcomes, weight : 50

```

**View Page 2:**

```
Path: node/%/ecg-outcomes/outcomes-viewer
Menu: Type : Default menu tab, Title : Outcomes Viewer, weight : -10

```

**METHOD 2** I think it can also be done with 4 menu items and 1 view page, in which case you only define view page 1, and include this menu item:

```
$items['node/%node/ecg-outcomes/outcomes-viewer'] = array(
    'title' => 'Add New User', // NO page callback and access callback necessary
    'type' => MENU_LOCAL_TASK,
    'weight' => -9,
);

```
> 0 votes

---
Tags: routes
---


# Question
Title: How do I check which of my installed modules is unsupported?
When I go to `admin/modules`, I get this scary warning:

> The installed version of at least one of your modules or themes is no longer supported. Upgrading or disabling is strongly recommended. See the project homepage for more details. See the available updates page for more information and to install your missing updates.

That sounds like something I'd like to fix! So I click the "available updates" link, but that page tells me:

> All of your projects are up to date.

Hmmm. I tried checking for updates with Drush (`drush up`) but Drush doesn't find any updates either. **How can I find which modules installed in my site are unsupported?**

# Answer
> 4 votes
As stated here, you need to go to admin/reports/updates rather than admin/reports/updates/update to see which module is having the problem.

---
Tags: 7
---


title: create menu filter price product

text:
# Question
Title: create menu filter price product
salute you. I have one problem need your help. I want to create 2 menu list of product categories and product prices. there should be a link between two product categories menu to the product menu to display the products desired by the user. for example i have 2 menu after

categories:

* dell servers
* ibm server
* hp server

price:
* $ 100 to $ 500
* $ 500 to $ 1000
* $ 1000 to $ 2000

When I click on dell server it will display all the products dell server and when I continued to click $ 100 to $ 500 it will display the products of dell servers have priced 100 $ to 500 $. thank you

# Answer
What you're looking for there is not a menu but faceted search, the best way to do this is to install and configure Apache Solr Search and Facet API.
> 0 votes

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


# Question
Title: Drupal 7: Webform Emails: How to change content based on a condition?
I have a webform and I want to send email on submission to this form.

Currently, I configured the emails and its working fine. However, I would like to put conditions on sending the email. Like if field\_1 = "xyz" then change the email content to "abcd" else change email content to "pqrs"

Can this be done using the inbuilt module for emails? Please help

# Answer
I reckon you can get there just using Webform and applying some Conditions. Here is the recipe I just tested.

1. Add a 'country' select field, with options NZ and USA
2. Add a 'usa1' textfield, set as private, and enter default value you want to go in your email when USA is chosen ('love usa').
3. Ditto for an NZ textfield (nz1) ('go nz').
4. Now set up a condition that will 'show' (to admins only as it is private) the USA text field when USA is chosen as country,
5. ditto a condition so if NZ is chosen, the NZ text fields 'shows'.
6. Now set up your email with eg \[submission:values:usa1\]\[submission:values:nz1\]

and presto hey!

If i select USA as country I get email saying 'love usa'. if i chose NZ I get 'go nz'

Is that pretty much what you need?

NB: I thought this route would work as we had done similar when we needed an email to go out to addressX 'only' if a user chose USA as country. We used webform conditions and We craeted an email field that was set to private. Then used conditions to 'show' it (to admin only) if USA was chosen. Then we could just set up a new webform email using that field, and it only fired if the condition was met.
> 11 votes

# Answer
I would probably use the Webform Rules module (https://www.drupal.org/project/webform\_rules) and then create a rule that on submission of the form, it is sent to the appropriate role or a specific email address is that was required.
> 1 votes

# Answer
You can change the rendering of a webform submission easily. See hook\_webform\_submission\_render\_alter.

I wrote this code 2 days ago to change a submission embedded in a View, and also change the submission's appearance in a PDF from webform2pdf. The same approach is doable using Emails. I hate webform 4's new tokens. I bypass them completely.

```
/**
 * Implements hook_webform_submission_render_alter().
 *
 * Add a download PDF link to the beginning of the submission view.
 */
function MYMODULE_webform_submission_render_alter(&$renderable) {
  // use Devel to see what $renderable array looks like.
  // dpm($renderable);

  // If we're on a custom View path embedding a submission, add a download
  // link.
  if (current_path() == 'open-applications') {
    $nid = $renderable['#node']->nid;
    $sid = $renderable['#submission']->sid;
    $download_pdf_link = l('Download Pdf', "node/$nid/submission/$sid/downloadpdf");
    $renderable['reference_regarding']['#prefix'] = $download_pdf_link.'<br>';
  } else {
// DEBUG
// ... if we wanted to prefix the $renderable array with say a <style> tag
// we could do that via  #prefix. I couldnt get this to work for PDFs.
//    $renderable['reference_regarding']['#prefix'] = '**' . substr(current_path(),-11) . '**';
  }
  // This glorious hack from: https://drupal.org/node/1597892
  //
  // and see:
  // http://drupal.stackexchange.com/questions/50086/how-to-use-submissionvalues-in-email-template-in-webforms

  // If we're downloading a PDF, checking the page url, then append break tags
  // after a title.
  if (substr(current_path(),-11) === 'downloadpdf') {
    foreach ($renderable as $i => $item) {
      if (is_array($item) && !empty($item['#title'])) {
        $renderable[$i]['#title'] .= "<br>";
      }
    }
  }
  // Unset a hidden webform field from viewing, which I have pointing to a
  // Relation ID.
  unset($renderable['webform_rid']);
}

```

Like I said I bypass the use of tokens in my PDF with the use of a helper function and also custom PHP in the PDF content body (you could do the same for your email body):

```
/**
 * This function builds an array of HTML fragments of rendered submissions from
 * a collection of Submission IDs.
 */
function _MYMODULE_render_reference_submissions($sids) {
  $content = array();
  if (count($sids)) {
    module_load_include('inc', 'webform', 'includes/webform.submissions');
    $webform_nid = 1;
    $webform_node = node_load($webform_nid);

    foreach ($sids as $sid) {
      $submission = webform_get_submission($webform_nid, $sid, TRUE);
      $webform_renderable = webform_submission_render($webform_node, $submission, 'test@test.com', 'html');
      $content[] = drupal_render($webform_renderable);
    }
  }
  return $content;
}

```

My PDF body content custom PHP code (requires Core PHP input being enabled) is as follows:

```
<?php
// path of a submission PDF download is of the format:
// node/1/submission/1/downloadpdf
$path = current_path();
$parts = explode('/', $path);
$sid = $parts[3];
$content = _MYMODULE_render_reference_submissions(array($sid));
return $content[0];
?>

```

Webform submissions can be rendered as like `plaintext`, `html` and something else I think out of the box via the `$format` value passed into `webform_submission_render`.
> 0 votes

---
Tags: webforms, emails
---


# Question
Title: How can I get the email field value from a webform and use the rules module to send mail on submit event?
How can I get the value of the email field value in a webform and apply it in

rule \> action \> send email \> to address

I have tried using a token but could not get the value.

# Answer
If you have an email field on the webform then that field will be available to you at webform/emails in the selector alongside the radio button = Component Value

That then becomes the 'to' field unless you then overwrite it.

You will also find 'select' type fields in that selector as you can then set email address for each of the options in the email settings directly.

You would use this if for example you had a field on the form for 'country' and needed to send the submission to different contacts based on which country was chosen.

Hope that helps
> 8 votes

# Answer
i got the vale from rule data replacement in the data section which has \[data:data\] contains all data of webform content and through \[data:"component\_key\_value"-value\] we will get the value of the component,the double quotes should not present while replacing component key value
> 1 votes

---
Tags: webforms
---


# Question
Title: Drupal Commerce Authorize.net gateway and POODLE
I got a notice today that Authorize.net is going to shut off their SSLv3 protocol on November 4 (7 days from today) in response to the POODLE threat. I'm using Drupal Commerce's commerce\_authnet module to accept credit cards on our web storefront, how can I tell whether I connect via SSLv3? And if I do, how can I change that to connect via TLS or whatever I need to do?

Thanks.

# Answer
> 7 votes
The commerce\_authnet module is using the PHP curl() functions to communicate with Authorize.net, and it does not explicitly requests the SSLv3 protocol in the curl options (see file commerce\_authnet.module, lines 1163 to 1172).

curl will therefore rely on the HTTPS handshake to determine the protocols and ciphers, and since the Authorize.net will not advertise SSLv3, another protocol will be selected during the handshake (most certainly TLS v1.2).

So you have nothing to change, the transition will be handled automatically by the HTTPS handshake. I would only advise you to upgrade your openssl library to the latest version.

---
Tags: commerce, security, ssl
---


# Question
Title: What Continuous Integration System is most geared?
I am looking for a Continuous Integration System to use with Drupal 7. Preferably it should be widely used and easy to support.

Do you have any thought?

# Answer
> 7 votes
Among open-source PHP projects, the two most widely-used CI implementations are easily Jenkins (***jenkins-ci.org***) and Travis (***travis-ci.org***). Both have significant communities, and you can find examples of using them with Drupal (eg ***wiki.jenkins-ci.org/display/JENKINS/Drupal+Development*** and ***www.vmdoh.com/blog/how-we-test-drupal-7-modules-travis-ci***).

Between the two:

* Jenkins' positioning is more like Drupal's -- it's an open-source product with a lot of add-ons/options/features, but you have to think a lot about deployment and picking options. It's useful for testing and many other things (e.g. deployment, nightly tarballs, cron-jobs).
* Travis is a proprietary SaaS offered on a freemium basis -- free for public/FOSS code; paid otherwise. It's generally easier to setup because Travis provides servers and bundles more features in the default. It has a more focused/limited range of use-cases.

For some specific features that differentiate them (at time of writing):

As a rule of thumb:

* If you have a large project (with lots of code, lots of tests, peculiar integrations, some budget), then Jenkins' deeper feature-set and configurability make it the better choice.
* If you have a small project published on Github (e.g. an individual Drupal module or PHP library with no budget), then Travis's simplicity and bundling make it the better choice.
* If your project is in between, then there is no clear rule of thumb; it's a judgment call.

Aside: You may find buildkit.civicrm.org interesting. The summaries and explanations are written for an audience that works with Drupal/Joomla/WordPress, although a lot of technical details would need tuning for a Drupal-only audience (e.g. replace "civibuild" with "drush"; replace "Build Types" with "makefiles").

(NOTE: I left several links as plain-text because stackexchange limits the #links from new users.)

# Answer
> 3 votes
I don't think there's a better-than-anything-else reason why you should use *some tool* over other CI tools, they all do pretty much the same thing (get source, do stuff).

I'm using Jenkins at the moment and it works quite well.

At the moment we're using Jenkins to:

1. Fetch the latest code from the code repository
2. Update the database
3. Clear the cache
4. Run tests
5. Generate documentation using Doxygen

You could also add steps for syncing databases, code review, deployment, ... A lot of Drupal specific work (update the database, clear cache, run test) is done using Drush. If you are planning to use a CI system Drush is pretty much a must-have.

Hint: run-tests.sh or `drush test-run` can generate JUnit compatible XML reports, so Drupal tests are supported by default in Jenkins.

Hint: if you're on a multisite installation and you're moving stuff between `/sites/all` and the site specific directory, use Registry Rebuild to fix the registry.

There are lots of plugins available, ranging from deployment to agile dashboards, but we've got a pretty standard setup.

At first it requires some experimenting but once you have the right setup for your team, it's pure profit. The way I see it you'll need to do more thinking on how you're going to organize your configuration (using Features or other exportables) in Drupal.

# Answer
> 0 votes
There are so many now but there isn't so much a clear cut winner. It is a very hard decision because there are so many and they all do a lot of the same things.

Basically I guess you have to decide what your specific requirements are, see which options provide what you need. Then there will probably still be multiple that meet your needs you have to try as hard as possible to find any pros and cons of each (maybe some are better supported, fit your existing technical skillset better, have more community, etc.) and in the end just choose the one you like the best and go with that.

If you wanted and had the time and resources you could also try out a couple of your top preferences and see which you prefer.

Here are some continuous integration related options. Some hosted, some self managed, some with both options. Some aren't focused solely on CI.

Good luck choosing :)

---
Tags: 7
---


# Question
Title: Is it possible to use civicrm stand alone profile page to edit existing contacts?
Is it possible to use civicrm stand alone profile page to edit existing contacts? Is it also possible to alter or override civicrm stand alone profile page via Drupal hook apis?

# Answer
> 9 votes
1. no - since standalone html cannot do smart things like populate stuff from db etc
2. not via drupal hook but civicrm also has a hook system similar to drupal. so u can modify stuff via civi hooks.

If you think SE is a good place for a Q&A forum, please follow and upvote a few questions at:

http://area51.stackexchange.com/proposals/77367/civicrm

lobo

# Answer
> 10 votes
Generally agree with the previous commenters -- you can do an edit screen using "civicrm/profile/edit", and "webform\_civicrm" is generally the next level to go if you want the effect of a standalone profile managed in a Drupal-way. There are hooks for manipulating Civi's profile screens, but they're different from the hooks of typical Drupal forms.

For completeness, we should add some links about Civi's profile hooks. The most concise reference I can think of is:

It's a bit dense, so let's drill down on an example section:

```
civicrm/profile/edit:
    CSS: form#Edit .crm-profile-name-{NAME}
    Region: profile-form-{NAME}
    Hooks: buildProfile($name), validateProfile($name), processProfile($name)

```

What this says: If you're dealing with the page "/civicrm/profile/edit?gid=X", then there are three ways to precisely customize that profile (and no other profiles). All three require that you know the {NAME} of the profile. (This is internal name that corresponds to the DB field "civicrm\_uf\_group.name".)

* To customize with CSS or jQuery, use a selector like "form#Edit .crm-profile-name-{NAME}". (As always, it's helpful to "View Source" and see the precise tags on your form.)
* To append/prepend content programmatically, use a region named "profile-name-{NAME}".
* To execute code while processing the profile, you can use hook\_civicrm\_buildProfile($name), hook\_civicrm\_validateProfile($name), or hook\_civicrm\_processProfile($name).

For information about other Civi hooks, see wiki.civicrm.org/confluence/display/CRMDOC/Hook+Reference .

(NOTE: I left some links as plain-text because stackexchange limits the #links from new users.)

# Answer
> 7 votes
1) It's important to clarify what you mean by "standalone profile page".

a) If you mean the form presented by CiviCRM at e.g. example.com/civicrm/profile then yes. Construct the url like so: ...civicrm/profile/edit&gid=1&reset=1 where ... represents whatever normally comes before civicrm in your site's url, and in gid=1 replace the number 1 with the id of your profile. This will auto-fill the form with the logged-in user's contact record. If you are an administrator and wish to use the form to update a different user, append &cid=123 to the end of the url (where 123 is the id of the contact you wish to update). You can also use CiviMail tokens to allow anonymous users to update their records without logging in.

b) If you mean the html snippet that you can copy-paste, then no. As Lobo mentioned that will not work because the html snippet once pasted will not dynamically based on the logged-in user (it's only html after all)

2) Another recommended tool is the Drupal Webform-Integration module (http://drupal.org/project/webform\_civicrm), which can do all of the above, with the added flexibility of being able to display in a drupal block, or as a panel pane, or anywhere you can display a node. It includes additional features not available for profile forms such as working with multiple contacts, creating activities, etc.

---
Tags: civicrm
---


title: How to backport db_merge() to drupal 6?

text:
# Question
Title: How to backport db_merge() to drupal 6?
I am converting a module from drupal 7 to drupal 6. I have a query in drupal 7. The query contains function db\_merge()

```
   db_merge('facebook_rules_user_tokens')
    ->key(array('uid' => $form_state['user']->uid))
    ->fields(array(
      'user_grant' => $form_state['values']['facebook_rules_allow'],
    ))

```

Which function should I use in d6 for the above sql?

# Answer
> 2 votes
From the MergeQuery docs

```
An ANSI SQL:2003 compatible database would run the following query:

MERGE INTO table_name_1 USING table_name_2 ON (condition)
  WHEN MATCHED THEN
  UPDATE SET column1 = value1 [, column2 = value2 ...]
  WHEN NOT MATCHED THEN
  INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...

Other databases (most notably MySQL, PostgreSQL and SQLite) will emulate this statement by running a SELECT and then INSERT or UPDATE.

```
1. You need to do a `SELECT` using db\_query first, to find out if your data already exists.
2. Then you can use drupal\_write\_record, which will do either an `UPDATE` or an `INSERT` depending on whether or not you populate the tables primary key(s).

---
Tags: 6, database
---


title: mod_expires enabled and cache flush

text:
# Question
Title: mod_expires enabled and cache flush
I my apache I have mod\_expires enabled. My htaccess contains:

```
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On
  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

```

Problem: If I make html change, it is not visible even after flushing all caches in drupal. Question: Is it possible to setup html expiring to say 1 hour and other things like css/scripts/images to say 1 day? Thank you.

# Answer
> -1 votes
If you use boost module "flushing all caches" maybe not work. Go admin \> configuration and open boost configuration, there a tab named "cache expiration" then undo click "Ignore a cache flush command if cron issued the request." I think this usable for you

---
Tags: 7, .htaccess
---


# Question
Title: Webform - Show the preview page on confirmation instead
I have a Webform and there are options that you can set a "preview" page if you want to. I think it's very nice displayed but I want to show this instead on the confirmation page so when a user submits the form it will get posted but the form will be displayed on the confirmation page as it did on the preview page. like a confirmation, this is your Webform that was sent it.

# Answer
You can achieve that like follows

Go to your Webform form settings, then find *Redirect Location* and select *Custom URL*:

Here you can insert tokens but for that you need to install the Token module.

After install and enable the Token module, Click on Browse available tokens link.

Let's say your webform URL path is node/5.

You need to insert Custom URL path like follows

```
node/5/submission/[submission:sid]

```

Then whenever user submits the webform, will be redirected to their webform submission results page.

Hope this simple solution helps you.

There is another way you can achieve that by writing some custom code in tpl files. Follow the Print submitted data on confirmation page
> 7 votes

---
Tags: 7, webforms
---


# Question
Title: How do I speed up `drush test-run` (compared to the SimpleTest UI)?
I have a number of Feature modules for which I've written tests to assure they work as expected. For performance reasons, I've overridden the parent's setUp() method in each test case so that it doesn't create a brand new database each time.

When I run my tests in the SimpleTest admin UI, all of my Feature modules' tests take about 15-20 seconds total to complete. When I run them via `drush test-run [feature-group-name]`, they take about 75 seconds total. I noticed that drush seems to pause in between test cases to output something like the following:

```
Contact page 7 passes, 0 fails, and 0 exceptions  [ok]
No leftover tables to remove.                     [status]
No temporary directories to remove.               [status]
Removed 1 test result.                            [status]
 Group  Class  Name

```

If you're curious, my setUp() function looks like this:

```
public function setUp() {
  $this->setup = TRUE;
  // Prevent PHP warnings about a missing public_files_directory variable:
  $this->public_files_directory = variable_get('file_public_path');
}

```

Any ideas why drush is so much slower than the admin UI? I'd really like to get drush more performant, as I want to integrate these tests into a continuous integration environment.

Thanks!

# Answer
> 6 votes
Consider using "php scripts/run-tests.sh" instead of "drush run-test". The former supports parallel test execution which improves runtime (as long as you have multiple test-classes). Compare:

```
$ php scripts/run-tests.sh --url http://d45.l User
...
Test run duration: 11 min 45 sec
$ php scripts/run-tests.sh --url http://d45.l --concurrency 3 User
...
Test run duration: 4 min 13 sec
$ php scripts/run-tests.sh --url http://d45.l --concurrency 6 User
...
Test run duration: 3 min 7 sec

```

---
Tags: testing
---


# Question
Title: Omega theme responsive grid two break point
I want to make responsive grid with Omega 3 theme. Grids will be 4 columns in large. 2 columns in normal width. 1 column in narrow devices. Is there a way with omega 3 with css classes?

# Answer
> 2 votes
Omega 3 uses the 960 grid, but you can alter it adding a custom 960.

Go to http://grids.herokuapp.com/ and design your grid and override the default one (on a sub-theme).

But I strongly recommend going with Omega 4. Is far more powerful and it is designed to give you the freedom to use any grid or presentation framework you like! If you don't like sass (bad for you) you can just alter the css directly.

Edit: As @Clive mention it, the Omega 5 alpha is out there! It's fantastic and follows all the html/css best practices + complies with D8 standard. Go test it, it's almost stable and your themes will be ready for D8.

Disclaimer: It has been ages since I use the Omega 3.

---
Tags: theming
---


# Question
Title: How to block users to accessing Drupal website if javascript is not enabled?
I checked many pages in Drupal Answers, which didn't have the answer of the following question:

Consider a case that I need javascript to be enabled for visual effects in drupal design.

How can I stop my website and show a message , if javascript is not enabled in user's browser?

Stop means to block the access of user to the website and showing a message like:

Please enable JS in your browser!

(I use Drupal 7.x)

# Answer
It is not possible, not in the way you think of. Workflow is:

1. Server gets HTTP request.
2. Drupal process that request and returns HTML.
3. Browser runs JavaScript, or does not.

As you can see, server never knows if JS is there. If JS is on, you can send AJAX request, but if it's not, you can't do anything at this point.

You have three options:

1. Graceful degradation - this is what I would recommend. Use modules and write code that will simply not fail if JS is not there. It may look differently, that's OK, but should look good and work all right. I recommend these articles: Fault tolerance, Unobtrusive JavaScript
2. Use HTML `<noscript>` tag. It will not hide the rest of your site, but it will tell your users what is happening. This method can be used together with 1st one. Related Q&A: How to Add noscript in head tag (Thanks Wtower for link)
3. Output a page with "Please enable JS in your browser!" message and immediately load real content with AJAX. That's the only way I can think of to make your site work like you want it to, but it is so wrong, on so many levels... Remember, some bots may be unable to index your page if you don't have JS enabled, your users with JS on would see message while waiting for real content anyway, and so on. And while Google can read JS-generated content now, Bing and other search engines apparently still cannot.
> 6 votes

# Answer
I just wrote the following code by reading the answer of Mołot for the question, as follows:

```
function MYMODULE_init(){

  if(current_path()!="enable-javascript"){

    $target = url('enable-javascript', array('absolute' => TRUE));
    $meta = array(
      '#theme' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'http-equiv' => 'refresh',
        'content' => "2; url=$target"
        )
      );
    $noscript = array(
      '#theme' => 'html_tag',
      '#tag' => 'noscript',
      '#value' => drupal_render($meta)
      );
    drupal_add_html_head($noscript, 'noscript');
  }
}

```

Just put the code inside a module, and clear the cache. The reason for the condition is to prevent the meta tag for the **/enable-javascript** path itself. It means to stop rechecking and refreshing for this path every 2 seconds (according to the setting in the code).
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: Grouping galleries with Colorbox modules
Since two days that i'm looking around to find a easy and simple gallery for Drupal 7.32 and it seems much more complicated that how should be.

I think Colorbox is exactly what i'm looking for but I cannot find a good tutorial or resource that explain how to create a page with thumbnails that groups different galleries.

So when click on them I should go in another page and see all those thumbs from one specific gallery and be able to click on that and see them as slideshow.

More or less like here: http://www.hopkinsco.com/portfolio

Can you please point me in the right direction?

Of course if you want to suggest another module or method is fine as well.

# Answer
> 1 votes
**The content-type "gallery"**

First of all, I created a content-type "gallery" which has several fields of my choice and a field "image" with illimited number of images.

**The View**

If I don't want something too specific, I use the Views module to create a View of all my galleries. I hope you already know that module. If not, go read the basics.

* Choose **content** of type **gallery**
* Set the title and the path of the page, etc...

You can choose which fields to show. If you want something like the site you linked in your question, you can use this configuration:

* Format: grid (with number of columns to 4)
* Fields:
    + Title
    + Image
        - Image style to thumbnail or whatever you created
        - Link to content (to land on gallery page when you click on the image)
        - Multiple value fields settings: display 1

Normally, you have now the equivalent of http://www.hopkinsco.com/portfolio when you open your View page.

**The gallery page**

The page of the content-type gallery displays all the fields you created for this content-type, in the order you arranged them in the admin. If you want something simple with the Colorbox module, you can go to admin/content-types/gallery/manage display and set the image field config like this (sorry for the french):

Then go click on the little gear on the right to set the advanced config:

Now you've got the equivalent of http://www.hopkinsco.com/portfolio/colonial.

**The template and/or the style**

Now that you've got the right content in the right place, you can customize the rendering with a little template and/or CSS.

---
Tags: media
---


title: Weird appearances in a node

text:
# Question
Title: Weird appearances in a node
For some reasons I have too weird appearances in a node.

1. A "Read more" button appearing near to my "Tags" list (even though my display settings dictate only "Full page" appearance, and I've disabled any other option.
2. An RSS button, that appears there although I never installed the Aggregator module.

How can you explain these phenomena?

# Answer
> 0 votes
It seems that the problem was some kind of data mixing made by mistake at the `page.tpl.php`.

I think it's fixed now.

---
Tags: feeds, nodes
---


# Question
Title: How to validate input data that are previously saved?
I am creating a module that can store user input in db and populate in a listing page with validation. I am collecting all values before submit i.e. any change in any field I store the form state in database, next I need to validate it on a listing page which will validate those input and give the error.

I have tried node\_validate\_form & drupal\_validate\_form but it's not working.

I think drupal\_validate\_form will do what I want but it omit default field validation like required validation or email validation are not validating properly and also in listing page it only validate the 1st one after that it is not checking any validation.

```
$header = array(
    array('data' => t('Field')),
    array('data' => t('Error')),
  );
  $rows = array();
  $owner = '';
  $result = db_select('MY_MODULE', 'lt')
    ->fields('lt', array('owner', 'form_state', 'form_state_input'))
    ->condition('lid', $lid)
    ->range(0,1)
    ->execute();

  if (!$result) {
    $rows[] = array(array('data' => t('No Result found.'), 'colspan' => 10));
  }
  else {
    $old_msg = drupal_get_messages();
    $_SESSION['messages'] = array();
    $node_form = (object) array(
      'type' => 'MY_CONTENT_TYPE',
      'language' => LANGUAGE_NONE,
    );
    $form = drupal_get_form('MY_CONTENT_TYPE_node_form',$node_form);
    $form['#submit'] = array('#type' => 'submit', '#value' => t('Next'));
    foreach($result as $r){
        $owner = l(t(user_load($r->owner)->name), 'user/'.$r->owner);
        $old_fs = @unserialize($r->form_state);
        $form_state_input = @unserialize($r->form_state_input);
        $old_fs['values']['uid'] = $user->uid;
        $form_state = array();
        $form_state['values'] = array_merge($old_fs['values'],$form_state_input);
        $form_state['values']['op'] = t('Save');
        $form_state['submitted'] = 1;
        $form_state['complete form'] = array();
        $form_state['rebuild'] = TRUE;
        $form_state['triggering_element'] = array('#parents'=>array('next'),'#button_type'=>'submit');
        unset($form['#token']);
        drupal_validate_form('MY_CONTENT_TYPE_node_form', $form, $form_state);
        $errors = form_get_errors();
        $noOfError = 'empty';
        if (!empty($errors)) {
          $noOfError = count($errors);
          foreach($errors as $field => $error){
            $field_name = explode(']',$field,2);
            $info = field_info_instance('node',$field_name[0],'MY_CONTENT_TYPE');
            $rows[] = array(
                    array('data' => $info['label']),
                    array('data' => $error),
                  );
          }
        }
        else{
          $rows[] = array(array('data' => t('No Error found.'), 'colspan' => 10));
        }
        form_clear_error();
    }
    $_SESSION['messages'] = $old_msg;
  }
  $build = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => array('id' => 'MY_MODULE'),
  );

```

Thank You In Advance....:)

# Answer
> 0 votes
oh..

drupal submit form hook does the magic

---
Tags: 7, forms, nodes
---


# Question
Title: drupal_validate_form not validating more than one time on listing page
i am using drupal\_validate\_form on a node listing page . it is validating it correctly only for 1st item after that it is not checking validation.

here is my code

```
     foreach($result as $r){
        $node_form = (object) array(
          'uid' => $user->uid,
          'type' => 'MY_CONTENT_TYPE',
          'language' => LANGUAGE_NONE,
        );
        $form = drupal_get_form('MY_CONTENT_TYPE_node_form',$node_form);
        $form['#submit'] = array('#type' => 'submit', '#value' => t('Next'));

        $old_fs = @unserialize($r->form_state);
        $old_fs['values']['uid'] = $user->uid;
        $node = (object) array(
          'uid' => $user->uid,
          'type' => 'MY_CONTENT_TYPE',
          'language' => LANGUAGE_NONE,
        );
        node_object_prepare($node);
        $form_state = array();
        $form_state['build_info']['args'] = array($node);
        $form_state['values'] = $old_fs['values'];
        $form_state['values']['op'] = t('Save');
        $form_state['submitted'] = 1;
        $form_state['complete form'] = array();
        $form_state['triggering_element'] = array('#parents'=>array('next'),'#button_type'=>'submit');
        unset($form['#token']);
        drupal_validate_form('MY_CONTENT_TYPE_node_form', $form, $form_state);
        $errors = form_get_errors();
        $noOfError = 'empty';
        if (!empty($errors)) {
          $noOfError = count($errors);
        }
        form_clear_error();
    }

```

thank You in advance

# Answer
> 0 votes
i just change the validated flag of every form in the foreach and after that it works fine

---
Tags: 7, forms
---


# Question
Title: How to insert data into multiple tables in one query
I created custom user registration form. the data get saved in the user table as required but the others field like fname,mobile and address are not getting saved in the following tables. 1. table name- field\_data\_field\_name
field name- field\_fname\_value

2. table name- field\_data\_field\_mobile
field name- field\_mobile\_value
3. table name- field\_data\_field\_address
field name- field\_address\_value

unfortunately i am not aware of how to insert data into three different table.so please help me with the solution for the same

i create another user registration from.the standard registration form is for doctor so they have different fields. this registration form is only for user to save basic information like address,fname and mobile number.this 3 fields are same as standard form fields.so thats why i want to insert this data into those tables.please help me

```
  function register_form($form,&$form_state)
     {
     $form = array();

    $form['name'] = array(
    '#title' => 'Username',
    '#description' => 'choose a username',
    '#type' => 'textfield',
    '#required' => TRUE,
     );

    $form['mail'] = array(
    '#title' => 'email',
    '#description' => 'enter a valid email address',
    '#type' => 'textfield',
    '#required' => TRUE,

    );

     $form['fname'] = array(
        '#title' => 'Full Name',
        '#type' => 'textfield',
        '#required' => TRUE,
     );

     $form['mobile'] = array(
        '#title' => 'Mobile',
        '#description' => 'Mobile',
        '#type' => 'textfield',
        '#required' => TRUE,

      );
       $form['address'] = array(
        '#title' => 'Address',
        '#type' => 'textfield',
        '#required' => TRUE,
      );

    $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit'
    );
    return $form;
    }

    function register_form_submit(&$form, &$form_state) {
   $pass=user_password();

   $account = array(
  'name' => $form_state['values']['name'],
  'pass' => $pass,
  'mail' => $form_state['values']['mail'],
  'init' => $form_state['values']['mail'],
  'status' => 1,
  'access' => REQUEST_TIME,
  );
  user_save(drupal_anonymous_user(), $account);
  }

```

# Answer
> 1 votes
It is **impossible**. Drupal uses MySQL by default, and MySQL's INSERT Syntax requires one and only one table name.

In theory you could use PostgreSQL and it's triggers \- create a view from these 3 tables, and in insert trigger of that view perform inserts to underlying tables, but it wouldn't be universal solution, and I can't think of any particular reason to do it in one query anyway. If you need to ensure data consistency, DatabaseTransaction is the way.

---
Tags: users
---


# Question
Title: Unable to return session value in views Field
I am storing a session value via Rules when the user is logged in

```
session_start()
$_SESSION['userkey'] = "12345";

```

Also testing it below there

```
echo $_SESSION['userkey'];

```

Although when I am trying to retrieve this value in my view in a field as Global: PHP

with Value Code:

```
return $_SESSION['userkey'];

```

Output code:

```
<?php
echo $value;
?>

```

It does not return anything. Unsure whether the session is not being set properly or I am retrieving the value incorrectly?

Thanks.

# Answer
You need to remove `session_start()` from Rules. Drupal calls `session_start()` when firing `drupal_session_start()`.

Check out session\_start manual on php.net

> As of PHP 4.3.3, calling session\_start() after the session was previously started will result in an error of level E\_NOTICE. Also, the second session start will simply be ignored.

Screenshot for PHP field settings in Views:
> 1 votes

---
Tags: 7, views, rules, sessions
---


# Question
Title: Is it possible to display user's first login (activation) date in a view?
All the users are imported (only admin can create accounts), they receive an activation email to connect with a one-time login. What I would like to know is how to display the date when they actually came at first (first login) and/or activate their account with the account process (password changing and save)?

Apart from the basic profile augmented with a few fields, my users have a native role that is dropped when they activate their account just to unlock automatically a function. So if there is a lead on "when the role was removed or changed" that I can't figure out right now, I might work with that.

I didn't put https://www.drupal.org/project/login\_history yet unfortunately.

# Answer
There is no field that stores this information in the database.

The only thing you have by default are user account creation date, last login date and last access time.

Once a user has logged in for a second time those values are no use to you.

There are also not user revisions by default so you can't see when the first time a user changes their username/password/etc. you can only see the data the most recent change was made.

The only way is to use something like login history or user revisions, however that only helps you from now on, not for existing users.

Off the top of my head I can't think of any way you can get reliable data for this for existing users.

**\[EDIT\]**
Actually, the drupal watchdog log stores user login events.

When a user logs in this watchdog call happens:

```
watchdog('user', 'Session opened for %name.', array('%name' => $user->name));

```

So if you check your drupal logs for "Session opened for" you can find all user logins.
This will only help you if you have a record of all your watchdog logs since the beginning of your site (probably not likely).
If you only use the dblog module that logs to the drupal watchdog table it is likely you don't have all logs because old ones will usually be purged to keep the database table size under control.
If you use the syslog module to that logs to your web server's file system it is possible that you could have backups of all logs for the whole life of your site, however that also isn't guaranteed.
It's probable that old logs are also purged in this case too.
> 3 votes

---
Tags: views, users
---


title: Remove facets from breadcrumb

text:
# Question
Title: Remove facets from breadcrumb
I'm using FacetAPI-SearchAPI and I notice that, on every view based on search api in the breadcrumb there is the "all items" link and, when I add a facet to the search, the facet value is added to the breadcrumb.

Is there a way to remove "all items" and other facets elements from the breadcrumb?

# Answer
> 4 votes
In `/sites/all/modules/facetapi/plugins/facetapi/url_processor_standard.inc` there's a function `setBreadcrumb()` (around line 61).

Simply comment it out or put a `return;` on line 62.

A better way is to create your URL Processor which implements `FacetapiUrlProcessor::setBreadcrumb()`

# Answer
> 2 votes
**This is something I used to reset the breadcrumb**

```
/**
 * Implements hook_facetapi_searcher_info()
 */
function yourmodule_facetapi_searcher_info_alter(array &$searcher_info) {
  foreach ($searcher_info as $key => $value) {
    if($value['url processor'] == 'standard'){
      $searcher_info[$key]['url processor'] = 'yourprocessor';
    }
  }
}

function yourmodule_facetapi_url_processors() {
  return array(
    'yourprocessor' => array(
      'handler' => array(
        'label' => t('Your module URL processor'),
        'class' => 'FacetApiYourClass',
      ),
    ),
  );
}

class FacetApiYourClass extends FacetapiUrlProcessorStandard {
  public function setBreadcrumb() {
    // Keep default behavior.
  }
}

```

---
Tags: 7, breadcrumbs, search
---


title: How to relate nodes in Drupal 7

text:
# Question
Title: How to relate nodes in Drupal 7
How can I relate content in Drupal 7?

I have three content types:

* Product Group ( With detail page )
* Product ( With detail page )
* Application ( With detail page )

A product belongs to a product group.

An application belongs to a product group.

How can I do this kind of relationship?

# Answer
> 3 votes
The best way is to use the Entity Reference Module.

1. Install the module
2. At the *Product* add a field *My Product Group* and Field Type: Entity Reference. If you have many *Products* use the autocomplete widget.
3. On the next page chose Target type: Node and then the as Target bundles the *Product Group*.

Now when you add a ‘Product’ you can assign the parent ‘Product Group’.

Do the same for *Application* and *Product*.

The final structure will be:

```
- Product Group
- (have) Product
-- (have) Application

```

To display the results is another story. You can go to ‘M*anage display*’ of the content type and Render the entity. Or you can use views if you like something more complex.

# Answer
> 1 votes
You can use https://www.drupal.org/project/entityreference. This module allows you to reference all entities with each other.

So in your case, on your CT product, you can add a field that references to product group and on CT application add a field that references to product group.

---
Tags: nodes, entities
---


# Question
Title: Drupal 7, passing URL arguments page not found
Good evening. Please help me.

I built my website on my home pc using Wamp as webserver. On one page I pass arguments to backend.php via URL.

Like this

```
echo "<a href='backend.php?g=$row[2]'><button >nbsp$row[1]</button></a>";

```

The code is working fine.

Now I uploaded the site to my godaddy hosting and can’t send the argument in the same manner. I gives me 404. The requested page "/backend.php?g=http://bc.luckyfaucets.com/" could not be found.

The code is exactly the same as on my home server, .htaccess is the same and they both have clean URL enabled. Can someone tell me the cause of this ?

This is the backend.php file.

```
<?php
define('DRUPAL_ROOT', getcwd());
require_once
DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
variable_set('ref', $_GET['g']);
$g = $_GET['g'];

$con=mysqli_connect($db_host,$db_user,$db_pwd,$database);

// Get infos siteid sitecyle from _sites_
$result = mysqli_query($con, "SELECT `siteid`, `sitecycle` FROM `_sites_` WHERE     `siteurl` = '$g'");

while($row = mysqli_fetch_row($result)) {
$siteid = $row[0];
$sitecycle = $row[1];
// Count time + sitecycle
$next = (time() + ($row[1]*60)+15);
}
// Update _counters_
$result = mysqli_query($con, "SELECT `siteid`, `uid` FROM _counters_ WHERE `uid` ='$user->uid' AND `siteid` ='$siteid'");
if( mysqli_num_rows($result) > 0) {
    mysqli_query($con, "UPDATE _counters_ SET `cycleend` = '$next' WHERE `uid` = '$user->uid' AND `siteid` = '$siteid'");
    }
else
{
    mysqli_query($con, "INSERT INTO _counters_ (uid, siteid, cycleend) VALUES ('$user->uid', '$siteid', '$next')");
 }
 drupal_goto('page');
?>

```

I would like to know what/why the same code does work with Wamp but not on my hosting. Is this maybe cause by some setting at godaddy?

Thanks for the help

# Answer
Try editing your .htaccess file and uncomment the following line:

```
RewriteBase /

```
> 0 votes

---
Tags: uri
---


title: Define form for field_attach_form

text:
# Question
Title: Define form for field_attach_form
I have an custome made entity

```
  function sbsl_order_entity_info() {
    $entitys = array();

    $entitys['sbsl_delivery_information'] = array(
      'label' => t('Delivery information'),
      'controller class' => 'EntityAPIController',
      'base table' => 'sbsl_delivery_information',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'delivery_information_id',
        'bundle' => 'bundle',
      ),
      'bundle keys' => array(
        'bundle' => 'bundle',
      ),
      'bundles' => array(),
      'load hook' => 'sbsl_order_delivery_information_load',
      'view modes' => array(
        'full' => array(
          'label' => t('Full content'),
          'custom settings' => FALSE,
        ),
      ),
    );

    return $entitys;
  }

```

I want to attach a form to my widget with field\_attach\_form

but can't figure out where i should define the form elements

# Answer
> 2 votes
You need to do more than simply declare the entity. The Entity Examples in https://www.drupal.org/project/examples will walk you through each step in the process of declaring the entity, defining the form, and adding menu hooks to be able to manage the entities and the field structure for both the form and display.

---
Tags: 7, entities
---


# Question
Title: Redirect a view page to another view page with arguments in the url
I have a custom view with button in the main tab placed in the local\_task tab bar area (Outcomes). I have sub local\_task navigation items under that as well that are regular drupal views. (See below)

View | Edit | **Outcomes**
Outcomes Viewer | **Custom View** | Another Drupal View

When you click on Outcomes you are taken to the Custom View tab or the Default for that custom view. However I want to redirect the Outcomes tab to go to the Outcomes Viewer tab. The Custom View tab is the /default for the menu, so it is s separate link and should work.

However, you can not use /%/ in a redirect. Does anyone have any ideas on how to do this. I have tried the basics but am lost on how to make it work.

Thanks!

# Answer
> 0 votes
So, solving this took a few different directions to figure this one out. The problem was I needed to redirect a view with an argument in the url (node/%/outcomes) to a new sub-button so there was an actual button. (Yes this is also a UX issue that the user needed to have the button)

So, I created a new panel page and in the content area I created new custom content. I used the module, php filter, this way I can use the PHP input for the wysiwyg. Then I pasted this code to redirect.

```
global $base_url;
header("Location: %node/:nid");

```

That redirected and kept the argument so everything would work fine. Hope that helps someone!

---
Tags: views, redirection
---


title: Add new taxonomy term on node edit form

text:
# Question
Title: Add new taxonomy term on node edit form
I'd like to add a new taxonomy term and assign the node while adding or editing the node. I don't want to use any of third party modules. I'd like to do it by myself in code. Maybe some of you have faced this problem. Anyone know how to do it?

# Answer
> 2 votes
1. Go to admin/structure/types/manage//fields
2. Add new field:

* Select field type -\> Term reference
    * Select a widget -\> Autocomplete term widget (tagging)

You should now be able to add new terms in node add/edit form via the autocomplete field. You don't need any custom modules. Drupal's core taxonomy module offers this functionality.

# Answer
> 0 votes
you can use the core term reference field and make the field formatter to use tags style

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


# Question
Title: Define zone-wrapper in Omega 4 and 960px
I'm using omega 4 and i got problems. How can i define 960px in omega 4 ? should i define it in `_grid.scss` like this :

```
$grid: 12px ;
$gutters: 1/3;

$tab:44em;
$desk:77em;
$mobile:15em 35em;

```

If it's true , how can i have something like omega 3 zone-wrapper with 100 % width ?!!!

# Answer
If you are using Susy, something like that will do the job:

```
$total-columns: 12
$column-width: 6em;
$gutter-width: $column-width / 3;
$grid-padding: $gutter-width / 2;
$container-style: fluid;

html {
  font-size: 62.5%;
}

.l-page {
  @include container();
}

```
> 0 votes

---
Tags: theming
---


# Question
Title: Rules: action before a user gets deleted
I'm trying to fetch a user's profile before the user account gets deleted.

I'm using the rule 'when user get's deleted' but once it gets deleted i cannot obviously access his profile.

Is there a way to get the profile 'before' the user gets deleted ?

Pulling my hairs out; any ideas ? Thanks folks !

(i'm using drupal 6)

# Answer
> 4 votes
I may need a bit more info on what you're trying to access and what conditions or actions you're trying to perform on the deleted user, but I'll give it a shot.

You should have access to the deleted user's data when using the "User has been deleted" trigger. If by profile you mean data connected to the user using something like the Content Profile module, then you may want to instead use the "After deleting content" trigger, since Content Profiles are actually just regular nodes.

If that doesn't help, let me know more specifics on what you're trying to do and I'll see if I can help.

---
Tags: rules, users
---


title: Displaying Taxonomy on the menu

text:
# Question
Title: Displaying Taxonomy on the menu
Friends -

Please help with this... to some of you, this is really easy. But, I have been struggling with this issue since two weeks: I need to create categories structures such as Creating Categories/Subcategories/Subsubcategories/Products and have it appear on the menu of a newly install drupal commerce. this is what I have done so far:

1. I created the taxonomies necessary
2. I created the categories and subcategories: i.e.: Products Categories\Air Conditioners\
3. I created the product "Samsung Air Conditioner Unit" and inserted it into the correct categories
4. I clicked on All Products and observed that Samsung Air Conditioner is properly inserted into the correct subcategories
5. However, when I clicked on the root category "Product Category" on the main menu, which is generated by Taxonomy, I do not see the product listed.

I just need to know how to configure the content type to allow the product to display in the correct category\subcategory group.

# Answer
> 0 votes
The reason the Samsung Air Conditioner Unit was not showing as we clicked on the category was because we inserted as Product Categories\Air Conditioner\Air Conditioning Unit instead of Product Categories\Air Conditioning Unit.

The subcategory Air Conditioner was not defined. So, drupal did not know how to display it. Once we moved to Product Catogoies\Air Conditioning Unit, it displayed.

Now, the task is how to create the subcategory Air Conditioners so that we could insert Air Conditioner Unit there instead of inserting it directly under Product Categories.

---
Tags: taxonomy-terms
---


title: Views related nodes with same Title

text:
# Question
Title: Views related nodes with same Title
I am building a booking system for a local theatre company. Each theatre event is its own node, and for the same show on different nights, the first night is created, and the node is cloned, with a different date and time for each show.

On the node event page I want to show a block view of other nodes with the same title, and different show times.

I have created a contextual filter by node ID, and excluded the current node from the view already, now I need to display all other nodes that have the same title.

I'm a bit stumped though, I can create a contextual filter by node title, but I cant figure out which options I need to select to achieve this.

Appreciate any help or advice.

# Answer
I actually found the solution I was looking for here

I was close with what I was doing, I just needed to do the following...

1. Add contextual filter by Content:Title
2. Under "When the filter value is NOT available" Provide Default by Content ID from URL
3. Under "When the filter value IS available" Specify validation Criteria as PHP Code
4. Enter the following PHP code...

> ```
> if (is_numeric($argument)) {
>   $node = node_load($argument);
>   $handler->argument = $node->title;
>   return TRUE;
> } else {
>   return FALSE;
> }
>
> ```

5. Click Save.
> 0 votes

---
Tags: views
---


# Question
Title: How to add Javascript in Drupal 7 with jQuery?
I am trying to provide the option that users be able to put comment under each paragraph. So at the end of the article, I have something like this:

Comments for paragraph 1

```
  /* here I show the comment for paragraph 1 */

```

Comments for paragraph 2

```
  /* here I show the comment for paragraph 2 */

```

Comments for paragraph 3

```
  /* here I show the comment for paragraph 3 */

```

so I have added the following to node.tpl.php:

```
    for($b=1;$b<$number;$b++)
   {
         echo "Commentsfor Paragraph $b:" ."<br>" . "<br>" ;

        foreach($cid_numbers as $no)
          {

             $e=($content['comments']['comments'][$no]['#comment']->paragraph_id);
             if($e==$b)
             print render($content['comments']['comments'][$no]);

           }
        }

```

and it works. But now I want to hide the comments and only when users clicks on a link like: Comments for paragraph 1, then he be able to see the comments.

In order to do that I have added the following to node.tpl.php file:

```
 <script type="text/javascript">
     (function($) {
        $(document).ready(function(){
           $(".toggler").click(function(){
            $(this).next().slideToggle("slow");
            return false;
          }).next().hide();
        });
    })(jQuery);
  </script>

```

and also changed the first code to this:

```
    for($b=1;$b<$number;$b++)
   {  ?>
  <p class="toggler" style="cursor:pointer;"><?php echo "Commentsfor Paragraph $b:" ."<br>" . "<br>" ; ?> </p> <div>
 <?php
   foreach($cid_numbers as $no)
    {

  $e=($content['comments']['comments'][$no]['#comment']->paragraph_id);
   if($e==$b)
    print render($content['comments']['comments'][$no]);

   }   ?> </div> <?php

   }

```

This is the website that gave me the idea that how to do the hide/show: http://renaudjoubert.com/en/article/how-add-javascript-drupal-7-jquery?utm\_source=twitterfeed

But the output looks like this:

comments for paragraph 1

```
 here it show comments for paragraph 3

```

comments for paragraph 4

and then when I click on the link "comments for paragraph 1" then it displays the comments for paragraph 1 and also the link " comments for paragraph 2". So what is my mistake? Have I put tag in the right place? Or do you have any suggestion that how can I hide comments and show them when click on the link?

# Answer
> -1 votes
I may be wrong but I would remove your inner foreach and just use your $b variable instead of $no.

Alternatively here is another way to do it:

http://jqueryui.com/accordion/

---
Tags: javascript
---


title: behaviors javascript executing

text:
# Question
Title: behaviors javascript executing
I want to pass params via Drupal to my JS file. I have no problem fetching them with the code below, the problem is that as the $(document).bind('leaflet.map' function executes FIRST, it is not able to find the user\_name parameter

my\_module.module

```
  function my_module_preprocess_html(&$variables) {

  $user_name=$GLOBALS['user']->name;
  drupal_add_js(array('my_module' => array('user_name' => $user_name)), array('type' => 'setting'));
  drupal_add_js(drupal_get_path('module', 'my_module') . '/js/external.js');
  }

```

external.js

```
(function($) {

Drupal.behaviors.fewo_map= {

 attach: function (context, settings) {

 alert('get params');
 //we can fetch the data
 user_name=settings.fewo_map.user_name;
}

```

}

$(document).bind('leaflet.map', function(e, map, lMap) {

```
//it fires first, so is unable to get user_name data
alert('leaflet')

console.info(user_name)
})

```

If I do...

```
(function($) {

 Drupal.behaviors.fewo_map= {

 attach: function (context, settings) {

  $(document).bind('leaflet.map', function(e, map, lMap) {
    alert('leaflet')

    console.info(user_name)
    })
  }
 }
})

```

the result is the same

Also tried using JS injector, no success neither. I need the user\_name as parameter to define the settings inside leaflet 'function' Thanks

# Answer
> 0 votes
Difficult to separate your php from javascript, but if you set js variable with this php code it should execute first and can be used within leaflet js function later:

```
<?php render('<script>var username = "'.$GLOBALS['user'].'";</script>'); ?>

```

---
Tags: javascript
---


title: How can I view my log files via ssh?

text:
# Question
Title: How can I view my log files via ssh?
I currently cannot access `http://example.com/admin/reports/dblog` as I cannot authenticate as an admin as my page is getting a 500 error.

I wonder if there is an actual location on my production server where Drupal errors are logged.

# Answer
If you have drush set up, you can use `drush watchdog-list` to look at the items logged to watchdog.

If you don't have access to drush, but your DB is up and running fine, you can always query the watchdog table with `Select * from watchdog;`

From personal experience, you might want to check your apache error logs as well to see if those hold anything that can help.
> 3 votes

---
Tags: 7, ssh
---


title: How do I use the photoswipe script?

text:
# Question
Title: How do I use the photoswipe script?
I want to use photoswipe script on my site to preview images. I downloaded the script, copied two JS files `code-photoswipe-1.0.11.min.js` and `simple-inheritance.min.js`. Include them in a file theme.info:

```
scripts[] = js/code-photoswipe-1.0.11.min.js
scripts[] = js/simple-inheritance.min.js

```

Next, I overwrite template with image field:

```
<div id="Gallery">
    <div class="gallery-row">
        <div class="gallery-item">
            <?php print $output; ?>
        </div>
    </div>
</div>

```

HTML generate this code:

```
<div id="Gallery">
    <div class="gallery-row">
        <div class="gallery-item">
            <a href="/node/36">
                <img ...">
            </a>
        </div>
    </div>
</div>

```

But nothing your working. What's wrong? FireBug displays two errors:

```
Uncaught ReferenceError: SimpleClass is not defined       code-photoswipe-1.0.11.min.js:28
Uncaught TypeError: undefined is not a function                                       8:62

```

# Answer
The order of includes should be reversed (as you did). There is also accompanying css file and the following initialization js code (see examples src http://github.com/downloads/dimsemenov/PhotoSwipe/code-photoswipe.v1.0.11.zip).

```
<script type="text/javascript">

        // Set up PhotoSwipe with all anchor tags in the Gallery container
        document.addEventListener('DOMContentLoaded', function(){

            Code.photoSwipe('a', '#Gallery');

        }, false);
</script>

```
> 0 votes

---
Tags: 7, javascript, media
---


title: Perform task on opening the site

text:
# Question
Title: Perform task on opening the site
I'm new to writing modules.

I would like my custom module to perform a task whenever the main page is loaded and no user is logged in, like when a user enters the url to my page, then the page loads and does something. I searched for a while now, but can't find the hook for this

What i tried was this:

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

  $items['/'] = array('page callback' => 'mymod_do_it');

  return $items;
}

```

But this does not work. At the moment despair is joining me with this.

Any help would be very appreciated.

Thank You!

# Answer
> 3 votes
You might check out the 'Examples for Developers' project page for some relevant examples: https://www.drupal.org/project/examples

I think you want to use hook\_init instead of hook\_menu. Try this:

```
function mymod_init() {
  if (drupal_is_front_page()){
    $items = array();

    $items['/'] = array('page callback' => 'mymod_do_it');

    return $items;
  }
}

```

---
Tags: 7, users
---


# Question
Title: Why my theme suddenly gone blue after an update?
After updating the Bartik 960 template on Drupal the homepage highlight each of the blocks on the page in blue. It looks like it's gone into a debugging mode, but I'm not sure how to fix it.

# Answer
Check the css with your browser's inspector and see what elements are surrounding this behavior. Is this occurring for all users (admin to anonymous)?

Does this happen in all regions or just the "highlight" region?
> 0 votes

---
Tags: blocks, theming, updating
---


# Question
Title: Drupal 7 menu translation and url aliases
I am building a multilingual site with Drupal7 and enabled i18n and menu translation module. I can translate menu items and it is working fine with only one little problem:

If the menu item points to an internal page (i.e: /user) everything is OK, however if the menu item points to a node, the title is translated but I can only specify one path.

I.e.: I have an English page "About us" which is **node/1** and have the URL alias **/about-us**

I have the Hungarian translation of this node "Manunkról" under **node/18** and URL alias **/magunkrol**

I see the correct titles in each language and I get the correct language versions when I click them. *BUT* on the English page, the link has **/about-us** in the HREF, but on the Hungarian page it has **node/1** (the node path of the English version). The link gets redirected but this is not an ideal solution in regards of SEO. Is there a way to display the URL alias in the HREF for each language?

# Answer
Setting up a menu per language (as stated in other answer) seems to me more like going around the problem rather than fixing it. I created an issue for it at https://drupal.org/node/2051041 and attached a patch.

Using that patch you don't need to the unnecessary hassle of setting up tons of menu items per language just because the href doesn't render as expected.
> 1 votes

# Answer
The way to do this is to create 'Fixed Language' menus, one for each language. I wrote a post on this topic. Setting up multilingual menus in D7.
> 0 votes

# Answer
Another approach to this is to use Entity Translation, and have a single, language-neutral alias for every node. The URLs are not as nice (same for all languages) but everything else should work well.

It really seems that language-specific aliases *should* work, but they don't. They result in 404. It seems to me like this is a bug / known limitation of the Entity Translation module.

Aliases default to the current language, so if you go this route, be prepared to have to edit every alias manually to reset it to "All languages", or figure out how to tweak the code to make this automatic.
> 0 votes

---
Tags: routes, uri, i18n-l10n
---


# Question
Title: How to create a view mode preview within the display suite module
I am using Display Suite to create two new view modes within my D7 instance. They are:

* Wide
* Square

I can get them created and and added to the content creation form BUT I'd like to create a preview image for those two view modes to give the end user some type of visual of what they're selecting.

I see there are layout previews when a layout is chosen but not for view modes. Do i just need to create a new layout template for the view mode? if so where should these files live?

First time using this module.

# Answer
> 1 votes
View modes are a Drupal concept, and layouts (in this context) are specific to Display Suite. Selecting a preview image for a view mode (if it can be done) has got nothing to do with Display Suite. The preview images that Display Suite show is specific to the layouts that it offers.

In Display Suite, you can define your own custom layouts, and there are a few ways of doing so. Some modules add layouts as well. To investigate how a module does that, download Display Suite Bootstrap Layouts and have a look at the files. You will see the module file, wherein the layout is declared as such:

```
$layouts['bootstrap_12'] = array(
    'label' => t('Bootstrap One Column: 12'),
    'path' => $onecol . '/bootstrap_12',
    'regions' => array(
      'central' => t('Content'),
    ),
    'form' => TRUE,
    'image' => TRUE, // this tells it that there is an image for the layout
  );

```

Note the key 'image' is set to TRUE to indicate the presence of an layout image, which you will find in the sub folders.

The template files that goes with this declaration is found in `layouts -> onecol -> bootstrap_12 -> bootstrap-12.tpl.php` and looks like this:

```
<<?php print $layout_wrapper; print $layout_attributes; ?> class="<?php print $classes; ?>">
  <?php if (isset($title_suffix['contextual_links'])): ?>
    <?php print render($title_suffix['contextual_links']); ?>
  <?php endif; ?>
  <div class="row">
    <<?php print $central_wrapper; ?> class="col-sm-12 <?php print $central_classes; ?>">
      <?php print $central; ?>
    </<?php print $central_wrapper; ?>>
  </div>
</<?php print $layout_wrapper ?>>

<!-- Needed to activate display suite support on forms -->
<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>

```

Here you can see how the **central** region defined in the module file is rendered within the template using a naming convention.

You can add layouts to this module directly if you want by following the convention above. But better would be to define them in your own theme folder so that you don't wipe out your changes during an upgrade.

You can do that manually or using drush, and the layout files will live in a subfolder 'ds\_layouts' within your theme folder. The process is fully described in Adding custom layouts to your theme. It is really very easy to do, and well worth the effort.

**So to come back to your question**, in order to associate a preview image with a view mode, you could declare a new layout with a peview image that is used only for a specific view mode, thereby creating a one-to-one relationship between them.

---
Tags: 7, display-suite, entities
---


# Question
Title: Change content of email verification email based on gender provided by user
In my website when a user submits the registration form and email verification is sent to them. Is there a way to change the content of the verification email that is sent after the user submits the registration form based on the gender they have selected. I'm trying to make a separate emails for male and female users.

The default email provided by Drupal says

> \[user:name\],
>
> Your account at \[site:name\] is created. You may now log in by clicking this link or copying and pasting it to your browser: \[user:one-time-login-url\]
>
> This link can only be used once to log in and will lead you to a page where you can set your password.
>
> After setting your password, you will be able to log in at \[site:login-url\] in the future using: username: \[user:name\]
> password: Your password
>
> -- \[site:name\] team

I want to change this. For example if the user selects "Male" for gender in the registration form so instead of `[user:name]`, it says "Hey Boy!" and if the user selects "Female" in the registration form the email says "Hey Girl!".

Is it possible to make that change?

Thank You.

# Answer
Okay if it's only the "Hey Girl" or "Hey Boy" you want to change,

1. You can just simply replace the `[user:name]` with the gender field token which is accessible via "Available tokens" link at the bottom of the page.

so you just replace `[user:name]` with Hey `[user:field_gender]`

Note that the name of the gender field is the machine name of the field you've chosen while creating the field.

**If it's not just the token and the whole content of email:**

2. Use Rules module to override the default registration email:

**Event**: Before saving a user account

**Condition**: Data Comparison (Gender is Male or Female)

**Action**: Send E-mail (Configure as you'd like it to be based on gender you selected at condition)
> 2 votes

# Answer
You've got two options:

1. Create yourself a custom token and use that.
2. Use the hook\_mail\_alter function

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

The token approach is the more elegant approach, but needs a bit of head-wrapping to understand the concepts. The hook\_mail\_alter might be an easier quick hack.
> 2 votes

---
Tags: forms, rules, emails, users
---


title: Facets with default

text:
# Question
Title: Facets with default
Anybody know how to set a default facet value?

I have facets set up and working using facet\_api blocks alongside a view in a panel. Is there a (hopefully easy) way to set one of the facets have a value selected by default on an initial page render?

//fyi Drupal 7.

Thanks.

# Answer
If you using module Search API, you can use hook\_search\_api\_solr\_query\_alter.

Try to add filter for your facet:

```
$call_args['params']['fq'][] = 'your_field:your_value';

```

It should help. It's a short way to do this but you have to know a name of the field in the index.
> 0 votes

---
Tags: search
---


title: Large file upload guidelines

text:
# Question
Title: Large file upload guidelines
I have a site built in Drupal 7.23, which is supposed to handle large files uploads to it.

I have a node form with 5 File upload fields which is supposed to take 200MB files for each.

What should be the Apache server adjustments that i need to taken in favour of making the upload process seamlessly?

Also i have Video module with FFMPEG configured to convert on cron. Someday I got message form server support team that my FFMPEG is taking 100% CPU.

Also i got some MySQL errors, like Lock TimeOut etc. what to do ?

Please let me know an optimal settings for these kind of server which runs Drupal.

# Answer
It is normal for the CPU usage to be at 100% when FFMPEG runs. Video compression is a computationally difficult task.

See this related question. If you have a two core VPS then you could make sure that FFMPEG only uses one core and thus always leaves at least one core for Apache/PHP/MySQL.

I created a similar site and it generally worked but it certainly had the occasional errors. It was a 4-core VPS and when transcoding all four cores were often at 100%. If I were to design the site again I think I would use a video transcoding service such as Amazon's Elastic Transcoder. Making sure FFMPEG would recognize all the different file encodings especially MP4 was quite a pain.
> 5 votes

# Answer
You may try File Resumable Upload:

> File **Resumable Upload** aka **file\_resup** adds large files multiple and resumable upload to the *File* and *Image* field widgets.
> 2 votes

# Answer
I think you can do it with Remote File Source module without affecting locally.

> Remote File Source allows you to add a file from a remote server to a filefield without transferring it locally.
> 1 votes

---
Tags: files
---


# Question
Title: Is it possible to autoplay a video when using module media_youtube, and perform an action when the video ends?
I am using media\_youtube module for embedded videos from youtube.
I am looking for a way to autoplay video as soon as it appears. Is it possible with this module?
Also I would like to make some action as soon as video ends. It would probably be going to some other drupal article. Is it possible?

# Answer
> 10 votes
The module developers hid these options well!

1. Click on Configuration (or Structure depending on versions)
2. Click on File Types
3. For Video, click on manage file display
4. For the display you are using (Default, Link, Preview, etc..), click on the YouTube Video tab under Display Settings.
5. Check the box called "Autoplay video on load"

# Answer
> 1 votes
just want to add here that if you're using Safari and you have an extension such as ClicktoFlash installed and enabled it might be that your browser will automatically play the video depending on your settings of that extension. So if you have your video still 'autoplays' have a look there as well.

---
Tags: media, files
---


# Question
Title: Add all the fields to view automatically in csv export
I am using entity registration module for node registration.Now i wants to export the registrants.

I am using view export module to export registrants list. Its working fine

But as the registration fields is different per node i can not add a fix number of field to export.

I am trying to use global php field, its working for single column.

Is there any alternatives?

What other i have tried?

```
function paticipant_export_views_pre_view(&$view, &$display_id, &$args) {
          if ($view->name == 'paticipants_export') {
            views_db_object::add_item($view->current_display, 'field',
    'field_data_field_first_name_1', 'field_first_name_1',
$options = array(
            $handler->display->display_options['fields']['field_first_name_1']['id'] = 'field_first_name_1',
            $handler->display->display_options['fields']['field_first_name_1']['table'] = 'field_data_field_first_name_1',
            $handler->display->display_options['fields']['field_first_name_1']['field'] = 'field_first_name_1',

            ), $id = NULL);

          }
        }

```

Thanks for your suggestion.

# Answer
> 0 votes
This might be a really stupid suggestion but why dont you just edit the view and add all the registration fields manually. The view will have empty cells for fields thats not a part of the registration type at a specific row, but thats something you'll get anyways.

Another way to go is to skip views alltogether and export data with a module of your own using the entity api. You aparently are writing a module to override view fields above so you have already started down that road (so to speak)

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


# Question
Title: Drupal 7: Views RSS module - fields not showing up
So I wanted to create a custom RSS feed for my site and was told that I could use the views fields capability with this module: Views RSS. I downloaded and installed and followed the steps explained here for the basic usage. And also took a look at the minimal instructions given at the module's doc

The problem is I end up with; the fields getting picked up by the page display but the feed display returns the default with title and body fields only (regardless of other fields). Also the XML is not outputted correctly and the link. It's as if the Views RSS is not there or is not doing anything.

I have no idea why it is not working...I am think if the steps I followed aren't correct and when I try to follow what is described here I run into the same error and have no idea how the person who posted that solved it.

# Answer
First think first: On a RSS feed you can't have as many `<xml_tags>` as you want. It's fixed-predefined for web concurrency.

Now a quick and dirty tutorial:

1. Enable Views RSS, Views RSS: Core Elements, Views RSS: DC Elements
2. Add new view without create a page or a block
3. Add a Display Feed
4. Format-\> from RSS Feed to RSS feed- Fields
5. Fields-\>Add the basic fields (It will display nothing!)
6. Format-\>Settings-\>Item elements : core Map the fields to RSS elements (do the same for Item elements : dc)
7. Feed settings-\>Path: give a path
8. Save..
9. Browse the URL, for debug (and not fancy Chrome/Firefox styling) `CURL example.com/rss`
> 0 votes

---
Tags: views, feeds
---