title: How do I send a mail with attachment?

text:
# Question
Title: How do I send a mail with attachment?
I try with this, but no success:

```
$params = [
  'body' => 'My body',
  'subject' => 'My subject',
];

// I check by debug this code and $file get the right file
$file = File::load($myfile_id);

$attachment = [
  'filepath' => $file->getFileUri(),
];

$params['attachment'] = $attachment;

// This send a empty mail, without subject and not body
$send = \Drupal::service('plugin.manager.mail')->mail('mymodule', 'mykey', 'myuser@gmail.com', 'es', $params);

```

Why doesn't `\Drupal::service('plugin.manager.mail')->mail` work?

Then I tried this and it worked fine, but without attachments.

```
$system = \Drupal::service('plugin.manager.mail')->getInstance(array('module' => 'mymodule', 'key' => 'mykey'));

$file = File::load($myfile_id);

$params = [
  'headers' => [
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal',
  ],
  'to' => 'myuser@gmail.com',
  'body' => 'My body',
  'subject' 'My subject',
  // I try with:
  'attachment' => $file;
  // or
  'attachment' => ['filepath' => $file->getFileUri()];
  // with not success
];

// the mail was sent but without attachment
$send = $system->mail($params);

```

How do I send a mail with attachment on Drupal 8?

# Answer
Drupal core doesn't support mail attachments/HTML mails.

You need to use an alternative mail implementation, like the Swift Mailer module.

Also, the reason the first implementation doesn't work is because you need to go through a `hook_mail()` implementation instead. See how core does it.
> 7 votes

---
Tags: emails, 8
---


# Question
Title: flexslider is failing on version recognition and perms
Updated via drush, flexslider module v.7.x-2.0-alpha3 is installed.
Installed latest version of library 2.3.0, released 17 days ago as of the time of this writing.
Getting drupal pesky error about version not recognized, so decided to downgrade library to 2.2.2, same error. Moreover I am getting following errors in status report:

```
Warning: fopen(sites/all/libraries/flexslider/jquery.flexslider-min.js): failed to open stream: Permission denied in _flexslider_requirements_library_installed() (line 212 of /var/www/asflorida.com/sites/all/modules/flexslider/flexslider.install).
Warning: fread() expects parameter 1 to be resource, boolean given in _flexslider_requirements_library_installed() (line 213 of /var/www/asflorida.com/sites/all/modules/flexslider/flexslider.install).

```

Before somebody tells me that this is a perm issue: I checked thoroughly and perms are 775 throughout and ownership is correct.
Either alpha 3 is not working with older library or viceversa.
Thanks in advance.

# Answer
> 0 votes
Basically this is a duplicate issue, workaround (cannot be called solution) is to downgrade from v.2.3.0 to 2.2.2.
I already posted in the module's issue queue. The other issues were caused by ownership and perms issues, while I was testing both library versions, disregard that part.

---
Tags: javascript
---


# Question
Title: Contextual Filters for a Block on a Page
I am trying to figure out how to create a page with dynamic content within a block.

For example, a simple "About Us" page may have sub pages of "Contact," "Blog," "History," "Locations"

I would like the Page to remain the same, but only the content within the block change.

So, assuming that from an expanding menu you have the choices noted above. When you click on the "About Us" menu option you get:

# About Us

Picture\_Default
Text\_Default

Now, if you click on the "History" sub menu, you get:

# About Us

Picture\_Default
Text\_Content\_Default

# History

Text\_Content\_History

Thus far, I have created a page with the static "About Us" content. I created a Views block with a contextual filter based on Node ID. I also configured the blocks to display only on the about and about/\* pages.

When I go to domian.com/about I get the default page. (That works) If I go to domain.com/about/history, I get a "page not found error" where the static content should be and the correct sub page.

I have been searching for this answer and I am sure it has already been answered, but I am not sure if I am using the right terminology to bring up the relevant results. If anyone could point me in the right direction, I would greatly appreciate it.

Thanks!

# Answer
> 0 votes
**First, what you'll need to do is create the content.**

So, for example, if you are going to have the structure:

```
/about
    /history
    /location

```

Create a basic page, or any custom content type, for each page (about, history, location). This is where the content will exist, even though you wont access these pages directly. Do not create menu items or URL aliases for these pages - this will be done later. Only create a menu item and URL alias for the about page at this point. The URL alias should be "about" to match the view we create next.

Once you have the content created, create a new view:

* Show Content of type Basic Page (or whatever type you created the pages with)
* Check "Create a page"
* Path: about/%
* Display format: Unformatted list of full posts
* Save and continue

So you have a new page view ready to configure. Under "Filter Criteria" add `Content: Nid` and set it to the nid of the /about page you created earlier. Now, this view basically mimics your about page.

**Next, add a new view display attachment.**

This is where the dynamic part is done.

**Under "Attachment Settings":**

* Attach to: Page
* Attachment position: After
* Inherit contextual filters: Yes

**Under "Contextual Filters":**

* Choose "Content: Nid"
* For: "This attachment"
* Check "Provide default value"
* Select "Raw value from URL"
* Path component: 2
* Apply

Save the view. So the original about page you created at the start should already be accessible at /about if you set the URL alias properly. Now you can access the dynamic content below by visiting `/about/(nid)`. Nid should be the nid of the subpages you created earlier, for example, if the history page has an nid of 2 - you will access it by going to `/about/2`.

The last thing you will need to do is create menu items for your dynamic pages. Add menu links for each sub page ie.

* Menu title: History
* Path: about/2
* Parent Link: About

Some things to consider: On your dynamic view page, the page titles will link to the original nodes - you'll need to create and use a new display at `/admin/structure/types/manage/page/display` to remove the linking. Then update your page view to use the new display under `Format -> Show -> View mode`

# Answer
> 0 votes
First create a taxonomy whose terms will be those 'contact', 'blog', 'history', 'locations'.

Then create a views page with contextual filter based on term id and set path as about/%

# Answer
> 0 votes
I would experiment with Quick Tabs. What you're looking at is creating simple nodes, and Views might just be a bit of overkill here.

---
Tags: blocks, views, 7
---


# Question
Title: A way to generate line charts where each dataset comes from a view with specific arguments
I've got a view which shows download count and playback count (for musical works). This view may be filtered on time intervals, and is capable of returning downloads and playbacks for this time interval only.

Now, I'd like to generate an "overview" which simply will be the product of this view but with different time intervals. I'd like the resulting table to be something like:

when downloads playbacks last week 10 100 last month 50 287 last quarter 200 437 last year 1000 1836

Is there a way to achieve this without doing it as a specific module? Is there a module out there which is capable of collecting data from a view, putting it together and generate a table and possibly charts for that?

# Answer
'I' can answer that very last part of your question about charts. The views integration of the charts module is a solution for that. Here is an intro about it from the charts community pages:

> Anybody familiar with the views UI can use the charts module to create charts without coding PHP snippets, as one typically does when using the Charts API.
>
> So site building knowledge is sufficient to create charts using Views, you don't have to be like an experienced Drupal developer (who probably would rather want to use the Charts API instead).

To be complete: I'm the new co-maintainer of the **charts** module ... Working on transforming the latest (pretty old and stable) RC1 release of it in an official release of it.
> 1 votes

# Answer
You could create two flags called 'download' and 'replay' with the Flag module and flag the music node when people download or replay that music. After that, you can create a view that shows how many times the nodes have been flagged with the aggregation function. I can't help you with the last part of your question, because I'm looking for a way to graph data too: How to create a line graph of the total user points on a profile page?.
> 0 votes

---
Tags: views, charts
---


# Question
Title: How to access a variable in the ready event within charts_google.js without hacking the chart module?
I need to be able to respond to the ready event within the Chart module.

I have Homebox installed and one of the blocks used in it is a google chart. The homebox resize action takes place before the chart has finished rendering and is misalligned.

I need to call the homebox resize action from the chart ready event. Currently I have added this code to the charts\_google.js file, which works fine but I need to move it out of the chart module into my custom module.

```
function myReadyHandler(){ // added this
  Drupal.homebox.equalizeColumnsHeights();
}

function renderCharts() {
 ...
 google.visualization.events.addListener(wrap, 'ready', myReadyHandler); // added this
 ...
}

```

The variables in question is wrap. How can I get access to this variable in my own module without hacking charts\_google.js?

# Answer
Consider looking at issues #1196712 and 1715638, which seem to be like variations of your request.
> 1 votes

---
Tags: charts, dashboard
---


# Question
Title: Views Infinite Scroll doesn't hide pager
I need infinite scrolling for a View. I installed Views Infinite Scroll, and it will work if I set jQuery Update to version 1.8, but when it loads the next page, it leaves the pager in plain site. I don't want the pager to display, and I can't figure out how to disable it. Also, when it's loading the next page of content, it displays that ugly progress GIF. Is there a way to hide that as well, and just get a nice scroll functionality, like on Twitter?

I don't know if this is causing an issue, but my View results are nodes, using Display Suite view mode. In these nodes, I have another View that displays product pricing and other fields, using Commerce Add To Cart Extras. Would this other View (in each node) conflict with the Views Infinite Scroll module for my main View?

If I have to do this through code, what is the best route? Should I use the Views Ajax API somehow, or is there another JS or jQuery library that I can integrate with Views?

I tried to use the Views Load More with Wayports, but I couldn't get that to work either. The best I got was the View to just display the "Load More" link, which I don't want.

# Answer
> 0 votes
To hide the pager, I just set the display: none in the CSS.

# Answer
> 0 votes
Here's an issue regarding this in Drupal.org.

https://www.drupal.org/node/1234704

---
Tags: 7, views, ajax, javascript
---


# Question
Title: How to change column chart color programmatically
I have created view block using different content type. I am displaying this block as a column chart using Drupal module Highcharts, it is working but if I want to display separate color of content type node I mean one color for one content type node and other color for other content type. Can any one tell me how to change this? Is there any module by which I can sort out my problem?

# Answer
> 1 votes
Attempt to answer the last question, i.e.:

> Is there any module by which I can sort out my problem?

To create charts in Drupal, consider the comparison of charting modules as a possible place to start from, to find the module that best fits your needs. That comparison does include the modules mentioned here, but quite AbitMORE charting modules ...

Possible alternatives that should solve this specific question, are the Chart module, or the Charts module. I recently created quite a lot of new Chart documentation, and Charts documentation. Though there are other alternatives in that comparison that might be a better fit for this specific case.

The **license** that comes with the related charting library (engine) in each of these modules, should be considered also. It is one of the (important?) selection criteria for deciding on the module to go for. 'Possible privacy concerns' or 'Yes or no support for saving charts in PDFs' is another typical item to consider.

Be aware: I'm a new (co-) maintainer of both module 'chart' and 'charts' (confusing names, I didn't invent those names), and the author of the comparison.

Ps: the question does not say **why** it has to be done programmatically. But note that the Charts module ships with out-of-the-box samples which seems to be very close to what you are trying to create. Adapting these samples to exactly fit your needs seems like cloning these samples in a new views display or a new view.

---
Tags: charts, views, blocks
---


# Question
Title: Drupal 7 Comments Alternating Row Colors
I'm interested in making the comments that appear on my resource content type nodes show with alternating background colors. Anyone know how to make this happen?

I tried something like this with CSS but I'm not seeing how I can make this work as the comments don't seem to have anything regular I can target (as the class is quite a bit different if the comment is made by a logged in user vs. an anonymous user for instance):

```
.comments-by-anonymous .field-item:nth-child(even) {
    background: #fcfc33;
}

```

Then I thought, well I could try and do some PHP if/then hackery to my comment.tpl.php template but I'm unfamiliar enough with that template to know if its a) even the correct one to edit, and b) if perhaps there might just be a better way to do it.

Anyone have any good ideas?

# Answer
Looks like you can use the `$zebra` class in the comment template.

Add it in the preprocess hook as a class:

```
/**
 * Implements hook_preprocess_comment
 */
function THEME_preprocess_comment(&$variables) {
  // Zebra classes are added in the default template_preprocess function
  if (!empty($variables['zebra'])) {
    $variables['classes_array'][] = $variables['zebra'];
  }
}

```

You can then style the 'odd' and 'even' comments with CSS

e.g, something like:

```
.comment.odd{
  background-color: #efefef;
}
.comment.even{
  background-color: #ffffff;
}

```
> 2 votes

---
Tags: theming, comments
---


# Question
Title: Add a filter to my view before executing
I have a view and I want to get it's results.

```
$nview = views_get_view('tasks');
$nview->set_display('page');
$nview->pre_execute();
$nview->execute();

```

If I have 'nid' filter added to my view, I can **modify** it and get my view filtered.

```
$nview = views_get_view('tasks');
$nview->set_display('page');
$nview->pre_execute();
$nview->display['page']->handler->handlers['filter']['nid']->value['value']=180;
$nview->display['page']->handler->handlers['filter']['nid']->operator='=';
$nview->execute();

```

But what do I need write to **add** a filter **if no filter present in view settings** of my view?

```
$nview = views_get_view('tasks');
$nview->set_display('page');
$nview->pre_execute();

//some code here

$nview->execute();

```

UPD: Unfortunately, I can't use hook\_views\_query\_alter because I need to use my code in my custom function which accepts view's name as an argument. My target is to alter any view which name passed as an argument to my custom function. So I need to alter filter/query only if I need get view's result and the view executes from my function. But if the view executes from it's page or block it needs to be executed without altering.

# Answer
> 3 votes
Another way is to add the filter as an exposed filter in the view and then set it programmatically like this:

```
// Set created date range filter.
$item = $view->get_item($display_id, 'filter', 'created');
$item['value']['min'] = $settings['min'];
$item['value']['max'] = $settings['max'];
// Disable exposed filter in UI, for programmatic filter.
$item['exposed'] = FALSE;
$view->set_item($display_id, 'filter', 'created', $item);

```

That should come *before* `$view->pre_execute();`

You can also add a completely new filter in a similar way, by building up a valid `$item` to use with `$view->set_item`.

# Answer
> 0 votes
If you want to add a filter on your view when it is not defined in the view UI you can use hook\_views\_query\_alter

Something like this:

```
function MYMODULE_views_query_alter(&$view, &$query) {
  dpm($view, __FUNCTION__);
  dpm($query, __FUNCTION__);
  if ($view->name === 'your_view_machine_name') {
    // Alter query.
    $query->where....
  }
}

```

---
Tags: 7, views
---


title: How to use long file description?

text:
# Question
Title: How to use long file description?
Is there any easy way to store a long text description of an uploaded file?

I want to provide a long description field (textarea) when users upload files, so they can write as much as they need. Current title field is limited to 255 chars.

Any ideas on how to do this?

Thanks!

---

**Edit 1**

The `file_entity` module does not support Inline Entity Form unfortunately, so this solution won't work.

Here are the related issues on Drupal.org:
https://www.drupal.org/node/2038053
https://www.drupal.org/node/2327369

# Answer
The Inline Entity Form pushed me in the right direction.

Here's what worked for me:

1. Install File Entity module. It will allow you to add fields to files, in my case a "Description" textarea field.
2. Install File Entity Inline module. It will allow you to optionally include some of the fields directly in the file upload widget.
3. Add a file field and on configuration page under "Inline fields" choose either "All available fields" or "Only selected fields".

That's it - hope this helps someone!
> 1 votes

---
Tags: 7, files
---


# Question
Title: How to create a different page.tpl.php for different page, if pathauto is active?
I am new in drupal 7. I have created a page about us. My url is look like:

http://domain\_name/content/about-us

Now I want a different page.tpl.php for this particular page.

Please help how to do this?

Thanks

Prabeen

# Answer
It is all outlined on the Drupal 7 Template (Theme Hook) Suggestions page.
eg. page--node--1.tpl.php
> 1 votes

---
Tags: nodes
---


# Question
Title: Custom redirect for form-edit displayed in Views header
I have a content type called '*Checklist*' which I bring forward using Views, in it's node-edit form.

I wrote PHP code within the header in order to do this, here it is:

```
<?php

    $view = views_get_current_view();
    $arg0 = $view->args[0];

    $nodeToLoad = $view->result[0]->nid; //I get the node to load from Fields within my view
    module_load_include('inc', 'node', 'node.pages');

    $node = node_load($nodeToLoad);
    dsm($nodeToLoad);
    $edit_page = drupal_get_form('page_node_form', $node);

    $edit_page['additional_settings']['#access'] = FALSE;
    $edit_page['buttons']['submit']['#submit'][] = 'redirect_submit';
    print drupal_render($edit_page );

    function redirect_submit($form, &$form_state){
        $form_state['redirect'] = 'www.google.com';
    }
?>

```

Now what I want is to add a *custom redirect upon saving* this particular form.

I've tried this to no avail:

```
    $edit_page['buttons']['submit']['#submit'][] = 'redirect_submit';
    print drupal_render($edit_page );

    function redirect_submit($form, &$form_state){
        $form_state['redirect'] = 'www.google.com';
    }

```

Is it possible to this within the Views header?

---

**Notes:**

* I have also done this with the *Rules* module but I'd like to learn if it's possible to do with PHP code in the Views header so I don't split functionality in 2 parts of my project.
* This can also be easily done using a custom hook but again, if it's possible to do this within the Views header then that's the trick I'm looking for.

Thanks.

# Answer
You could to use hook\_form\_FORM\_ID. Something like this:

```
function mymodule_form_page_node_form_ater(&$form, &$form_state, $form_id){
   if(current_path() == 'page/where/my/view/is'){
     $form_state['redirect'] = 'page/to/redirect';
   }
}

```

If you don't want to use a hook, you can do something like this:

```
 $edit_page['buttons']['submit']['#submit'][] = 'redirect_submit';

```

Then,

```
 function redirect_submit($form, &$form_state){
  $form_state['redirect'] = 'path/to/rediect';
 }

```

Still it is bad practice to inlcude php in your views header. You should implement a custom area handler.

1. How to create a view area handler
2. https://api.drupal.org/api/views/handlers!views\_handler\_area.inc/group/views\_area\_handlers/7
3. https://oliverhuynh.wordpress.com/2011/06/23/custom-views-handler-drupal-7-template/
> 1 votes

---
Tags: 7, views
---


# Question
Title: Php libchart with value from my custom table
I want select value from my custom table where there are tweets saved. I have the column for the counter of retweets and I want the sum of the count hourly for 24 hour.

I write this code:

```
$time = time();
$prev_date = date('d-m-Y H:i:s', $time);

$dataSet = new XYSeriesDataSet();

foreach($req as $val){
 $serie = new XYDataSet();
 $val_id = (int)substr((string)$val, 0, strpos((string)$val, "-"));

    for($i=23; $i>=0; $i--){
        $next_date= date('d-m-Y H:i:s', $time - 3600*$i);
        $prev_date= date('d-m-Y H:i:s', $time - 3600*($i+1));
        $next_date = mysql_real_escape_string(trim($next_date));
        $prev_date = mysql_real_escape_string(trim($prev_date));
        /*$weight_q = db_query("SELECT SUM(`retweetCount` + `favoriteCount`)/2 as peso
                        FROM  `ax_twitter`
                        WHERE (`date` BETWEEN '{$prev_date}' AND '{$next_date}') AND (`ID_request` = %d)", $val_id);
        */
        $weight_q = db_query( "SELECT SUM(`retweetCount`) as peso FROM `ax_twitter` WHERE (`date` BETWEEN '$prev_date' AND '$next_date') AND (`ID_request` = %d)", $prev_date, $next_date, $val_id);

        while($row= db_fetch_object($weight_q)){
            echo($row->peso);
            $serie ->addPoint(new Point($next_date, $row->peso));
        }
        $prev_date = $next_date;
    }
$dataSet-> addSerie($val, $serie);

}
$chart->setDataSet($dataSet);

$chart->setTitle("Andamento dei Retweet e Favorite");
$chart->getPlot()->setGraphCaptionRatio(0.8);
$chart->render($path_image);

}

```

I tried different ways with query sql but I have the following errors:

> warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '18:39:52 AND 01-10-2014 19:39:52) AND (`ID_request` = 1)' at line 1 query: SELECT SUM(`retweetCount`) as peso FROM `ax_twitter` WHERE (`date` BETWEEN 01-10-2014 18:39:52 AND 01-10-2014 19:39:52) AND (`ID_request` = 1) in trigger\_error() (line 134 of C:\xampp\htdocs\drupal\includes\database.mysqli.inc). =\>

When I added the quotes to the parameters of the sql query , however do not get any results for my graph. My question: is right way?...is right query? With PHPAdmin I get right results if set two dates manually sorry for the language.

# Answer
> 1 votes
Looking at the error msg, I think the code needs to be adapted, so that the current string (as it is now in the error message) like `BETWEEN 01-10-2014 18:39:52 AND 01-10-2014 19:39:52` is replaced by `BETWEEN "01-10-2014 18:39:52" AND "01-10-2014 19:39:52"`. So basically prepend and append a `"` to the variables $prev\_date and $next\_date ...

What isn't clear to me in this question though:

* What is that 'libchart' in the title of this question?
* What's the purpose of the $chart in your code? If it is because you're using some charting module, it'd be interesting to know which module you're using, and you might want to add the **charts** tag to this question also ...

---
Tags: 6, database
---


title: Use theme_image_style twice

text:
# Question
Title: Use theme_image_style twice
I am trying to add different html class attributes to images based on what view they are being output with. I have created two image styles using the administrative interface, here are the two machine names.
1. front\_page\_recent\_blogs
2. blog\_page\_view

I have assigned each of these to the image field in the two different views. I have successfully added classes to the front\_page\_recent\_blogs images using the following code:

```
function mythemename_image_style($variables) {

  $variables['attributes'] = array(
    'class' => 'img-responsive center-block',
  );

  $variables['path'] = image_style_url('front_page_recent_blogs', $variables['path']);
  return theme('image', $variables);

}

```

How do I add classes to the blog\_page\_view image style, and to any future image styles? Calling the function twice breaks the entire site. If there is a better way to add classes to multiple image styles than overriding theme\_image\_style, please let me know.

# Answer
For this situation overwriting the image\_style theme function seems a bit heavy-handed, and as best I can tell your overwritten version omits some logic that it probably should not (see the core theme\_image\_style()). This could explain why things "break".

You would probably be better off implementing a preprocessing function that simply alters that 'attributes' variable that your site's exiting image\_style theme function uses, something like:

```
function mytheme_preprocess_image_style(&$vars) {
  if ($vars['style_name'] == 'front_page_recent_blogs' || $vars['style_name'] == 'blog_page_view') {
    $vars['attributes']['class'][] = 'img-responsive';
    // etc... add other var adjustments as needed
  }
}

```

You may also be able to avoid custom theme changes altogether if you have enough flexibly in your CSS. It sounds like you need to add some CSS rules only to images in specific fields within specific views, so CSS like this may work too:

```
.view-id-my_view_name .views-field-field-my-field img {
  // Add your CSS for .img-responsive here
}

```

Of course this may require duplicating the CSS for .img-responsive if it's used all over the place already (probably likely), which may only be realistic if you are using a CSS preprocessor. I assume you ruled this out already for good reason, but I figured I'd mention it anyway.
> 0 votes

---
Tags: views, media, theming
---


# Question
Title: Hook_form_alter in Views header PHP code
I have a content type called 'Checklist' which I bring forward using Views, in it's node-edit form.

I wrote PHP code within the header in order to do this, here it is:

```
<?php

    $view = views_get_current_view();
    $arg0 = $view->args[0];

    $nodeToLoad = $view->result[0]->nid; //I get the node to load from Fields within my view
    module_load_include('inc', 'node', 'node.pages');

    $node = node_load($nodeToLoad);
    dsm($nodeToLoad);
    $edit_page = drupal_get_form('page_node_form', $node);

    $edit_page['additional_settings']['#access'] = FALSE;
    $edit_page['buttons']['submit']['#submit'][] = 'redirect_submit';
    print drupal_render($edit_page );

    function redirect_submit($form, &$form_state){
        $form_state['redirect'] = 'www.google.com';
    }
?>

```

**I'd like to remove the 'Delete' button of this form**(*which normally deletes the content*). I have read that this is easily done with hook\_form\_alter() but my code resides within the header of a View and I'd like to keep it that way.

Is there a way to do this?

# Answer
> 0 votes
Found a solution, but if there is a better way I'd like to hear more.

```
$edit_page['actions']['delete']=false; //removed delete button
$edit_page['title']=false; //removed title display as well

```

---
Tags: 7, views
---


# Question
Title: Entity Reference | View - Display content based on a entity reference field's value that is randomized?
We are using Entity Reference.

We have a content type "Dog", and a content type "Breed". In the Dog content type, there is an entity reference field to Breed

We want to have a View that displays pictures and names dogs of a random Breed. If the page is refreshed, it should select a new random breed by which to filter the Dogs displayed. We are displaying Dogs by Breed no problem, but getting it to load (and refresh) with a Random breed (and populating the Dogs accordingly) is the challenge we cannot yet solve.

I have a feeling we need to use a PHP Contextual Filter to handle this, but not sure what the approach is to make it work properly. Does anyone have any insight here??

# Answer
you just have to configure a view that:

1. shows 1 breed, sorted random.
2. has another display that shows dogs based on a contextual filter on the breed nid
3. Install views field view
4. use the block from step 2 as a field in your first display and give the nid of the breed as a contextual filter to your views field.

So this views will show one random breed and has a view field to show the dogs that are of that breed. Hope this helps you out.
> 0 votes

---
Tags: views, entities
---


# Question
Title: setting up drush AFTER drupal multisite installed
new to drupal and even newer to drush. godaddy shared hosting, I manually setup drupal 8.x multisite where one site is the host account and the rest are subdomains to it. (I didn't use the cpanel install wizard)

I just ssh'd in and setup drush but now I don't understand how to configure it to see all my sites. all the info I've seen relates to setting up drupal using drush, not configuring drush with an existing installation, especially multisite.

do I need to create aliases? any help is appreciated. thanks!

# Answer
Drush does not need configuration, as long as you run commands from the relevant site folder such as `www-root/drupal-core/sites/mysite` it will work.

Do check that your version of drush is compatible with Drupal 8 though.
> 2 votes

---
Tags: drush, 8, multi-sites
---


# Question
Title: How to create a view to display poll results formatted as a chart?
By using core module **poll**, every time somebody participates in it, the poll module creates data representing the selected option of the poll, called 'poll results'.

How can these poll results be transformed using the views module? By creating a view and using a relationship to poll results, I only get 0, no matter what.

After I succeed in showing some tabular format of these results, I want to further enhance this view to display these poll results using some 3rd party charting app. This by using some charting module with views integration, which uses a charting library as its rendering engine.

Thank you

# Answer
About this phrase in the question:

> display poll results using 3rd party charting app

To create charts in Drupal, consider the comparison of charting modules as a possible place to start from, to find the module that best fits your needs. That comparison includes the following: *"Poll Chart Block displays poll's results in a block, with a selectable chart type, and using the Chart module."* So it looks like what you're trying to achieve already exists as a contributed module, no?

Be aware: I'm a new (co-) maintainer of Chart, and the author of the comparison of charting modules.
> 1 votes

---
Tags: 7, views, polls, charts
---


# Question
Title: Move to Online Mode only one site of two multi sites sharing the same code base
When I was working on one local site, I used to copy all the folders & files including the "sites" folder into my FTP account in addition to the database in order to have my local site online and be accessible by a specific domain name for example: www.FirstWebsite.com

However, Now I am using multi local sites (Two websites) on my laptop with separated databases, but sharing the same code base... Which means the code base files for both websites are the same except the following folders which are specific for each website: C:\DrupalSites\devdesktop\drupal-7.32\sites\FirstWebsite C:\DrupalSites\devdesktop\drupal-7.32\sites\SecondWebsite

What are the files which I have to upload to my FTP Account in order for example to put only the website name: "Second Website" online ?!

Any help will be highly appreciated,,, Thank you in advance... ---------------------------------------------------------------

Okay, i will rephrase my question... if you are working locally on one site named "FirstWebsite" and you want to host it online by using one of the hosting server available like for example "HostGator.com", you have only to transfer to the cpanel/file manger all the files and folders of your website . However, when you want to create LOCALLY another website, you should make a multisite configuration . Whichmeans, all the folders will be used by both websites except the two folders named: "FirstWebsite" (for the existing website) & the "SecondWebsite" (the new folder created for the new website) . Okay, So let say now we want to host online ONLY the new website whom all its files are under the "SecondWebsite" Folder without hosting also the existing website whom all its files are under the "FirstWebsite" Folder . Note: Do not forget that both websites are sharing the same code base.

My question: What folders and files i should transfer to the cpanel/file manager to ONLY host online the new website whom basically all its files are under the "SecondWebsite" Folder?

Thank you very much for trying to understand my problem even if it is not well explained...

# Answer
if you mean "update" with "put online" then it is not possible, because - as you pointed out - all sites share the same code base.. updating the sites/all folder will update both. the database updates need to be performed separately.

if you have only one website online that you want to update then just upload the changes from the sites/all folder.. that updates themes and modules.

cheers, j
> 0 votes

---
Tags: multi-sites
---


# Question
Title: How to modify the query that the views integration with the chart API module provides?
I am using Google Charts API module to generate a pie chart of a content type with the fields **Blood-group** and **count** representing the sectors.

For this I need to completely alter the query (= select from a different table) that the views integration provides.

**My question**: Can I use `hook_views_query_alter`?

# Answer
> 1 votes
To create charts in Drupal, there are plenty of modules available. Refer to the comparison of charting modules for an overview. After doing so, it should be clear that the names (and namespaces) of various charting modules are pretty confusing. Therefor I suggest you add a link to the exact 'Google Charts API' module this question is about.

Moreover, if I correctly understand the question, it seems to me that this is a rather straight forward requirement that can be easily addressed with (at least) the Charts module, i.e. the views integration of it (provides a new views style plugin to transform tabular view results into a chart). I recently created quite a lot of new Charts documentation that should help to get started with it.

The Charts module ships with out-of-the-box samples which are straight forward to adapt to fit your needs, e.g. by cloning these samples in a new views display or a new view. Of course there are other alternatives in that comparison that might be a better fit for this specific case.

Be aware: I'm a new (co-) maintainer of both Chart and Charts (confusing module names, I didn't invent them), and the author of the comparison of charting modules.

---
Tags: views, charts
---


# Question
Title: Drupal 7 Views Chart Statistics Over Time
I want to create a View of node requests/views over time. The problem is grouping the Access log timestamps (minute,hour,day, etc) so that these are chartable. Does anybody know of a solution for this in Drupal 7 Views 3?

# Answer
> 1 votes
Within the Charts module, there is an interesting issue about this, i.e. Graph node input over time (support date formatting on a continuous axis). In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'. The patch(es) included in this issue are expected to soon be applied.

---
Tags: 7, views, charts
---


# Question
Title: How to redirect "relationships/received" to "user/[requestee:uid]/relationships/received?
(D7) When a user sends a friend's invitation to another user (User Relationships) the other user, once he logs in, sees a green message that informs him so-and-so sent him a friends request. There is a link that takes the viewer (requestee) to *example.com/relationships/received.*

However, I have created a view that displays the received requests in a different format. Of course the page view has a different path and I want the user to be redirected to: *user/\[uid of the requestee\]/relationships/received* and the requestee only to be allowed to see the requests he received.

I have created a rule (Rules module) as follows:

* Event: A user relationship has been requested
* Condition: Relationship has type *(friend)*
* Action: Page redirect *(user/\[requestee:uid\]/relationships/received)*

*\[requestee:uid\]* is in the allowed replacement patterns but it doesn't work. Clicking on the link still takes the viewer to the original path.

What do I do wrong? :)

# Answer
> 1 votes
If you want to redirect to the current user profile page, you could try using the redirect module with redirect\_token

```
Use tokens in "To" paths in Redirect module.

```

Then you can redirect from http://example.com/relationships/received to http://example.com/user/\[user:uid\]/relationships/received

---
Tags: rules, users
---


# Question
Title: Why does adding a relationship change the display of my view?
I have a simple view based on my commerce\_product? When I add a relationship to Flags, the display changes from 12 per page, to 2. I'm confused why adding the relationship changes the markup?

# Answer
It does not alter the markup, it just potentially reduces the result set, depending on whether the flag is set as required or not.

It depends on how you add the flag. If you add it and **tick** `Include only flagged content`, then you make the relationship required and the relevant SQL has this form:

```
INNER JOIN {flagging} flagging_node ON node.nid = flagging_node.entity_id AND flagging_node.fid = '1'

```

whereas if you add it and **don't** tick `Include only flagged content`, then the relationship is not required and the relevant SQL has this form:

```
LEFT JOIN {flagging} flagging_node ON node.nid = flagging_node.entity_id AND flagging_node.fid = '1'

```

So views alters the type of join depending on whether the relationship is required or not - **INNER JOIN vs LEFT JOIN.**

Look at A Visual Explanation of SQL Joins and Visual Representation of SQL Joins
> 1 votes

---
Tags: views
---


# Question
Title: how to develop features delivered by drupal if there is no cms
I'm quite familiar with drupal, had done a few projects using drupal. I had an interview where the interviewer asked a few unexpected questions (atleast for me they were like unexpected!!). Few of them were

> How do you develop the same features that you did, if there is no CMS (Drupal)?
>
> What tables/scheme (mysql) do you create to generate all possible fields??
>
> If you are going to attach a pdf file (corresponding to each record) where do you specify that pdf file, do you use sql table or else what??

These were a few questions that I couldn't explain with full confidence.

I didn't even thought of the process behind drupal. I just used to work with my requirements and needs, I never thought of what the process might be. And more specifically with sql.

Do any of you have any views?

# Answer
The first one is easy.

> How do you develop the same features that you did, if there is no CMS (Drupal)?

With a MVC framework like Symfony, CakePHP or Zen.
> 1 votes

# Answer
With Drupal as a Content Management Framework you could develop a site without using any of the CMS features.

Each entity has base fields (attributes) attached to the same table. Besides the base table, entities can have other supporting tables, such as revision, hierarchy, roles, or whatever the entity needs to make it tick. When you create a bundle and attach new fields, each attached field has its own database table, as well as its own revision table.

Attaching a file field to a bundle will require the 2 tables as mentioned. I addition, Drupal also keeps other information about the files in the system which is stored in other tables, such as file\_managed and file\_usage tables, reason being File is also an entity in Drupal, though slightly lacking in features in Drupal 7 (that is why contrib File Entity) exist.
> 0 votes

---
Tags: 7
---


# Question
Title: Dynamic data forms and reports from non-Drupal databases
I have the task of displaying non-Drupal data which is stored in SQL Server within Drupal. I need to display search pages (ad-hoc style) and results based on page and field definitions stored in a SQL Server database. I will also need to display them based on permissions defined in the SQL Server database. This information will be a copy of the users and organic groups from the Drupal system, but will be stored in SQL Server so that they are available to other systems leveraging the same data, so in essence it can be considered a completely separate system.

I need to read the list of permissions (which will be managed down to the field level) and dynamically manage the display of fields, in both search criteria and result sets. For example, if Form1 has 10 fields and 2 of them require you to be an admin to see, there will be the following tables (structure hasn't been decided so there are just samples):

```
tbl_forms: form_id, form_name
tbl_fields: field_id, form_id, field_name
tbl_users: uid, username, etc
tbl_role_permissions:
 - roleperms_id
 - element_id (id of form or field)
 - element_type (form or field)
 - roles_show (an array of roles that have access to see this form or field)
 - roles_edit (an array of roles that have access to edit this form or field)

```

With this information, I believe it's possible to create an ad-hoc reporting system with roles level control of who can see individual fields for editing or in the data results of searches. I may need to also add a roles\_search field, but I can't think of anything else.

Is there an existing approach to displaying external data dynamically within Drupal? If not, does this type of structure appear granular enough for effective creation of this type of external data management and reporting system?

# Answer
Consider the Forena module, not many people know about it, which is why I wanted to mention it here.

Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS ... And there are quite some reasons for considering Forena.

Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.

**Note**: I'm a co-maintainer of Forena.
> 1 votes

---
Tags: forms
---


# Question
Title: Add custom title and custom alternative text to Logo Image Settings
I am looking for a module that adds custom Title and Alt fields to the box shown below in the Appearance Settings of a theme

# Answer
> 4 votes
You can alter theme form using, `form_system_theme_settings_alter` in `theme-settings.php`

```
function test_form_system_theme_settings_alter(&$form, &$form_state, $form_id = NULL)  {

$form['logo']['settings']['alt_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Alt Text'),
    '#description' => t("Alt text")
  );
$form['logo']['settings']['title_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Title Text'),
    '#description' => t("Title")
  );

}

```

You can get this value `theme_get_setting('title_text')` in `page.tpl.php`,and i haven't tried this. Check from your side, let me know if you face any issue.

# Answer
> 1 votes
I think this functionality you seek will be found on themes and not in a module. The designer of the theme will decide to add such functionality at the theme level. You could add this to your own theme or sub-theme if you wish as well. Here is a link to Creating advanced theme settings

Alternatively, as it is a once-off site-specific setting, just add it to your theme's page.tpl.php file. This is from Bartik's page.tpl.php file

```
<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
    <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
  </a>
<?php endif; ?>

```

---
Tags: forms
---


title: Price lists on a site

text:
# Question
Title: Price lists on a site
I'm creating a website for a company. One of the requirements is to have their price lists displayed on the website. All the data is in the MS SQL database. The question is, what would be the best way to:

1. Feed the data to Drupal (is it easier to connect directly to MS SQL database, or import data in XML or whatever else format?)
2. Display the data on the website (create a separate node for each separate price list and display the table it it? How to build that table?)

I'm using Drupal 7.

# Answer
This really depends on the amount of data, how you have access to it and what you want to do with it in Drupal.

If you simply want to display it and if you have direct access to the MS-SQL database, have a look at the sqlsrv module, which provides a Database driver that allows to directly connect to MS-SQL databases. You can then set up the database configuration in your settings file and easily connect to it and fetch your data. To avoid performance issues, you can cache the result with the cache\_get()/cache\_set() functions if you need to.

That is probably your easiest solution, especially if you want to be certain that your price lists are always up to date (remember to set the cache expiration correctly).

When querying the data directly, you don't *need* to create nodes or another data structure, you expose them directly by implement `hook_menu()` and so on.

Alternatively, when importing the data into your site (could be useful if you want to integrate it more tightly with your site, like site search, views, ..), you might want to look into the Migrate project. It has both support for external databases and XML so that's not relevant. To store the data, you could set up content types with fields and then map that to your external data. What fields you want to use depends on the structure of your price lists. If they are simple key/value lists, you could look into Properties* and if it is more complex, maybe something like TableField would be useful.

* Disclaimer: I developed Properties and am also (somewhat) maintaining it.
> 3 votes

# Answer
Another option to consider might be the Forena module. Not many people know about it, which is why I wanted to mention it here.

Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS ... And there are quite some reasons for considering Forena.

Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.

**Note**: I'm a co-maintainer of Forena.
> 1 votes

---
Tags: theming, database
---


title: Drupal pager in views

text:
# Question
Title: Drupal pager in views
I have a view created for product categories, now I want pager, I configure the settings by displaying specified num of items instead of all items, now I am getting the specified num of items on a page but not getting the pager when I added more than specified number of items?

# Answer
> 1 votes
In view, select full/mini pager & do necessary settings. Please check screeshots below

Change pager type

Change settings

---
Tags: 7, views
---


# Question
Title: How to send HTML/Rich text email from /contact
I want to allow other text formats on the /contact form than just plain text. I haven't been able to find a module that does this. Is it possible to do this in D7?

# Answer
You have two solutions one is

1. https://www.drupal.org/project/htmlmail \- html mail module especially for html mails
2. you have to customize the drupal\_mail function to accept html

https://www.drupal.org/node/900794

https://www.drupal.org/node/224333#email-html

below is the sample:

Since Drupal 7 automatically converts all HTML emails to plain text before sending them (http://drupal.org/node/224333#email-html), you must now write your own implementation of MailSystemInterface and set a variable telling Drupal to use it in order to send HTML emails. Here is the class which needs to go in your module:

```
<?php
/**
 * Modify the drupal mail system to send HTML emails.
 */
class ExampleMailSystem implements MailSystemInterface {
  /**
   * Concatenate and wrap the e-mail body for plain-text mails.
   *
   * @param $message
   *   A message array, as described in hook_mail_alter().
   *
   * @return
   *   The formatted $message.
   */
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    return $message;
  }

  /**
   * Send an e-mail message, using Drupal variables and default settings.
   *
   * @see http://php.net/manual/en/function.mail.php
   * @see drupal_mail()
   *
   * @param $message
   *   A message array, as described in hook_mail_alter().
   * @return
   *   TRUE if the mail was successfully accepted, otherwise FALSE.
   */
  public function mail(array $message) {
    $mimeheaders = array();
    foreach ($message['headers'] as $name => $value) {
      $mimeheaders[] = $name . ': ' . mime_header_encode($value);
    }
    $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
    return mail(
      $message['to'],
      mime_header_encode($message['subject']),
      // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
      // on Unix and CRLF on Windows. Drupal automatically guesses the
      // line-ending format appropriate for your system. If you need to
      // override this, adjust $conf['mail_line_endings'] in settings.php.
      preg_replace('@\r?\n@', $line_endings, $message['body']),
      // For headers, PHP's API suggests that we use CRLF normally,
      // but some MTAs incorrectly replace LF with CRLF. See #234403.
      join("\n", $mimeheaders)
    );
  }
}
?>

```

Rename the class for your module (i.e. ForwardMailSystem). Then, you need to set the mail\_system variable:

```
<?php
variable_set('mail_system', array('default-system' => 'ExampleMailSystem'));
?>

```

If you wish to have only emails from your module be sent in HTML but leave all others untouched, use this code:

```
<?php
variable_set('mail_system', array('default-system' => 'DefaultMailSystem', 'example' => 'ExampleMailSystem'));
?>

```

That code can go in your module's install file in hook\_install to set that variable as soon as your module is enabled. Make sure to also set the variable back to the default in `hook_uninstall`.
> 1 votes

---
Tags: theming, emails
---


# Question
Title: How to display content from a second database
I have two separate mysql databases setup:

1) With all the Drupal 7 related tables etc etc

2) A custom database into which I will feed simple high score data from an external source eg. username, score, time etc

Is there currently a module which will turn my second database into something an end user can view/sort in a Drupal Page or content type? Obviously there is little point in collecting user high scores data is the users can't see it. I have come across only the Data module, but it is unclear to me as to if this does exactly I would need it too. For example there doesn't seem to be an options to change the tables appearance or style, something which the D6 only module Table Wizard did do. Has anyone used this module before, and if so has it been for a purpose similar to mine?

# Answer
> 1 votes
Maybe consider the Forena module for accessing your data in your custom database. It seems like a perfect fit for what you're asking for. It also includes charting features, which is typically a related requirement. Not many people know about it, which is why I wanted to mention it here.

Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS. You didn't specify if your custom database is any of those, but any of these will do ... And there are quite some reasons for considering Forena.

Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.

**Note**: I'm a co-maintainer of Forena.

---
Tags: 7, database
---


# Question
Title: What causes the 'DB Error: unknown error' after adding custom fields to a report in CiviCRM?
I have one particular set of custom fields made up of plain text fields and rich text fields. But if I try to add any of them to a report for display, the following error is returned:

> DB Error: unknown error

I don't have this problem with other similar custom field sets, just this one. Is this something anyone has experience before? What's the cause of it?

# Answer
After turning on the debugging tool,it appears the field label was changed at some point and now cannot be referenced through reporting because the database is expecting the old field label and set name of the database cell to be referenced. It doesn't affect exporting the data though. If you have no access to the actual server then a solution is to create a new field and export and import all the data from the errant field to the new field, as far as I understand.
> 1 votes

---
Tags: entities, civicrm
---


# Question
Title: How to add classes to some images in a multi value image field?
I have content type with a multi value image field. When adding images is it possible to add a class to some of these images? The mark up I'm trying to achieve is some thing like:

```
<div class="field-item even">
<div class="field-item odd">
<div class="field-item even">
<div class="field-item odd my-class">
<div class="field-item even my-class">
<div class="field-item odd">

```

So when creating a new node I would like to add 'my-class' to come of the images. I've looked as Field Formatter modules but these seem to add the class on all items in the field.

# Answer
You can create a tpl.php file for your image field.

```
Possible override templates are:

field.tpl.php
field--field-type.tpl.php
field--field-name.tpl.php
field--content-type.tpl.php
field--field-name--content-type.tpl.php

```

code for field--field-name.tpl.php file as below.

```
 <?php

/**
 * @file field--field-name.tpl.php
 * Default template implementation to display the value of a field.
 *
 * This file is not used and is here as a starting point for customization only.
 * @see theme_field()
 *
 * Available variables:
 * - $items: An array of field values. Use render() to output them.
 * - $label: The item label.
 * - $label_hidden: Whether the label display is set to 'hidden'.
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. The default values can be one or more of the
 *   following:
 *   - field: The current template type, i.e., "theming hook".
 *   - field-name-[field_name]: The current field name. For example, if the
 *     field name is "field_description" it would result in
 *     "field-name-field-description".
 *   - field-type-[field_type]: The current field type. For example, if the
 *     field type is "text" it would result in "field-type-text".
 *   - field-label-[label_display]: The current label position. For example, if
 *     the label position is "above" it would result in "field-label-above".
 *
 * Other variables:
 * - $element['#object']: The entity to which the field is attached.
 * - $element['#view_mode']: View mode, e.g. 'full', 'teaser'...
 * - $element['#field_name']: The field name.
 * - $element['#field_type']: The field type.
 * - $element['#field_language']: The field language.
 * - $element['#field_translatable']: Whether the field is translatable or not.
 * - $element['#label_display']: Position of label display, inline, above, or
 *   hidden.
 * - $field_name_css: The css-compatible field name.
 * - $field_type_css: The css-compatible field type.
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 *
 * @see template_preprocess_field()
 * @see theme_field()
 *
 * @ingroup themeable
 */
?>
<!--
THIS FILE IS NOT USED AND IS HERE AS A STARTING POINT FOR CUSTOMIZATION ONLY.
See http://api.drupal.org/api/function/theme_field/7 for details.
After copying this file to your theme's folder and customizing it, remove this
HTML comment.
-->
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
<?php $i = 0; ?>
<?php foreach ($items as $delta => $item): ?>
<?php $i++; ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?> custom-class-<?php print $i;?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
    <?php endforeach; ?>
  </div>
</div>

```

For more info check field.tpl.php

To override node.tpl.php check

You can also check this link https://api.drupal.org/api/drupal/includes%21theme.inc/function/template\_preprocess/7
> 1 votes

# Answer
I think you should use the field preprocess function. You place it in your theme's `template.php`. You can make it only fire for specific fields, something like this:

```
    function MY_THEME_preprocess_field(&$variables, $hook) {
      $element = $variables['element'];
      if (isset($element['#field_name'])) {
        // Test to see if matches your field.
        if ($element['#field_name'] == 'field_MY_MULTI_IMAGE_FIELD') { // Add your additional logic here
          $variables['classes_array'][] = 'my-class';
        }
      }
    }

```

(Adapted from: https://stackoverflow.com/a/7582794/716845)
> 0 votes

---
Tags: media, theming
---


# Question
Title: alter the exposed form , make field hidden and accept it through node form field
can it be possible to alter the exposed form , make field hidden and accept it through node form field.

for example

Both node and views exposed filter will have the common date field and this view is shown on node/add pages. Instead of showing exposed filter field (date field) I

want to pass node form's field as filter to views which is in block.This will inform user what has been created on that date and prevent duplication.

Is this possible with just hook\_form\_alter ?

# Answer
> 1 votes
Yes its possible we do it like this

```
 function module_name_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "views_exposed_form"){
        $formId1 = "views-exposed-form-view-name-block-2";
        if($form_state['view']->name == "view_name"){
            if($form['#id'] == formId1){
                $form_state['input']['field_name'] = $value_field_name;     //set value
                $form['field_field_name']['#default_value'] = $value;//set default value
                $form['field_field_name']['#value'] = $value;//set the field value
            }
        }
    }
}

```

---
Tags: forms, views
---


# Question
Title: How to query the Database logs and create summary reports and/or charts of them?
Is there a module for querying and creating summary reports of the Database logs?

I need something that can create an equivalent of SQL Group by queries on the Database logs, eg, group by type, severity, count, IPs etc, and create views and possibly graphs on them.

# Answer
> 4 votes
The Views Watchdog module might be useful.

> The Views Watchdog module extends the Views module and allows to create customized lists (pages, blocks, feeds) of watchdog entries.

Combine it with the Charts module and a bit of custom code and you should be able to get a wide array of reports.

# Answer
> 1 votes
Here are some modules to consider:

1. The Charts module is indeed something you may want to consider for this. Refer to the recently created community docu about it for details. It should make it clear that "a bit of custom code" is indeed one of the possible approaches (using the Charts API). But it also offers Views integration that can typically be used by site builders also (without coding).
2. The Chart module (which is different from Charts ...) includes a **system charts** component. However, it appears to be rather undocumented (and hence unknown?). The goal of the issue about Docu about system charts? is to get that documented. For now the headers and menu tabs in the screenprint attached to issue 418736 should explain the kind of info you can get from it, **watchdog data** is part of it.
3. The Forena module is yet another module to be considered for watchdog related reported. It comes with all sorts of Sample reports and solutions, such as the *Site administration reports*, which contain data about the actual Drupal site.

Here are some details about those reports:

* **Active Users** \- A variation of D7's admin/people, including hyperlinks to the Logs for User report.
    * **Active Users Email** \- A demo of the ability to send email to all active users of a drupal site.
    * **Logs for User** \- Most recent watchdog log entries for a user (specified as a report parameter).
    * **Role Details** \- A table displaying all users for a Drupal role (specified as a report parameter), and the Drupal permissions granted to them, with for each user hyperlinks to either view or edit the user's profile.

Cloning these sample reports into custom variations is straight forward. E.g. tune the **active users** report with some report parameters to only report about user registered this week. Or as in this report (with drill-down links also, i.e. the numbers in red in it):

Refer to my comment in the forena issue queue for more details about the above screenshot.

There is even AbitMORE: this module also supports charting of those data (a typical related requirement ...).
4. For somebody looking (only) for info related to visitors of a website, the visitors module might be a valid alternative to consider also (and/or addition to any of the above modules). Refer to its \[community docu\]\[11\] for some more details.

**Be aware**: I'm a new (co-)maintainer of the first 3 modules, and the new maintainer of the last one.

---
Tags: 7, nodes, charts, log-messages
---


title: Date Of birth in drupal

text:
# Question
Title: Date Of birth in drupal
I am newer in Drupal. I am using Drupal services. I want to insert user birthdate by Drupal rest services. I want How we do this, Any help would be appericiated. Thanks in advanced

# Answer
> 0 votes
You can do that using the Date module

> This package contains both a flexible date/time field type Date field and a Date API that other modules can use.

---
Tags: 7, nodes, hooks
---


# Question
Title: Drupal 7 - Webform 3 - How do you expose form results to Views Easily?
What is a good module to use to expose Webform 3.x results to views? I want to create a views page with links to each form submission so search engine spiders can crawl and index user submitted questions.

# Answer
> 2 votes
If you want to make a page with links to each webform submission, you can just use Views itself; you don't need an extra module. Add a new view. Choose show *Content* of type *webform*. Check the box for *Create a page*. As the display format, I would recommend choosing the format you want and using *fields*; this will easily allow you to add links to the forms.

To be sure the search engines (Google, Bing, etc.) index your content, though, I wouldn't use this approach. I would use the XML Sitemap module.

# Answer
> 0 votes
Your only option, really (short of upgrading to at least D7/Webforms 4.0, or converting to real nodes -- see webform entity module):

https://www.drupal.org/project/webform\_mysql\_views

Limited, but may accomplish your goal.

---
Tags: views, webforms
---


title: Change view query

text:
# Question
Title: Change view query
I've a view and I would like to change it's query (slightly). Below is an example of what I have.

```
SELECT * FROM {node} node ORDER BY my_field ASC

```

I want to inject '***COLLATE utf8\_danish\_ci***' into query. My expectations below

```
SELECT * FROM {node} node ORDER BY my_field COLLATE utf8_danish_ci ASC

```

How would I do that in most correct way?

I'm also wondering if there is a way to apply such 'injection' only for specific view(s).

# Answer
You can achieve this by altering view query as follow:

```
/**
 * Implementation of hook_views_query_alter
 * @param type $view
 * @param type $query
 */
function <MODULENAME>_views_query_alter(&$view, &$query) {

  //simple example: change the order of the master display
  //if you want to do it only  on a certain display add something
  // like  "&&$view->current_display == 'panel_page_1'"
  if ($view->name == '<VIEWMACHINENAME>') {

    //to find out what the fieldname ist: use devel and add your desired field as
    //first filter ( =>orderby[0]). install devel and uncomment the next line
    //dpm($view->query->orderby)
    $view->query->orderby[0]['field'] = "{$view->query->orderby[0]['field']} COLLATE utf8_danish_ci";
  }
}

```

Add above code to your module, do necessary changes & clear cache.
> 2 votes

---
Tags: views, database
---


# Question
Title: How can I print usernames in order using entity_load function?
I'm using drupal 7.28, and I have fetched user id using `entity_load('user')`, so I need descending sorting on usernames using this way of logic, let me know if anyone has an idea.Here is my code that I have written in my file.

```
$users = entity_load('user',$sort);
$usersIds = array_keys($users);
foreach($usersIds as $usrId)
{
   $user = user_load($usrId);
   $user_load_name = array($user->name);
   echo "<pre>";
   print_r($user_load_name);
}

```

# Answer
> 1 votes
small change in your code will do it for you

```
$users = entity_load('user');//load all user in your site
$usersIds = array_keys($users); // get all uid of the user
foreach($usersIds as $usrId) {
    $user = user_load($usrId);
    $user_load_name = $user->name;//get the user name
    $user_load_name1[] = $user_load_name;// store all user name in array
 }
 natcasesort($user_load_name1);//For sorting array in ascending order INCASE SENCITIVE order
 $arr = array_reverse($user_load_name1, true);// For making it in descending

```

This code will only give the user name in Decending order if you want it in ascending order just remove array\_reverse() line that will be enough.

hope it helps you :)

---
Tags: 7, users
---


# Question
Title: How to change the price componnents order in the order total field view
I have a commerce site, I want to change the price componnents order of total order field in the order view page.
In the edit order page the last added line item -fee in my case , I add them manually- become the first in the in the price componnents field, I want do the inverse.
I didn't find any view to edit the added line items order. So I want to ask if there is a way to do that.

# Answer
> 1 votes
Implementing `hook_commerce_price_component_type_info_alter` hook you can change weight of price components to change sequence. Check following example:

```
<?php
/**
* Implements hook_commerce_price_component_type_info_alter()
**/

function <MODULE_NAME>_commerce_price_component_type_info_alter(&$components) {
  if (!empty($components['tax|tax_on_shipping'])) {
    $components['tax|tax_on_shipping']['weight'] = 30;
  }
}

```

---
Tags: commerce
---


# Question
Title: Updating other modules schema when creating custom module
I need to add a information to a content types within my module. Generally, is it good practise to update `node_type` schema or is it better to create my own and join it to the `node_type` via primary key?

Thanks.

# Answer
> 1 votes
You should make use of the `hook_schema_alter` to update entity schema of existing schema's.

```
function YOURMODULE_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['users']['fields']['timezone_id'] = array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Per-user timezone configuration.',
  );
}

```

---
Tags: 7
---


# Question
Title: How can I disable JavaScript in Drupal themes or Drupal itself?
How can I disable JavaScript in Drupal themes or globally?

# Answer
Javascript in and of itself is not the problem. I'd place more energy into ensuring that your Rich Textareas (body, comments, etc) and permissions are configured properly. This is one area where people can slip in rouge JavaScript which may be run on other visitor's browsers. Use TLS (Https) by default and use modules that aid in security such as Security Review, Secure Pages or Secure Login help secure the login process.

There is also tons of great advice and direction on line:
> 0 votes

---
Tags: theming, javascript
---


title: problem with Single Page Website module

text:
# Question
Title: problem with Single Page Website module
I wanted to try out the Single Page Website module for Drupal 7

I followed the instructions and all seemed to work well, except my anchor links wouldn't work i.e. it wouldn't scroll down the page when I clicked on them.

What might have been the problem there? The only anchor that seemed to work, was the link to a view.

Any ideas where I might have gone wrong or what I might have missed? Any experiences?

# Answer
I had this issue when I was testing out this module as well.

Solution: Create an Alias for each piece of content.

Each node/page you want to include on the single page, visit and add the alias. As admin, visit say, your default page you wish to have at the top, click Edit, and create the alias. In MY experience, once I did this for the pages for the Single Page using the single\_page module, it worked.
> 2 votes

---
Tags: 7
---


# Question
Title: Private files won't be saved anymore in their intended location? (D7)
I've got a D7 installation for some time now, with a content type that has a "private file" field.

It was working just fine up until now.

My files usually got uploaded like: http://....com/system/files/curso/file.txt And they get saved inside: **.../files/private/Private - accessible only to group members/\[nodeid\]/file.txt**

Now I've created a new node with an uploaded private file: demo.txt

When its downloaded it gets this path: http://....com/system/files/curso/demo\_1.txt

But I get "**Not Found**" when I click it because it gets saved in other location (?): **.../files/private/curso/demo\_1.txt**

## Notes

* The \_0, \_1 etc are automatically added to the files when they are saved into the node.
* I've tried accessing the file from its real location (.../files/private/curso/demo\_1.txt) with no luck.
* The "files" folder is directely inside public\_html because the original setting was that way (the site comes from a D4.7, D5 and then a D6 installation).
* It worked just fine with other files up until now. I've not done anything special (like installing new modules), except creating a few new node types and rebuilding the permissions.

What could I do? (BTW, I've read this information, and sadly it didn't helped).

## Update - Error Logs:

\[Mon Mar 02 12:37:40 2015\] \[error\] \[client 181.28.74.188\] client denied by server configuration: /home/sitio/public\_html/files/private/curso/demo\_1.txt (I've found more info about this here)

# Answer
You spoted your problem in your apache log file : Apache is forbiding access.

You have 2 options here :

If you want apache to allow access to these files then add this to apache conf file :

```
<Directory /home/sitio/public_html/files/private/curso>
  AllowOverride None
  Order Allow,Deny
  Allow From All
</Directory>

```

then restart apache and I guess you should be ok to access your file.

But if you want these files to be private then you want to restrict access rather than open it, so

Alternatively,

you let apache restrict access to these files, and you set drupal serve these files via alternative drupal-generated links. Check the documentation for setting up access to private files here, look for the section on "Accessing Private Files".

If you've got no .htaccess file for the folder as you said then create one with :

```
Deny from all
Options None
Options +FollowSymLinks

```
> 1 votes

---
Tags: files
---


# Question
Title: How to report about how many users have registered in a given timeframe?
We want to know how many users registered to our website as a report.

I'm looking for a way (or a solution) in D7 that allows me to give me a report of how many user have registered to my website. Ideally will show me how many user register yesterday, weekly, monthly and annual.

# Answer
Here are some modules to consider, for anybody who is not able or willing to write some PHP coding to answer such typical reporting question (or anybody who does not want to enable the PHP filter in a site):

1. The Forena module can be used for such types of reporting. It comes with all sorts of Sample reports and solutions, such as the *Site administration reports*, which contain data about the actual Drupal site. Here are some details about those reports:

* **Active Users** \- A variation of D7's admin/people, including hyperlinks to the Logs for User report.
    * **Active Users Email** \- A demo of the ability to send email to all active users of a drupal site.
    * **Logs for User** \- Most recent watchdog log entries for a user (specified as a report parameter).
    * **Role Details** \- A table displaying all users for a Drupal role (specified as a report parameter), and the Drupal permissions granted to them, with for each user hyperlinks to either view or edit the user's profile.

Cloning these sample reports into custom variations is straight forward. E.g. tune the **active users** report with some report parameters to only report about user registered this week.
2. For somebody looking for info related to visitors of a website (registered users is a subset of them, no?), the Visitors module might be a valid alternative to consider also (and/or addition to the above module). Obviously, to submit a registration request one has to "visit" an URL like `user/register` (or something similar).

The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module module. Refer to the Visitors community docu for some more details.

Extra reporting features can be enabled via these sub-modules:

* The **Visitors GeoIP** module, to also report about countries and cities.
    * The **Visitors Browscap** module, providing statistics on visiting browsers.

Both modules also support charting of those data (a typical related requirement ...)

Disclosure: I'm a (co-)maintainer of Forena, and the maintainer of Visitors.
> 4 votes

# Answer
Why are you searching for a module. You can create a block & add custom code.

1. Enable the PHP filter
2. Create a block
3. Add the following code

```
$result= db_query("SELECT count(1) from {users}") -> fetchField();

print '< ul > < li >' . $result . ' < /ul>''< /ul>';

```
> 1 votes

---
Tags: 7, users, log-messages
---


# Question
Title: Restrict acces to file field only to certain role
I have a node-type called "download" that has a field "file" with unlimited entries. Those files are already stored inside a private path. Now I want to restrict access only to a certain role. I already tried field\_permissions but when I enable `View field_file, regardless of content author.` and grant that permission only to authenticated users, I still can view/download that file as a guest. What am I doing wrong here?

Besides it would be nice to set permissions on a node base. Like "This Node is only Viewable by Role XYZ".

Thanks for any hints!

# Answer
> 4 votes
like Colin McClure says, to control per node you can use with http://drupal.org/project/content\_access .In the respective Access Control tab of each Content Type (when you edit a content type), you will find, in the bottom, the option to enable per content node access control settings.

About control per fields, seems that exist several modules to achive this:

and, from this resource you can find hooks to get permissions per field:

http://drupalcode.org/project/cck.git/blob/refs/heads/6.x-3.x:/modules/content\_permissions/content\_permissions.module

```
<?php

/**
 *  Implementation of hook_perm().
 */
function content_permissions_perm() {
  $perms = array();
  foreach (content_fields() as $field) {
    $perms[] = 'edit '. $field['field_name'];
    $perms[] = 'view '. $field['field_name'];
  }
  return $perms;
}

/**
 * Implementation of hook_field_access().
 *
 * @see content_access().
 */
function content_permissions_field_access($op, $field, $account, $node = NULL) {
  switch ($op) {
    case 'view':
    case 'edit':
      return user_access($op .' '. $field['field_name'], $account);
  }
  return TRUE;
}

```

# Answer
> 0 votes
If you are looking to set permissions on a node basis then you need another module called Content Access. Do bear in mind though that the more ACL permissions you use the slower the site will become. Unfortunately, this is a side effect.

# Answer
> 0 votes
For the actual download ability, you can try https://www.drupal.org/project/private\_files\_download\_permission.

> ...a simple permission to allow downloading of private files by role...

---
Tags: 7, users
---


# Question
Title: Drupal - block deleted - how to retrieve
I just posted this to StackOverflow, but then I noticed this group, so apologies if this is a duplicated question.

We're running version 6.14 of Drupal (old, I know). On of our users recently deleted a block by accident in a series of rotating images. (Administer \> site building \> block). So now the block shows up as a blank, or "n/a".

She did manage to add another block in its place, but apparently that doesn't help - the n/a still displays. What is the solution to this problem?

# Answer
> 0 votes
The problem was that the new block the user created had a block number of "8", whereas the original block that was deleted had a number of "2". The fix was to go into custom themes for the homepage, edit page.tpl.php, and change the "module\_invoke" to refer to the correct block

---
Tags: blocks
---


title: Theming translatable nodes in D7

text:
# Question
Title: Theming translatable nodes in D7
We used i18n module to have our nodes as translatable. However we also themed a specific nid with e.g node--9.tpl.php.

Problem is that i18n *creates separate nodes*(this separate nids), for each translation language, thus the theme file only applies to 1 version of that particular node.

How can I handle this?

# Answer
> 2 votes
Add following code to `template.php` and clear cache

```
function <THEME_NAME>_preprocess_node(&$vars) {
    if(!empty($vars['node']->tnid) && $vars['node']->tnid !== 0){
        $vars['theme_hook_suggestions'][] = 'node__'.$vars['node']->tnid;
    }
}

```

---
Tags: 7
---


# Question
Title: View (Read Only) access for Drupal Commerce - Orders
I have added 2 attributes into my Drupal Commerce Orders set of fields - Fivestar Rating & Review. My client needs me to show the ratings and reviews in "Testimonial" section of home page in ticker format. I was able to successfully integrating Rating + Review into Orders and show the testimonial section for users with role as Admin.

Below pictures show my configuration:

A chunk (Sidebar second) of my home page for Admin user with running ticker:

However, the anonymous visitor to the webiste is not able to view the contents of this ticker because anonymous does not has view access on the orders created in the website:

Now, ideally the orders (and hence the ratings and reviews inside the orders) should be accessible to the anonymous users. But yet, the ticker does not show any content and also the Orders page "**/admin/commerce/orders**" will not show any orders at all:

I need help with the following 2 items:

1. Why anonymous user is still not granted the view permission for the orders (and it's contents). How can I fix this?
2. I do see that there is a security implication even to provide "View" access to anonymous users on my Orders. How serious is this threat? Is there any safer way to get view access to orders and its contents? What is the right way of doing this?

Thanks for any efforts by the community to help me out :)

# Answer
> 1 votes
Inside your view, what are you access options (located under "Page Settings")? That would be a good place to start. Naturally clear the cache after every permission change.

I also don't think it would be wise to allow anonymous users to view any/all orders.

---
Tags: 7, users, commerce
---


# Question
Title: How to concatenate a string in a WHERE clause of an SQL query?
I'm trying to execute the following query but when I append the **'n.nid = "node/" + ua.source'** condition I'm getting an error page:

```
        $query = db_select('node', 'n')->extend('PagerDefault');
        $query->join('url_alias', 'ua', 'n.nid = "node/" + ua.source');
        $nids = $query
            ->fields('n', array('nid', 'sticky', 'created'))
            ->condition('type', 'news')
            ->condition('status', 1)
            ->orderBy('sticky', 'DESC')
            ->orderBy('created', 'DESC')
            ->limit(3)
            ->addTag('node_access')
            ->execute()
            ->fetchCol();

```

Any suggestions to resolve this?

# Answer
> 4 votes
There is a small changes in code. I think it will help you.

```
$query = db_select('node', 'n')->extend('PagerDefault');
        $query->join('url_alias', 'ua', "ua.source = CONCAT('node/', n.nid)" );
        $nids = $query
            ->fields('n', array('nid', 'sticky', 'created'))
            ->condition('type', 'news')
            ->condition('status', 1)
            ->orderBy('sticky', 'DESC')
            ->orderBy('created', 'DESC')
            ->limit(3)
            ->addTag('node_access')
            ->execute()
            ->fetchCol();

```

For more info check

---
Tags: database
---


# Question
Title: How to make specific custom table data searchable in Drupal 7?
I just created custom module with name `example` , And it has a form to enter data to it's specific custom table. I want to make the data in this custom table searchable with Drupal default search feature.

Please guide me.

Thanks in advance.

**Update**

I already skimmed through the Drupal api docs and followed the instruction but I couldn't make it working.

# Answer
> 1 votes
The Drupal search interface manages a global search mechanism.

Modules may plug into this system to provide searches of different types of data. Most of the system is handled by search.module, so this must be enabled for all of the search features to work.

There are three ways to interact with the search system:

* Specifically for searching nodes, you can implement hook\_node\_update\_index() and hook\_node\_search\_result(). However, note that the search system already indexes all visible output of a node; i.e., everything displayed normally by hook\_view() and hook\_node\_view(). This is usually sufficient. You should only use this mechanism if you want additional, non-visible data to be indexed.
* Implement hook\_search\_info(). This will create a search tab for your module on the /search page with a simple keyword search form. You will also need to implement hook\_search\_execute() to perform the search.
* Implement hook\_update\_index(). This allows your module to use Drupal's HTML indexing mechanism for searching full text efficiently.

If your module needs to provide a more complicated search form, then you need to implement it yourself without hook\_search\_info(). In that case, you should define it as a local task (tab) under the /search page (e.g. /search/mymodule) so that users can easily find it.

The full documentation can be found at https://api.drupal.org/api/drupal/modules%21search%21search.module/group/search/7

---
Tags: 7, search
---


title: Converting entity to JSON

text:
# Question
Title: Converting entity to JSON
I am quite new to Drupal and Drupal 8.

I have created a custom module that creates a custom content type. I am attempting to extract those entities and display them as JSON or XML.

I have read through the Entities Api on loading, querying, and rendering entities but I am struggling to find view\_mode\_name types :

```
$build = $view_builder->view($entity, 'view_mode_name', $language->getId());

```

Would I be able to do something like :

```
$build = $view_builder->view($entity, 'xml', $language->getId());

```

or does this only produce a 'render array' ? If this is the case then should I be looking at the Serializer Api ? If so would anyone be able to guide me in the right direction on using this ?

Here is my code so far :

```
public function display() {
// use the debug component
Debug::enable();

// get node -> testimonial content types
$entity_ids = \Drupal::entityQuery('node')
->condition('type', 'testimonial')
->execute(); // fetch

$node_storage = \Drupal::entityManager()->getStorage('node');

$data = $node_storage->loadMultiple($entity_ids);

$view_builder = \Drupal::entityManager()->getViewBuilder('node');

// render multiple
return $view_builder->viewMultiple($data, 'xml');

}

```

# Answer
View builders only display HTML/render arrays.

Look into the serialization/rest/hal modules if you want to extract the data of your entity, as you guessed already.

Note that REST in core only supports content entities at the moment, but I assume you have one of those.

Also, I'd recommend hal+json serialization, provided by the hal.module instead of the raw json seralization, as that can't deal with things like references properly.
> 2 votes

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


title: Hiding Email Address Form Alter

text:
# Question
Title: Hiding Email Address Form Alter
I'm trying to hide non-admin users to view the email address field in the user section. I have the following hook. Right now, I have the current password hidden, but the email sends back a naughty validation requiring email to be added.

# Answer
You can use similar code as below to hide pass and mail field with optional value.

```
//drupal_set_message('not admin!');
$form['account']['current_pass']['#required'] = FALSE;
$form['account']['current_pass']['#access'] = FALSE;
$form['account']['mail']['#required'] = FALSE;
$form['account']['mail']['#access'] = FALSE;

$form['#validate'] = array_diff($form['#validate'], array('user_validate_current_pass'));
$form['#validate'] = array_diff($form['#validate'], array('user_validate_mail'));

```
> 1 votes

# Answer
If you want to alter Drupal so that it doesn't require email addresses for users, you should look at this module: https://www.drupal.org/project/optional\_mail

Read the module description carefully. User emails are deeply integrated into Drupal, and not having them can cause all kinds of unexpected problems.
> 0 votes

# Answer
You can use Field Permission module. It allows you to set permission for every field for every role in your website. So if you prevent non-admin users from accessing this field, they wont see it.
> 0 votes

---
Tags: emails, users
---


title: Featured product-Drupal commerce

text:
# Question
Title: Featured product-Drupal commerce
I have this issue:I have on a product display a "Featured" checkbox. I want when this "Featured" checkbox be selected,the price of the product to be increased by some amount when being added to the cart. So:Normal product will cost 100$ ,if Featured is selected the price will be +50 (150$). Can this be done with a rule?If so,how? thanks

# Answer
> 0 votes
Event: adding product to the cart. Conditions:
1. Entity has field (the featured field). 2. Data comparison: (is that field "on"?) Action: add amount to the unit price.

I'm not looking directly at the Rules interface, but that should get you well on the correct path.

---
Tags: commerce
---


# Question
Title: Solr Search - Adding taxonomy to Search results
I'm using the 'Solr Search' module ( not Apache solr search ) .

What I need to do is return results that have a taxonomy term relationship.

In my search indexes 'fields' I have the taxonomy I want 'Keywords' selected. The type for this is 'Taxonomy term' . I have also added 'Keywords » Name' through 'Add Related Fields' . This is type 'Fulltext' and after reindexing and saving this field appears in views/search/page / search ‘full text’ / Searched fields.

However when I search for a keyword through the exposed filter the results are not being returned. They can however been seen in Facets.

Any idea what I might be missing.

# Answer
I rebuilt the view and this time it worked fine.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to add a button to report (flag) some content item to an administrator for that content?
I would like to print near a given type of content a button "report" that, when pressed, send a notification to the admin related to that content.

In this specific case, I have a textual field with a link and I would like to allow users to be able to report (signal) some content item to the administrator if some link is not working anymore. So that the administrator can fix it.

# Answer
> 1 votes
You should investigate the flag module https://www.drupal.org/project/flag and Rules https://www.drupal.org/project/rules (remembering to use version 2.7 of the latter if using drupal commerce) that should allow you to create a "report" flag and send a notification to an admin.

---
Tags: 7, flags, notifications
---


# Question
Title: I'm probably completely over thinking this
I am working on a calendar for our agency and want to have public access to submit events using a webform created from the webform module, and of course this event would not be published without admin signing off on it.

It doesn't appear this is a normal feature in webform/views/calendar module. What am I missing?

# Answer
> 0 votes
Have a look at Entity forms https://www.drupal.org/project/entityform rather than webform then the user can create an entity that can be converted to your event style content type. Some form of workflow will clearly be involved. Rules may help you avoid coding.

---
Tags: datetime
---


# Question
Title: How to redirect everything to 404 not found?
I need to block an entire Drupal 7 site from being indexed for a while. So, I think it is best to redirect everything to 404 instead of actually deleting all my files. How can I do that?

PS: using the following code on .htaccess does not seem to work.

```
RewriteEngine On
RewriteRule ^ - [R=404,L]

```

**-- Update 03/04/2015 --**
The server is nginx

# Answer
If you are just trying to keep it from being indexed, you can just add

```
User-agent: *
Disallow: /

```

To the top of your robots.txt
> 5 votes

# Answer
You'll need to remove the existing Drupal rewrites for the moment; with them left in the .th access this code won't work.
> 0 votes

---
Tags: redirection
---


# Question
Title: best practice: what directory should the theme be located for a site install profile
I am building a site install profile. Trying to wrap my head around the file structure. I am creating a Drupal 7 install profile with a sub theme off of omega.

Is it better practice to put the theme in the

```
profile/themes

```

or

```
sites/all/themes

```

# Answer
> 0 votes
Normally, the theme would go in:

```
/profiles/YOURPROFILE/themes/YOURSUBTHEME

```

Also include the base theme at the same location:

```
/profiles/YOURPROFILE/themes/omega

```

---
Tags: theming, installation-profiles
---


# Question
Title: Can I safely delete auto-created Postgres Indexes?
Running Drupal 7.X with a Postgres 9.3 database.

When adding new fields, 8 database indexes appear to be created for each new field. Running the query "select * from pg\_stat\_all\_indexes;" shows that only 2-3 out of the 8 indexes are actually getting used ... primarily *field\_data\_field\_XXXXX\_entity\_id\_idx* and *field\_data\_field\_XXXXX\_pkey*. All the other indexes (*e.g., ...bundle\_idx, ... deleted\_idx, ... language\_idx, etc.*) show 0 for idx\_scan, idx\_tup\_read, and idx\_tup\_fetch.

Is it safe to delete those indexes that show 0? Once deleted, is there an easy way to recreate the indexes if needed?

The reason for wanting to delete those indexes is that hard drive space is limited. Deleting those indexes would recover significant amounts of hard drive space.

# Answer
> 0 votes
I used the following PSQL query to identify all the indexes not being used and to sort by biggest first:

```
SELECT nspname || '.' || C.relname AS "relation",
  pg_relation_size(C.oid) AS "size",
  idx_scan,
  idx_tup_read,
  idx_tup_fetch
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
LEFT JOIN pg_stat_all_indexes stat ON C.relname = stat.indexrelname
WHERE nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY pg_relation_size(C.oid) DESC

```

I deleted several dozen indexes. So far, no issues. It seems performance may be improved as I am noticing less CPU resources needed. Likely because there are fewer indexes to be updated.

---
Tags: entities
---


# Question
Title: Export a sqlite database through drupal admin?
I have a drupal site running on sqlite. I'd like to backup the entire sqlite db, but keep running into "reading secure data from server" issues on my server. How do I go about backing up just the sqlite db from within the drupal admin area?

# Answer
Not aware of an out of the box way to get it done in the admin area, but you shout be able to back the sql lite file up by downloading it in cpanel or ftp. There is a discussion about doing just that right here https://www.drupal.org/node/1156588
> 0 votes

---
Tags: 7, database
---


title: ng angular typeahead drupal

text:
# Question
Title: ng angular typeahead drupal
Has anyone got the angularjs bootstrap-ui "typeahead" widget to play nice with drupal autocomplete?

seems like a match made in heaven

I will try this in the next week or so - but just checking if anyone has a working example before I set out on the journey.

# Answer
OK. Its not hard.

To achieve the same thing in angular (being served by drupal), have to:

1. get angular and bootstrap ui working.
2. create the element in my view
3. add a function to the controller $scope to access $http ($http needs to be injected as a dependancy into the controller).

In my FAPI form I had a autocomplete\_path defined:

```
 '#autocomplete_path' => 'agc/ac/contact/_',

```

So to access the same call back, in my Angular template:

```
 <pre>Model: {{result | json}}</pre>
  <input type="text" ng-model="result"
   typeahead="suggestion for suggestion in cities($viewValue)">

```

The controller:

```
angular.module('contactFindControllers', []).controller('contactFindCtrl',
  ['$scope', '$http', function($scope, $http) {
    $scope.cities = function(cityName) {
    var path = '/agc/ac/contact/_/' + cityName;
    return $http.get(path)
    .then(function(response){
      // see note below regarding "_.values()"
      return _.values(response.data);
        });
  };

}]);

```

FYI: I used this as a starting point.

Note: my callback returns a JSON object (because I have non-numeric keys) not the array I needed, so I need to extract the values with `_.values()`. You many not need to use \_.values at all (or if facing the same issue just grab the values from the object *or* modify your call back to return a json array)
> 1 votes

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


title: Can I merge two views into a third one

text:
# Question
Title: Can I merge two views into a third one
I'm new to views and was wondering how I can accomplish this:

I have two views one that takes receivable invoices and displays them and then totals them at the end of the table using View Aggregate Plus. Another view that grabs invoices that are payable and once again totals these together.

What I'm looking for is a way to take the total of these two views and then display it in a third view called balance which will take the total of receivable invoices and subtract the total of payable invoices.

Is there a way to do this?

# Answer
> 0 votes
Here is the way to render multiple views on a single template file.

you need to make use of views\_embed\_view Using this function, you can embed Views and even dynamically pass them filter arguments. - See more at: http://www.webomelette.com/drupal-embed-view-template-tpl

you can use this function multiple time to get your both views rendered and then do your operations on variables available from them \[you need to figure out this at-least\], here is the help

---
Tags: views
---


title: default field permissions

text:
# Question
Title: default field permissions
I have created a module that adds a an extra field for each user. I do this by first creating the field using field\_create\_field and then I bind it to the user object using field\_create\_instance. This is standard practice I think.

Now, I would like to add so that by default only administrators should be able to change the value of this field. I would like to keep down the number of external modules, so if possible I would like this to be the default behavior after installing my module, without relying on other modules such as field\_permissions to achieve this.

Is this possible?

Thanks in advance!

# Answer
> 0 votes
I found the answer. It is done using the hook\_field\_access. In my case, what I did was:

```
function my_module_field_access($op, $field, $type, $entity) {
    if ($op=="edit" && $field["field_name"]=="my_field") {
        if (!user_access("administer users"))
            return FALSE;
    }
}

```

---
Tags: users
---