# Question
Title: How to summarise different date ranges using this week, last week, etc?
I would like to display a table or graph showing revenue over the last year with sums divided into weeks or months.

I record every sale/value in an entity, and can show ie "total this week" or "total this year" with Views and aggregation, but I would like to show it like "this week", "last week", "last week -1" without having to make a view or attachment for each value.

Is this possible without making a new entity ?

**Notes**:

* I want to use Views, but I wonder if there is a way to group/aggregate values without having to make a new view for each aggregation (week or year). Then I will have to make 52 views/attachments for showing weeks and 12 to show the year.
* I can create a date field in my view and format it as year-month eg 2014-12 and then group by that and use aggregation. But then I will have to make one for 2014-11, 2014-10, 2014-09, etc

# Answer
"Date Views" (`date_views`) sub-module of the Date module extends the "Configure filter criterion" used in Views. It allows for using "**Relative dates**" that are computed when the view is displayed.

Some examples are:

* now
* now + 1 days
* -2 months
* Monday next week
* ...
> 0 votes

---
Tags: views
---


# Question
Title: how can i remove the login form from the home page
I'm trying to remove the login form from the front page, but i see both frontpage and user/login page are using the same template file: page--front.html.twig.

Is there a way to use two different template files for each page?

# Answer
> 3 votes
Try going to `Admin/Structure/Blocks` and set `User account menu`'s region to `None`.

# Answer
> 0 votes
I had the front page set to null. I had to create an empty basic page and set it as front page to be able to have a front page different than the /user/login page. I don't feel it's the best way to do it, but it works.

---
Tags: theming, 8
---


# Question
Title: CSS Not Displaying Correct Via .info File (ok on page.tpl)
Hello I have a strange situation that I just cannot get my head around and I hope someone can help.

If I add css directly in page.tpl as:

```
<style type="text/css">
  my css
</style>

```

Everything works as I expect. However, when I move the css to file called ross.css, and add stylesheets\[all\]\[\] = css/ross.css to my theme.info file the browser will parses the css code but the effect is not what I'm expecting. I don't know if I should post all the css in here as I don't think the code can be the problem if it displays as I expect when I insert it directly on the page.

PS: I'm using a bootrap-based theme.

# Answer
> 0 votes
I suspect it's because, when it's ross.css, your css gets applied before another .css file; while, when it's in .tpl it gets applied after.

Ex: if `h1` exists with the same command, it uses the last h1 (which is in some other .css file).

JS FIDDLE EXAMPLE

So try adding `!important;` to your css. ex: `h1 { border: solid red !important; }`

JS FIDDLE EXAMPLE 2

---
Tags: theming
---


title: Get url from image field

text:
# Question
Title: Get url from image field
For each user, I created a new field called `field_cover`, this field is an image.

I want to get the `field_cover` path, to use it into a `background-image` property.

I try this but it does not work.

```
<?php print render (file_create_url($user_profile['field_cover'])); ?>

```

Thanks for your help !

# Answer
The function `file_create_url()` in D7 needs a uri (see this useful article). You can typically access the uri of a file this way:

`$user_object->field_name[LANGUAGE_NONE][0]['uri']`.

In your case, since $user\_profile seems to be an array of fields, try:

`file_create_url($user_profile['field_cover'][LANGUAGE_NONE][0]['uri'])`.

This should return the full URL of the image.

Further information in your question may help me fine tune this answer.
> 0 votes

# Answer
You could use the URL FORMATTER module

> This module add a url formatter for image field. Then you can output image url directly.

Once enabled, go to your user manage fields, and change the picture field formatter to url.

If you are using Views, Views UI will give you an option to change the format to url in your field settings.
> 0 votes

---
Tags: entities, users
---


title: Transfer a site from SQLite to MySQL

text:
# Question
Title: Transfer a site from SQLite to MySQL
Is it possible to transfer the content of a site that I develop locally with SQLite as a database to the live site which uses MySQL or PostgreSQL when it is finished?

I don't want to have to install MySQL or PostgresSQL locally on my laptop. Can backup\_migrate module do it or does it export raw MySQL instructions?

# Answer
You are looking for the DBTNG Migrator module.

> This module is a UI and Drush interface to replicate a database from one database to another independant of what kind of database server they are. So long as ther are support by Drupal, you can migrate to them, including non-SQL stuff!
> 6 votes

# Answer
i have a lot of trobles doing that. So finnaly i did it, so what do you need to do migration goes well:

1. Delete other languages from site, exept english
2. disable locale, and localization update module.
3. Make migration in empty mysql database with dbtng migration module
4. You will have trobles with enable languages at new database, so create a fresh install of drupal and make export tables trought phpMyadmin: languages, locales\_sorce and locales\_target.
5. Import them to new mysql migration website database

Hope it help somebody
> 0 votes

---
Tags: database, backups
---


title: Issue license without an order

text:
# Question
Title: Issue license without an order
I'd like to issue free Commerce Licenses to files for users of certain roles without creating orders.

I haven't been able to find a tool for this in the Commerce License UI. Have I missed it? Or is it possible to create such a tool without having to code?

Thanks in advance for your answers

# Answer
I'm not sure if this solution applies to your specific case, but on my site, I award a role with the license. So, when I want to "give away" a license without creating an order, I just add the role to the account. Or, I use the Rules and Flag modules to flag a user (and there is a rule that automatically adds the role).

If you really wanted a license, you could also probably use Rules to create an order and fill it with dummy information, then award the license that way. Commerce License has decent Rules module integration, so you can get pretty far without any coding.
> 0 votes

---
Tags: commerce, users, files
---


# Question
Title: What permission gives users access to the "additional settings" options (author, etc.)?
Which permission should I give to users to allow them to change the author of node content?

# Answer
**Administer nodes** is the permission for changing the author.
> 0 votes

---
Tags: users
---


title: Having Views searchable by users

text:
# Question
Title: Having Views searchable by users
I would like to be able to search my views by a field that is generated by an Entity Reference of users of the site.

**Attempt #1 - Combine Fields Filter**
I added this filter as exposed with the setting of "Contains" either from the "Title" field or the "Responsible Party" field (which is the Entity Reference field that is a list of users. Here is a picture of the settings
The results of this were that the title field is filterable as pictured here
Yet the user generated field did not properly filter as shown here

**Attempt #2 - Search: Search Terms filter** Same process and same issues using this filter. Here is a picture of the settings

Then the same results as shown here.
Searching Title
Searching Users

# Answer
Looks like you did all the steps correctly, How To Create Combined Search Filters In Views?, which leads me to believe that this is a bug.

Upon looking at the View's issues, I found **Combined fields filter not working with entity reference.**

Therefore, you will have to use it as a standalone, not combined, filter until this bug is fixed, which does not look like it will be any time soon.
> 3 votes

---
Tags: 7, views, users, entities
---


# Question
Title: How can I show a message to visitors of a blocked user account page in Panels?
When a user account is blocked, the user profile can no longer be viewed. This makes sense, but is it possible to use Panels to override the user profile display to show a custom variant that has a message like "This user has closed his/her account"?

I looked through the available **Selection rules**, but the only one that seemed like it might work is *User has permission* (I tried one of the "edit content" permissions since I don't think that blocked users have permission to edit content). However, setting "not having edit permission" as a selection rule did not cause my custom variant to be displayed.

Again, what I want to do is show a message on the user profile page ("This user closed his/her account") instead of the default behavior, which is giving me a "too many redirects" error.

# Answer
You could try to use the Rules module for this, using an approach that is similar to my answer to the question "How to create a redirect to point to the user's id?", in which you use values for `the_old_path` and `the_new_path` that fit your needs here, i.e.:

1. Change all occurences of `the_old_path` to the path of the user profile.
2. Change all occurences of `the_new_path` to the path of your custom variant.
3. Add a Rules condition to check if the user account is blocked.
4. Fit the message being displayed to fit your needs. If you don't want such message to appear, then just delete the line containing `drupal_message` in the rule.
> 0 votes

---
Tags: users, panels
---


title: Number translation with 118n module

text:
# Question
Title: Number translation with 118n module
I have developed a multi-lingual site with i18n module (7.x-1.13) and everything works as expected.My Drupal version is 7.34.

Recently, my client have asked not to translate the number. The website works in English and Arabic.

To be more specific, when Arabic is chosen, we do not want the numbers to be displayed in Arabic, instead we need to display the same in English. Now, each numbers are translated to Arabic when the language is chosen as Arabic, even the user input.

The default language is Arabic and I haven't installed any modules for translation of numbers.

Any help would be much appreciated.

# Answer
You can use PersianTools modules,

**Features**

> This module is going to cover some basic features required for Persian websites.
>
> ```
> Fix possible misplaced chars in mixed Persian and English texts
> Find a way to fix Calendar.
> Convert English numbers to Persian numbers.
> Fix sort issues for persian characters.
>
> ```

One of its features is **Convert English numbers to Persian numbers.** ( indeed Persian number is Arabic digits ).

Install this module and go to its settings and just active convert digits.

Also you can convert all Latin digits to Arabic with some Js code.

Try something like this (put it in custom JS file and load in each page\_

```
String.prototype.toIndiaDigits= function(){
  var id= ['list of arabic digits'];
 return this.replace(/[0-9]/g, function(w){
  return id[+w]
 });
}
var content= $('body').html();
$('body').html(content.toIndiaDigits());

```

See this articles about how change Latin digits to Arabic

https://stackoverflow.com/questions/1675786/convert-from-english-digits-to-arabic-ones-in-html-page

https://stackoverflow.com/questions/21415121/convert-english-digits-to-arabic-digits-in-html-documents

http://jsfiddle.net/McxL5/
> 2 votes

# Answer
Thanks for the solution. But, the main problem was with the font that I was using when Arabic is loaded. This made the English numeric digits to convert to Arabic automatically. I have now made the same font to be loaded in both the languages. This solved my problem.
> 0 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: Block expands more than the height of content when using collapsiblock module?
I have applied the collapsible property to one of the block using Collapsiblock in Drupal 7. everything working fine, but the issue is that, after clicking for slide, it slides more than the content height and then after again in back slides and then fits to the content. I want that it just slide till its content and stops on first instance. Please see attached Image.

# Answer
This is a wild guess (no time to test this) but you could try some of the following and see if this will make a difference:

1. Try using a different version of jQuery (download and install jQuery Update and then go to Configuration\>Development\>jQuery update and test different versions. Don't forget to clear the cache every time before the test).
2. Try tinkering with your CSS classes for the block and its contents to include a max-height: 100% property. For example, try this for the ID of the block (e.g. #block-block-2) and/or for the .content class inside that block (#block-block-2 .content)
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: Twig C module not enabled causing issues with blocks?
I installed Drupal 8 on shared hosting and am having a problem in which blocks are not visible after I've placed them in a region. The blocks that came preinstalled with the themes are visible, but every new block that I place does not show up on the site. I did a status report and it said that Twig C extension is not available. I was wondering: could this could be something that affects the placement of blocks as Twig works with the new template system?

# Answer
To answer your question: No, the twig extension has absolutely nothing to do with that.

To actually figure out why your blocks don't show, you need to provide more information. Are you using a custom theme? How does the configuration of your blocks look like (screenshots of the block overview and edit page would be best).
> 2 votes

# Answer
Well, I couldn't find anyone else that seemed to have the problem that I was having. However, I think I found out what was going wrong.

Drupal has a directory called **../sites** that I was having permission problems with. I found that the lack of permission was affecting other issues that I was having with my site with CSS and JavaScript files in **../sites/default/files**. I was granted permission to the files via my server administration. I uninstalled Drupal, reinstalled and all of my problems were resolved.

I use One.com for my hosting. It seems that the server has a script that created a directory called **Sites** whenever I completely emptied my home directory. The directory contained files for host parking that seemed to restrict certain permissions to me. The naming convention, I believe, may have been causing problems. After correcting the permissions and reinstalling Drupal, everything is perfectly fine.
> 0 votes

---
Tags: blocks, 8, theming
---


# Question
Title: Override html.twig.html within custom module
According to this Drupal 7 answer, I'm looking for a Drupal 8 solution to simply print the page content within a custom html.twig.html.

```
namespace Drupal\custom_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class CustomModuleController extends ControllerBase {

  public function content() {

    return [
        '#theme' => 'custommodule_page',
        '#type' => 'page',
    ];
  }
}

```

This approach seems to be working, but I am not sure how I can remove the core and theme CSS components.

# Answer
> 2 votes
You can completely take over the printed page if your return value is an extension of Symfony's Response class.

Here your return value is a render array so Drupal assumes it is to be rendered in a normal HTML page.

This complex looking diagram shows the flow of request to response:  You can read more about the diagram here: https://www.drupal.org/developing/api/8/render/pipeline

The first takeaway on that docs page is

> Routes whose controllers return a Response object bypass the pipeline below. They rely directly on the Symfony render pipeline.

In other words, most of the complexity of that diagram covers the case where the return value of a controller is NOT a Response object. Returning a Response object cuts out what Drupal normally does to wrap the render array in the `html.html.twig file`.

There are a lot of examples in core of direct returning of a response object. Here is one:

```
public function testFeed($use_last_modified, $use_etag, Request $request) {
  $response = new Response();

  $last_modified = strtotime('Sun, 19 Nov 1978 05:00:00 GMT');
  $etag = Crypt::hashBase64($last_modified);

  $if_modified_since = strtotime($request->server->get('HTTP_IF_MODIFIED_SINCE'));
  $if_none_match = stripslashes($request->server->get('HTTP_IF_NONE_MATCH'));

  // Send appropriate response. We respond with a 304 not modified on either
  // etag or on last modified.
  if ($use_last_modified) {
    $response->headers->set('Last-Modified', gmdate(DateTimePlus::RFC7231, $last_modified));
  }
  if ($use_etag) {
    $response->headers->set('ETag', $etag);
  }
  // Return 304 not modified if either last modified or etag match.
  if ($last_modified == $if_modified_since || $etag == $if_none_match) {
    $response->setStatusCode(304);
    return $response;
  }

  // The following headers force validation of cache.
  $response->headers->set('Expires', 'Sun, 19 Nov 1978 05:00:00 GMT');
  $response->headers->set('Cache-Control', 'must-revalidate');
  $response->headers->set('Content-Type', 'application/rss+xml; charset=utf-8');

  // Read actual feed from file.
  $file_name = drupal_get_path('module', 'aggregator_test') . '/aggregator_test_rss091.xml';
  $handle = fopen($file_name, 'r');
  $feed = fread($handle, filesize($file_name));
  fclose($handle);

  $response->setContent($feed);
  return $response;
}

```

# Answer
> 1 votes
Here is my simple controller for a custom page response:

```
  namespace Drupal\custom_module\Controller;

  use Drupal\Core\Controller\ControllerBase;
  use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
  use Drupal\Core\Template\TwigEnvironment;
  use Symfony\Component\HttpFoundation\Response;
  use Symfony\Component\HttpFoundation\Request;
  use Symfony\Component\DependencyInjection\ContainerInterface;

  class CustomModuleController extends ControllerBase implements ContainerInjectionInterface {

  protected $twig;

  public function __construct(TwigEnvironment $twig) {
    $this->twig = $twig;
  }

  public static function create(ContainerInterface $container) {
    return new static($container->get('twig'));
  }

  public function content(Request $request) {

    $response = new Response();

    $twigFilePath = drupal_get_path('module', 'custom_module') . '/templates/custom_module_page.html.twig';
    $template = $this->twig->loadTemplate($twigFilePath);

    $markup = $this->twig->loadTemplate($twigFilePath)->render();
    $response->headers->set('Content-Type', 'text/html; charset=utf-8');
    $response->setContent($markup);

    return $response;
  }
}

```

---
Tags: 8, page-controller
---


# Question
Title: How to create a simple shopping cart without Drupal Commerce or Ubercart?
I want to make a simple order web site for selling some poster. I don't need to add to basket or complicated order stuff. I need only list my posters in catalog view and when clicked one of them appear detail about poster. And in the detailed page I need an order button and then order form.

What is the best way for this? I mean I use Views for catalog and detail page. My question is How to configure when user click an catalog item and the user goes to detailed page with created views?

# Answer
Maybe you should just use webform or entityform. With the flag module you can achieve that multiple items can be ordered. If there is no need for payment or checkout like in a 'normal' webshop, do not make it more complicatet than it is: actually you want your visitors to be in contact about one or more items on you website and get their details.
> 1 votes

# Answer
Below are 2 possible alternatives (options) for setting up a simple shopping cart without using the Drupal Commerce or Ubercart modules (as in your question title).

# Option 1: A lightweight e-shop

**If** you're only looking for a simple and lightweight e-commerce solution, **Then** have a looking at the Light Shop module (for D7, not for D6, not (yet?) for D8). Here is a quote from its project page:

> * Session-stored basket.
> * Adding to basket and its subsequent editing/checkout process is done using AJAX. Also it works fine when JavaScript is turned off.
> * Node based shopping. As the product can be assigned to any node type. One or more. With full support Field API features (regarding nodes).
> * Orders history. For each order will be created a separate node.
> * There is no dependence on other modules.
> * Full support for working with anonymous users
> * Integration with Views.

# Option 2: A simple shopping cart

**If** you're only looking for a shopping cart (as in your title), **Then** have a looking at the Basic Cart module (for D7, not for D6, not (yet?) for D8). Here is a quote from its project page:

> Basic cart is a very simple shopping cart / checkout process for Drupal, that just sends 2 emails after each order. Along with the shopping cart, this module also provides a block where you can view your cart's content. It's ideal for small websites with only a few products or other content types being sold, for example touristic offers.
>
> **Main difference from Ubercart and Commerce:**
>
> The main difference from Ubercart and Commerce is the possibility of choosing the content types that can be added to the cart. It also doesn't bother you with the Product SKU, that can be a pain when you have just a few products.
>
> **Features:**
>
> * The possibility of choosing the content types that can be added to the cart.
> * The possibility of sending, or not, an email to the customer once an order is placed.
> * Custom email messages for both the site administrator and the customer, along with the order details.
> * Order registration and listing in the administration area using Views module.
> * Integration with Rules module.
> * A block with the contents of your shopping cart.

Here is a screenshot of it (note the "**Checkout**" button also ...):
> 1 votes

---
Tags: views, commerce, 7
---


# Question
Title: db_select condition with subquery causes PDOexception
I want to build a relative simple select query with a subquery in its condition. What I want to achieve is to get the list of users updated after a given timestamp.

The working SQL-Query which I want to build as dynamic query is:

```
SELECT uid
FROM `users`
WHERE `vid` > (
  SELECT vid
  FROM `user_revision`
  WHERE `timestamp` > 1379494886
  ORDER BY `timestamp` ASC
  LIMIT 1
);

```

I've written the following code to build above query with Drupal's Database API:

```
$subquery = db_select('user_revision', 'ur')
  ->fields('ur', array('vid'))
  ->where('ur.timestamp > 1379494886')
  ->orderBy('ur.timestamp', 'ASC')
  ->range(0, 1);

$query = db_select('users', 'u')
  ->fields('u', array('uid'))
  ->condition('u.vid', $subquery, '>');

$result = $query->execute()->fetchAssoc();

```

But, I'm getting the following PDOexception error:

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 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 'SELECT ur.vid AS vid FROM user\_revision ur WHERE (ur.timestamp \> 137949488' at line 1: SELECT u.uid AS uid FROM {users} u WHERE (u.vid \> SELECT ur.vid AS vid FROM {user\_revision} ur WHERE (ur.timestamp \> 1379494886) ORDER BY ur.timestamp ASC LIMIT 1 OFFSET 0) ; Array ( ) in MYMODULE\_page\_callback() (line 22 of /path/to/the/module/includes/page\_callback\_file.inc).

What am I doing wrong building the subquery?

# Answer
Thanks to @Clive's comment, I checked the documentation about the subqueries on https://drupal.org/node/310086 and I noticed the note about:

> Note: Currently it is only possible to use subselect conditions with the IN operator because with the other operators the sub-query is not wrapped in parentheses and so results in a syntax error. See #1267508: Subselects don't work in DBTNG conditions, except when used as value for IN.

I've changed my code to use `IN` instead of `>` and it worked like a charm. Here's the working code for future reference if someone falls into the same situation:

```
$subquery = db_select('user_revision', 'ur')
  ->fields('ur', array('vid'))
  ->where('ur.timestamp > 1379494886')
  ->orderBy('ur.timestamp', 'ASC');

$query = db_select('users', 'u')
  ->fields('u', array('uid', 'vid'))
  ->condition('u.vid', $subquery, 'IN');

$result = $query->execute()->fetchAll();

```
> 7 votes

# Answer
You could separate your subquery into another query to return just the value, see below:

```
$vid = db_select('user_revision', 'ur')
  ->fields('ur', array('vid'))
  ->where('ur.timestamp > 1379494886')
  ->orderBy('ur.timestamp', 'ASC')
  ->range(0, 1)
  ->execute()
  ->fetchField();

$query = db_select('users', 'u')
  ->fields('u', array('uid'))
  ->condition('u.vid', $vid, '>');

$result = $query->execute()->fetchAssoc();

```
> -1 votes

---
Tags: 7, database
---


title: Bootstrap sub-theme override CSS

text:
# Question
Title: Bootstrap sub-theme override CSS
I just set up an new Drupal 8 website. I was used to use CSS injector on Drupal 7, but since the module is not ready yet, and I thought I'd better start with subthemes, I tried to create a new Boostrap subtheme. I used the CDN method, activated it in my admin panel, but when I try to override CSS by creating CSS styles in css/style.css, nothing work. In Drupal 7 with CSS injector, my main difficulty was to find the proper class. So I tried a lot of different possibilities, copied/paste CSS from original files in Bootstrap. Nothing works.

Have anybody already tried to create a sub-theme with Bootstrap? Did overriding CSS work?

I looked at the CSS file link, it's loading lumen theme nicely. I tried to change h2 color in this file: `themes/bootstrap/css/3.3.5/overrides-lumen.min.css` and it works...Clearly, seems that style.css is not used...

# Answer
> 0 votes
I'd wager that the stylesheet has not been added to the page. The documentation is pretty solid on this: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

This page isn't likely to go anywhere, but I'll summarise here. Please go and read the full documentation page though, there is MUCH more there:

> ## The general steps for loading assets (CSS/JS) are:
>
> 1. Save the CSS or JS to a file.
> 2. Define a "library", which can contain both CSS and JS files.
> 3. "Attach" the library to a render array in a hook.
>
> But in the case of themes, there is an alternative to step 3: themes can choose to load any number of asset libraries on all pages.
>
> ## Libraries
>
> \[...\] a library could just as well only contain CSS assets, or only contain JS assets. Most themes will probably want to have a global-styling asset library, for the stylesheets (CSS assets) that it wants to be loaded globally (i.e. on all pages where the theme is active — usually the whole site except the administration pages):
>
> ```
> global-styling:
>   version: 1.x
>   css:
>     theme:
>       css/layout.css: {}
>       css/style.css: {}
>       css/colors.css: {}
>       css/print.css: { media: print }
>
> ```
>
> ## Attaching a library to page(s)
>
> ### Attaching to all pages
>
> To attach a library to all the pages on the site that use your theme, declare it in your theme's \*.info.yml file, under the libraries key:
>
> ```
> name: Example
> type: theme
> core: 8.x
> libraries:
>   - fluffiness/cuddly-slider
>
> ```

---
Tags: 8, bootstrap-theme
---


# Question
Title: Have a Rules condition that will take the current time minus last comment posted time
**Overall goal:** If a node has not been commented on in a given time frame, send an email.

**How it could possibly be done:** Have Rules look at the last time a comment was posted when cron runs. Then do a data comparison of that unit (current time - last comment posted time) to see if its greater than the time frame assigned to the node (ex: hours). If so, send email.

Is this approach correct? I am struggling to get the Rule to work if it is.

# Answer
> **Overall goal:** If a node has not been commented on in an in a given time frame, send an email.

Here is a bare bones solution. On paper this should work.

Basically, we use sticky as the tell tell sign if a new comment has been added (if it's not sticky, no one has commented). Once the e-mail gets sent, we set node to unsticky.

1) Create a rule after **saving new comment**.

* Add Action: Under Node, **Make Content Sticky** \>\> **comment:node**

> Then it's very similar to my answer to your question Rules Conditions being evaluated after schedule time elapsed?
>
> ## Create a New Component
>
> 1) Add Compotent of Rule.
>
> 2) For Data Type: select Node. Name, Label and Machine name use whatever you want.
>
> 3) Add condition of **Content is of type**
>
> * For Data Selector: put your Node Data Type machine name. Ex: if you gave the node data type a machine name of `test` you put `test`
> * Select your content type

4) Download and Install Conditional Rules Module

Then for action, click on Add IF \>\> DATA COMPARISON \>\> test:sticky \>\> False

Then **in IF: Data Comparison row** click Add Action \>\> Send Mail

Then in Conditional row (1st row white) you will now see an Else button, click on it.

Then in Else click on Add Action \>\> Make Content Unsticky \>\> test

> ## Now Create a new Rule
>
> 1) For action use after content is created
>
> 2) Leave the condition empty (no need for condition here)
>
> 3) for Action add the scheduled component evaluation and select the component you just created.
>
> * use `node` as your data selector
> 2 votes

---
Tags: 7, rules, comments
---


# Question
Title: Show page content on another page using views
I have a 'presentation' page where I would like an image gallery where all the uploaded images that users upload to the site are displayed.

So far these images are being displayed only on the 'upload' page as default. (users are effectively modifying the same page when adding content)

I want to keep the 'upload' only as means to upload the images but I want all the images to be displayed **ONLY** on the 'presentation' page!

How do I do it with views?

# Answer
Not sure if I'm understanding you correctly, but you can create two view modes for the node that contains all the images that users upload, one for 'presentation' and one for 'upload' using Display Suite (see tutorial on view modes). If you don't want the upload version to show the images, simply hide the Image field in the 'upload' view mode.

Additionally, you can use a module like Juicebox to create a nice-looking and easy to navigate Javascript gallery in the 'presentation' view mode - just select "Juicebox Gallery" as the formatter for the Image field (instead of the default Image formatter) in your 'presentation' view mode.
> 0 votes

# Answer
1. Create a view block
2. Create custom page or your defined page.
3. Open views block configuration select option show block on specific page
> 0 votes

---
Tags: 7, views, entities, media, files
---


# Question
Title: How to send an automatic reply using webform?
I'd like to send an automatic reply to every user who fills the form "Thank you for registration"+ link to a restricted webpage on my website -available only to registered users who filled that form.

Is it doable?

# Answer
Yes you can do that in the following way:

* Add an email field in webform. Set that field to get the users email by clicking "User email as default" option in the field's edit page.
* Configure your forms to send emails by going at node/%nid/webform/emails and choosing "Component value", then choose your component.
* After you add this "rule" you can then configure the actual email send to the user.

PS if you are not sure what the capabilities of a module are you can try it out at https://simplytest.me/.
> 2 votes

# Answer
Webform Reply To

> A key part of the Webform module is sending e-mails. Webform lets you customize the name and e-mail address that is used for outgoing e-mails, but often this is not enough. You cannot use Webform to set a custom "Reply-To" e-mail header, for instance.
> 0 votes

---
Tags: forms, webforms
---


title: user cannot edit the page

text:
# Question
Title: user cannot edit the page
I have given the marketing role the 'create new', 'edit own' and 'delete own' permission for the Article content type however when I log in with that account the 'edit' button doesn't appear on the article page so that user cannot modify the page\]

# Answer
Use this code may be it helpful

```
if ($query == $user->uid && arg(0) == 'node' && is_numeric(arg(1)) && arg(2)== 'edit' ){

$query_path= db_query("select n.nid from {node} n
where n.nid =$nid")->FetchField();
 drupal_goto('node/'.$query_path);
}

```

place uid with your role id
> 0 votes

# Answer
While the query you posted is vague, you can follow few below checks to debug more on this issue:- a.) Check if the logged in user has the role(Marketing) which you allowed to edit the content.

b.) Check if the node you want to edit actually belongs to that specific user.

c.) Try to access the url /node/\[content-node-id\]/edit manually and see if you are able to access the page. If so is the case then Check if your theme is supressing the tabs by any chance. Try by changing the theme to a different one and look for tabs.

Hope this helps :)
> 0 votes

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


# Question
Title: How to display nodes on front page with Search API?
I have installed the Search API, Facets API, along with Search Pages. When the user goes to the front page, I want to display some default node results. How can I do this with just the node results for a particular view mode, without the user setting filter criteria?

# Answer
I have very good experience in search api and the easiest way to display the search results is use module search\_api\_views (included into search\_api).

Just create view for your search api index and select there required view mode and filtering criterias. Put this view on your front page and it will work.
> 2 votes

# Answer
You could do that by building a view based on search api index created for nodes.

**Steps**

enable the Search views module (search\_api\_views) a search api sub module build a view && add display page set the Default front page the url of the view page

Now you could have a front page from search api based on the index that you build before

the same thing will be done with module by adding pages

detailed tuts on search api will help you found here
> 1 votes

---
Tags: search
---


title: Embed controls 8 #table element?

text:
# Question
Title: Embed controls 8 #table element?
I'm using the Drupal 8 #table element to populate a table on my form, and it's working great for displaying static data.

```
foreach ($entries = getData() as $entry) {
  $row = array_map('Drupal\Component\Utility\SafeMarkup::checkPlain', $entry);
  $rows[] = $row;
}
$form['table'] = array(
  '#type' => 'table',
  '#header' => $headers,
  '#rows' => $rows,
  '#attributes' => array('id' => 'my-module-list'),
  '#empty' => t('No entries available.'),
);

```

However, I would like to embed a control in each row of the table, for example:

```
foreach ($entries = getData() as $entry) {
  $row = array_map('Drupal\Component\Utility\SafeMarkup::checkPlain', $entry);
  $row["field_name"] = array(
    '#type' => 'textbox',
  );
  $rows[] = $row;
}
//dpm($rows);
$form['table'] = array(
  '#type' => 'table',
  '#header' => $headers,
  '#rows' => $rows,
  '#attributes' => array('id' => 'my-module-list'),
  '#empty' => t('No entries available.'),
);

```

However, the #textbox field is currently being ignored, and an empty cell is shown in its place.

Is there a way I can embed fields in a Drupal generated table, or do I need to build my own table from scratch?

# Answer
It is no problem to put form elements in a table. See the example in core/lib/Drupal/Core/Render/Element/Table.php:

```
$form['contacts'] = array(
    '#type' => 'table',
    '#title' => 'Sample Table',
    '#header' => array('Name', 'Phone'),
  );

  for ($i=1; $i<=4; $i++) {
    $form['contacts'][$i]['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#title_display' => 'invisible',
    );

    $form['contacts'][$i]['phone'] = array(
      '#type' => 'tel',
      '#title' => t('Phone'),
      '#title_display' => 'invisible',
    );
  }

```

Maybe you should start from here and then put step by step your code in this example and see when it breaks.
> 18 votes

---
Tags: forms, 8
---


# Question
Title: Can jquery code be triggered by ajax success?
I know that I can add any code inside ajax success like this

```
$.ajax({
      type: 'GET',
      url: element.href,
      dataType: 'json',
      success: function (data) {
        //mycode

```

And mycode would be executed after previous script is done. But is it possible that jquery script alone can somehow detect certain ajax success and be triggered only by that? I posted this question to this forum because drupal uses behaviours which might be helpful with that. But that is my guess only. Thank you for any clues.

# Answer
> 5 votes
Yes this is possible to track ajax reuests anywhere in code by jQuery alone, there are some Global Ajax Event Handlers in jquery you can use methods from it like:

**.ajaxComplete()**:Register a handler to be called when Ajax requests complete. This is an AjaxEvent.

**.ajaxError()**: Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.

**.ajaxSend()**: Attach a function to be executed before an Ajax request is sent. This is an Ajax Event.

**.ajaxStart()**: Register a handler to be called when the first Ajax request begins. This is an Ajax Event.

**.ajaxStop()**: Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.

**.ajaxSuccess()**: Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.

The last one **.ajaxSuccess()** is what you need.

you can use it like this:

```
$( document ).ajaxSuccess(function( event, xhr, settings ) {
  if ( settings.url == "ajax/test.html" ) {
    $( ".log" ).text( "Triggered ajaxSuccess handler. The ajax response was: " +
      xhr.responseText );
  }
});

```

# Answer
> 0 votes
In my case y use Jquery custom events.

for example

```
$('form').submit(
    function(){
        return $.ajax({
            url: $(this).attr("action"),
            data:data,
            processData: false,
            contentType: false,
            type: "POST",
            dataType : "json",
            success: function( result ) {
                $form.trigger('submit:success');
            },
            error: function( xhr, status, errorThrown ) {
                console.log( "Error: " + errorThrown );
                console.log( "Status: " + status );
                console.dir( xhr );
                $form.trigger('submit:error');
            },
            complete: function( xhr, status ) {
                $form.trigger('submit:complete');
                console.log( "The request is complete!" );
        }
    }
);

 $('form.SpecialForm').on('submit:success', myFunction1);

 $('form.OtherSpecialForm').on('submit:success', otherFunction);

 $('form.ThirdSpecialForm').on('submit:error', thirdFunction);

 $('form.OneMoreSpecialForm').on('submit:complete', oneMoreFunction);

 $('form.theLastSpecialForm').on('submit:complete', theLastFunction);

```

---
Tags: ajax, javascript
---


# Question
Title: Why is AJAX pager in Views not recording the history
I have a listing of news, used with Views module in Drupal 7. I have activated Use Ajax in advanced section. So now the pager loads the content smoothly, without loading other page. That is nice, but the pager is not recording the history of the browser, so when I hit several pages of the same listing, it loads all the content perfectly but when I hit the **Back button** of the browser, instead of going to the last page clicked on the listing, goes to a previously visited site, even a different website, depending on my browser history. This happens, aparently, because there seems to be no built-in mechanism to record website history or at least change the toolbar address with "#" so it can have a behaviour similar to what be expected. Is there some way of circumventing this?

# Answer
I have not used but you can take a look

Statehandler module and History.js module
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: Is there a good reason to prefer one method of installing over another?
Starting to play around with drupal 8. My first method of installing was installing drush8 (as mentioned in https://www.drupal.org/documentation/install/download):

Get drush8:

```
composer require drush/drush:dev-master

```

and then

```
drush dl drupal
mv drupal-8.0.1/* .
mv drupal-8.0.1/.* .
rmdir drupal-8.0.1

```

Then I later read that instead of installing via drush I can install via composer (Using Composer in a Drupal project). The earlier drupal instructions that I read above had no mention of this installation method.

```
composer create-project drupal/drupal my_site_name 8.0.*`

```

I also found a slightly different variation (Composer in relation to Drush Make):

```
composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction

```

Which I understand creates a slightly different directory structure (according to this article it also creates a 'web' sub directory).

There's also the Drupal Console method:

```
drupal site:new my_site_name

```

Other than personal preference, is there a good or valid technical reason to use one method over another?

# Answer
First of all, you are describing methods to download drupal, not install. If you use `drush dl` or `drupal site:new my_site_name`, this is the same as downloading the tar ball and extracting it. If you want to install drupal, you use `drush si` or `drupal site:install`, where you can provide the details for installation like database connection on the command line instead in the standard web installer.

To describe the different download methods, as mentioned drush dl and console site:new are only a shortcut for downloading the tar ball. On the other hand, if you use composer, you don't load the tar ball, but use composer to load each of the components, that are in drupal. If you plan to use only the drupal releases and want to follow the normal upgrade path, you don't need to do this. If you want to use dev versions and want to update without the need to download the whole project, use composer. Probably in combination with git for a complete dev workflow.
> 1 votes

---
Tags: drush, 8, installation, composer
---


# Question
Title: How do I get a user profile's picture from entity_metadata_wrapper()?
I am using `entity_metadata_wrapper()` for getting values from the user profile.

This is my code:

```
$user_wrapper = entity_metadata_wrapper('user', $uid);
$user_name = $user_wrapper->name->value();

```

How do I get the user picture field from `$user_wrapper`?

# Answer
> 1 votes
You can get the information about user picture *indirectly* as follows:

```
$user_picture = $user_wrapper->value()->picture;

```

I said *indirectly*, since the picture object itself is not an entity wrapper anymore, so you cannot chain it further using `entity_metadata_wrapper` functions. However, it should have all the information you need about the user picture, like the `fid`, `filename`, `uri`, `filemime`, `filesize`, `metadata`, and any other fields that could be attached to a file, for instance using File Entity module.

---
Tags: 7, entities, users
---


# Question
Title: Strict warning: Only variables should be passed by reference in Open Restaurant
I installed Open Restaurant based on Drupal 7.x.

As soon as I insert any menu item into create categories, I get this warning:

> Strict warning: Only variables should be passed by reference in sizzle\_preprocess\_views\_view\__content\__menus\__all\_menus() (line 69 of /web/htdocs/xxxxxxxxxxx/home/profiles/restaurant/themes/sizzle/includes/menu.inc).

I checked the line and I got this code:

```
// Render the category and add it to template.
$variables['term'] = drupal_render(taxonomy_term_view($term, $view_mode));

```

I don't know how to improve this, in order to solve the issue. Writing to the group that made Open Restaurant I didn't got any answer. Hence my post here.

# Answer
> 1 votes
`drupal_render` takes reference. `taxonomy_term_view($term, $view_mode)` is not a variable, so you shouldn't use it in places where reference is needed - because if something takes reference, it will try to update what it got, and it's impossible with a function. So to fix this, you need to create variable, then store result of `taxonomy_term_view` in it, and pass that variable to `drupal_render`.

Then, create patch file nd post it in their issue queue for everybody to see.

---
Tags: 7, theming
---


# Question
Title: Setting up a Drupal environment on Ubuntu
After a few years of setting basic Drupal environments on Windows only, with WAMP (both the installment and the WAMP program) and Drush 7.0.0, I came to the conclusion I also need to work with LAMP and especially Ubuntu-based as it would give me access to more development tools, and more easily, for example in relation to tar, tar.gz, curl (non-core UNIX command), Composer, Drush master (which as of 2015 is not recommended for Windows usage) Xdebug, and more.

I have installed Ubuntu on a virtual machine, but what do I do now? Of course there is no WAMP (Windows, AMP) on Linux, and my options seem to be manual installation of the server \ Linux-XAMPP... But besides that, my question is what are the main differences between a Windows Drupal environment to a Linux one, in these points:

* Is there something else needed for a Drupal (8) environment besides the things I mentioned?
* In Windows, my WAMP folder was in c:\WAMP\ --- What is the drupal folder hierarchy in Linux?

Please answer on these points and detail as much as you can on the process, for newcomers like me could have a nicer acquaintance.

# Answer
So, Ubuntu doesn't come with LAMP out of the box but it's super easy to set up with `sudo apt-get` ubuntu command. The basics of setting up a lamp environment are beyond the scope on an answer here, but there are plenty of tutorials on how to do it and robust community of Ubuntu users for questions.

Based on what you're describing, I would recommend using ubuntu desktop rather than server on your VM. This will give you a GUI interface which will be a little more familiar than trying to run Unix commands through your terminal on the VM, which will require further setup of your windows box.

Once you've set your VM up the basics you will need are: Mysql (or your db of choice), php, and Apache (or your web server of choice). You can download and install all of these free, but you'll do most of this from the command I mentioned above, so I would school up if you're not comfortable Ubuntu LAMP set up. There are many tutorials on how to turn Ubuntu into a wed dev machine, pick and choose what you find useful.

You'll have to set up the Mysql server and most of the programs manually before you have a set up you can install drupal on.

To answer your two questions:

1. No, you don't need any tools that you didn't mention, although depending on your set up and being new to Unix environments I would look into GUI tools like Mysql workbench.
2. Ubuntu Desktop and Server have a designated html folder it will be in /var/www/html

Where it gets tricky for someone who isn't familiar with the environment is that you need to configure your folder and file permissions for the /var/www/html folder. It has to be owned and readable to the apache or your webserver user.

This here is a good tutorial, it will get you where you need to go once you have a working LAMP server on your dev machine.Ubuntu Drupal

So, from here you have to ssh into your virtual machine or use the GUI interface to set your drupal install. This is the same as on windows:

1. Get a copy of Drupal Core in your web root folder.
2. create a drupal database, database user
3. point your site to the db with settings.php in your sites folder.
4. Run the install.php script in your web browser.
5. drupal and profit.

You mentioned using a lot of Drupal dev tools. You'll have to configure those yourself, but you'll have to either do it on the VM (and work natively on VM) or configure your windows drush to connect to your VM like you would a remote server. This is all good practice but, beyond the scope of a single post.
> 1 votes

# Answer
Some years ago I made a similar "jump" to a LAMP environment (to start working on D7). At the time I got a recommendation to "start" with the Quickstart: Prebuilt Drupal Development Environment project.

This project today is "unsupported", though it may (still) be worth checking out to get an idea about the various components/features it included (Drush, etc).

The project page also suggests these possible alternatives:

> * DrupalPro 14.
> * Lazy Dubuntu \- A shell script that will set-up your Drupal Dev Environment in Ubuntu.
> * DrupalPro \- Unity-based fork of Quickstart 1.
> * BitNami Drupal Stack \- All-in-one free native installers, virtual machines, and Cloud Images that simplify the Drupal installation and hosting.
> 0 votes

---
Tags: installation
---


title: Print five star ratings and reviews

text:
# Question
Title: Print five star ratings and reviews
I am using Fivestar rating in custom print. See image:

I'm trying to print a fivestar as follows:

```
$your_average = $variables['result']['node']->field_rating['und'][0]['average'];
$your_maximum = "100";
print theme('fivestar_static', $your_average, $your_maximum);

```

But, I'm getting the following error:

> Fatal error: Unsupported operand types in /var/www/html/book1/includes/theme.inc on line 1088

Any suggestions?

# Answer
> 3 votes
Looking at the definition of `fivestar_static` theme-function in `fivestar.module` file under `fivestar_theme()`, you need to provide the theme function with an array including the following keys: `rating`, `stars`, `tag`. A working example should look like:

```
$fivestar_variables = array('rating' => $your_average, 'stars' => $your_maximum);
print theme('fivestar_static', $fivestar_variables);

```

# Answer
> -1 votes
Try this:-

```
$your_maximum="100";
$your_average  = "21";
print render(theme('fivestar_static', $your_average, $your_maximum ));

```

---
Tags: theming, rating
---


# Question
Title: Updating the PHP version of an existing site?
I am asking this as a total ignorant in differences between PHP versions: Is it possible to update the PHP version of an existing Drupal site that is installed on a local server on Ubuntu?

I mean, let's assume my Apache is in the last version possible, as well as my mySQL, and PHPmyadmin, and I want to update from PHP 5.x.x to 7.x.x. Is this possible? Is it done by an internal Drupal module or an external tool?

# Answer
> Is it possible to update the PHP version of an existing Drupal site that is installed on a local server on Ubuntu?

Yes, upgrading server software for existing applications is common practice both inside and outside of the PHP/Drupal worlds.

If your operating system supports a newer version of php than you currently have, and Drupal (plus the contrib modules you're using) supports the same version you're planning to upgrade to, then you should have no problems.

> Is it done by an internal Drupal module or an external tool?

Drupal can't upgrade the software on your server, that's something that gets done at the operating system level; consult the documentation for your OS for details on how to actually do it (Google "ubuntu upgrade php 7"). Make sure you back up and perform this in a test environment before doing anything on a production server, just in case.

PHP 7 has significant performance improvements, and Drupal 8 supports it, so the particular upgrade you're suggesting would be a good move.
> 5 votes

---
Tags: upgrading
---


# Question
Title: why are users logged out after 2 days of not logging in
We got LDAP SSO working for our site. Employees go to the site everyday and everyday they do not have to input their credentials... until Monday. I believe this has to do with cookies maybe? I think if the employees have not logged in in a couple of days (weekend) then they have to log back in. Every Monday they have a http authentication dialogue box (LDAP Authentication from the /user/login/sso url). It saves their credentials (if they hit remember my password), but they don't like hitting the `enter` key.

My /admin/config/people/ldap/authentication settings look like this:

I then found this post: Why is session.cookie\_lifetime set to 23 days?, where they say that in drupal it might have a `session.gc_maxlifetime`setting in `settings.php` that is set to 23 days, but that the `session.cookie_lifetime` is set to 2.3 days. And that if the user doesn't visit the page withing 2.3 days then they start a new session or something. Does this mean if I adjust the `ini_set('session.cookie_lifetime', 200000);` to like 4 days that the employees wont need to hit `enter` anymore?

# Answer
> 2 votes
The answer here explains the difference between the cookie types and when they destroy the session: Why is session.cookie\_lifetime set to 23 days?

To answer your question specifically:

If you extend the `session.cookie_lifetime` to be longer, the session will last longer and users will less frequently require to login. If the user opens the page within `session.cookie_lifetime` from the last visit, the session will be extended for another `session.cookie_lifetime`. This can be repeated several times, but never longer then `session.gc_maxlifetime` after which a user is always forced to log in again.

If you extend the `session.cookie_lifetime` to last for eg. 4 days (so it survives the weekend), users that always open the page on workdays will have to login once every 23 days (`session.gc_maxlifetime`). You can also extend this value to last as long as you want.

Please keep in mind that although hitting the enter might be annoying, if security is part of your job as well, it might not be a good idea to have sessions lasting for long periods of time. Have them survive the weekend by having them last a day longer will not cause much problems, but allowing them to extend for ever and ever (`session.gc_maxlifetime`) could introduce security vulnerabilities.

---
Tags: users, cookies
---


# Question
Title: How programatically choose between multiple shipping methods commerce_shipping?
I'm using Commerce Shipping Postal Code Weightto configure weight based shipping very happily. However, I have cases where I need to use flat rate shipping for certain items. The issue is that I don't know how to resolve the conflict between the shipping services. The particular case I have is that the weight-based shipping charge is less, and I don't want to show that to the customers.

So, how do I set up the conditions, where different shipping services are called?

# Answer
So, this doesn't answer the question as posted but all I had to do was set my series of conditions for the Postal Code Weight method. My scenario had to Flat Rate Shipping methods based on specific products in the cart. What I did was configure the Rule for Commerce Shipping Postal Code Weight with two conditions, 1) that it didn't contain one of the products, and 2) AN and OR condition that it didn't contain a product. I also had to specify the conditions for the two Flat Rate Methods similarly, one had to have an exclusion targeting the first product condition.
> 1 votes

---
Tags: commerce, rules
---


# Question
Title: Different way for users to add content on pages
On my website each user can only edit the existing main content via the 'edit' button on the page.

I don't want each user to see what was added previously on the page like it happens on my website:

Is there a way the user can add their own new content and be displayed on the page in ascending order (new content on top of the previous one) WITHOUT modifying/ viewing the previous post? E.g. like on this example I found online:

# Answer
Yes. You can use the built in content types and the default 'node' page which allows this for just the front page or if you want more complex uses with multiple pages you will need something like views and a custom content type with a taxonomy term to tie the content pages to the view.
> 0 votes

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


# Question
Title: How to delete a scheduled task using Rules Scheduler?
I use the rules scheduler module (D7). So far all fine.

What I use it for:

* a user registers with username and email
* this users then gets 4 emails over the next four weeks, sent by the scheduler

**BUT:** In case a user wants to unsubscribe from these scheduled emails? How can I achieve it?

It is true that one can delete particular sort of scheduled tasks with the according action (Delete scheduled tasks). But I don't know how to indicate it shall only delete the tasks that are related to a particular?

When I list the schedule with ... */admin/config/workflow/rules/schedule*

... there is one column called "USER PROVIDED IDENTIFIER" - maybe it would help to do it with such an identifier. But I don't know how?

**UPDATE TO THE QUESTION:**

I tried to import with the suggested changes, this is how my rule looks like now:

```
{ "rules_user_reminder_after_30_days" : {
"LABEL" : "User Reminder After 30 Days",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_scheduler" ],
"ON" : { "user_login" : [], "node_insert--article" : { "bundle" : "article" } },
"DO" : [
  { "schedule_delete" : {
      "component" : "rules_send_email_notification",
      "task" : "[account:name]"
    }
  },
  { "schedule" : {
      "component" : "rules_send_email_notification",
      "identifier" : "[account:name]",
      "param_user_to_notify" : [ "account" ]
    }
  }
]
}
}

```

But now I got this error:

> Integrity check for the imported configuration failed. Error message: Missing configuration for parameter **date**

# Answer
> 0 votes
Have a look at my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder" for an illustration about how to delete scheduled tasks, using the "`schedule_delete`". As explain in that answer: the `schedule_delete` that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).

To make this work (that you actually indicate the exact scheduled task to be deleted), you need to specify an appropriate "`identifier`", like "`[account:name]`" in my example. To understand how I know what in my case the identifier is of the task to be deleted, look at the way I specified my (new) scheduled task to be created: it is `"identifier" : "[account:name]"`, which is what I used as my identifier to schedule a task.

In your case, I think "`[account:name]`" would be a pretty good choice for such identifier. But your questions states "*... users then gets 4 emails over the next four weeks, sent by the scheduler ...*". So if the 2nd email only gets scheduled after the first email (and not schedule all 4 emails upfront together), and similar for the 3rd and 4th email, then you should be fine using this identifier also.

**Note**: Specifying an "identifier" like "`[account:name]`" is what you'd do in your Rules Action (similar to my "step 3" in the above sample). While you'd probably want to create a Rules component similar to my "step 2" in the above sample to actually send an eMail.

**Update**: The "*integrity check*" problem shown near the end of the updated question, is probably because in your rule, as shown in the updated question, does not specify the ***date*** to schedule your component. Have a look again at my answer I mentioned above: the rule there specifies a date via this part of it:

```
  "date" : {
    "select" : "account:field-next-article",
    "date_offset" : { "value" : 2592000 }
  },

```

---
Tags: 7, rules
---


title: Different order for cart product

text:
# Question
Title: Different order for cart product
I have using Commerce Kickstart and Commerce Marketplace. I have added 2 products into the cart (products from different stores).The problem is when I taken review order page it shows as different order, also different order created. What is wrong with me.I wish to add these two product as the same order.

# Answer
> 1 votes
It sounds like you have something misconfigured. With the Marketplace module, you'll actually have 3 orders created. One is a **Marketplace Order** and one is a **Store Order**. It appears that your **Store Orders** are being displayed instead of the **Marketplace Order**. Check your pane configuration and ensure that you've enabled the proper marketplace modules and that your Views are showing the **Marketplace Order**.

---
Tags: commerce
---


# Question
Title: A commerce fees rule works fine, but is giving the warnings in the log
I've enabled the Commerce Fees module and added a rule with the following details:

```
{ "rules_setup_fee" : {
    "LABEL" : "Setup Fee",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce License Billing" ],
    "REQUIRES" : [ "rules", "commerce_fees" ],
    "ON" : { "commerce_fees_order" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "commerce-order:commerce-line-items:0:line-item-label" ],
          "match" : "book"
        }
      }
    ],
    "DO" : [
      { "commerce_fees_apply" : {
          "entity" : [ "commerce-order" ],
          "fee" : "setup_fee",
          "amount" : "999",
          "currency_code" : "USD"
        }
      }
    ]
  }
}

```

which correctly adds $9.99 setup fee to a shopping cart when customer selects any product which has the "book" string in its title (or SKU which we try to keep the same). So the whole thing serves its purpose just fine, however unfortunately it also leaves the following traces in the logs:

> Unable to evaluate condition text\_matches. Unable to get the data value for the variable or parameter text. Error: Unable to get the data property line\_item\_label as the parent data structure is not set.

What am I doing wrong here? Thanks!

# Answer
> 0 votes
You should add a `data_exists` to ensure that the delta/label you're trying to access actually exists. It looks like `line-item-label` is a custom property.

---
Tags: commerce
---


# Question
Title: How to dynamically populate radio button widget in DrupalGap (with InApp Purchase Products)?
I am pulling products from the iTunesConnect using the in-app-purchase cordova plugin and want to show the valid products (title) in a radio button list.

The store.('product')update function renders this (I don't know why they are shown twice?!)

```
2015-12-27 10:59:12.158 paypal3drupal[1059:18480] 200 - OK
2015-12-27 10:59:12.896 paypal3drupal[1059:18480] product_item:     {"id":"120points","alias":"120  Points","type":"consumable","state":"valid","title":"120 Points","description":"Get 120 points for asking questions","price":"€10,99","currency":"EUR","loaded":true,"canPurchase":true,"owned":false,"downloading":false,"downloaded":false,"transaction":null,"valid":true}
2015-12-27 10:59:12.897 paypal3drupal[1059:18480] product_item: {"id":"120points","alias":"120 Points","type":"consumable","state":"valid","title":"120 Points","description":"Get 120 points for asking questions","price":"€10,99","currency":"EUR","loaded":true,"canPurchase":true,"owned":false,"downloading":false,"downloaded":false,"transaction":null,"valid":true}
2015-12-27 10:59:12.897 paypal3drupal[1059:18480] product_item: {"id":"200points","alias":"200 Points","type":"consumable","state":"valid","title":"Points 200","description":"Get 200 points for everything","price":"€15,99","currency":"EUR","loaded":true,"canPurchase":true,"owned":false,"downloading":false,"downloaded":false,"transaction":null,"valid":true}
2015-12-27 10:59:12.897 paypal3drupal[1059:18480] product_item: {"id":"200points","alias":"200 Points","type":"consumable","state":"valid","title":"Points 200","description":"Get 200 points for everything","price":"€15,99","currency":"EUR","loaded":true,"canPurchase":true,"owned":false,"downloading":false,"downloaded":false,"transaction":null,"valid":true}
2015-12-27 10:59:12.900 paypal3drupal[1059:18480] \o/ STORE READY \o/

```

The cordova example renders the product like this

```
// When any product gets updated, refresh the HTML.
store.when("product").updated(function (p) {
    app.renderIAP(p);
});

```

and

```
app.renderIAP = function(p) {
var elId = p.id.split(".").pop();
var el = document.getElementById(elId + '-purchase');
if (!el) return;
if (!p.loaded) {
    el.innerHTML = '<h3>...</h3>';
}
else if (!p.valid) {
    el.innerHTML = '<h3>' + p.alias + ' Invalid</h3>';
}
else if (p.valid) {
    var html = "<h3>" + p.title + "</h3>" + "<p>" + p.description + "</p>";
    if (p.canPurchase) {
        html += "<div class='button' id='buy-" + p.id + "' productId='" + p.id + "' type='button'>" + p.price + "</div>";
    }
    el.innerHTML = html;
    if (p.canPurchase) {
        document.getElementById("buy-" + p.id).onclick = function (event) {
            var pid = this.getAttribute("productId");
            store.order(pid);
        };
    }
}

```

**How can I dynamically target and populate a radio button widget in Drupalgap?** More specifically, how can I populate the radio button options and values (option value = product\_item\_id, option label = product\_item.title)?

Based on the form documents example I have a custom page with static values that displays the form with a submit button.

```
/**
 * Implements hook_menu().
 */

function my_module_menu() {
   try {
var items = {};
items['in-app'] = {
  title: 'get points',
  page_callback: 'drupalgap_get_form',
  page_arguments: ['my_module_payment_form']

};
  return items;
}
catch (error) {
console.log('my_module_menu - ' + error);
}

```

}

```
/**
* Define the form.
*/
function my_module_payment_form(form, form_state) {
try {
form.elements['points'] = {
  type: 'radios',
  title: 'Points',
  options: {
    0: 'cancel',
    70: '70 Points', // should look something like product_item.id[0] : product_item.title[0]
    120: '120 Points',
    250: '250 Points'
    },
    default_value:0,
    required: true
};
form.elements['submit'] = {
  type: 'submit',
  value: 'Buy points'
};
return form;
}
catch (error) { console.log('my_module_payment_form - ' + error); }
}

/**
 * Define the form's submit function.
*/
function my_module_payment_form_submit(form, form_state) {
   try {
     drupalgap_alert('You selected ' + form_state.values['points'] + '!');
}
  catch (error) { console.log('my_module_payment_form_submit - ' +    error); }
}

```

# Answer
> 2 votes
Use a pageshow callback:

```
function my_pageshow() {
  // Retrieve the data from the server
  // During the retrieval's success callback, place the items into the empty radio button widget.
}

```

You can leave the radio buttons empty in your form builder function, then handle the dynamic population of the radio buttons with the `pageshow` callback.

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


# Question
Title: How to present a field or another in a content type, depending on context
I have a custom content type, let's call it `seo_data`. I want that the user will be presented, in the Admin view, with some of the fields, not all, depending on the context. So for some nodes, based on nid and other database queries, the user will see, for example, fields `field_image` and `field_image_alt` or `field_video` and `field_video_alt`. So, sometimes the user will see the fields corresponding to video or image, depending on some values in other data.

The question is about how can I, programmaticaly (prefered) or with a custom module, present just a bunch of fields.

# Answer
For the module approach i recommend to evaluate this one: Conditional Fields.

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
> 0 votes

---
Tags: 7, views, entities
---


# Question
Title: How to add gratuity when a commerce cart is updated?
I need to add a gratuity to my site when user add a product to a cart. The function is the same to the ioby.org site. Each time the cart is updated we will update the gratuity on the cart. I have read the solution for this function from newsignature who developed this site but it's hard for me to using rules to do it. Anyone can help me? Thanks so much!

Here is the solution from newsignature:

> Gratuity was at first going to be a tax type in the Commerce system. However, one of the requirements was to also give the user the ability to remove the gratuity if they felt that they didn’t want to cover the costs for it. Since tax isn't usually an optional item in shopping carts, the ability to remove it has not been placed in the Commerce tax module. To enable that ability, we place the gratuity into a line item that is calculated every time the cart is updated. Once again we used the Entity API to generate a new product, and this time the gratuity type that has an individual SKU, and a price that is a percentage of the order total. Another custom feature we added was to show a popup message when a user removes the gratuity, explaining to them the importance of gratuity for ioby. Since the view doesn’t discriminate between the different line items, it was necessary to use some front end javascript that handles this feature. And of course, with items being added and removed from the cart, it was necessary to change the price of the gratuity on the fly, assuming it wasn’t removed.

# Answer
I would use the Rules module for this, with trigger event "add item to cart" and action being "add another product to the cart", where the second product is a gratuity. You might need to use a further rule to set the price of the "gratuity" product as proportional to the original product.

If you don't need to do it separately for each item, like if it's the same percentage for all, you could apply it as if it were a tax, a (negative) discount, or a handling fee, using the relevant modules for those.
> 0 votes

# Answer
Have a look at the Commerce Donate module. From its project page:

> This module provides a donation line item type along with a donation product and product display. This is partially based on Randy Fay's excellent screencast at http://commerceguys.com/blog/using-custom-line-items-provide-donation-fe...
>
> It uses the Select or Other module to provide the donation amount form field. If you need to modify the default donation option values, the install the Commerce Customizable Products module in order to modify the line item type form settings.
>
> In addition to being able to create a donation product, this module also provides a donation checkout pane, allowing customers to add a donation to their order as part of the checkout process.

Especially the last paragraph seems pretty close to the "*... add a gratuity to my site when user add a product to a cart ...*" (= the 1st phrase in your question).
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How can I sort taxonomy term using attachment in drupal view
I would like to sort taxonomy term using attachment in view like this (A B C ...). When I created sort for Taxonomy term using contextual filter, the Alphabetical(radio button) was disabled under "When the filter value is NOT available" section for taxonomy term. This radio button already enabled for content: title but it was disabled for taxonomy term.

# Answer
> 0 votes
If u are creating view of taxonomy term, then it gives you option for sorting taxonomy term using name, However if u are using content type view and u want to show attachment, then add Global:View in attachment fields, and choose a view of taxonomy, with passing contextual filters in it.

---
Tags: input-formats
---


# Question
Title: How do I display the attachment's file size of a node?
Is there any way in Drupal 7 to display the attachment's file size of a node through the manage file / display of the file field, or is this programmatically achieved?

# Answer
> 4 votes
You can do this hardcoded with the `$node` object by doing so (preferably in theme\_preprocess\_node in `template.php`) :

If you field `field_my_field` as a single value :

```
$file = field_get_items('node', $node, 'field_my_file');
if ($file) {
    $file_size = $file[0]['filesize'];
    $file_size_formated = format_size($file_size);
}

```

If you field `field_my_field` as a multiple value :

```
$files = field_get_items('node', $node, 'field_my_file');
if ($files) {
    $files_size_formated = array();
    foreach ($files as $key => $file) {
        $file_size = $file['filesize'];
        $files_size_formated[] = format_size($file_size);
    }
}

```

In template.php you should have something like this :

```
// This function allow one preprocess_node function per content type
function mytheme_preprocess_node(&$vars) {
  $node = &$vars['node'];
  // Preprocess function for each node type
  $function = __FUNCTION__ . '_' . $node->type;
  if (function_exists($function)) {
    $function($vars);
  }
}

function mytheme_preprocess_node_my_content_type(&$vars) {
  $node = &$vars['node'];
  $file = field_get_items('node', $node, 'field_my_file');
  if ($file) {
      $file_size = $file[0]['filesize'];
      $vars['file_size_formated'] = format_size($file_size);
  }
}

```

Then in you `node--my-content-type.tpl.php` you can print your var `$file_size_formated` where you want like this for example :

```
<div class="file-size"><?php print $file_size_formated; ?></div>

```

# Answer
> 1 votes
You can also modify the theme function theme\_file\_link in your `template.php` to add the file size to link with something like this:

```
function YOURTHEME_file_link($variables) {
  // ...

  $file_size = format_size($file->filesize);

  return '<div class="file">' . $icon . ' ' . l($link_text, $url, $options) . '<span class="file-size">' . $file_size . '</span></div>';
}

```

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


# Question
Title: Ajax callback on select box change event not working on second time
I am building a form with form API in a custom module. Certain fields should be populated based on the selected value of a dropdown.

User will select the pre-entered profiles, based on which other fields should be populated.

I have used ajax callback on select box, it works fine for the first time. But not working on next time.

```
function multi_step_user_info_form($form, &$form_state) {
$form['user_data_form']['reference_number_ajax'] = array(
'#type' => 'select',
'#title' => 'Select a Patient',
'#ajax' => array(
        'callback' => 'ref_number_dropdown_callback',
        'wrapper' => 'ref_number_list',
        'event' => 'change',
        'method' => 'replace',
        'effect' => 'fade',
        ),
'#attributes' => array('class'=>array('dynamic-select')),
'#default_value' => isset($values['reference_number_ajax']) ? $values['reference_number_ajax'] : NULL,
'#prefix'=>'<div class="col-md-12">',
'#field_suffix'=>'</div>');

$form['user_data_form']['patient_name'] = array('#type' => 'textfield',
'#title' => 'Patient Name','#value' => $patient_name, '#default_value' => isset($values['patient_name']) ? $values['patient_name'] : NULL,
'#prefix'=>'<div id="ref_number_list"><div class="col-md-12">',
'#field_suffix'=>''
 ); return $form; }

function ref_number_dropdown_callback($form, $form_state) {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'query')
      ->propertyCondition('status', NODE_PUBLISHED)
      ->fieldCondition('field_reference_number', 'value', $form_state['values']['reference_number_ajax'], '=')
      ->range(0, 1);
    $result = $query->execute();
    $nid ='';
    if (isset($result['node'])) {
       $nid = $nid = current($result['node'])->nid;
       $node = node_load($nid);
    }
  //  $form_state['rebuild'] = TRUE;
  // THESE TWO VALUES SHOULD BE POPULATED ON AJAX CALLBACK //
    $form['user_data_form']['patient_name']['#value'] = $node->field_patientname[$node->language][0]['value'];
    $form['user_data_form']['age']['#value']          = $node->field_age[$node->language][0]['value'];
    $elements = array($form['user_data_form']['patient_name'],$form['user_data_form']['age']);
    return $elements;
  }

```

# Answer
You are using wrong notation for form elements, instead of field\_suffix you should use "suffix" tag, as drupal is not able to track your closing tag, for a form element.

```
function demo_pane_form($form, &$form_state) {

 $options= array(1=>1, 2=>2, 3=>3, 4=>4, 5=>5);

 $form['user_data_form']['reference_number_ajax'] = array(
  '#type' =>'select',
  '#title' => 'Select a Patient',
  '#ajax' => array(
     'callback' => 'demo_pane_dropdown_callback',
     'wrapper' => 'ref_number_list',
     'event' => 'change',
     'method' => 'replace',
     'effect' => 'fade',
   ),
   '#attributes' => array(
     'class'=>array('dynamic-select')
   ),
   '#default_value' => 1,
   '#options' => $options,
   '#prefix'=>'<div class="col-md-12">',
   '#suffix'=>'</div>'
 );

 $form['user_data_form']['patient_name'] = array(
  '#type' => 'textfield',
  '#title' => 'Patient Name',
  '#value' => 1,
  '#prefix'=>'<div id="ref_number_list"><div class="col-md-12">',
  '#suffix'=>'</div></div>',
 );

 return $form;

 }

 function demo_pane_dropdown_callback($form, $form_state) {

   $form['user_data_form']['patient_name']['#value'] =
   $form_state['values']['reference_number_ajax'];
   $form['user_data_form']['age']['#value']          =
   $form_state['values']['reference_number_ajax'];
   $elements =  array(
     $form['user_data_form']['patient_name'],
     $form['user_data_form']['age'],
   );

  return $elements;
 }

```
> 0 votes

---
Tags: 7, forms, ajax
---


title: IEF with custom profile2 type not work

text:
# Question
Title: IEF with custom profile2 type not work
I have node reference field attached to profile2 type entity and I can't add new entity to user profile. Even as admin (uid=1).

See my screenshoots for details

view user profile

add node to user profile

save changes and see no changes at all

Big WTF for me. Thought is is permissions related but why it's not working for superuser also. When I'm using IEF with node to node reference all is working.

I need advice how to resolve this issue. What check first, etc.

# Answer
No chance for working: https://www.drupal.org/node/2043177

!@#!@#!
> 0 votes

---
Tags: 7, users, entities
---


# Question
Title: How to make the Rules module perform a redirect to an URL that includes a query string?
I have created ***Task*** nodes, and I want to redirect to the previous (source) page after creation of a new task. I don't want people to see the task node. That page includes a view of all tasks.

For that I have created a simple rule:

* Event: After saving new content
* Condition: Content is of type tasks
* Actions: Page redirect to `[site:current-page:url]`

This works, but not for a page that includes a query string. The rules redirect action chops off the query string of the source page.

In my case, I have a source page that always includes `?og_group_ref=[node:og-group-ref]` in the URL in order to create group tasks. After creating a group tasks, the redirect happens but the query string in the URL is gone.

I tried to change the Rules redirect using Rules Action "*Page redirect to `[site:current-page:url]?og_group_ref=[node:og-group-ref]`*". However, that gives an error:

> Input evaluation generated an invalid URI.

Is there a way to accomplish Rules redirect including the query string?

# Answer
> 0 votes
You may want to try the "Rules URL argument" module to get this to work. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

Refer to my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?" for way more details about this module also.

---
Tags: 7, rules, redirection
---


# Question
Title: CKeditor to search images on PC instead of server
I have added the CK editor WYSIWYG to my website.

However I want user to browse their own local PC directory when uploading images and not the server. The default Image module from drupal core does this fine how can I do this with CKeditor?

# Answer
This is one way to do this:

1. Install IMCE
2. Go to Configuration \> Content authoring \> CKEditor. Click **edit** for the **Full** profile
3. Expand the **File browser** fieldset. Select **IMCE** in the dropdown menu under **File browser type.** Save.

Then, when you click the **Browser Server** button, you will see the following window. Notice the Upload button. Clicking it will allow the user to select a file from their computer.
> 1 votes

# Answer
As @PatrickRyan suggested to add images to the server from your local PC you will have to click on 'upload'
> 0 votes

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


# Question
Title: How to automatically update entity that is created programatically?
Using Entity API, I can create entities easily like this:

```
// SomeEntity class extends ContentEntityBase
$entity = SomeEntity::create(['my_id' => 'id123']);
$entity->save();

```

Works fine as long as `my_id` is unique. When it's not, I get `EntityStorageException` with message complaining about `my_id` not being unique. I could first try to load entity to see if it exists and update it manually but that seems like unnecessary overhead.

Is there a way to automatically save or update existing entity programatically?

# Answer
> 3 votes
Not really. To figure out if an entity exists, you have to check that somehow.

If you're trying to optimize, you could run an entity query instead of loading it completely. But in case you want to update, you need to load the original entity anyway, so just do that.

```
$entity = SomeEntity::load(['my_id' => 'id123']);
if (!$entity) {
  $entity = SomeEntity::create(['my_id' => 'id123']);
}
$entity->save();

```

# Answer
> 0 votes
Using `SomeEntity::load()` first manually and then manually updating fields if entity exists seemed like huge overhead and inefficient. In that case, how `Entity::save()` knows if it's saving new entity or loaded from database? My investigation led me to `EntityStorageBase::create()` method which invokes `Entity::enforceIsNew(true)`.

So the answer seems to be simple: make sure that the entity that was created via `SomeEntity::create()` was explicitly instructed that it should not enforce new when saving. This seems to work fine:

```
// SomeEntity class extends ContentEntityBase
$entity = SomeEntity::create(['my_id' => 'id123']);
// Call Entity::enforceIsNew(false) only if you know that entity already exists.
$entity->enforceIsNew(false);
$entity->save();

```

**Note that entities might have metadata attached like creation date, author etc. This approach would overwrite and lose that.**

---
Tags: entities, 8
---


title: Installed drush 8, got Parse error

text:
# Question
Title: Installed drush 8, got Parse error
Got Drush 8 installed alright, but when I try to **drush up** my Drupal 8.0.0 site I get a **Parse error: syntax error, unexpected '\[' in /is/htdocs/.../.composer/vendor/drush/drush/includes/output.inc on line 188**

Line 188 looks alright to me. What may be wrong?

# Answer
> 2 votes
You are running with php 5.3 or earlier. Drush 8 needs php 5.4 or later. Unfortunately, php 5.3 does not understand array syntax, so the failure is raised before any Drush code runs. For other sorts of errors, Drush will tell you that your php is too old.

I am guessing you are using php 5.5 for Drupal 8; check `which php` and `php --version` to see if your php-cli is the same version as your Web server php.

**UPDATE**:

Set the environment variable DRUSH\_PHP to the full path of the PHP executable that you would like to run. Note that this will only work if you are using a Composer or git install of Drush; if you are using drush.phar, this feature is not available. For the .phar, you would need to use a shell script named "php" that calls php5.6. Then, set your PATH such that your php script comes before the one offered by default on the platform.

---
Tags: drush, 8
---


# Question
Title: Views, how to show x-items from each tag?
I wan't to create an view that show MAX:10 items of tags (football,basketball,tenis etc...)

I want the view to show 3 items for each tag

* \[football\_article\_1\]
* \[football\_article\_2\]
* \[football\_article\_3\]
* \[basketball\_article\_1\]
* \[basketball\_article\_2\]
* .....

Any idea?

# Answer
> 3 votes
A possible solution involves creating two views, one of taxonomy terms, and another one of articles, and using Views Field Fiew to embed the article view as a field in the taxonomy terms view.

1. Create a taxonomy term view that shows fields. Add the title (optional) and Term ID fields. We'll come back to this one in a moment.
2. Create a view of content - of your sport articles that contain the tags. You can use an unformatted list of teasers, or if you want to include only some fields, an unformatted list of fields. My example uses teasers. IMPORTANT: Select a limited number of items to display. In my example I'm limiting it to 3. I won't use a pager in this example.
3. In the **Advanced** fieldset of the second view, add **Contextual Filters**. Select **Content: has taxonomy term ID**. Then in **When the filter is not in the URL** : Display content of "no results found".
4. Go back to your taxonomy term view. Add field **Global: View**. Select the View and Display of the view of content created in step 2. IMPORTANT: in the **Contextual filters** textfield, add the token for the Taxonomy term ID field (usually `[%tid]`)

That's it. Visit your taxonomy term view and you'll see a list of 3 articles per term.

This is what the Views UI for the two views look like:

**View of terms**

**View of content**

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


# Question
Title: How to filter views output base on custom field
I've created a view listing a content type named *foo*, it has a custom field 'start\_date' which can be left blank.

When a node's *start\_date* field is left blank, it should always show in the listing. When it's populated, and the date is less than the current date - then the node should also be listed.

I've tried to use `hook_views_query_alter` to do this, but it didn't do what I wanted as it's for changing the query itself.

Which hook should I use?

# Answer
> 1 votes
You can use the Views UI to accomplish this.

Add two date filters: one of them should filter date fields for "is empty" and the other should filter date fields for "is less than" and choose "Enter relative date" and type "now".

Then create an "OR" group and drag the two date filters to it. It should look like this:

---
Tags: views
---


# Question
Title: Core search, when only one result, open result
Is there a simple way to accomplish the feature in the title ? When a search results in one result, don't show the result but go directly to the node.

# Answer
> 0 votes
As I see the only way is use hook menu alter for this item

```
/**
 * Implements hook_menu().
 */
function search_menu() {
  $items['search'] = array(
    'title' => 'Search',
    'page callback' => 'search_view',
    'access callback' => 'search_is_active',
    'type' => MENU_SUGGESTED_ITEM,
    'file' => 'search.pages.inc',
  );

```

I propose to replace page callback "search\_view" to your own and put there your logic.

---
Tags: 7, search
---


title: How to get complex form field value

text:
# Question
Title: How to get complex form field value
I have form field name like

```
name="commerce_discount_fields[commerce_discount_offer][und][form][commerce_fixed_amount][und][0][amount]" value="" size="10" maxlength="128" class="form-text required" type="text">

```

How to get value in form alter???

# Answer
> 3 votes
Use the following code in validate or submit to get the **% off** form field value.

```
$value = $form_state['values']['commerce_discount_fields']['commerce_discount_offer'][LANGUAGE_NONE]['form']['commerce_percentage'][LANGUAGE_NONE][0]['value'];

```

Hope this will help you.

# Answer
> 0 votes
I guess that like this

```
$form['commerce_discount_fields']['commerce_discount_offer'][LANGUAGE_NONE]['form']['commerce_fixed_amount'][LANGUAGE_NONE][0]['amount']

```

---
Tags: commerce
---


# Question
Title: Hide other user comments, but not to admins
I have created a node, anyone can able to comment on the node. Now, what I want is:

* For Authenticated users, **show** their **own comment only** (not other user's comments)
* For Administrators, show all comments. (I want them to see all comments)

For this functionality, is there any contrib drupal module available? or else show me a way to do in custom module.

# Answer
> 1 votes
Hidden comment

> * Optional field to let users know the reason why a comment is hidden.
> * Disallow edit/reply/delete on hidden comments
> * Optional permission to allow user to hide personal comments (comments on their own nodes). This permission can not unhidden comment.

if you want to do custom edit your node.tpl file add following code:

```
    global $user
    login_uid = //get user id of commnet
    if ($user->uid == login_uid){
      print render($content['comments']['comment_form']);
     }

```

---
Tags: 7, comments
---


# Question
Title: How to change taxonomy term path for table and grid view
I am using taxonomy term module. I have categories vocabulary and in term so many categories and I have created the view using taxonomy term.

With two page first is in table format and another is grid format and in both view page header I place the two icon one is list icon and another is matrix icon.

My issue are that when I click on list icon the page redirect to table view and path are show `taxonomy/term/%` but I want show the path in this format `[vocabulary name]/[term name]/[tid]/list`

# Answer
In Pathauto, for taxonomy term paths, put

```
[term:vocabulary]/[term:name]/[term:tid]/list

```

Then click on the **Bulk Update** tab and check mark **Taxonomy term paths** and then click **Update**.
> 0 votes

---
Tags: views, taxonomy-terms, path-aliases
---


# Question
Title: hook_entity_presave showing error in commerce kickstart
I have created a field calculated price in commerce add product, the code used to save calculated price on saving product.

```
function custom_module_entity_presave($product, $type) {

  if ($type == 'commerce_product') {

$cal=commerce_product_calculate_sell_price($product);
$currency_code=$cal['currency_code'];
$amount=$cal['amount'];
$total_amount = commerce_currency_format($amount, $currency_code);

$product->field_calculated_price['und'][0]['value']=$total_amount;
//commerce_product_save($product);

}
}

```
But this code showing error on saving product

# Answer
> 1 votes
Try the code without using the following line.

```
$total_amount = commerce_currency_format($amount, $currency_code);

```

The remaining code will be the following,

```
function custom_module_entity_presave($product, $type) {
  if ($type == 'commerce_product') {
    $cal=commerce_product_calculate_sell_price($product);
    $currency_code=$cal['currency_code'];
    $amount=$cal['amount'];
    $product->field_calculated_price['und'][0]['value']=$amount;
  }
}

```

If this code not showing error, then the problem will be on your `field_calculated_price` field type. I think it is a custom field and the problem is the field type is not compatible with `commerce_currency_format`.

Please make try... Hope this will help you.

---
Tags: commerce
---


# Question
Title: How to create a includes folder inside sites/all/module/custom/<includes>
I want to create a folder name include in-side sites/all/custom/contrib/ and inside this want to write some `.inc` files like `date.inc`, `string.inc` in each file a class is created which holds function.

Now I want to use this functions in each module under sites/all/custom/contrib. I have 10 custom module so this .inc functions are available to each custom module.

What is the directory structure I have to follow and how can I achieve this?

# Answer
In one of your custom modules, just create a directory **includes** and place your .inc files inside it.

To use the .inc files in your .module file, you can use module\_load\_include.
> 0 votes

---
Tags: 7
---


# Question
Title: Display content having the taxonomy of the logged in user
I need help creating a view in Drupal 7 with the following logic:

* My users have taxonomy reference field.
* My articles also have taxonomy reference field.

**When a user is logged in I want them to see only the articles that have the same term as the logged in user.** How to set the relationships and contextual filters in this view?

# Answer
> 0 votes
Create a view to display the article content, then add as relation for user and add a contextual filter for UID for logged in user.

Add new filter for content taxonomy and it must be equal to user taxonomy.

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


# Question
Title: Determine front page for specific language
I'm using I18n and I am trying to choose which front page to use for each language.

I actually get the following message for every page :

> The requested page "/en" could not be found.

Same for /de (deutch). Has anyone met this problem before ?

# Answer
Found it. It was in "Administration » Configuration » System" that I didn't set the default front page !
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: How to call js and css file and replace the script in code
I'm trying to display a map in node page, it's working but the code doesn't look professional.

```
function customodule_block_info() {
    $blocks['customodule'] = array(
        'info' => t('Google Map Exemple'),
        'cache' => DRUPAL_NO_CACHE
    );
    return $blocks;
}

function customodule_block_view($delta = '') {
    $block = array();
    switch ($delta) {
        case 'customodule':
            $block['content'] = '<!DOCTYPE html>
<html>
<head>

<style type="text/css">
  #map_canvas { height: 560px; width: 100%  }
    #map_canvas img {
max-width: none;

}

    #map_canvas div {
    -webkit-transform: translate3d(0,0,0);
}
</style>

<script type="text/javascript">
  function initialize() {
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 4,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

</script>
</head>
<body onload="initialize()">

<div data-role="page">

<div data-role="content">
  <div id="map_canvas" ></div>
</div><!-- /content -->

 <!-- /header -->
</div><!-- /page -->
</body>
</html>';

    };
    return $block;
}

```

I want to know how **hook\_block\_view** can read the css and js files?

# Answer
> 0 votes
Create the JS and CSS files and then in the block view add them in the following way:

```
drupal_add_css(drupal_get_path('module', 'my_module') . '/css/my_css_file.css');
drupal_add_js(drupal_get_path('module', 'my_module') .'/js/my_js_file.js', 'file');

```

We have done something similar at a module we develop: Guardian news

---
Tags: blocks
---