# Question
Title: Perform "Add to cart" through web services
I am working with Drupal 7 web services. I created few services on my project but now stuck in the commerce's services.

I could not understand how can I add an item to cart with some line item values through web services. What will be the json structure ?

The commerce's cart, checkout, review perform many functions through rules and hooks, so are we going to write code for all of those steps in our custom services module?

# Answer
I have found a similar post on stackexchange, which is little bit helpful. Click here!

But there, they have used commerce line item's ids which will not available in my case because how could we know the lineitem's id before submitting it to cart ?.

Found the below solution for my above query. But I am not sure, what are the standard way to implement this.

1) First I have to create an cart order using commerce services module. http://localhost:8080/drupal7/serviceendpoint/cart

2) Second I have to create new line item and attach it to the order created above using the same module. http://localhost:8080/drupal7/serviceendpoint/line-item

In that way I am able to create a new order with line items. But I will appreciate if anyone could suggest me a clean, better and a proper way.
> 0 votes

---
Tags: commerce, services
---


# Question
Title: How to enter incomplete or partial date with date module? (Day-Month-Year / Month-Year / Year)
I have a content type A and it has a date field.

I'm selecting `Day-Month-Year` for this date field. But not every content has a day and I want to select only `Month` and `Year` for these content.

If I select (enter) only month and year, it gives **error**:

> The value input for field Date is invalid: The value March 1979 does not match the expected format.

I installed and tried the Partial Date module but still couldn't do what I want although it says on the module page:

> This module provides date and time fields that allows any individual component to be left blank, while still providing a sortable listing of the fields.

How can I do that? I want to enter **full** date (`Day-Month-Year`) for some nodes and for some others **partial** date (only `Month-Year`) and maybe for some others only `Year`. **Isn't this possible?**

* `Day-Month-Year`
* `Month-Year`
* `Year`

(And also there is an **unsolved** issue about this: Allow "fuzzy" granularity.)

# Answer
> 1 votes
It is not possible with one date field. But you can achieve it by adding two different date fields with different configuration i.e.:

* Date, Month and Year for **Date1** field.
* only Month and Year for **Date2** field.

# Answer
> 0 votes
The only way do to that is to set the widget type to `Select`, and omit the `Day` part, as seen in the below screenshot.

UPDATE: I don't know why I haven't read the question completely; but Nikhil is right, the only way is create two `Date` components with different configurations.

# Answer
> 0 votes
Create three different Date fields, using different date formats. You can specify the Date entry option during Date field creation (click on More settings and values and choose Custom format in Date entry options, the custom input format for only a month would be F, for example)

---
Tags: 7, datetime
---


# Question
Title: Allow customer to change Quantity in cart
On my site it's not possible for customers to edit the quantity field in the cart view.

How do I allow that? I can't find a permission setting for this anywhere.

# Answer
Go to the display settings of the product(#overlay=admin/structure/types/manage/product\_display/display) Click on the gear icon and select the checkbox "Display a textfield quantity widget on the add to cart form."
> 0 votes

---
Tags: commerce
---


# Question
Title: How to resolve this fatal error '2006 MYSQL server has gone away'?
I'm trying to send 750 emails through cron job.
After it sends nearly 40 emails, like after a few minutes it throws this error,

> Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away' in /public\_html/ehs/includes/database/database.inc:2171 Stack trace: #0 /public\_html/ehs/includes/database/database.inc(2171): PDOStatement-\>execute(Array) #1 /public\_html/ehs/includes/database/database.inc(683): DatabaseStatementBase-\>execute(Array, Array) #2 /public\_html/ehs/includes/database/database.inc(2350): DatabaseConnection-\>query('select name, d...', Array, Array) #3 /public\_html/ehs/sites/all/modules/elysia\_cron/elysia\_cron.module(424): db\_query('select name, d...', Array) #4 /public\_html/ehs/sites/all/modules/elysia\_cron/elysia\_cron.module(632): elysia\_cron\_get('rules\_cron', false, 'running', 0, false) #5 /public\_html/ehs/sites/all/modules/elysia\_cron/elysia\_cron.admin.inc(753): elysia\_cron\_is\_job\_running('rules\_cron') #6 \[internal function\]: elysia\_cron\_execute\_page\_cleanup() #7 {main} in /public\_html/ehs/includes/database/database.inc on line 2171

I have tried upgrading max\_allowed\_packet to 500M under \[mysqld\] in my.ini and also php\_memory\_limit to 1024M, but still it didn't improve anything.
Is there any other possible thing I could do to resolve it?

*FYI, I'm sending a view in emails to all the users using **Insert view**. The views are generated per user basis, and that involves aggregation operations and computed fields.*

# Answer
> 1 votes
A few minutes to send 40 emails indicates that this cron job is computationally expensive. You are probably hitting against MySQL's wait\_timeout limit.

I wouldn't necessarily suggest changing your MySQL configuration. Drupal's cron runs aren't meant to take more than a few minutes at a time. Instead, this may be better suited to a **cron queue**.

In a cron queue, each individual email to send would be a job in this particular queue. During each cron run, as many of those jobs in each queue are processed until some set time limit has passed, and the remaining jobs are deferred for the next cron run.

---
Tags: views, cron
---


# Question
Title: Devel 'Display Query Log' not showing any queries
I've enabled 'Display Query Log' in the Devel Settings but I don't see any logged at the bottom of my page when I load a page. I just get 'Queries exceeding 5 ms are highlighted.'.

I'm running Drupal on PHP 5.3.2 with a mySQL database.

The issue is present in both the Admin theme and my custom theme.

Other Devel outputs seem to display fine.

Any ideas why the queries aren't showing?

# Answer
You need to check 'Collect query info' in the devel settings: /admin/settings/devel

Otherwise no logs can be shown.
> 3 votes

# Answer
The admin module routinely breaks this. Try disabling it.
> 1 votes

# Answer
I often forget to set appropriate user permissions on the devel module when I re-enable it.
> 0 votes

---
Tags: database, debugging
---


# Question
Title: Single click function in a Drupal behaviour?
The following in a Drupal behaviour is working fine:

```
  $('.trigger', context).click(function(e){
    e.preventDefault();
    $('.target').toggleClass('open');
  });

```

However I know that I should be using the once function. Is the following correct? It does work but so did the code above so im not sure how to check if its been done with best practices.

```
  $('.trigger', context).once('toggle-name', function(){
    $(this).click(function(e) {
      e.preventDefault();
      $('.target').toggleClass('open');
    });
  });

```

# Answer
If you don't use .once() then your code will still work but - depending on whatever else happens on the page - your click() function may be attached multiple times to the same element, which is less efficient and may cause undesired effects if, as in this case, you are using a toggle function in your callback.

Because you are limiting the scope of your selector by context, multiple attachment is less likely, but you should definitely use once() if you want your code to be robust.
> 0 votes

---
Tags: javascript
---


# Question
Title: Search API returning no results even though nodes have been indexed
I have a very simple set up as described below.

modules: Search API 7.x 1-1 Search Pages 7.x - 1.2 Database Search Devel Generate

I’ve set up a database server and an index for indexing nodes. The nodes were created using the Devel Generate module. The nodes have been indexed as shown on the Search API -\>View-\>Index Status. On the Nodes-\>Index-\>Fields tab I’ve several options like Node ID, Content Type, Title, Status, etc. In Structure-\>Blocks I’ve added the Search Index to the page in the sidebar. I also set permissions so anonymous users can administer search.

But when administering a search nothing is returned. For test purposes, when entering in the same search term (‘Amet’) in the default search, results are being returned.

How do I troubleshoot this? What is the problem here? Anyone help would be appreciated.

# Answer
What type have you selected for your indexed fields? I think search\_api\_page only handles fields using **fulltext** indexing, and wouldn't be so useful for numeric fields like nid, or text fields indexed with the **string** type.

You could also try using Views with search\_api
> 1 votes

---
Tags: search
---


# Question
Title: How to change value of a node field after a webform is submitted?
I have a content type "items" with a Select list field with the options 0|Free and 1|Reserved.

I am trying to change the fields value from 0 (default) to 1 when a certain webform is submitted (the webform gets the Nid from the url).

For this I have made (and enabled) a custom module (by following a tutorial I found) with the code below:

```
function reservable_item_change_status_webform_submission_insert($node,$submission) {
  if($node->nid == 5){ //my webform has an id of 5
    $nodeID = $submission->data[3]['value']['0'];
    $reservableItem = node_load($nodeID);
    if($reservableItem ->type == 'items'){
      $reservableItem->field_item_status['und'][0]['value'] = 1;
      node_save($reservableItem);
    }
  }
}

```

My problem is that nothing is happening. No errors, but the field status is not being changed to reserved.

I am using Webform version 3.2 because the tutorial stated it was meant for Webform 3.x. I will test with 4.x after I get this working.

Any help would be greatly appreciated.

# Answer
> 1 votes
If typo:

```
if($reservableItem ->type == 'items'){

```

change into:

```
if($reservableItem->type == 'items'){

```

In my implementation I get the submission values like:

```
$submission->data[3][0]

```

So try to change it accordingly

---
Tags: nodes, webforms
---


# Question
Title: How to make 2 different code run acording to different cron schedule?
I have 2 different code running under hook cron like below:

```
function custom_module_cron(){

  // First here code run for posting nodes to Facebook pages
    (this should run for cron tab Ist )

  // Second code runs for sending new posted links in form of digest
     to users according to their selected hours. (This should run for cron tab 2nd )

}

```

For above process I have different cron tabs running on my server such as:

**http://oexample.com/cron.php?cron\_key=something7rsds**

For Facebook at : 23:30, 23, 21, and many more hours

For Digest at : 7 , 8 , 10 and many more

How can we differentiate that each code run according to required hours. Can we make different urls to run for different code to prevent running of code at unwanted hours? I am using rough technique by using `in_array` for current time and hours in cron tab but thats very handy and I think its not solution.

Please suggest what I can do to make my codes run according to separate schedules ?

Thanks!

# Answer
This is how I solved my problem, If anyone have better approach please suggest.

```
function custom_fb_menu() {

   $items['cronjobs'] = array(
     'title' => 'Custom Cron Jobs',
     'page callback' => 'custom_cron_jobs',
     'type' => MENU_CALLBACK,
     'access callback' => TRUE,
 );
   return $items;
}

function custom_cron_jobs() {
  $type = arg(1);

  switch($type) {
    case "facebook":
        facebook_callback();
        break;
    case "digest":
        digest_callback();
        break;
 }
  return "";
}

function facebook_callback() {
    dd("Hi I am in facebook_callback"); // to write file in temp folder with help of debel mdule
}

function digest_callback() {
   dd("Hi I am in digest_callback");
}

```

*** * * * * /usr/bin/curl http://www.example.com/cronjobs/facebook \> /dev/null 2\>&1**

*** * * * * /usr/bin/curl http://www.example.com/cronjobs/digest \> /dev/null 2\>&1**

Thanks!
> 0 votes

# Answer
Adding a GET parameter should work. In your crontab edit the url and add something like `&type=facebook`.

In the hook\_cron implementation you should be able to catch the type via `$_GET['type']`
> 0 votes

---
Tags: 7, hooks, cron
---


# Question
Title: I want to change the order of fields in login/registration form
I've user login/registration form in my drupal 7 site. Two links in this form: "Create new account" and "Request new password" are appearing before captcha. And I'm trying to place these links after captcha and before button. How can I achieve this?:

# Answer
You probably should hide this fields, and show them with javascript before captcha input value is not empty. Check it with "on change" function:

```
 $('body').on('change', '#CAPTCHA INPUT', function(){}

```
> 0 votes

# Answer
You could try implementing hook\_form\_alter and changing the weights of the form elements.
> 0 votes

---
Tags: users
---


title: How to make a OG private?

text:
# Question
Title: How to make a OG private?
I want to make an Organic group private,to be seen only from members of this group. All the other will get an "Access denied" or something like that. For the time being,I can see the Group but not its content. I would also want NOT to be able to see the existance of the group,if I am not a member of it. I am working on Drupal 7. How to do that? Thanks

# Answer
> 14 votes
You need to enable og access control module.

see below:

Then navigate to admin/config/group/fields, add an visibility field to your og bundle

Then edit the og bundle content type, there is a new field added to it, make your change for public or private

# Answer
> 2 votes
Please consider that to make a group truly "private" you have also to remove the "register" permission for non-members otherwise even if the group is "private" non-members that can guess its nid can subscribe (at http://www.example.com/group/node/\[nid\]/subscribe) and hence view the group's content \[OG 7.x-2.2\].

# Answer
> 0 votes
This required additional steps for me. Also an unfortunately specific recipe. Viewing `node_access` records using Devel Node Access module & block provided some pointers.

* Admin \> People \> Permissions
Set Anonymous and Authenticated to can view content
* Admin \> Modules
Enable OG permissions via Organic Groups Access Control module
* Admin \> Configuration \> Organic Groups \> OG Field Settings
Add visibility controls (fields) to group node-types
* Configure other NAC modules, Content Access in my case, to weighted less than, before, OGAC.

Defaults are now allow viewing, unless set by the group-type node. If you change content visibility from a group page, the subpages have to be resaved or `drush php-eval 'node_access_rebuild();'`

---
Tags: organic-groups
---


# Question
Title: FedEx Address Validation module setup help
I am trying to force accurate city, state and zip code entries when a user inputs their address. the Address Field module by default doesn't require any accuracy. For example i can type "fake city" and it will accept that.

I found the FedEx Address Validation module, but as stated on the module page there is no user interface for connecting your FedEx credentials.

Does anyone know where to add my credentials?

> This module has no User Interface, so you must set the following variables: fedex\_address\_validation\_environment - must be either "test" or "live".

Live credentials are made up of the following 4 values:

* fedex\_address\_validation\_live\_key
* fedex\_address\_validation\_live\_password
* fedex\_address\_validation\_live\_account
* fedex\_address\_validation\_live\_meter

Test credentials are made up of the following 4 values:

* fedex\_address\_validation\_live\_key
* fedex\_address\_validation\_live\_password
* fedex\_address\_validation\_live\_account
* fedex\_address\_validation\_live\_meter

I tried adding to settings.php

```
$conf['fedex_address_validation_environment'] = 'test';
$conf['fedex_address_validation_live_key'] = 'LIVE KEY';
$conf['fedex_address_validation_live_password'] = 'FEDEX PASSWORD';
$conf['fedex_address_validation_live_account'] = 'ACCOUNT NUMBER';
$conf['fedex_address_validation_live_meter'] = 'METER NUMBER';

```

with no change. status still "Not configured for test"

# Answer
Unless you desperately need those vars to be administered through the UI (in which case a small custom module would be the way to go), you can just add the variables through settings.php, using the following format:

```
$conf['fedex_address_validation_environment'] = 'test';
$conf['fedex_address_validation_live_key'] = 'foo';
$conf['fedex_address_validation_live_password'] = 'bar';
// etc...

```
> 2 votes

---
Tags: entities
---


# Question
Title: Using hook_mail_alter() for pending approval admin does not make any effect
I want to disable the emails sent to admins when a new user account is being created, Account details for (user name) at site name. (pending admin approval).

I tried adding the piece of code in the hook\_mail\_alter function but that does not give me any change. Below is the code change that i made

```
function hook_mail_alter(&$message) {
  if ($message['id'] == 'modulename_messagekey') {
    if ($message['id'] == 'modulename_register_pending_approval_admin') {
      $message['send'] = FALSE;
      return;
    }

    if (!example_notifications_optin($message['to'], $message['id'])) {
      // The usual code for sending mails.
    }
  }
}

```

Please let me know how can i disable the emails sent to admins. I could not find any place where I can disable the email functionality from the UI end.

# Answer
The emails are being sent because in admin/config/people/accounts the option *Visitors, but administrator approval is required* is selected for *Who can register an account*.

>

If you selected *Visitors* or *Administrator only* no email would be sent.

In the case you wanted to just avoid emails where sent to the administrators, but still wanted the administrator users to approve accounts, then the implementation of `hook_mail_alter()` should look for messages whose ID (`$message['id']`) is equal to user\_register\_pending\_approval\_admin\_. Also, the example in the documentation of hooks don't show the correct name a hook implemented by a module should have: Always replace hook\_ with the short name of the module implementing the hook.
> 1 votes

---
Tags: 7, hooks, emails
---


# Question
Title: Reducing number of DB queries when using views, search_api and relationships
I have a view which uses search\_api (and solr) to get a list of nodes, and then displays selected fields, including some from a relationship to commerce\_product

This is resulting in about a thousand database queries to display about 20 nodes, which I think is inefficient.

Digging in further, it looks like search\_api returns a list of nids, which are then loaded with a single invocation of entity\_load (which causes several DB queries as field\_attach\_load loads each of the bundle's fields in turn, loading values for all nodes at once)

But when it comes to the commerce\_products in the relationship, these are loaded one-by-one somewhere during the field render process, rather than all in one go. So the total number of queries is close to (number of results) x (number of fields) instead of just (number of fields) like it would be without the relationship.

(Yes, I have quite a few fields)

Is there any way I can get Views to load all of the referenced entities in one go, rather than in this inefficient one-by-one manner?

# Answer
> 1 votes
Is there any way get Views to load all of the referenced entities in one go? No, there's not much you can easily change to fix that.

There's a lot of behaviour built in so that Drupal can handle multilingual data or different data storage back ends like MongoDB.

If you're not already doing so, you can use entitycache module to lighten the load. For cached entities, you will eliminate a lot of queries.

FYI, Entitycache will not work on its own. You will need to integrate with a cache back end like Redis or Memcache. See the module documentation and READMEs for configuration details.

---
Tags: views, entities, performance, search
---


# Question
Title: How to provide free tagging ability when saving nodes using services
A content type is going to be saved , this type contains a taxonomy term reference field named field\_ucectgry . I'm developing an app so the user can create new node types remotely. Services module is used to provide a REST service for that.

Now for filling field\_ucectgry during node creation I must pass the term ID , but the problem is that this field must has free tagging ability which means new tokens for this field is accepted.

So , how can I provide the ability of free tagging for my program?

PS: this is the structure of the field in node :

---

# Answer
In D7, a taxonomy term reference field with the autocomplete widget uses **JSON** like this: `"field_tags":{"und":"Foo,Bar"}"` When it is an autocomplete, the term name needs to be used instead of the term id for free tagging it will simply create the term.
> 1 votes

---
Tags: taxonomy-terms, services
---


# Question
Title: Custom field in XML with Views RSS module
I need to create an XML using Views RSS module, and it's created correctly. But I want to add a custom field to the XML. For example, an item from the XML is:

```
<item>
<title>Liburu bat</title>
 <link>http://whatever.com/comercios/productos/1022/botak</link>
 <description>Produktu bat</description>
 <category>Forros para botas %% Espuelas %% Calzado</category>
 <guid isPermaLink="false">1022</guid>
 <source url="http://whatever.com/es/comercios/productos/whatever.xml">Escaparate Whatever</source>
</item>

```

And I want to add a custom field to that item, for example: Something else

Any idea how can I do it?

# Answer
You need to implement a `hook_views_rss_item_elements()` invocation if you're wanting to add a custom item element. For example:

```
/**
 * Implements hook_views_rss_item_elements().
 */
function MYMODULE_views_rss_item_elements() {
  $elements['my_element'] = array(
    'title' => t('My Element'),
    'description' => t('Provides a my_element to an item element in Views RSS.'),
  );
  return $elements;
}

```
> 2 votes

---
Tags: views, feeds
---


title: Location of Drush Error log

text:
# Question
Title: Location of Drush Error log
I am getting a "terminated" message from Drush ARD command after it runs awhile. This happens in a shared environment on bluehost. I checked the error logs accessible via cpanel, but found nothing. There are also no messages in the Drupal error log. I need more information that just "terminated" to solve this problem. Where are Drush error messages logged?

Putty commands -

```
    Using username "columck5".
Authenticating with public key "imported-openssh-key"
Passphrase for key "imported-openssh-key":
Last login: Fri Nov  6 10:51:16 2015 from 98.142.53.79
columck5@columbiablooms.org [~]# drush status
 PHP executable         :  /ramdisk/php/54/bin/php54-cli
 PHP configuration      :  /usr/php/54/etc/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home5/columck5/.composer/vendor/drush/drush/drush.p
                           hp
 Drush version          :  7.1.0
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

columck5@columbiablooms.org [~]# cd /usr/php/54/etc
columck5@columbiablooms.org [/usr/php/54/etc]# ls -l
total 160
drwxr-xr-x 5 root root  4096 Nov  6 05:17 ./
drwxr-xr-x 5 root root  4096 Nov  6 05:17 ../
drwxr-xr-x 2 root root  4096 Nov  6 05:17 pear/
-rw-r--r-- 2 root root  1176 Jul 13 15:25 pear.conf
drwxr-xr-x 2 root root  4096 Nov  6 05:17 php.d/
-rw-r--r-- 2 root root 67071 Oct 29  2014 php.ini
-rw-r--r-- 2 root root 66936 Jul 23  2012 php.ini.rpmnew
drwxr-xr-x 2 root root  4096 Nov  6 05:17 rpm/
columck5@columbiablooms.org [/usr/php/54/etc]# nano php.ini
Error writing php.ini: Read-only file system
chmod gets the same error message

```

# Answer
> 4 votes
The Drush logs are emitted only to the console. Use `--debug` to get more information about what is happening.

Your ISP is probably deciding that your Drush command is taking too long, and are killing the process. Ask support at your ISP to determine if this is the case, and whether there is a way to increase the limit. Drush does not have any support this sort of limitation; it assumes that it is running in a shell with no time limits.

PHP can also be configured to apply a maximum timeout to your requests. To find out what php.ini Drush is using, run `drush status`. One of the lines will provide the full path to your php.ini file. Ideally, you should use a different php.ini for Drush than you do for your web server. Set the environment variable PHP\_INI to point to the php.ini file that Drush should use. Copy your webserver php.ini to serve as a starting point, and then customize to suit.

The variable you are looking for is max\_execution\_time.

---
Tags: drush
---


title: Views custom sorting

text:
# Question
Title: Views custom sorting
How can I create a custom sort of items in a view? For example, I want to order content by: **`(rating * 10) - age in hours`**. (Rating is 5 star module percentage.)

I've been looking at the Computed Field module and the Views API but I'm not finding what I need.

# Answer
In the end I created a custom module with a Views Sort handler to write the custom ORDER sql.

```
function custom_module_views_query_alter(&$view, &$query) {
  if($view->name === 'viewname') {
    /**
     * Order = (rating * 10) – (hours old / 2)
     * Note: the rating field is divided by 2 because in the DB the rating is out of 100
     */
    $view->query->orderby[0]['field'] = "(if(field_data_field_rating.field_rating_rating, field_data_field_rating.field_rating_rating,0) / 2) - ROUND((UNIX_TIMESTAMP(NOW())-created)/60/60/2)";
    $view->query->orderby[0]['direction'] = "DESC";

    $view->query->orderby[1]['field'] = "created";
    $view->query->orderby[1]['direction'] = "DESC";
  }
}

```

For this to work you either have to add the SQL JOINS in this module or add the rating and posted date fields as a 'sort' in your view.
> 10 votes

# Answer
I would use the Views PHP module for this matter.

> This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code.

* Install and enable the module (along with Views)
* Add all necessary fields in your view and exclude from display
* Add a new *Global: PHP* field where you specify the code you need in order to calculate the desired result.
* In the value code add: `return (($rating * 10) - $age);` (also consult the collapsed *available variables* section).
* In the output code add: `<?php print $value; ?>`
* Add a new *Global: PHP* sorting field with: `if ($row1->php < $row2->php) return -1; else return 1;`
> 2 votes

# Answer
Using a field with the sort value ((rating * 10) - age in hours) will no work unless you update that field value continuosly (because it should change while time pass).

Probably you should write your own Views Sort handler. A Views sort handler allows you to set the sort order in the SQL.

In your SQL you will need:

* A computed column with your sort value: (rating * 10) - age in hours
* ORDER BY sentence using that column.

I've never written a sort handler but I think it could resolve your issue.

Check contrib modules that use their own sort handlers.
> 0 votes

# Answer
You can only sort the CURRENT PAGE if you use the `Global:PHP` field. However, if you have a pager and need the select query to order by that expression, you need to implement `hook_views_query_alter` and add the custom field.

First you need to add these fields in your expression at the view's *FIELDS* section, and then add the hook like this:

```
function MODULE_NAME_views_query_alter(&$view, &$query){

    if($view->name == 'name' && $view->current_display == 'page'){
        $query->add_field(NULL, 'TABLENAME.rating * 10 - TABLENAME.age', 'sort_field');
        $query->orderby = array(
            array(
                'field' => 'sort_field',
                'direction' => 'DESC',
            ),
        );

    }
}

```

Look for details in the document add\_field of `views_plugin_query_default`
> 0 votes

---
Tags: 7, views
---


# Question
Title: Fatal error: Call to a member function execute() on a non-object - db_select() addExpression
I'm fixing up a module and I have the following db\_select() code, but I'm getting the following error:

> Fatal error: Call to a member function execute() on a non-object in /var/www/xxx/sites/all/modules/xxx/xxx.module on line 414

I think it has something to do with the addExpression line, but I'm unsure of what this line does or what is the equivalent of addExpression in sql? What is MAX(poss), poss -- mean?

```
$query_poss = db_select('saved_lists', 'saved_lists')
  ->condition('saved_lists.lid', $lid)
  ->addExpression('MAX(poss)', 'poss')
  ->execute()
  ->fetchField();

```

# Answer
> 3 votes
The `addExpression` method returns the unique alias that was assigned for this expression, and thus cannot be chained.

Please look at this example and the document.

```
$q = db_select('parser_subtasks', 'st')
 ->condition('QueueID', $task['ID'])
 ->condition('IsDone', 0);
$q->addExpression('MIN(Delay)');
$min_time = $q->execute()->fetchField();

```

---
Tags: 7, database
---


title: Facebook login only

text:
# Question
Title: Facebook login only
I'd like to allow user register/login via Facebook only. After installing Simple FB Connect, there is a new `Facebook login` tag at: `user/simple-fb-connect`

The question is, how can I remove:

* Create new account
* Log in
* Request new password

tags from: `user/register`?

# Answer
1. Create custom `tpl.php` file of user registration
2. Comment the `$tabs` section or `$conten`t
3. Render facebook login form using form id and render it.
4. Another method is that use penals create a new page and add facebook login block in that page,Set page path on user login
> 3 votes

# Answer
I'd say there's 2 ways to go about this.

One is to disable those tabs at the Drupal level. This can be done via `hook_menu_alter()` or for a solution that doesn't need custom code, use the Tab Tamer module.

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.

The other way, is change your theme to hide those tabs via CSS (e.g. using a `display: none;` property). This way the URLs are still accessible to users that don't want to be forced to login via FB (e.g. admins).
> 2 votes

---
Tags: users, social-network
---


# Question
Title: How adding the current title to the breadcrumb?
I have two centent type ：Course and eLesson.

I need make a breadcrumb like this: **Home\>\>Course\_title\>\>eLesson\_title**

How should I do ? I added path breadcrumbs module

# Answer
Menu Breadcrumb

> * Append the **page title** to the breadcrumb (either as a clickable url or not)
> * Hide the breadcrumb if it only contains the link to the front page.
> * Generate the breadcrumb from the URL structure if content does not belong to a menu (7.x-1.6 and older only)

How to set breadcrumbs

Custom Breadcrumbs

> Many new features have been added including support for Views, Panels, Taxonomy vocabularies and terms, paths, and a simple API that allows contributed modules to enable custom breadcrumbs for module pages and theme templates. These are implemented using optional, independent submodules that depend on the main Custom Breadcrumbs module.
>
> In addition to breadcrumb visibility, this version provides an option permitting PHP code snippets to be used in forming the breadcrumb titles and paths. Multiple languages are also supported.
> 0 votes

---
Tags: breadcrumbs
---


# Question
Title: Fetch third Level Depth Data from taxonomy with performance
I have taxonomy with 4 Level **State-\>District-\>Block-\>Villages**. I want to get all villages of all Blocks of all Districts of a State.

I have done it by loops but my performance is very slow. please help me this take more time than expectation and very slow process.

# Answer
You can fetch all child at any level by using this code :

```
function taxonomy_get_children_all($tid, $vid = 0, $key = 'tid'){
  $c = taxonomy_get_children($tid, $vid, $key);
  $result = array();
  foreach ($c as $t => $d){
    $result[$t] = $d;
    $below = taxonomy_get_children_all($t, $vid, $key);
    if (!empty($below)) {
      $result[$t]->children = array();
      foreach ($below as $nt => $nd){
        $result[$t]->children[$nt] = $nd;
      }
    }
  }
  return $result;
}

```

OR

You can do it by adding custom database query using function function taxonomy\_get\_children
> 0 votes

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


# Question
Title: Using hook_menu in a custom module, how do you add a menu item to more than one menu in Drupal 7?
I am working with Drupal 7. I have created a custom module that supplies several menu items using hook\_menu. I am adding one of these menu items to the main menu:

```
$items['my-chapter'] = array(
    'title' => 'My Chapter',
    'page callback' => 'mymodule_my_chapter',
    'file' => 'includes/pages.inc',
    'menu_name' => 'main-menu',
    'weight' => '110',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

```

Adding the menu item to the main menu works fine using this code. But I have a secondary menu that also needs this link. Is there a way to add it to another menu in addition to the main menu I'm already adding it to? Adding another $items\['my-chapter'\] will obviously just overwrite the previous one and the 'menu\_name' only takes a single string.

Can anyone shed some light on how/if this can be done? Thanks.

# Answer
I'm pretty sure you are looking for `menu_link_save()` as adding the `menu_name` in `hook_menu()` just puts this callback in that menu instead of defaulting it into the `navigation` menu. So, after creating it above, with or without the `menu_name`, you should be able to add it to any other menu(s) with `menu_link_save()`.
> 2 votes

# Answer
You can simply add another entry, such as the following one.

```
$items['my-chapter-2'] = array(
  'title' => 'My Chapter',
  'page callback' => 'mymodule_my_chapter',
  'file' => 'includes/pages.inc',
  'menu_name' => $menu_name,
  'weight' => '110',
  'access callback' => TRUE,
  'type' => MENU_NORMAL_ITEM,
);

```

Replace `$menu_name` with the name of the menu where the menu item should appear.

Drupal just needs to know the page callback to call, and the users just see the menu title. In this way, you can have two menu items showing the same page.
> 0 votes

# Answer
Maybe `hook_enable()` would be a more appropriate place for using `menu_link_save()` as it is only fired once and after the `.module` file is fully loaded, so your custom menu item would already be in place. You will also need to add `'customized' => 1,` to your menu link array otherwise it wont be added. ref.. Don't forget to the remove the menu link in `hook_disable()`. They should both be placed in the `.install` file of your module.

hook\_enable()
> 0 votes

---
Tags: routes, hooks
---


# Question
Title: Using custom author name in a node instead of author field
I have a display name field I created for my users (available in account settings). I'd like to display the display name in the node if the person authored that node. I see I have an author field I can use... but that displays the login of the user, while I want to display their pretty display name that I setup instead. Is there a way to include this field instead of the author field?

In views it's easy to do, but I'm trying to use the field in a node.

# Answer
> 3 votes
There is a module for it. You can choose which custom user field to use. This module only works for drupal 6 and drupal 7 https://www.drupal.org/project/realname

---
Tags: nodes, theming
---


# Question
Title: How to assign a specific color to each taxonomy term in a chart created with the Charts module?
I have a view with format "Chart" and I'm using Highcharts as my charting library.

In the settings there is a section to choose the colors of the chart.

My content has a field that can have 3 different values. On the chart, the colors are assigned randomly for that field.

Is it possible, using the Charts module, or in any other way, to assign a specific color for each of the field values (the field is a taxonomy term)?

# Answer
As you must have noticed, creating charts using the Views UI of the Charts module, you can only select 1 color for each chart.

However, if you would rework your chart to a **Combination chart**, you could set a color for each of the charts. Here are some more details about how I'd create the combination chart (with 1 color for each taxonomy term):

1. Use your current chart display as the parent chart for 3 child charts to be added to it (as explained below). Adapt its chart settings where needed, so that it won't get in the way of the 3 child charts to be added to it. For that, I'd make it a "line chart", possibly with some other refinements like color and label of that chart also.
2. Add a 1st (child) chart display with a views filter that limits the values to only your **1st taxonomy term**, and specify a **1st color** in its chart settings. Use the chart in bullet "1." as its parent chart.
3. Add a 2nd (child) chart display with a views filter that limits the values to only your **2nd taxonomy term**, and specify a **2nd color** in its chart settings. Use the chart in bullet "1." as its parent chart.
4. Add a 3rd (child) chart display with a views filter that limits the values to only your **3rd taxonomy term**, and specify a **3rd** color\** in its chart settings. Use the chart in bullet "1." as its parent chart.

Here is an example of a column chart created as a combination chart:

And this is a variation of it in the format of an area chart (for "total") with 2 line charts:

As both examples illustrate, for each chart in such combination chart, you can assign any combination of colors ... Which is what this question was about, no?

**Note**: Using this approach, the parent chart in bullet "1." above will avoid that you run into the issue about "holes" in your X-axis data. Refer to my answer to the question about "How to create a combination chart with the Charts module if some X-axis values are missing?" for more details on that.
> 0 votes

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


title: Should I go for Drupal7 or Drupal8?

text:
# Question
Title: Should I go for Drupal7 or Drupal8?
I am currently developing my website. It is in initial stage. I got pretty good hand on Drupal7. But as Drupal8 is going to release in few days should I shift to drupal8 from now itself as my development is in very initial stage Or should I stick to Drupal7?

# Answer
Drupal 8 is a better platform , it has a better structure , more features in core , it is based on symphony2 and so the module development is different from what you knew in drupal 7. template engine also is changed to twig so again you have to change your point of view about how used to theme before .

Another thing must be mentioned before making your decision is that there are too many module for drupal 7 and you can find a module for almost any job but cause drupal 8 is new , many modules are not still developed for this version.

All in all I should suggest you that it is a good idea to migrate to drupal 8 but if you have a deadline for your project this may not be a good decision to start it with drupal 8 ,cause it will take some times to be adopted.
> 2 votes

---
Tags: nodes
---


title: Best way to choose users to email?

text:
# Question
Title: Best way to choose users to email?
I have a content type of things to be worked on. I want to be able to select which user is responsible for a certain project. Then use the Rules module to email them with other various conditions and action sets.

What is the best way to create a field in this content type that will change dynamically by the users with certain criteria?

# Answer
> 1 votes
Using Entity Reference module it is possible .

> * A generic entity reference field
> * Four widgets:
> * Two implemented on top of the Options module (Select and Radios/Checkboxes),
> * Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)
> * Two formatters:
> * A "Label" formatter, with optional link that displays the label of the referenced entity (the node title, the user name, etc.)
> * A "Rendered entity" formatter, that renders the references entity using a configurable view mode

Add field in your content type of user entity reference then it is automatically select value of user for emails

# Answer
> 0 votes
Use of Chosen module with Entity Reference will be more better for you.

---
Tags: 7, entities, rules, emails
---


# Question
Title: I have a tpl.php file. How can i check variable is set and print the value if the variable is set
I am using in this way. Please correct me if i am wrong

I want the output as "(variable\_value)"

`<?php if isset(variable_get('variable_name'))?>{
(<?php print t(variable_get('variable_name'));?>)}:`

# Answer
Assuming your variable is a string:

```
<?php if(isset($variable)): ?>
  <div class="wrapper">
    <?php print $variable; ?>
  </div>
<?php endif; ?>

```

With variable\_get() and brackets:

```
<?php if isset(variable_get('variable_name')): ?>
  "<?php print t(variable_get('variable_name')); ?>"
<?php endif; ?>

```
> 0 votes

# Answer
```
<?php if isset(variable_get('variable_name')): ?>
 <?php print t('('. variable_get('variable_name') . ')'); ?>
<?php endif; ?>

```
> 0 votes

---
Tags: theming
---


# Question
Title: What is the right way to count filled multi value field values in drupal?
I've a term reference multi value field. What is the right way to count filled values which is also portable to D8, D9 etc.

The dsm output shows like this:

# Answer
> 1 votes
```
$wrapper = entity_metadata_wrapper('entity_type', $entity);
dpm($wrapper->{FIELD_NAME}->count());

```

Dealing with entity reference field you can get the identifires like this:

```
dpm($wrapper->{FIELD_NAME}->value(array('identifier' => TRUE)));

```

# Answer
> 1 votes
Using Entity Metadata Wrapper, you can achieve it this way.

```
$wrapper = entity_metadata_wrapper('node', $node);
$count = count($wrapper->{FIELD_NAME});

```

# Answer
> 0 votes
It really depends on the type of field, and on when you are trying to retrieve the values.

During `hook_form_alter()` for checkboxes, radios, and select fields, the values you are referring to are typically set via the #options property. Example: `$form['artist_tags']['und']['#options']`. You can wrap that in `count()` to get the number of values.

During `hook_form_validate()` or `hook_form_submit()` or a function called from the `$form['#after_build']` property, you will also have access to the number of **selected** values via `$form_state['values']['artist_tags']['und']` (or when `$form_state['submitted']` is TRUE, check `$form_state['input']['artist_tags']['und']`).

---
Tags: 7, entities
---


# Question
Title: How to filter the view2 fields and show by clicking on view1 node
I have view1 and view2, when I click on the node link of view1 say

ex: **id \[mc\]** it should get view2 and display corresponding information like strain , projects etc based on the **id\[mc\]**.

So far to get the view2 while clicking on view1 node, I have performed following,

* In view1 I have rewritten the tittle\[node\] output to link and specified the path of view2.
* Given contextual filter to filter and to get the related field value of view2.

Problem is **when I click on particular node of view1 it gives the view2 but it is not filtering based on the node we have clicked**.

So can you please tell me how to filter and get the field values of view2.

# Answer
> 1 votes
**Step 1)**

I added a Entity Reference field called 111 to my Content Type

**Step 2)**

In view1 in **RELATIONSHIPS** click Add

* in search type `ref`
* select **Entity Reference: Referenced Entity**

**Step 3)**

In **FIELDS** click add, select **File Usage: Entity ID**.

* Under Relationship, select your entity reference
* check mark exclude from display.
* Thousand Marker, select none

**Step 4)**

**Move** your **title** field **below** the File Usage: Entity ID field.

**Step 5)**

Click on your Title field.

* Uncheck link this title to the original piece of content
* Under Rewrite results, checkmark output this field as a link
* link path: `/view2/[id]`

**Save view1**

**Open View 2**

**Step 1)**

**Add a Contextual Filter** of **File Usage: Entity ID** (Do the same as picture below)

**Step 2)**

In **RELATIONSHIPS** click Add

* in search type `ref`
* select **Entity Reference: Referenced Entity**

**Step 3)**

Change the page path settings to `/view2/%`

## **DONE :)**

---
Tags: views
---


# Question
Title: Putting a <div> tag around fields in nodes
I have three fields in my node that I'd like to group together with a tag (so I can center them all next to each other) but I'm not sure how to do this.

The fields are a user photo (the author of the node) a field that just says 'by' and then the 'author name' field.

Right now they look like this:

```
PHOTO
by
authorname

```

I could just 'float: left' but I also need to center the whole group on the page so that actually won't work in this case. Hence my need to put them inside a tag.

Note: I'm also currently trying to use display suite to display my nodes, if that make a difference.

I looked at the display suite tpl file I'm using and frankly it doesn't give me many options other than 'print $ds\_content;'

Anyone know how to do this?

# Answer
If you are using Display Suite you can change the layout. For Example: Two Column stacked (fluid) and assign the 3 fields to the header column and the rest in the bottom column.

If you inspect the element with your browser, the header column should have a wrapper, so then you can center the content with css.

**PS:** You could also create your own Display Suite layout by modifying the `ds-2col-stacked-fluid-node.tpl.php` file. (ex: get rid of the left and right fields. so its just a top and bottom) or add a 3rd horizontal column if you need another one.
> 2 votes

# Answer
To provide the custom markup, you have to override the tpl.php file for that node. To override this, follow these steps :

1) Copy the node.tpl.php in your theme.

2)Rename it node--"yourContentTypeMachineName".tpl.php for example my custom file is now node--image\_archive.tpl.php

3) to test it out write some text(anything) in your new node.tpl file.

4)paste your new node.tpl file back in you theme folder

5)Clear all cache

Now access all the field and provide the custom markup as you want.
> 4 votes

---
Tags: nodes, theming
---


# Question
Title: How do I get a nodes authors email address within views?
I have a view that list nodes of a certain type. These nodes are created by different users.

In my view, how would I get the email address of the creator of the particular node (I will pass this email to a webform)?

# Answer
> 2 votes
1. Create the view of content type or use existing view
2. Go to admin/structure/views and edit your view
3. Under advanced section tab **add relationship** `Content: Author`
4. Add the relationship.
5. Add the email field `User: E-mail (E-mail)` under field section.
6. Save the view

# Answer
> 1 votes
1. Create a view of content type
2. Add required fields
3. Add relationship of user named node content author

4. Again Add field of author name and email.

---
Tags: views, nodes, users, emails
---


title: Change five module user rating text

text:
# Question
Title: Change five module user rating text
I am using fivestar module to rate the content. I have added it to my view and full node view. I have configured it only to display number user voted the content. By default it is displaying as `No votes or (10 Votes)` and so on. I want to alter the text as `(0) or (10)` and so on. How can I alter the text. In contrib it is written in http://www.drupalcontrib.org/api/drupal/contributions!fivestar!includes!fivestar.theme.inc/function/theme\_fivestar\_static/7

# Answer
> 0 votes
You programmatically alter it via hook\_node\_view\_alter()

> This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete node content structure has been built.

---
Tags: 7, rating
---


# Question
Title: Is it good practice to override simple db_query or EntityFieldQuery with a View
I am using several autocomplete fields in a form. To retrieve the data, I have used `db_query` for very simple queries, `EntityFieldQuery` for more complex, until I found one that is somehow convoluted, so I used a **View** and `views_get_view_result` to retrieve the list of suggested terms. Is it a good practice or am I consuming too many resources instead of digging a little more in my code?

# Answer
There is no simple answer possible to this question because it very much depends on circumstances. The customary response to such fears is to invoke the spectre of Premature Optimization and to advise you not to worry until you **know** you have a performance issue.

However, from an educational perspective it's probably worth at least looking at the query Views is executing and considering whether it is efficient: is it scanning every row of a large table because of the lack of an index, for example.

On the Views settings page there's an option to display the SQL for a query. You can copy and paste it into a tool such as PhpMyAdmin (removing the curly brackets peculiar to Drupal SQL queries) then put "EXPLAIN" in front of it to see what's happening under the hood.

But in general I would not bother to rewrite a query like this until there's a proven need to do so.
> 2 votes

---
Tags: views, entities, ajax
---


# Question
Title: how to get information about discounts on product?
Short: I have commerce product and commerce discount that affects this product's price. I want to presents details of this discount to users in shop.

Long story: I use Drupal Commerce with Drupal Commerce Discount which is based on Rules. Discount module is used for configuring promotions on products. Some of promotion (configured discounts) are time-limited ie. they ends on 11.11.2015. I would like to get information about discounts that affect product when displaying details. First of all I need to display information how much time is left before discount ends.

Is there any way to get information about active rules on product level?

# Answer
> 2 votes
On the line item, you have the `field_unit_price` field. Inside of that field's data attribute, you'll find information about the discounts that are applied to that product:

```
array(1) {
  ["components"]=>
  array(2) {
    ...
    [1]=>
    array(3) {
      ["name"]=>
      string(22) "discount|discount_test"
      ["price"]=>
      array(3) {
        ["amount"]=>
        float(-240)
        ["currency_code"]=>
        string(3) "USD"
        ["data"]=>
        array(2) {
          ["discount_name"]=>
          string(13) "discount_test"
          ["discount_component_title"]=>
          string(5) "Test"
        }
      }
      ["included"]=>
      bool(true)
    }
  }
}

```

Iterate over the components. If there is a discount applied to one of the items, you'll find one with a name that begins with `discount|`. Then you can then load that discount and grab more information about it:

```
$discount = entity_load('commerce_discount', array('discount_test'));

```

From here, if you've added dates, the date fields will be accessible on the field `commerce_discount_date`.

---
Tags: commerce, rules
---


# Question
Title: How do I change total number of rows in a view programmatically?
I had to remove manually some rows from a View programmatically for a lot of good reasons, too long to explain. I did it removing item in the pre-render hook from the array

```
view -> result

```

It works fine, but the total number of items contained in the view is not changed. How can i change it programmatically? I tried changing

```
view -> total_rows

```

but it seems not to be enough. I saw a lot of **total\_items** elements in the object view, and i think changing them would work, but there are 60 items like that, each contained in objects contained in arrays that are contained in objects and so on and i am not really sure how to change every element with that name, parsing the structure of the object view and changing every total\_item with the number X instead of the number Y.

# Answer
> 2 votes
You're probably looking for the `view::set_items_per_page()` method, e.g.

```
/**
 * Implements hook_views_pre_build
 **/
function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'foo') {
    $view->set_items_per_page(10);
  }
}

```

That method updates both the instance var and the limit on the internal query that Views will eventually run.

Note that you need to make this change before the query is executed (i.e. in a pre build, not pre render, hook), or you'll get inconsistencies with pagers etc.

---
Tags: 7, views
---


# Question
Title: How to make a discount on specific products quantity that have specific fields
I'm a bit lost with a workcase.

I'd like to apply a discount to a few line items depending on their quantity and if the product if the line items have some specific fields.

An example will be a bit clearer: If the user orders at least 10 differents product that share the same field value (let's say 5 different tshirt with the same color), the 10 corresponding line items in the order get a 5% discount.

I'm not familiar with rules. I tried to make some loop on line items but i'm really in the dark here.

Some advices? Thanks!

# Answer
Hopefully you're using taxonomy fields for your color on your shirts. If you are, then your solution is easy because Commerce Taxonomy Conditions will do the job. You can have it set to a quantity of a particular taxonomy field being present in an order and have it apply some discount.
> 0 votes

---
Tags: rules, commerce
---


# Question
Title: How to programmatically add a field to a view depending on another field and reorder fields then
I broke a site yesterday using views global php, even if it was working in the preview, so I'm a bit nervious about that php in database and I'm trying to implement the same thing with Views API.

Depending on the key value of a hidden field in the current display, I need to put a custom text. Something like (global php version) :

```
if( isset($data) && isset($data->field_field_statut_depart) ) {

  switch(  $data->field_field_statut_depart[0]['raw']['value'] ) {

    case 1:
      $text = 'ABC';
      break;
    case 2:
      $text = 'DEF';
      break;
    //and so on

  }
  print $text;
}

```

I'm trying to build it with `hook_views_pre_view(&$view, &$display_id, &$args)` but I can't find the required `field_statut_depart` value in `dpm($view)`.

Maybe it's not the right hook ?

EDIT : after applying solution described in the answers below (views\_post\_execute hook) and 12 hours running, I'm facing a strange behaviour : the changes made by views\_post\_execute hook are not stable : after clearing caches, they are visible for a while but raw data (without my function applied) is displayed then ! I'm afraid it's still not the right place to do that. Any help is welcome.

# Answer
You may want to try the views\_post\_execute hook.

Otherwise there is a reduced list of hooks used for views rendering at the bottom of the Views Hooks API page.

It is a little hidden but I have used it many times and you may find a solution to your issue there.
> 2 votes

# Answer
Thanks to @kartsims suggestion, this did the trick :

```
function MODULE_views_post_execute(&$view) {
  if ($view->name == 'foo' && $view->current_display == 'bar') {
    //dpm($view);
    foreach ($view->result as $result) {
      //dpm($result);
      if (isset($result->field_field_statut_depart)) {

        switch($result->field_field_statut_depart[0]['raw']['value'] ) {
          case 1:
            $text = 'ABC';
            break;
          case 2:
            $text = 'DEF';
            break;
          //and so on
        }
        $result->field_field_statut_depart[0]['rendered']['#markup'] = $text;
      }

      if (isset($result->field_commerce_stock)) {

        $result->field_commerce_stock[0]['rendered']['#markup'] = '';

        if($result->field_commerce_stock[0]['raw']['value'] < 6 ) {
          $result->field_commerce_stock[0]['rendered']['#markup'] = $result->field_commerce_stock[0]['raw']['value'].' items remaining';
        }
      }
    }
  }
}

```
> 1 votes

---
Tags: views
---


# Question
Title: How do I list all nodes created by the same author on a (custom) profile page?
In my setup each user has a profile page. The profile page is a custom content type (each user can only have one and they have to add it them selfs).

On this profile page I would like to list all nodes of a certain type created by the same user as the profile page.

How do I do this (in a views block preferably)?

# Answer
> 1 votes
I think this might be the solution

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

---
Tags: views, nodes, users, blocks
---


title: Bypass node access with Panels

text:
# Question
Title: Bypass node access with Panels
I'm using modules Content Access and Panels.

I need to modify the appearance of a node according to its accessibility by the user.

With Panels, I made 2 variants with selection rules (page "Node template"):

1. when the node is not accessible
2. when it is accessible.

But when the user has no access to the node he has a denied access and not the panel.

Do you know how to bypass node access with Panels?

# Answer
To overrider the default `Access Denied` page of the Drupal, you have to change the path of this page.

To change the page path, follow these steps:

1. Go to `admin/config/system/site-information`.
2. At the bottom of the page, there is a `Error Pages` section.
3. There is a field `Default 403 (access denied) page`. Provide your custom panel page link.
4. And the save it.

I hope it will work.
> 0 votes

---
Tags: 7, views, theming, panels, users
---


# Question
Title: getFormId() must be compatible with Drupal\Core\Form\FormBuilderInterface::getFormId (Drupal 8)
I newish to Drupal and very new to Drupal 8, as this comes out in a couple of weeks it seems to make sense to grab the bull by the horns and start any new project with this now! Anyway I was following pretty good tutorial: http://www.drupalwoo.com/content/blog/my-first-drupal-8-module on creating a Drupal 8 module but it looks to be a year or two old and things have changed. I am getting the following error:

Fatal error: Declaration of Drupal\bd\_contact\AddForm::getFormId() must be compatible with Drupal\Core\Form\FormBuilderInterface::getFormId($form\_arg, Drupal\Core\Form\FormStateInterface &$form\_state) in modules\custom\bd\_contact\src\AddForm.php on line 7

This is the file in question: https://github.com/nlisgo/bd\_contact/blob/master/src/AddForm.php could anyone tell me what would be the correct way? I have googled it quite a bit and found similar issues but I can't see how I'd integrate those changes into mine.

# Answer
In my project it works as public function without arguments since drupal beta 1 until today (i've updated today to rc3):

```
 public function getFormId() {

```

You only have to add public to your function.

Otherwise your error suggest, that there are the two arguments form and form\_state missing, what is also described in the api.drupal.org:

public function FormBuilder::getFormId

But I don't think, that you need these arguments in the definition of the getFormId(). This is probably a false alarm. You only need these arguments, when using the function in the context of formBuilder, when you don't provide the form through your class, for example like this:

```
this->formBuilder->getFormId($form_arg, $form_state)

```

Edit: Berdir has the right clue, you have to change this:

```
wrong: class AddForm implements FormInterface {
right: class AddForm extends FormBase {

```

and the use statements for this are:

```
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

```

This is a complete example:

```
<?php
/**
 * @file
 * Contains \Drupal\mymodule\Form\OrderForm
 */

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements an form.
 */
class OrderForm extends FormBase {

  /**
   * {@inheritdoc}.
   */
  public function getFormId() {
    return 'mymodule_order_form';
  }

  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

  }

   /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

   /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

```
> 2 votes

# Answer
I think you are implementing the wrong interface (always include example code, if it's long, post it somewhere and link to it).

`Drupal\Core\Form\FormBuilderInterface` is the API that one calls when displaying a specific form. It's basically what drupal\_get\_form() and other functions from form.inc used to be.

What you want to implement in a class that *represents* a form is `Drupal\Core\Form\FormInterface`.
> 0 votes

---
Tags: forms, 8
---


# Question
Title: How to get drupal 7 default file upload directory?
I have trouble to get the upload directroy from drupal. Is there some function returning the relative or absolute path?

# Answer
This information is saved in Drupal's variables table. Use the `variable_get` function to get this information, passing in the name of the correct variable:

* **Public Filesystem Location**: `variable_get('file_public_path', conf_path() . '/files');`
* **Private Filesystem Location**: `variable_get('file_private_path');`

If you want the temporary upload directory use `variable_get('file_temporary_path');` If you want to determine the system specific upload directory, regardless of the actual site configuration use the `file_directory_temp` function.

`variable_get('file_public_path', conf_path() . '/files');` will pull the default path for you in case it has not been modified or explicitly set by the site administrator.
> 24 votes

# Answer
To get the absolute file system paths use `drupal_realpath` (Drupal API) instead of `file_create_url`:

```
drupal_realpath('public://');
// returns e.g. /var/www/drupal/sites/default/files

drupal_realpath('private://');
// returns e.g. /var/www/drupal/sites/default/files_private

```
> 11 votes

# Answer
You can also use these functions to get a valid url from a relative uri:

```
file_create_url('public://');
file_create_url('private://');

```

They return the path to the public or private folders.
> 3 votes

---
Tags: files
---


title: Drupal private field

text:
# Question
Title: Drupal private field
I have got a status column for a web form event and so that it is editable by admin. Once the status is updated the end user is not able to see it, because it is a private field.

# Answer
> 1 votes
Use one theses modules :

User Field Privacy

> * All the user fields should have an "alterable privacy" checkbox.
> * If this checkbox is ticked, the user should be presented with an additional checkbox for the privacy-enabled fields on user edit forms to be able to make that fields' values private.
> * If this second checkbox is ticked for a field of a user, only the site administrators (members of roles with the "Access private
> fields" permission) and the user herself should be able to view that
> field's value.

CCK Private Fields

> This module allows users to mark administrator selected CCK fields as Public (visible to everyone), Hidden (visible to node author, hidden from everyone else) or Private (visible to node author and "friends"; see requirements section below).

Field Permissions

> * Enable field permissions on any entity, not just nodes.
> * Role-based field permissions allowing different viewing patterned based on what access the user has.
> * Author-level permissions allow viewing and editing of fields based on who the entity owner is.
> * Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.

---
Tags: users
---


title: Find the page from link

text:
# Question
Title: Find the page from link
This is a scenario. I wanted to find the content of the page from a link.

For eg while navigating the website, i clicked a link and the page loads. The page link is like www.example.com/gallery/videos

While checking I found there is a view named Gallery Videos and contains a 4 blocks attached. In the configuration of one block's path setting has been given "gallery/videos". But I did not find the page created for it. How can I easily detect where the content is loading and which view is it?

This seems to be a very basic question , but it seems hard to find when there are lot of contents, views and blocks used in the site.

# Answer
> 0 votes
Programatically speaking, if a View is involved in a template, the module injects the `$view` object into the available variables. So you can get to it pretty easily:

```
function MYMODULE_preprocess_node(&$vars) {
  if (isset($vars['view']) && $vars['view'] instanceof view) {
    if ($view->name == 'foo') {
      // ...
    }
  }
}

```

From a UI perspective, enabling the Contextual Links module might be a good solution to your problem. That will add direct edit/delete/etc links to nodes/blocks/views, and others depending on the contrib modules you have installed).

You can browse the site and simply click the edit link on a view to be taken to the edit page, where you can find out everything you need to know. Same for content, assuming it's been rendered in an entity view mode and not as fields.

---
Tags: views, blocks
---


# Question
Title: How to translate !title field is required
I want to translate '!title field is required.'. I can see it in 'admin/config/regional/translate/translate' but if I put a translation, it will override the name/label of each field.

So it is taking '!title field is required.' as one string. But I just want to translate 'field is required' and field names separately.

For example a Name and Email required in a form should display same translation but replacing !title with the name of the field.

How to do that.

# Answer
> 0 votes
To change the field name, you have to translate `!name field is required.` . To do this, follow these following steps :

1. Go to `admin/config/regional/translate/translate`.
2. Search for the string `!name field is required` in the `String contains` textfield.
3. In search result, change the string for all the languages.
4. And then save it.

I hope it works.

---
Tags: i18n-l10n
---


# Question
Title: Which is the cache I have to clear to refresh list of view blocks?
I created a new block (a view block) but it is not available to use in other modules (like panels). If I clear all cache then it shows up.

I don't want to clear all caches but only the right one to get the same.

# Answer
> 1 votes
If you use **Drush** you can clearly see there are cache for **block** and **views**. Clear both these cache and you will get the required result

# Answer
> 1 votes
Block cache is stored in the `cache_block` bin.

The cache ID is decided by the `_block_get_cache_id()` function, which you would use like so:

```
$block = block_load($module_name, $delta);
$cid = _block_get_cache_id($block);
cache_clear_all('cache_block', $cid);

```

It's worth bearing in mind that advanced modules like ctools and panels keep their own cache, so if the above doesn't work, have a look through the code for those modules and see what they use instead of the standard block cache to store data. Then clear that one instead.

---
Tags: blocks, caching
---


# Question
Title: Separating User Picture from Submitted by date in Node
on my node pages (drupal 7) the user picture is displayed along with the submitted by date. I'd like to separate them somehow so I can style them separately.

Anyone know a great way to do this?

# Answer
> 3 votes
Use the Display Suite Module

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

Watch the screencasts to see it all in action!

# Answer
> 1 votes
Assuming by "user" you mean specifically the author of current node, there are two pieces to look at:

1) The byline: Modifying the byline is straightforward in template\_preprocess\_node() and/or node.tpl.php.

In `template_preprocess_node()`, modify `$variables['submitted']` to be whatever you want it to be.

Here's a quick example,

```
$variables['submitted'] = t('Posted by !username on !datetime', array('!username' => $some_variable, '!datetime' => $some_other_variable));

```

2) The picture: In `node.tpl.php` you can easily control where the user picture and the byline printout by using the `$user_picture` and `$submitted` variables.

Here's a quick example,

```
<div class="user-picture"><?php print $user_picture; ?></div>
<div class="byline"><?php print $submitted; ?></div>

```

Lastly, if you want to modify the markup used for `$user_picture`, create and modify user-picture.tpl.php in your theme.

Hope this helps.

# Answer
> 0 votes
If you are developer and don't want to use heavy modules use `template_preprocess_node($vars)` function. Use dpm to display variables and node values. From there you can easily extract image and assign it to new variable.

like

```
$var['image_only'] = <the image part>

```

Then you can use you newly defined variable in your node.tpl.php

```
print $image_only

```

---
Tags: nodes, theming
---


# Question
Title: Form validation: text has to be a number
I have a textfield in a form that must contain a number. Using an integer for the field type is not possible - it must be text; however, I need to ensure that the input is actually a number. I've used:

```
function myfunc_form_user_register_form_validate($form, &$form_state) {
  if (!is_numeric($form_state['values']['number'])) {
    form_set_error('number', t('Field must be Numeric'));
  }
}

```

However, it does not work, that is, no errors are ever displayed. I have implemented the above code in `template.php`. I know there are Form Validation modules; however, I would like to do such a simple thing myself. I also think it's a bit overkill to create a whole module to simply validate a single field in a single form! I also wonder how to find the `$form[]` keys. I named the input field `number` so I imagine that's the key but it's just a guess. I've looked through the Form API and it is not very clear what I am supposed to do. Simple things, such as finding out what's even in `$form[]` alludes me and it doesn't seem to be clearly explained.

# Answer
Drupal already has a helper for this, in the shape of the `element_validate_number()` validation callback:

```
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['number']['#element_validate'][] = 'element_validate_number';
}

```

You can also use `element_validate_integer()` or `element_validate_integer_positive` if either of those make more sense for your use case.
> 4 votes

# Answer
You need to define your validate function in `hook_form_<form_id>_alter($form, $form_state)`

like the following

```
<themeName>_form_user_register_form_alter($form, $form_state) {
// your rest of the code
$form['#validate'][] = "myfunc_form_user_register_form_validate";
}

```

Clear the cache afterwards and check if the function is properly called

Hope this will help!
> 0 votes

---
Tags: forms
---


title: Create content programmatically

text:
# Question
Title: Create content programmatically
In Drupal 8, how can I create content programmatically ? From the "Drupal 8" administration, I created a new type "House" (contain a description, an image, a reference field to users ...). How can I create a entity type "House" from a custom module ?

In my custom module, I have a form file (contain a class who extends FormBase). In the submit callback, I want create a new "house" and set values and save the new Entity.

I don't find examples on the web, in core...

# Answer
The following code creates a node in Drupal 8.

```
$data = [
  'type' => 'article',
  'title' => 'My new title',
  'uid' => 1
];
$node = Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($data);
$node->save();

```

For testing code snippets like this, `drush core-cli` works great.
> 19 votes

# Answer
As of Drupal 8 nodes are now treated as entities. You can simple create a node by the following code

```
$new_page_values = array();
$new_page_values['type'] = 'my_content_type';
$new_page_values['title'] = $form_state['values']['page_title'];
$new_page_values['path'] = $new_page_path;

$new_page = entity_create('node', $new_page_values);
$new_page->save();

```
> -1 votes

---
Tags: 8, entities
---


# Question
Title: How make surveys with many questions whose answers are very similar
I want build a survey with many different questions whose answers are of evaluation range kind (strongly disagree, disagree, neutral, agree and so on) or yes/not kind. I have to create n different fields (I suppose text list and boolean fields) or is there a better way? I'm using Entity Form module.

# Answer
I will suggest using Survey Builder module

Key Features

1. Create survey forms with a drag and drop interface
2. Re-use questions across surveys (can be disabled)
3. Respond to surveys
4. Aggregate responses to surveys with Views

There some other nice modules too, such us LimSurvey Sync or you can use webform together with webform builder which will save you a lot of time.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Passing a node variable into views filtering
I have content type called "season", which has a custom field. This field can have two options: Helloween and Christmas. Article content type contains the same field.

I want to create a View, which would sort articles by actualy selected field value of single "season" node. Is this possible in Drupal7?

# Answer
> 0 votes
Yes, this is possible. You are wanting a context filter.

More details about your situation will let me give a better answer.

---
Tags: views, nodes
---


# Question
Title: Drupal views filter exposed with condition fields
I have a page about buying/selling the car, on the views I have filter with by exposed function. My expected is, when I select the first category, the hidden sub level 1 category should be visible then the User can select level 1 category, we continue show the level 2. Then we make the filter with this filter.

For ex.

* All Categories
* Used Cars for Sale
* Motorcycles
* Boats

1. \[Selected \[Used Cars for Sale\]:
* Acura
* Honda
* Toyota
* Huynhdai...\]

2. \[Selected \[Motorcycles\]
* Cruiser/Chopper
* Off-Road/Dual Purpose
* Sport Bike\]

Select All Categories with Used Cars for Sale, 1 should show and 2 show invisible, select Motorcycles 1 should invisible and 2 should visible, and so on.

Click Filter, it should filter the current views.

It should be customize with the text, the range slide, the checkboxs... So what is the best modules or best way that I can do with the Views module?

Looking for somebody help me the solution

Kind regards, John

# Answer
> 1 votes
If you have planed to use just one vocabulary and you have designed it properly , then Hierarchical Select Module can help you to provide the functionality you expect.

# Answer
> 0 votes
Functionality which you need, is in development phase, more info: https://www.drupal.org/node/1669940

---
Tags: views
---


# Question
Title: Why won't my custom content field update on save/edit?
I am building a custom content type programmatically within my module. Everything appears as I thought it would on the "Add Content" page, but whenever I create a new piece of content or edit the created content the data from the field is not being saved. When I go back into the content nothing is there.

What am I missing? Is there a better approach? I wanted to keep the scope of this module inside of the related "Add Content" page because it needs to be able to follow the Drupal Workbench workflow.

On .install:

```
function header_maker_enable(){
  $contentType = "brand_header";
  $readableType = "Brand Header";
  $type = node_type_load($contentType);

  //Verify that the content type has not already been created once for this module
  if(!$type){
    $type = array(
      'type' => $contentType,
      'name' => t($readableType),
      'base' => 'node_content',
      'description' => t("Test"),
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    );

   $type = node_type_set_defaults($type);

   //Creating Custom Test Field
   $field = array(
    'field_name' => 'brand_header_config',
    'type' => 'text',
    'entity_types' => array('node'),
  );
  $field = field_create_field($field);
  $instance = array(
    'field_name' => 'brand_header_config',
    'entity_type' => 'node',
    'bundle' => 'brand_header',
    'label' => t('Test Field'),
    'widget' => array('type' => 'text_textfield'),
  );
  $instance = field_create_instance($instance);

  node_type_save($type);
}

}

```

Here is my .module file. Something a bit more tricky is going on here with some JS. Basically I am rendering a UI to create some JSON. That JSON is then being added to the input field that was created on install in real time.

```
function header_maker_form_brand_header_node_form_alter(&$form, $form_state, $form_id){
  if ($form_id == 'brand_header_node_form') {
  $form['header_maker_ui'] = array(
    '#prefix' => '<div class="header-builder">',
    '#suffix' => '</div>',
  );
  $form['header_maker_render'] = array(
    '#prefix' => '<div class="header-render">',
    '#suffix' => '</div>',
  );

$order = array(
'header_maker_render',
'brand_header_node_form',
'brand_header_config'
  );

  foreach ($order as $key => $field) {
// Set/Reset the field's
// weight to the array key value
// from our order array.
$form[$field]['#weight'] = $key;
  }
  }
  return $form;
  }

function header_maker_preprocess_page(&$vars, $hook){
  if(isset($vars['page']['content']['system_main']['#form_id'])){
$formid = $vars['page']['content']['system_main']['#form_id'];
if($formid == "brand_header_node_form"){
  drupal_add_css(drupal_get_path('module', 'header_maker'). '/css/brand-header-form.css', array('group' => CSS_THEME, 'every_page' => FALSE));
  drupal_add_js(drupal_get_path('module', 'header_maker') . '/js/header_maker.js');
}
}
}

```

# Answer
I figured out what my issue was. In order to force users to use the UI I set the input field as being disabled from my JS file.

```
 document.getElementById('edit-brand-header-config-und-0-value').disabled = true;

```

Apparently setting it to disabled prevents it from being stored even though I could add a value to it programmatically through JS.

Removing "`disabled = true`"
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to change values views exposed filter based upon view results?
I have a view which, in addition to showing event nodes, also shows "fake" event nodes. The "fake" event nodes are inserted in `hook_views_pre_render()`.

The view also has an exposed filter to filter out content tagged with a certain term ID on the event\_type field. The exposed filter list has gotten too large so now it would make sense to only show the terms in the list that can filter out the view results (including the "fake" events).

Now I tried this with `hook_form_alter()`, but the problem is that the "fake" event nodes aren't available by using views\_get\_view\_result() and I'm not sure what other function could be used to do that here.

I tried using `dpm($view);` in `hook_views_pre_render()`, `hook_views_pre_build()`, and `hook_views_pre_view()`, but I could not find how to change values in the exposed filter in any of those.

Where can I see the values of the view result at the same time as the value options in the exposed filter?

# Answer
> 0 votes
Here is sample exposed filters form altering: http://www.tylerfrankenstein.com/code/drupal-alter-views-exposed-filter-form

Maybe you can call a function which returns fake nodes twice?

So in hook\_views\_pre\_render():

```
$fake_events = get_fake_events();
add_fake_events_to_rows($view->result);

```

and calling it in hook\_form\_alter() too:

```
$fake_events = get_fake_events();

```

Any problems with working that way?

---
Tags: hooks, views
---


title: Custom field not saving updates

text:
# Question
Title: Custom field not saving updates
I've created a widget which has two textfields and a hidden uniqid. One of these fields is for the name of an item, the other is the number of people who can be involved in that item. These save without any problem, and they re-populate on the edit page correctly, but if I change the values, they do not update correctly.

I am not a Drupal expert, so I am uncertain how much code will be required for diagnosis. These seem to be the most relevant parts, but there is a `volunteers_field_is_empty`, `volunteers_field_validate`, `volunteers_schema`, and a `volunteers_field_formatter_view`, as well as empty `volunteers_field_insert`, `volunteers_field_formatter_prepare_view`, and `volunteers_preprocess_node`.

```
function volunteers_field_info() {
  $t = get_t();
  $fields = array();
  $fields['volunteers_item'] = array(
    'label' => $t('Volunteer item'),
    'description' => $t('A position for volunteers'),
    'default_widget' => 'volunteers_field_widget',
    'default_formatter' => 'volunteer',
    'settings' => array('length' => 255)

  );
  return $fields;
}

function volunteers_field_widget_info() {
  $t = get_t();
  return array(
    'volunteers_field_widget' => array(
      'label' => $t('Volunteers widget'),
      'field types' => array('volunteers_item'),
      'settings' => array(),
      'behaviors' => array(
        'default value' => FIELD_BEHAVIOR_NONE
      )
    )
  );
}

function volunteers_field_schema($field) {
  $schema = array();
  switch($field['type']) {
    case 'volunteers_item':
      $schema['columns'] = array(
        'position_title' => array (
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE
        ),
        'position_count' => array (
          'type' => 'int',
          'sortable' => TRUE,
          'default' => 1,
          'unsigned' => TRUE
        ),
        'unique_id' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE
        )
      );
      break;
  }
  return $schema;
}

function volunteers_field_widget_form_alter(&$element, &$form_state, $context) {
  $type = $context['field']['type'];
  $lang = $context['langcode'];
  $delta = $context['delta'];
  if($type == 'volunteers_item' && isset($context['items'][$delta])) {
    $item = $context['items'][$delta];
    $element['position_title']['#value'] = $item['position_title'];
    $element['position_count']['#value'] = $item['position_count'];
    $element['unique_id']['#value'] = $item['unique_id'];
  }
}

function volunteers_field_widget_form(&$form, &$form_state, $field, $instance,
  $lang, $items, $delta, $element) {

  $t = get_t();
  $type = $instance['widget']['type'];
  switch ($type) {
    case 'volunteer_field_widget':
    case 'volunteers_field_widget':
      $element['position_title'] = array(
        '#type' => 'textfield',
        '#length' => 255,
        '#title' => $t('Position name'),
        '#weight' => 0,
        '#delta' => $delta,
        '#size' => 'big'
      );

      $element['position_count'] = array(
        '#type' => 'textfield',
        '#weight' => 1,
        '#length' => 10,
        '#delta' => $delta + 1,
        '#title' => $t('Number of participants'),
      );

      $element['unique_id'] = array(
        '#type' => 'hidden',
      );
      break;
  }

  return $element;
}

function volunteers_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if($field['type'] == 'volunteers_item'){
    foreach($items as &$item) {
      // setting default values.
      $count = $item['position_count'];
      if(!$count) $count = 1;
      $item['position_count'] = $count;
      if(!isset($item['unique_id'])) {
        $item['unique_id'] = uniqid(rand(),1);
      }
    }
  }
}

```

# Answer
> 1 votes
The problem is with `volunteers_field_widget_form` and `volunteers_field_widget_form_alter`. `volunteers_field_widget_form_alter` was preventing updates. If I set the `default_value` of the relevant elements appropriately in `volunteers_field_widget_form`, Drupal both allows updates and displays correctly.

```
$element['position_title'] = array(
  '#type' => 'textfield',
  '#length' => 255,
  '#title' => $t('Position name'),
  '#default_value' => isset($items[$delta]['position_title']) ? $items[$delta]['position_title'] : null,
  '#weight' => 0,
  '#delta' => $delta,
  '#size' => 'big'
);

```

# Answer
> 0 votes
In case anyone coming here with trouble of fields not being saved, try removing conditional fields. Sometimes conditional fields might clear fields before saving if not configured correctly.

---
Tags: entities
---


# Question
Title: How can I export the "Enable for OG Menus" content type option status in a feature?
How can I export the "Enable for OG Menus" content type option status in a feature?

I have successfully exported several different OG content types into their own feature. All my settings have exported, except for the "Enable for OG Menus" option. I have a couple types where that option is enabled, and I have og\_menu as a dependency. But when I enable the content type feature on a new Drupal instance, that option remains in it's default unchecked state.

I have Drupal 7.39, Features 7.x-2.6, OG Menu 7.x-3.0, and Strongarm 7.x-2.x-dev installed. As well as their dependencies.

Is there a Strongarm variable I'm missing? I don't see any in the list that look like they come from OG Menu.

I have Googled, didn't find anything relevant with the search terms I tried.

I searched the issue queues of Features, OG Menu, and Strongarm to no avail.

Any suggestions?

# Answer
> 0 votes
I was missing a Strongarm variable.

Strongarm lists:

* og\_menu\_assignment
* og\_menu\_block\_links
* og\_menu\_context\_limit
* og\_menu\_create\_by\_default
* og\_menu\_enable\_page
* og\_menu\_enable\_section
* og\_menu\_hide\_create\_option
* og\_menu\_hide\_help
* og\_menu\_max\_menus\_per\_group
* og\_menu\_show\_blocks
* og\_menu\_show\_nodetype

The variables I needed were:

* og\_menu\_enable\_page
* og\_menu\_enable\_section

og\_menu appears to create a variable per content type you want to use it on. In my case I had two content types, page and section. Once I added those variables to my feature, it successfully exported the setting.

---
Tags: organic-groups, features, strongarm
---


# Question
Title: Field Template Suggestions: Target a particular field type on a content type
I want to use a field template for all the fields on my "journal\_page" content type that use a widget of "long text".

How would I do this?

N.B. My field is not named "long text". "Long text" is the name of the widget I am using (It is a text field). I want to use the same template file for multiple differently named fields. The only thing they have in common is the widget type.

---

## Steps I have tried

On Drupal Theming suggestions it says you must use the following format: `field--[type|name[--content-type]|content-type].tpl.php`, so:

1. field--field-name--content-type.tpl.php
2. field--content-type.tpl.php
3. field--field-name.tpl.php
4. field--field-type.tpl.php

I tried the following but, none have worked:

1. field--long-text--journal-page.tpl.php
2. field--long\_text--journal\_page.tpl.php

# Answer
I just happened upon this question while trying to remember how to solve the same problem. In this case, Drupal simply doesn't do what you're asking for by default. There are two ways to approach it, one by accepting Drupal's default behaviour, and one by overriding that default.

## Default behaviour

As has already been pointed out here, Drupal's template suggestions for fields don't consider the **field** type (though they do accommodate the *content* type).

## Living with Drupal's default behaviour

This is the simplest solution, though it's a bit inflexible. Since your goal is to use only one template, what you can do is this:

1. Create a field template in our theme according to the `field--field-name--content-type.tpl.php` pattern. This will customize **one** of your fields.
2. Create symlinks to your original template containing the names of the other fields you need to customize.

For example, given fields with names `lorem`, `ipsum`, `dolor` and `sit`, and the content type `contenttype`, you'd create one template:

* `field--lorem--contenttype.tpl.php`

*Then*, you'd create the following symlinks to that template:

* `field--ipsum--contenttype.tpl.php`,
* `field--dolor--contenttype.tpl.php`,
* `field--sit--contenttype.tpl.php`

Drupal will see these as four different but identical files.

## Overriding Drupal's default behaviour

The previous solution is quick and simple, but slightly unsatisfying. If Drupal's so flexible, we should be able to handle this problem using the Drupal API, right?

Well, it turns out we can. It's possible for us to add *our own* template suggestions.

We do this like this:

### 1. Implement `template_preprocess_field()`

```
/**
 * Implements template_preprocess_field().
 */
function THEMENAME_preprocess_field(&$variables) {
  if ($variables['element']['#bundle'] === 'contenttype' && $variables['element']['#field_type'] === 'text_long') {
    $variables['theme_hook_suggestions'][] = 'field__contenttype__text_long';
  }
}

```

### 2. Copy `field.tpl.php` to your theme

Copy `field.tpl.php` from `modules/field/theme/field.tpl.php` to `sites/all/THEMENAME/field--contenttype--text-long.tpl.php` and then customize to suit.

---

## Notes

* The logic in the `template_preprocess_field()` implementation could be changed in several ways, e.g. to match only by field name in a given content type instead of all examples of a field type in that content type.
* The process is almost the same when doing this task in a module except that you'll also need an implementation of `hook_theme()` in the module to make it work.
* It would be possible to to this using only `theme_field()`, but theme functions are deprecated in Drupal 8, so this is the method that we'll all be using going forward.
> 1 votes

# Answer
**UPDATE**:

Try:

```
field--text_long.tpl.php

```

The naming above will tackle all fields that are created as "Long Text"

Tested field--text\_long.tpl.php a moment ago with the following. Note, I wrapped everything with H1 markup to test.

```
<h1><div class="<?php print $classes; ?>"<?php print $attributes; ?>>
<?php if (!$label_hidden): ?>
<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
<?php endif; ?>
<div class="field-items"<?php print $content_attributes; ?>>
<?php foreach ($items as $delta => $item): ?>
<div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
<?php endforeach; ?>
</div></div></h1>

```

---

**Removed all previous to clear confusion**

Helpful links:

Field Types and Settings \- Provides widget detail among others

D7 Template Suggestions \- Provides naming conventions among others
> 0 votes

---
Tags: theming, entities
---


# Question
Title: Disable Commerce Card on File for Donation Product Type
Using Commerce (7.x-1.1), Commerce Card on File (7.x-2.0-beta5), Commerce Recurring Framework (7.x-2.x-dev) and Commerce Donate (7.x-1.0)

I need Commerce Card on File for my recurring product entities, however I do not want the functionality applied to Donation Products.

How do I keep the Commerce Card on File functionality for recurring products, but disable it for donation products?

# Answer
If you go to the Payment method configuration screen (admin/commerce/config/payment-methods), you'll see that each payment method is a rule. If you click on 'edit' you'll get a rules configuration screen.

Next, click on "Add condition" under the conditions section. Here you can choose the various conditions that allow (or disallow) a payment method to be selected.

You've got the order object here so you can choose 'Order contains a particular product'.

Then enter the SKU of your donation product in the field provided:

Finally, make sure 'Negate' at the bottom of the rule configuration page is checked.

Now that payment option will only show up if the order does not contain that product.
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: Unable to get javascript to make first letter of every word LARGER on my site to load properly
I'm *trying* to use javascript to make the **first letter of every word** LARGER in titles with the class 'field-name-title' (so basically all nodes).

I found a couple of Javascript-based solutions online, notably here and here. But whenever I try and implement them nothing happens (by which I mean the titles that are supposed to be changed are NOT).

What's I've tried:

1) I replaced the boilerplate class name in the javascript linked to above with my class name (ir. replaced 'title-case' in the one with 'field-name-title', etc.).

2) I've ensured I have a first-letter class in my stylesheet with the following property:

```
.first-letter {
  font-size: 1.4em; // I also tried % such as 115%
}

```

3) I put my javascript file in js/first-letter.js. I referenced it in my .info file as 'scripts\[\] = js/first-letter.js.

4) I've flushed caches repeatedly (and besides aggregation is turned off).

What am I missing?

# Answer
If Alireza's answer doesn't work, try this one.

**js/first-letter.js**

```
(function ($) {
 $( document ).ready(function() {
  $('.field-name-title').html(function(i,el) {
    return el.replace(/\b([A-Z])/g, "<span class=\"first-letter\">$1</span>");
     });
  });
}(jQuery));

```
> 1 votes

# Answer
If you have used the first reference , then change script to this :

```
(function ($) {
  $( document ).ready(function() {
    $('.field-name-title').html(function(i,el) {
      return el.replace(/\b([A-Z])/g, "<span class=\"first-letter\">$1</span>");
    });
  });
}(jQuery));

```

for more info check Working with JavaScript and jQuery
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: Drush sql-dump but exclude multiple tables with a pattern
I have a gigantic database due to having over 1000+ individual tables created for every time someone logged in. (wasnt me that made this).

I want to now create a dump of the database using `drush sql-dump` but the file ends up to be over 15GB and 1GB zipped.

Is there a quick and easy way to exclude a bunch of tables matching a pattern using drush? The tables I want to exclude all begin with the word "`result-<username>`"

# Answer
> 10 votes
Drush has a number of options to exclude tables from sql-dump. These all now support wildcards (thanks @MPD for pointing this out), so for example you can do this:

```
drush sql-dump --skip-tables-list='result-*'

```

This will completely exclude any tables matching the pattern `result-*` \- that is, beginning with `result-` \- from the dump. You can pass multiple patterns (or individual table names) by separating them with commas. The quotes are necessary to prevent your shell from expanding the pattern.

If you want the tables' structure to be included but just not the data in them, use `--structure-tables-list` instead.

The other options are `--skip-tables-key` and `--structure-tables-key` which work similarly, but instead of providing the table names or patterns directly on the command line, you add them to an array in drushrc.php and specify the array key on the command line. This is useful if you have a set of tables that you routinely exclude, such as 'cache\_\*'. The example.drushrc.php provided with drush gives the following example:

```
/**
 * List of tables whose *data* is skipped by the 'sql-dump' and 'sql-sync'
 * commands when the "--structure-tables-key=common" option is provided.
 * You may add specific tables to the existing array or add a new element.
 */
# $options['structure-tables']['common'] = array('cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog');

```

---
Tags: 7, drush, database, backups
---


title: Possible to change cron link?

text:
# Question
Title: Possible to change cron link?
I use D6. Cron run often by some bots visiting example.com/cron.php Is it possible to change it somehow? Or restrict? I would like to prevent anonymous users to hit the script.I want to be able to run cron from drupal admin interface and also to run it automatically from linux crontab. I tried to set permissions to read for owner only (www-data is group) but it does not help.

Thank you.

# Answer
> 0 votes
Have you looked at Elysia Cron? I have it installed on all my sites as it allows finer control over how cron is run and has "Protection from external cron calling by cron\_key or allowed host list"

# Answer
> 0 votes
I should of searched before posting question - did not know what to search for though:) Solution seems pretty simple here https://www.drupal.org/node/41049

---
Tags: 6, cron
---