# Question
Title: How to display the number of contents of a node?
We have a property site that we use to categorize our listings. I would like to know how to make each category show the number of content it has e.g. Sales(45), Lettings(20), etc.

Any help about how to do this? I am new to Drupal.

# Answer
> 0 votes
could you add some details to your question that will tell us WHERE you want to see these counts? Is it in a page template? A view? A block? The answer will change depending.

In the meantime, please look at this: Count of nodes by type

# Answer
> 0 votes
This question is exactly what the purpose is of one of the Out-of-the-box examples that you get after install/enable of the Charts module, and without any additional configuration.

By doing so, a new view is added to your site. Here are some more details about it, quoted from the linked page above (to which I added some formatting here):

> You can see the charts created via this new view in your own site by navigating to charts/examples or by using a menu link with a title like Charts examples. After doing so, a page is shown with 2 sub-menu tabs:
>
> * the first tab is titled **Built-in examples** (this example is used to showcase Using the Charts API).
> * the second tab is titled **Views example**, and is what is created from the new view created during the installation of the charts module. As an alternative to using this tab, just navigate to charts/examples/views in your site. You should then see a column chart and a pie chart, which are followed by a tabular display also. ***Both charts and the table display contain data about the total number of nodes for each of the available content types.***

Visit the Charts demo site for an online preview of of these out-of-the-box examples.

Disclosure: I'm the maintainer of this module,
I hope this does not violate the site's policy on self-promotion.

---
Tags: nodes, log-messages
---


# Question
Title: How to count the node a user has created in a View?
I created a view to show **Users**. These users can create nodes of the "Questions" content type.

The view has to render a table to show how many (the total number) Questions the user has created. Something like:

```
User +++ Questions created
John --- 10
Ted  --- 4
Alf  --- 19

```

# Answer
> 8 votes
you have to use the **Aggregation** setting and active it in your view.

1. **Activate Aggregation**. *(It's in the "advanced settings" of the view)*
2. As your view is a view of users, **add the relationship** "*User : content authored*". If you set the option "*Require this relationship*", you'll skip users with no nodes created (can be useful)
3. Add your **user name field**, don't use aggregate
4. **Add a node field**, let's say *Node : nid* **with** the relationship set
5. **Use Aggregate for this field**, "***Count DISTINCT***".

Have fun !

# Answer
> 0 votes
This question is a variation of what the purpose is of one of the Out-of-the-box examples that you get after install/enable of the Charts module, and without any additional configuration.

By doing so, a new view is added to your site. Here are some more details about it, quoted from the linked page above (to which I added some formatting here):

> You can see the charts created via this new view in your own site by navigating to charts/examples or by using a menu link with a title like Charts examples. After doing so, a page is shown with 2 sub-menu tabs:
>
> * the first tab is titled **Built-in examples** (this example is used to showcase Using the Charts API).
> * the second tab is titled **Views example**, and is what is created from the new view created during the installation of the charts module. As an alternative to using this tab, just navigate to charts/examples/views in your site. You should then see a column chart and a pie chart, which are followed by a tabular display also. ***Both charts and the table display contain data about the total number of nodes for each of the available content types.***

To massage this out-of-the-box sample to match the question here, all that's needed is to add some appropriate fields (related to the users) and some filter(s), like node type. Done.

Disclosure: I'm the maintainer of this module,
I hope this does not violate the site's policy on self-promotion.

---
Tags: views
---


# Question
Title: Get all the nodes with matching taxonomy terms in a view Display
I have a view which shows all the page elements.

So, in five displays of view, it shows Hero area, description, sidebar etc.

The last display has to show all the nodes which has similar taxonomy terms of this current node.

For example, if Taxonomy is `Interests`, and I have selected `Basketball`, `Chess`, `Baseball`, then I am hoping to output all nodes with the same interests.

I am trying here to get all nodes within my display. Is it possible?

Many Thanks.

# Answer
If my understanding is correct, you have a view of content each with references to the taxonomy vocabulary `Interests`. If this is the case, then you can easily add a *filter* to your view with the selected terms in that taxonomy.

To allow users to select which term elements render on the page, make it an exposed filter (perhaps select or multiselect).
> 0 votes

---
Tags: taxonomy-terms
---


title: Replace file button missing

text:
# Question
Title: Replace file button missing
I am missing a button to press when replacing a file.

Go to admin/content/file and edit a file.

For example: i am on file 778 at /file/778/edit

If you look at the Replace File field, there is no Replace/Upload button! So, yes, I can only upload an image but not replace the image.

# Answer
The actual replacement does not happen until you save the entity. There is no fancy AJAX-based form manipulation here (unlike a core file field), so there is no specific "upload" button attached to that "replace file" field.

You just need to specify your replacement file (populate that field) and then save the full form ("Save" button at the bottom) for the replacement to happen.
> 1 votes

---
Tags: files, media
---


# Question
Title: How can i check if css class exists on page and add new one to the body
something like:

```
function mytheme_preprocess_html(&$vars) {
  //if css.class exists on page{
  $vars['classes_array'][] = 'my-class';
 //}
}

```

... All i want is to add class to other elements if there is custom views (module:views) on my landing-page

# Answer
```
function mytheme_preprocess_html(&$vars) {
  $vars['classes_array'][] = 'new-class';
}

```

or

```
if ($('body.mydivclass').length > 0) {
  $('body').addClass('new-class');
}

```
> 1 votes

---
Tags: theming
---


# Question
Title: Webfrom : Having two textfield boxes inline .
What I need to do is have two input boxes next to each other. As it's to except data that comes in two parts. I can do this with CSS but using inline errors causes me problems. Has anyone done this or have any ideas on a solution.

Drupal 7 - webfrom 7.x-4.9+2-dev

# Answer
You can easily accomplish this using the Webform Layout module.

This module allows you to arrange fields into rows or columns.
> 1 votes

---
Tags: webforms
---


# Question
Title: Is there a module that saves the node while you are creating it?
I have a blog, I write blogposts everyday. Today I was creating a blog post, I was almost finished, but for some reason my computer turned off. I lost all that I had in my article I have to write it again.

Is there a module or something that saves the node while you are creating it?

# Answer
> 1 votes
Looks like you need the Autosave module. Here is an excerpt from its project page:

> The Autosave module automatically saves a snapshot of your content type form using AJAX. If the user's browser or machine dies while editing a node; the edits will be presented to the user the next time they return to the node. The user may toggle back and forth between the last saved version and the version with the edits that were lost and select which of these they would like to continue with.
>
> How often a form is autosaved as well as which content types to enable autosave for are admin configurable.

---
Tags: 7, nodes
---


# Question
Title: Odd behaviour on form validation when in block mode
Hi gurus and fellows,

I have to generate an application form, that needs to be displayed both a as "page" (hook\_menu) and as "block".

I factorized the form generation within the same function (generate\_form). It works fine, except for the validation process. Clearly the validation happens (form is not submitted when it fails), but the form\_set\_error() is never displayed in *block mode* (in page mode, it works fine).

This "lack of display" also happens for regular validation ('#required'=\>'true'), so I don't think my custom validation code is at stake :

* When in *page mode*, the required fields get highlighted, the error message is displayed.
* When in *block mode*, the required fields get highlighted (red-bordered), BUT the error message is NOT displayed.

Of course, I checked that the page.tpl.php, used to display the block, has a 'message' section, within it. Proof is my drupal\_set\_message() gets displayed on submit.

Oddly enough, when I put a drupal\_set\_message() within my custom validation function, it gets displayed, as long as (and only when) the validation passes ! Wierd...

I pasted the \*.module code here : http://pastebin.com/cnwzp3UU

Any idea ?

# Answer
> 0 votes
Taking a bit of a stab in the dark here, but I'm suspicious of this comment in your linked code right above `hook_block_view()`:

```
// used in node--landing-page.tpl.php

```

That suggests that you're calling this block in directly from a template file, not through the normal block system, which won't work properly.

The problem is that the template files are built too late in the page build, in this case after the system messages have already been taken from the session and cleared out for the next page. So the validation messages do get added to the messages array in the session, but they won't be outputted until the next page is loaded.

I would suggest instead implementing `hook_node_view()` and adding your block into the content there. That hook is run early enough on in the page build that you won't see the delay with error messages.

# Answer
> 0 votes
Here is how I got it to work:

--- in my custom module ---

```
/**
 * Implements hook_node_view( ).
 */
function my_module_node_view ( $node, $view_mode, $langcode ) {

    switch ( $node->type ) {

        case 'my_content_type':
            my_module_add_form_to_node( $node, $view_mode, $langcode );
            break;
    }
}

/**
 * This function adds the form to a $node for use in an template.
 */
function my_module_add_form_to_node ( $node, $view_mode, $langcode ) {

    $node->content['my_form']  =  drupal_get_form( 'my_form' );
}

```

--- In the node's template file ---

```
<?php print render( $content['my_form'] ); ?>

```

---
Tags: forms, blocks
---


# Question
Title: D8 services errors - No route found for the specified formats : */*
I'm trying to get data from a Drupal 8 website to Go application.I created a view that it would display title and body on json format. Here is an example Th when the Go application try to get the request I got this error.

```
Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException: No route found for
the specified formats : */*. in Drupal\Core\Routing\AcceptHeaderMatcher->filter() (line
64 of core/lib/Drupal/Core/Routing/AcceptHeaderMatcher.php).

```

What I'm doing wrong ? As far I know, the Go application is asking the request properly.

Just in case you are wondering about the Go app here is the code.

# Answer
Nevermind, the issues was on my Go App. Apparently the on my Go app.

It did not like `Header.Set("Accept:", "*/*")`.
> 0 votes

# Answer
If you update to the next beta, You will have to use: "http://dev-d8go.pantheon.io/d8go/node/1?\_format=json"
> 3 votes

---
Tags: 8, services
---


title: Problem with specific permissions

text:
# Question
Title: Problem with specific permissions
I would like to set a role permission for displaying a field depending on the value of an other field. But I can't find how to do it.

For example, I have a content type Person. If I add a content Person that is a "policeman" (field Job = "Policeman") then his phone number (field Phone) is display only to user that have the role "Officer". But if the person is a "Secretary" then his phone number is display only to user that have the role "Direction".

Does anyone know how to do it ? Is there a module for that ?

Thanks !

# Answer
There are 2 modules out there that can do ***one part*** of what you're wanting, but not both.

If your content design is flexible these might help.

However, if you're looking for field display based on both ***a role and another field's value*** you might be better off adding a `template_preprocess_node()` function to **template.php** to check for rendering logic. For example:

```
function MYTHEME_preprocess_node(&$variables) {
  global $user;

  $job = isset($variables['node']->field_job[LANGUAGE_NONE][0]['value']) ? $variables['node']->field_job[LANGUAGE_NONE][0]['value'] : '';
  if($job == 'policeman' && !in_array('Officer', $user->roles)) {
    hide($variables['content']['field_phone']);
  }
  //@TODO: Add other role/value checks
}

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: File/function that is executed when I open node from view
I have created view for displaying the nodes. I want to know which function/file is executed when I click on the node listed in the view table. I want to add some code to the file when the node information is loading. Can anyone suggest me the function/file where i'm supposed to do the changes?

# Answer
> 0 votes
You've two ways to afford the problem: **Site building way** If you're using a wiew of rendered nodes (usualy teasers) you can redefine the layout, tags, fields, etc. on admin/structure/types/manage/YOURCONTENTYPE/display/teaser

If you need more options try display suite and fences modules: https://www.drupal.org/project/ds https://www.drupal.org/project/fences

**Developer way** Editing your view, on the "advanced" colum, "other section" you've the "templates" there the "Theme: Information" item. There you've the name of the templates the view is using. You can redefine then on your custom them.

**EXTRA BALL: Common sense way** Probably a mix of two others are que best option

---
Tags: views, rules, users
---


# Question
Title: How to calculate result from fields inserted?
I'm new to Drupal. Can anyone advice me on what's the method of collecting data information from inserted results?

For example, suppose I have book content type, when I insert data into its fields I want a page to show results of the following:

1. How many book has been inserted? (eg. 5 books)
2. How many magazine? (eg. 2 magazine)
3. How many references?(eg. 1 reference)
4. How many novels? (eg. 2 novels)
5. How many guide book? (eg. 0 guide)

I've been trying to figure this out through and my last option which is to code the result myself(the hard way).

# Answer
Such page can be creating using various approaches, as further explained below.

# Using Views and Views Calc

Use the Views module, together with the Views\_Calc module. Here is a quote about Views\_Calc (from its project page):

> ... adds simple calculations to a views table. Requires the Views module.
>
> You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).
>
> You can also create custom dynamic fields that can be used in any view using SQL snippets like CONCAT('field\_first\_name', ' ', 'field\_last\_name') or DATE\_FORMAT(node.created, '%m/%%d/%Y'). The custom fields are set up in admin/settings/views\_calc.

Refer to the question about How can I show average votes of fivestar nodes? for some screenprints about how to use this module.

# Using Forena

If you'd want to "roll your own cookies" (i.e. some report that perfectly fits your custom requirements), then you might want to consider the Forena module. Here is an excerpt about that from its Community documentation:

> Forena Reports is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
>
> It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

For an example of such custom report, created with Forena, start from the statistics (summary info) of the Watchdog Statistics, as in this Watchdog Statistics sample. Note the red numbers to the right of the table, which are actually hyperlinks that can be used as drill-down reports. I.e. if you click on any of them (like the "2" for "Page not found"), you get a details report about (in this case) the 2 specific records related to the "Page not found"). More details about this specific case can be found in comment #2 of issue 2337327. Obvious, I didn't really do any effort to beef up the look-and-feel of that report, like background, etc.

Disclosure: I'm a co-maintainer of Views\_Calc and Forena,
I hope this does not violate the site's policy on self-promotion.
> 2 votes

---
Tags: views, entities, log-messages
---


# Question
Title: tb mega menu is not showing in bootrap theams in drupal7
I am new user of drupal 7.3. I am using bootstrap 3.0 theme in drupal 7.3.

I am using tb mega menu which is not showing. Black color box will be occurred in navigation block.

Please help me to solve this I want solution step by step. I want used in my project please help me.

# Answer
I have refer you to below links :

1. LINK1
2. LINK2
3. LINK3
> 0 votes

---
Tags: routes
---


# Question
Title: How to reference existing entity using Inline Entity Form?
I'm using Entity Reference to create tasks in lists - both tasks and lists are content type, list contains multivalue Entity Reference to task. Because most tasks belong to only one list, it was only natural to use Inline Entity Form.

Problem is *most* \- there are *some* tasks that needs to belong to many lists.

Module's docs says:

> Existing entities can also be referenced.

That would do the trick. My question is very simple: **How do I do that?** Only button I see is "Add new node", and it opens node creation form. What should I do to see "Add existing node"?

# Answer
*To add more clarity to the answer:*

* In **Edit tab**, check "**allow users to select existing nodes**" as shown below

* In your content creation form, you could find two buttons: **Add New Node** and **Add Existing Node** as shown below
> 7 votes

# Answer
Inline Entity Form settings are in the **Edit** tab, not the **Field settings** one. Once I realized this, it was easy to find *Allow users to add existing nodes* checkbox. Once it's checked, there are two buttons on field's list: a button for creating a new reference, and one for referring the existing nodes.
> 4 votes

# Answer
The important yet confusing step I observed when wanting to add an existing term, for example, was to make sure you select "Inline entity form - Multiple values" not single values (see https://www.drupal.org/node/2134035). The current patch needs community review.
> 3 votes

---
Tags: entities
---


# Question
Title: CSS or and JS aggregations all makes site slower!
It is well known among Drupalists that generally, Aggregation of CSS\JS files should hasten webpage loading times in Drupal... So why the opposite is true for my site this time?

Bottom line: the natural aggregation options do the opposite of their inherit aim --- They are slowing my site instead of hasting it! Any reasons you could suggest for such wired behavior? Thx.

# Answer
> 1 votes
You're confusing PSI and webpage loading times; they are not the same thing.

PSI is series of benchmarks for optimizing performance. It's a checklist Google provides to give you suggestion for improving performance. It doesn't gauge what your site's actual speed is. Use your browser's network activity inspector if you'd like to analyze site load times against CSS/JS aggregation.

---
Tags: css-js-aggregation, performance
---


# Question
Title: Query a list of field values of a node in drupal 7
I am new to drupal 7, I have a question and hope to receive your helpful responses! :D

I've created a new content type named 'school', and create a custom 'city' field in it. After that, I create two new nodes of 'school', and their city are 'London' and 'Beijing'. How can I get a list of city of schools programmatically in Drupal 7?

Any help will be appreciated!

# Answer
> 0 votes
Consider using the Forena module, it comes with all sorts of reporting features. And all sorts of hooks if you want to use them in your own custom modules.

Here is an excerpt from its Community documentation:

> Forena Reports is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
>
> It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

Disclosure: I'm a co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.

---
Tags: nodes, entities, database, log-messages
---


title: how to delete a context

text:
# Question
Title: how to delete a context
I have created a sample context just for testing its work, and now it appears on every page because I have used a block in my context. I want to remove the sample context. I have searched in Drupal docs but nothing useful there. Any ideas how to solve it.

# Answer
You do it the same place where you add and edit contexts, the contexts admin page located at `admin/structure/context`. Context defined in code can't be deleted, but can instead be disabled.
> 1 votes

# Answer
1. Download and enable Devel module
2. Check your context name under admin/structure/context
3. Go to devel/php and run code:

```
$context = context_load('YOUR_CONTEXT_NAME');
context_delete($context);

```
> 0 votes

---
Tags: 7
---


title: Exclude more then one date

text:
# Question
Title: Exclude more then one date
I'm new to Drupal. I'm trying to make a work calendar.

I need to make weekly events in the calendar. And that's working real well but now I want to exclude dates from an event.

Is there a way to select more than one date at time?

# Answer
I think there are 2 possible approaches, as further explained below (I'm assuming you're using Drupal version 7, not 6).

# Use a boolean field to exclude from the calendar

For the content types that you want to include in your calendar, add a boolean field like "Exclude from Calendar" (Y/N). When creating your view, filter out the nodes that have a value of "Y" for this field.

# Use 'Views Contextual Filters OR'

Consider module Views Contextual Filters OR (which only has a dev version today). Excerpt from its project page:

> ... provides a views plugin which modify query to support OR conditions for contextual filters.

With that, you might be able to specify the various dates to be excluded, with something like date1 OR date2 OR ... (if you only have a few dates to be excluded o course).

Does this help?
> 0 votes

---
Tags: datetime
---


title: Accessing Webform 4 Submitted data

text:
# Question
Title: Accessing Webform 4 Submitted data
I have a webform on my site and on user submission, I want to send the webform data to some php application that get the value of some variables from the URL.

This task requires me to access the webform submitted data when the user clicks "Submit" button and construct a URL (/myphpapplication?query=....) containing user filled webform values. Please help me to achieve this.

# Answer
As Oswald mentioned, you have to implement some hooks in your custom module to redirect your form submission. Here is a quick example (assume your form\_id is 'webform\_client\_form\_1'):

````
// hook_form_alter()
function customform_form_alter(&$form, &$form_state, $form_id) {

if ($form_id == 'webform_client_form_1') {
    // Add form_submit() handler
    $form['#submit'][] = 'customform_webform_submit';
}

}

// form_submit()
function customform_webform_submit($form, &$form_state) {

// Submited values are in $form_state['values']['submitted_tree']
$field_values = customform_webform_values( $form_state['values']['submitted_tree']    );

// Build URL Query
$query = '';

foreach ($field_values as $value) {
    $query .= $value . '&';
}

$redirect = array (
                'myphpapplication',
                array (
                    'query' => array (
                        'query' => rtrim( $query, "&" )  // Get 'query' values with $_GET['query']
                    )
                )
            );

$form_state['redirect'] = $redirect;

}

// Recurse through webfrom submited values
function customform_webform_values($component) {

static $webform;

foreach($component as $key => $value) {
    if (is_array($value)) {
        customform_webform_values($value);
    }
    else {
        $webform[$key] = $value;
    }
}

return $webform;
}

````
> 2 votes

# Answer
Implement hook\_form\_alter() or one of its relatives by adding a submit handler to the form (i.e. to $form\['#submit'\]).

To find out the proper value of the `$form_id` parameter, your first implementation of `hook_form_alter()` can just drupal\_set\_message() that parameter. Use the same technique to find out how your submit handler receives the form values in `$form_state['values']`.
> 0 votes

# Answer
I'm late to answer but maybe it can help someone

Webform 4 data can also be accessed using Webform hooks, as in the following code.

```
function mymodule_webform_submission_insert($node, $submission) {
  if ($node->nid == 1) {
    $submitted_data = $submission->data;
    print_r( $submitted_data); // This will give you all the submitted value in a form of array which you can use according to your requirements.
  }
}

```

You can implement it in a custom module: Don't forget to replace *mymodule* with your module name.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: Create an Availability calendar/table in Views
I am trying to create a calendar table in Views to display availability states for multiple product rows, e.g. for a car rental site. I have spent the evening researching modules that might be suitable, namely availability calendars (which I am familiar with) and a bunch of views plugins, even considered modifying rooms or uc\_hotel modules to suit.. I haven't found anything that fits the bill exactly, but that's what I expected, so I'm looking for some recommendations or a solution. I have attached an illustration of what I am trying to achieve. Any help or pointers much appreciated.

# Answer
> 1 votes
An update.. in the end I decided against using views, and used a library called dhtmlx scheduler timeline. It's turned out to meet the requirements spot on, and wasn't too difficult to wrangle into Drupal..

# Answer
> 0 votes
If you're still interested in an answer, you could use the Views Table Group module (dates as columns and product names as rows) and with the Views Conditional or Views PHP module and/or a custom theme you could choose the style for the cell.

---
Tags: views, datetime
---


# Question
Title: how to use more then one content type filter in same views in drupal 7?
I have two content types animal and fruits. In animal content type fields description . content type = animal

conditions:

date = 2015 user = login If a record exists that satisfies the above 2 conditions:

show description..

Then the system should then get the “body” data field value from the content type “fruit” where the following 2 conditions are satisfied:

• “Type” date field value = “apple” AND • “Title” data field value = “appple is my fav”.

then body show " for ex : some content like fsdf lfdjldf

# Answer
You need to add both the content-type inside ***Filter Criteria***.

* Click on the "Add/Or, Rearrange"
* Create new filter group
> 0 votes

---
Tags: views
---


# Question
Title: There was an error with the file in gathercontent module of Drupal
I am importing content from gathercontent platform using the GatherContent module.

All the fields get populated except media type which gives a warning that states :

```
"There was an error with the file"

```

Any ideas what might be causing this?

# Answer
It might well be that your problem is caused by what is described in issue 1908144.

That issue also mentions CURL (as in the comment to your question).

Curious to hear if this somehow helps ...
> 0 votes

---
Tags: importing-exporting
---


# Question
Title: Drupal 7 + Services 3 : anonymous user can't access user/register endpoint (401 access denied)
I'm using Services for providing an external webapp to register new user to the Drupal server.

I'm able to login from the webapp, create node and post comment.

But I can't have access to user registration.

My endpoint is configured and got all CRUD functionnality for user checked.

But when I try to acces it : http://localhost/rest/user/register

I got a 401 : \["Access denied for user anonymous"\]

I guess I'm missing sone permissions, but I can't figure out which one ?

Could you please help me ?

Thanks in advance.

nieud

# Answer
> 1 votes
Well, apparently the 401 is a false error message.

I had an error in the data structure I posted to user/register, when I fixed it the 401 disappeared.

I still have an error on my user registration but this is now a 500.

# Answer
> 0 votes
Go to **Configuration -\> People -\> Account settings** and verify that `Visitors` or `Visitors, but administrator approval is required` is selected for the **Who can register accounts** setting. This page can be reached at:

```
admin/config/people/accounts

```

After that, try the **Rebuild permissions** link located under **Reports -\> Status report**. This page can be reached at:

```
admin/reports/status

```

And of course flush all of Drupal's caches after enabling/disabling Service Resources and endpoints.

---
Tags: 7, users, services
---


title: Taxonomy Term page visit report

text:
# Question
Title: Taxonomy Term page visit report
Is there any module which tracks page visit count for taxonomy terms?

Several module exists for node visit report (including Core Statistics). But I have not found any for taxonomy term page visit count.

Some posts found suggest using the Google Analytic module for this purpose. But my client does not want to use Google Analytic as this is intranet site. Still wants a report for category pages visit.

# Answer
> 0 votes
Consider using the Forena module, it comes with all sorts of reporting features. And all sorts of hooks if you want to use them in your own custom modules.

Here is an excerpt from its Community documentation:

> Forena Reports is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
>
> It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

In this specific case: if you know in which Drupal table (or combination of tables) the info is stored that you are looking for (like your *which tracks page visit count for taxonomy terms*), then it's a matter of putting together an appropriate SQL statement to retrieve those data, and then format it in a nicely looking report (and even chart if you'd want).

Curious to hear if this somehow could work in your case ...

Disclosure: I'm a co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.

---
Tags: taxonomy-terms, 7, log-messages
---


# Question
Title: Display file description in view using Download Count
I have created a view to display my most download files on the site and allow users to download them, to do this I am using the download\_file and download\_count modules.

The view should display a list of the most download attachment files on the site, I need to display the file name, a download link and then the file description.

When I try to insert the file description into the view I start running into problems, I am doing this by adding the field\_attachments field (which is the field inside of my content type that the files are entered into).

When I add field\_attachments all of the files associated with a files related node are displayed in the result, instead of what I expect which is just the single description for that file per row. This is probably an issue with relationships, does anyone know of a way to solve this?

# Answer
I have figured it out, I had to add another relationship for the fields file id "field\_attachments:fid" and then applied that relationship to all of the other fields.

Then I changed the aggregation settings for the attachment description field to group by 'fid' with 'display' and 'description' as additional grouping columns.

Now my view output only displays the matching description of the file in that row.
> 1 votes

---
Tags: views, files
---


title: Flags to create mutual friends?

text:
# Question
Title: Flags to create mutual friends?
I'm running a D7 system where users follow each other by using a 'follow' flag and then on user profile I've added a view to show all the users followed by a 'logged-in-user'.

What I'm struggling with is how do I generate a list of users who are followed by the friends of 'logged-in' user.

something like facebook 'mutual friends' functionality so 'logged-in' user get a list of users followed by the users he/she following.

# Answer
> 1 votes
You can do this by using Flag Friend module

> Flag Friend aims to be a lightweight friending module utilizing the excellent Flag module's API.

**Or**

Flag Follow

> This is a simple module which allows a user to view Heartbeat activities of his favorites/followed users. A user can add another user to his favorites list by just click on a 'Follow' button. It requires no approval to add a user to your favorites list.

**or**

You can do this by using Follow module.

> Follow adds sitewide and per user links that link to various social networking sites. The links reside in two blocks. The Follow Site block lists all the links for the site itself, and by default is visible on all pages. The Follow User block lists all the follow links for the user and is visible only on user profile pages.

---
Tags: 7, views, flags, users
---


# Question
Title: How to get Views Selective Filters working with Country Field from Address Field Module?
When I expose the country field from the address-field module as a selective exposed filter (to only show countries that are in the results of the view), the "selection" works, which means only the appropriate countries are shown in the dropdown of the filter. But after clicking "Apply" the results are zero.

I have tried to rewrite the field but to no avail. I think the problem is, that the country is taken from the core. If i try other fields from the address field, it works.

Any help appreciated! Thanks!

EDIT: I just found out about the checkbox on the field itself called: "Display the localized country name instead of the two character country code". If this is unchecked, the view and the filter are working. But now i have a unreadable list of country abbreviations in my dropdown.

Is there something i can do about this?

# Answer
> 0 votes
I found a workaround on this. In the content-type with the address field i created a new field with a token of the country-field that is now working like a charm with views-selective-filters.

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


# Question
Title: Override Entire Module Page using Template
I would like to override the entire page created by my custom module, I've used the hook\_theme function but my template only affects the markup within the content region, I need to define the markup of the entire page inside the template file, including the header footer etc.

I know that this can be done in the theme but I need to to keep the template file within the module itself.

# Answer
> 0 votes
You want to override the deliver callback for the menu route. https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_deliver\_page/7

But notice this might be very invasive and cause you issues later on.

---
Tags: theming
---


# Question
Title: Why are the Recent log messages not shown within admin/reports?
The usual log reporting option "Recent log messages" is not showing up under 'admin/reports' (in the admin menu).

Any idea what might be causing that? Is there a module that provides this functionality?

# Answer
The "Recent log messages" is one of the submenu options located within admin/reports/dblog.

It becomes available after the core module `dblog` (Database Logging) is enabled.

If that core module is enabled, and it still isn't showing up, then it is probably because permission "`View site reports`" (within "System") has not been granted to the user trying to access that report.
> 7 votes

---
Tags: log-messages
---


title: Row weights on taxonomy

text:
# Question
Title: Row weights on taxonomy
On my live site I am unable to see the drag and drop functionality only on taxonomy, whereas it is successfully appearing on menus.Below is my screen shot for taxonomy.

It should be like this:

Can any one have idea about this?

# Answer
Try enabling Aggregate JavaScript files option at `admin/config/development/performance`. Sometimes that resolves this type of issues

Here is the screenshot
> 1 votes

---
Tags: 7
---


# Question
Title: Accuracy of numbers provided by the "Statistics Advanced" module?
We use modules Google Analytics and Statistics Advanced, in Drupal 6. It is clear from the numbers that they provide very different readings.

Can anyone give any accuracy analysis for the Statistics Advanced module, perhaps by comparison with Google?

# Answer
As it relates to Statistics Advanced, you may want to take into account some of the options mentioned on its project page. Such as:

> Only track 'unique' views of content: If you keep viewing a node over and over again, the "x reads" counter won't increase each time. This is applied on a per-user basis as well as a per session id for anonymous users.

Refer to the project page for other options mentioned there.

Disclosure: I'm the (new) maintainer of Statistics Advanced.
> 0 votes

---
Tags: 6, nodes, google-analytics
---


title: Custom node Template for script tags

text:
# Question
Title: Custom node Template for script tags
I wanted to add script code to implement "LiveChat" functionality on just three pages of our website. So, I wanted to add one script code given by our LiveChat agency into three webpages of our website.

**Script Code**

```
<script src="http://www.examp.com/scripts/invitation.ashx?company=4444"></script>

```

So, I have created three separate html node templates based on their node ID.

Theses three custom node templates are under

**/sites/all/themes/mytheme/templates** along with (***node.tpl.php and html.tpl.php***)

1. (**contact page**) html--node--28.tpl.php

**Url of this page:** www.example.com/contact

2. (**admissions page**) html--node--1212.tpl.php

**Url of this page:** www.example.com/admissions

3. (**market page**) html--node--378.tpl.php

**Url of this page:** www.example.com/market

Code used in all custom node templates (html--node--28.tpl.php, html--node--1212.tpl.php, html--node--378.tpl.php) is the same:

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>
<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
 </head>
<body<?php print $attributes;?>>
<?php print $scripts; ?>
//Adding script for LiveChat
<script src="http://www.examp.com/scripts/invitation.ashx?company=4444"></script>
  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>
  </div>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>

```

But, I am not able to see my script (`<script src="http://www.examp.com/scripts/invitation.ashx?company=4444"></script>`) when I debugged it in view pagesource.

Thanks!

# Answer
Instead of adding three template files for three nodes with the same content in it in my opinion will be a better solution to add the JS file conditionally using `drupal_add_js`

For eg:

```

 $allowed_nid = array(28, 1212, 38);
 if(in_array(arg(1), $allowed_nid)){
  drupal_add_js("http://www.examp.com/scripts/invitation.ashx?company=4444", "external");
 }

```

You can add the snippet in a `hook_init` function in any of your custom modules. (Best is add in a custom utility module which hold all general function to be used throughout.) Else you can add it in your theme's `template.php` in the `template_preprocess_page` function.
> 1 votes

# Answer
You can do this to your `html.tpl.php`

```
<?php $node = menu_get_object();
      if ($node && $node->nid == NID):?>

<script>
<--! Your script goes here -->
</script>

<?php endif;?>

```
> 0 votes

---
Tags: theming
---


# Question
Title: How to create custom commerce order states?
I want to create custom order state's and in a view use a "button" or a "select list" to toggle those states.

For example I have view that display's a table of all orders that are marked completed. I would like to add a "button" or "select list" to each row so that I can toggle the state for each order.

Can this be done?

# Answer
> 2 votes
Check this module Commerce Custom Order Status it can help you with custom statuses.

# Answer
> 10 votes
Two things there:

A. Define your custom order states with one of the Order info hooks.

1. hook\_commerce\_order\_state\_info
2. hook\_commerce\_order\_status\_info

B. Create a commerce\_order based VBO view and add an operation to change the order state. It won't be a button on each row, just a checkbox or radio button, but you can batch update that way.

Alternatively, edit the order and set it's state on the edit form.

# Answer
> 1 votes
I found the documentation on this to be unclear, so for reference, here's **an example of adding a status (not state) programmatically**. This adds a new "credit card failure" status under the "Cancelled" state.

```
function mymodule_commerce_order_status_info() {
  $order_statuses['ccfail'] = array(
    'name' => 'ccfail',
    'title' => t('Credit card failure'),
    'state' => 'canceled',
  );

 return $order_statuses;
}

```

# Answer
> 0 votes
I had problems with the code in the previous example but this worked for me as a way to add a new status of 'Refunded' to the existing 'Canceled' State after the existing 'Canceled' status.

```
function mymodule_commerce_order_status_info_alter(&$order_statuses) {
    $order_statuses['refund'] = array(
            'name' => 'refund',
            'title' => t('Refunded'),
            'state' => 'canceled',
            'cart' => FALSE,
            'weight' => 10,
    );
}

```

Note that the 'cart' index is required and if you don't included you will get an undefined index error.

---
Tags: rules, commerce
---


title: Creating commerce iframe payment

text:
# Question
Title: Creating commerce iframe payment
I need to create an iframe to my payment provider that will do the actual payment in the checkout process of Drupal commerce.

In this iframe the user will actually insert his credit card details.

What is the best way to accomplish this?

I need this (of course) to interact with the commerce checkout process.

# Answer
> 2 votes
I did create a Commerce payment gateway with an almost similar challenge. You can have a look at the Commerce Pesapal module code.

A brief description would be;

1. Register a Commerce payment method.
2. Create settings for your payment method if any.
3. Implement `hook_menu()`and create at least three pages. One to hold the iframe, one to hold the callback from the payment gateway and another that will hold the form used to pass values to the iframe. The second page can also be used to pass a message to the user.
4. On the redirect form you will not use a 'Submit' button because we need to pass the values to an internal URL. Instead you will do something like this.

```
$form['#action'] = $base_path.'Path To Your Iframe';
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
 '#type' => 'submit',
 '#value' => 'Pay',
);

```
5. On the iframe page you can get all the variables rom your redirect from using `$_GET`.

The rest of the details I believe will depend on the gateway provider from that point on.

# Answer
> 1 votes
Quite an old question, but if anyone still faces this issue, here are few example payment method modules apparently implementing iframe integration:

---
Tags: 7, commerce
---


# Question
Title: How to create a drop down field to categorize content when creating new pages?
I want to have a drop down field available so that when a content author (user) creates a new page, they can select which section of the website this new content should get placed.

For example, my top navigation may be **About Us \> Services \> Products**. A user creates a new page that should go on in the Products section. When they go to add the new page, there should be a drop down field that shows **About Us, Services, Products**. The user would select **Products** and when they save the page, that page will automatically get placed in the **Products** section of the website.

Can anyone tell me how to achieve this?

# Answer
> 2 votes
The drop-down can be created as a Taxonomy.

The section pages can all be one View with a Contextual Filter for each taxonomy term.

# Answer
> 2 votes
Consider using the Taxonomy Menu module for this. Here is an excerpt from its project page:

> Transforms your taxonomy vocabularies into menus with ease!
>
> Features
>
> * Custom Menu per vocabulary
> * Uses the default taxonomy term path or custom paths
> * Integrate with Views
> * Integrate with Pathauto: use URL/path aliases
> * Does not interfere with other menu modules

By creating an hierarchical taxonomy, it should be straight forward for your content editors to use this feature. That would take care of the "dropdown" field you're looking for already.

Next you'd have to think of how to implement what you consider "section" of the website, how would you technically implement that? Could it be something like "can be accessed by a user who has access to role ABC?". I'm thinking of a few possible techniques for that, based on the Rules module, possible with integrations from a few other modules also, such as:

So please edit your question to better explain what you mean by "section". After you do, I can update my answer accordingly.

---
Tags: 7, entities, routes, nodes
---


title: Entity reference edit link

text:
# Question
Title: Entity reference edit link
I have two simple content types

* Parent
* Child

The *Parent* content type has an unlimited value entity reference field which allows it to reference *Child* nodes.

The *Parent* content type *Manage display* for the *Child* entity reference field is set to "**Rendered entity**".

Now when viewing a *Parent* node, each of its *Children* nodes are displayed as well. Great.

However, I'd like to see an "**Edit**" link next to each *Child* node when viewing a *Parent* node. How can I achieve this? I'm hoping for a hover feature that would pop up a cog icon.

I thought the "**Show links**" option on the field's display settings would show some type of link(s), but it appears none are showing.

# Answer
I hate to answer my own question, but all you have to do is enable the "**Contextual links**" module. This is a Drupal core module, and it can be enabled here:

```
admin/modules

```

Or with Drush via:

```
drush en contextual

```

This module is automatically enabled with a "*Standard*" Drupal installation, but if you use a "*Minimal*" installation this module will not be enabled.
> 0 votes

---
Tags: entities
---


title: After update to Drush 7 still version 6

text:
# Question
Title: After update to Drush 7 still version 6
Running on Debian I have updated Drush to version 7:

composer global require drush/drush:7.\*

composer global update

But the command 'drush --version' still tells me: Drush Version : 6.2.0

I have looked everywhere but didn't find a solution.

Thanx for any help.

# Answer
The problem is that the old version of Drush is still in your $PATH, and comes before the new version.

The Drush installation instructions says: `Now add Drush to your system path by placing export PATH="$HOME/.composer/vendor/bin:$PATH" into your ~/.bash_profile (Mac OS users) or into your ~/.bashrc (Linux users).` What it does not mention is that changes to your .bashrc file are not immediately reflected in your running system. You need do one of:

1. Restart.
2. Close and re-open all of your terminal windows.
3. Type `source ~/.bashrc` in all of your open terminal windows.

(Listed in order from easiest and most disruptive, to more work but less disruptive.) Substitute .bash\_profile in place of .bashrc if you made your modification there.
> 1 votes

---
Tags: drush, updating
---


title: Custom Drush command without module

text:
# Question
Title: Custom Drush command without module
I am a newbie into Drupal.
I recently learned to create custom Drush command inside a custom module.
I am wondering if I can write a custom drush command and its definition without any module or outside module. for eg. If I have no custom module in my drupal project.
This custom command is available for execution only if my module is enabled. Can I write a drush command which is completely module independent?

Is it possible?

# Answer
> 4 votes
You might be interested in the drushify project, which will create a Drush commandfile for you, from a template. You can give it the name of a module, and run it from a Drupal site to make a Drush command for a module, or just give it an arbitrary name and run it from outside any Drupal site, and it will create a global Drush command.

From there, you only need to go through and fill in the parts of the template that it made for you. You may delete any of the optional hooks that you don't need -- which is usually most of them.

# Answer
> 3 votes
No `.module` or `.info` file is needed. The required steps for creating a command:

1. Create a command file called `COMMANDFILE.drush.inc`
2. Implement the function `COMMANDFILE_drush_command()`
3. Implement the functions that your commands will call. These will usually be named `drush_COMMANDFILE_COMMANDNAME()`.

Drush searches for commandfiles in the following locations:

* The "/path/to/drush/commands" folder.
* Folders listed in the 'include' option (see drush topic docs-configuration).
* The system-wide drush commands folder, e.g. /usr/share/drush/commands
* The ".drush" folder in the user's HOME folder.
* /drush and /sites/all/drush in the current Drupal installation
* All enabled modules in the current Drupal installation

Some additional documentation authoring custom commands - http://www.drush.org/en/master/commands/

# Answer
> 2 votes
Yes, you can place any **\*.drush.inc** file in your **~/.drush** dir to make Drush pickup on it. Checkout the `drush_commandfile_list()` docs for all the locations that Drush looks for command files.

---
Tags: drush
---


# Question
Title: Add preprocess to content within body field
I need to be able to wrap an anchor tag with rel="shadowbox" and href with the path to the image on all img tags that are inserted into the body field of a node. I think I can somehow do this with preprocess?

I realise that I can have a field of images and do it that way, though the client wants the images within the body text itself.

Any advice would be much appreciated.

# Answer
There's a couple different ways one could go about this; I think the most elegant solution could be a text filter.

```
/**
 * Implements hook_filter_info().
 */
function MODULE_filter_info() {
  $filters = array();

  $filters['shadowbox'] = array(
    'title' => t('Image Shadowbox'),
    'description' => t('Wraps images in anchor tags.'),
    'process callback' => 'MODULE_shadowbox_cb',
  );

  return $filters;
}

```

Then, the callback:

```
/**
 * Image shadowbox callback.
 *
 * @param string $text
 *   The text to be parsed.
 * @param object $filter
 *   The filter, which includes context about which format is being used.
 *
 * @return string
 *   The replaced content.
 */
function MODULE_shadowbox_cb($text, $filter) {
  $ret_val = $text;
  // Logic goes here.
  return $ret_val;
}

```

You'll need to enable the filter:

* /admin/config/content/formats/full\_html
* /admin/config/content/formats/filtered\_html

Now, for the content of the callback; you could use a regular expression. https://stackoverflow.com/a/4456866/4619035 is an example for exactly this use case. The downside of regular expressions with HTML is that they're fragile, especially with potentially malformed code. A workaround would be to sequence the filter after anything that cleans up HTML.

Alternatively, use DOM to manipulate the content - https://stackoverflow.com/questions/18316527/php-dom-wrap-image-in-link-and-add-span-before-image-tag describes this approach well.
> 1 votes

---
Tags: nodes, theming
---


# Question
Title: Is it ever okay to ignore a warning about an inconsistent Database schema?
Can it ever be ok to ignore a Database schema = Inconsistent report?

The schema module is reporting the following mismatches:

contact

```
page_title: unexpected column in database
page_info: unexpected column in database

```

search\_dataset

```
column type - differences on: length, default
declared: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => 16, 'not null' => TRUE)
actual: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => '64', 'not null' => TRUE, 'default' => '')

```

search\_index

```
column type - differences on: length, default
declared: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => 16, 'not null' => TRUE)
actual: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => '64', 'not null' => TRUE, 'default' => '')

```

search\_node\_links

```
column type - difference on: length
declared: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => 16, 'not null' => TRUE, 'default' => '')
actual: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => '64', 'not null' => TRUE, 'default' => '')

```

# Answer
> 2 votes
It could be okay, for a time, until the module that has an out of date schema attempts to read, save, update, or delete data from an out-of-date database table. At that point, you'd get inconsistent data in your database at least, and possibly end up with a corrupted database or have your site return the WSOD (white screen of death) at worst.

The warning simply means there is at least one update that hasn't yet been run. It's always a good idea to run updates by visiting update.php or using `drush updatedb` whenever you update any modules or Drupal core.

# Answer
> 0 votes
Do you have the contact module enabled?

Do you have the search module enabled?

As stated in other comments, it looks like your site wasn't re-configured properly. The correct steps for removing a module are:

1. Disable the module
2. Uninstall the module
3. For contrib modules: delete the code

The other possibility is that one or more update hooks were skipped, or run out of order. This can happen if you are running "unstable" code, like dev releases, or you had patched a module directly.

For now, it looks like none of those are fatal. No code should be trying to access an "unexpected column". In the case of the search module, each time the actual amount is larger than the declared amount. So, any code trying to use a larger value won't have any problem.

---
Tags: database, updating
---


# Question
Title: Why are my menu items not showing under the top level menu item?
I'd like my other 3 menu items to sit under Manage Instagram in my Admin/Config menu but they are all being created as individual top level menu items.

```
  function instagram_menu() {

  $items = array();

  // Top Level Menu Item
  $items['admin/config/instagram'] = array(
    'title' => 'Manage Instagram',
    'type' => MENU_NORMAL_ITEM,
  );

  // Secondary Level Menu Item
  $items['admin/config/instagram/pull-images'] = array(
    'title' => 'Pull Instagram Images',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('instagram_form'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
  );

  // Secondary Level Menu Item
  $items['admin/config/instagram/client_id'] = array(
    'title' => 'Set Instagram Client ID',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('instagram_client_id_form'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
  );

  // Secondary Level Menu Item
  $items['admin/config/instagram/delete'] = array(
    'title' => 'Delete Instagram Data',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('instagram_delete_form'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

```

# Answer
According to Drupal menu item types you need to designate which item is the parent and designate the children as such. So in your case, I believe setting your 3 links as MENU\_LOCAL\_ACTION should resolve the issue. You might have to designate the top level menu item as MENU\_DEFAULT\_LOCAL\_TASK to make it work depending on your settings.
> 0 votes

---
Tags: routes
---


title: Unable to link media in CKeditor

text:
# Question
Title: Unable to link media in CKeditor
My setup is as follows:

Drupal 7.34 Media 7.x-2.0-alpha3 CKEditor 4.4.6.08188c4

My problem is:

When I add an image from the "library" via media browser in CKeditor and try and link it via the "link" icon - the image does not link up. If I switch to source view I can see that no tags have been added. If I save page - image link is not applied.

However, the link is saved if I edit source and add link tags in manually.

# Answer
From the question details it is not clear if you're using the CKeditor module, or it you're using the WYSIWYG module in combination with the CKEditor library (so without the CKeditor module).

As a possible alternative to consider, I'd suggest you try this:

* if you're using the CKeditor module, then replace the 4.4.6 ... version of CKeditor with some 3.6.x version of it (such as CKEditor version 3.6.6.1.7696), and see if your problem is resolved (the 4.x version is known to have "some" issues which don't exist in the 3.x version ...).
* alternatively, use the WYSIWYG module (without the CKeditor module, but only using the CKEditor library with version 3.6.6, since WYSIWYG module does not support the 4.x version yet ...). In this case, you may also want to experiment with the various '*cleanup and output*' options within `/admin/config/content/wysiwyg/profile/your_txt_fmt/edit` (with '`your_txt_fmt`' the text format you're using, eg '`filtered_html`').
> 1 votes

---
Tags: media, wysiwyg
---


# Question
Title: How to use number fields for drupal commerce attributes
I am using Drupal 7 with Drupal Commerce (not kickstart). My products are boxes setup in Series varying by height.

```
Examples:
Series 500 has 3 boxes
box 1 has dimensions of 120x20x10
box 2 has 120x20x20
box 3 has 120x20x30

```

Everything else about the boxes are the same, so "height" is my product attribute. Drupal Commerce attributes by default need to be an options\_select field, but I have over 1000 products of varying heights and I really didn't want to have to build and maintain a gigantic array of heights down to a thousandth of a inch (whether in the gui or in code).

My original thoughts were to build a module that has a sql table to store product heights. Then add two fields to the product, a decimal and an options field and hide the options field. When the user enters a decimal in the height field on the product page, on save the module will check to see if the value exists and if not insert the value into the sql table. The options field will be setup to use an allowed values function to query the sql table to build the "heights" array so again on save after the module stores the decimal in the sql table, it will then set the value in the options field keeping the two in sync.

This would allow me to have an options field I don't have to maintain, but seemed a little hacky so wondered if there was anyone else out there that found better way (as I have googled and had no luck).

Thanks!

# Answer
> 1 votes
For the answer, I actually found a possible dup of my questions here:

support integer or float values as an attribute

but it was never answered, which is why I left mine up. However, the question had a little more research into my problem and was able to give me insight that any field that implements hook\_options\_list and has an entity "property\_type" defined in its hook\_field\_info then it can be used as an attribute.

From here I created a module that installs a new widget for the "list" modules that allows textfield input and adds the sanitized value of the textfield to the "allowed\_values" on POST so that it passes validation. From the viewmode standpoint it works like a normal list and you can use the select widget on the commerce product attribute settings to use this as an attribute.

I know the security ramifications of this could be dicey, however I am sanitizing the field input and I have only myself actually contributing content so I feel this solution works for me.

---
Tags: commerce
---


# Question
Title: Support integer or float values as an attribute on a Drupal Commerce "Add to Cart" form
I have created a product type which has integer and float fields. I would like to store my data as the correct data type and allow users to make decisions about which product to buy based on those fields. These are ineligible to become part of the commerce "Add to Cart" as defined by the following commerce function:

```
function commerce_cart_field_attribute_eligible($field) {
  // Returns TRUE if the field is single value (i.e. has a cardinality of 1) and
  // is defined by a module implementing hook_options_list() to provide an array
  // of allowed values structured as human-readable option names keyed by value.
  return $field['cardinality'] == 1 && function_exists($field['module'] . '_options_list');
}

```

It looks like the concept of implementing hook\_options\_list is hardcoded into a few places, including the field config forms:

```
if ( ... && function_exists($form['#field']['module'] . '_options_list')) {
  // Enable this field to function as an attribute field on Add to Cart forms.
}

```

By looking at how this has been setup, it seems reasonable that if you want commerce to cooperate with a field type, it must implement the hook.

I have considered implementing this hook for the "number" module and returning the entire dataset of values defined on the website for the specific field (this seems to work without any issues from what I can tell with 5 products).

I'm not sure if this will cause issues with Commerce or core down the track, perhaps with:

* Too much data grinding things to halt.
* The core "options" module not playing nicely with float/int fields.
* Other modules assuming the field is a list of data?
* The weirdness around implementing another modules hook.

Looking for some advice on the best way to move forward with the problem.

# Answer
I ran into the same problem (and asked a similar question which I ended up answering myself here)

Basically with the knowledge you gave I was able to implement a new module which installs a widget for the "list integer" and "list float" types that uses a textfield for input and on POST it sanitizes and adds the value of the textbox to the "allowed\_values" setting on the field allowing it to pass the standard list field validation and use the standard list field storage.

This allows you to enter and display a "number" and use the value as a product attribute. Best part is I did not have to alter another modules code, which addresses the majority of your concerns as:

> * The core "options" module not playing nicely with float/int fields.

The options module defines the widget, since you are doing this, you don't need to worry about it.

> * Other modules assuming the field is a list of data?

Since you defined your own widget and are not using the standard "options", other modules will not know it exists so you don't have to worry.

> * The weirdness around implementing another modules hook.

Again, by adding the sanitized field into the allowed\_values setting on POST you pass validation and this allows you to use the "LIST" modules standard implementation of hook\_options\_list and you don't have to modify someone else's code

As far as your first point on too much data, this is possible that you will have a problem here if you have a multitude of products OR if you are added and removing products all the time (which would continuously add to your "allowed\_values" list). For the first point, you could probably also implement a field type in your module and do your own implementation of hook\_options\_list to follow your logic and just return all the values in your database (i don't have that much so didn't bother). For the second point, you could implement hook\_cron and clean up on the allowed values setting based on the values for the field in the database.

hope this helps and if you have any questions let me know!
> 0 votes

---
Tags: commerce
---


title: Front page as link in Views

text:
# Question
Title: Front page as link in Views
This is pretty straight forward. How do I print a link to the homepage as field in Views?

I have added a global text field with html code `<a href="/">Home</a>` but this is just the path to the root & my website is installed in a subdomain.

Using D7 and latest Views module.

# Answer
> 5 votes
it should work this way:

* create the global text field, with the text as the link text -

* **then rewrite the results, and output as a link using `<front>` as the path -**

---
Tags: views
---


# Question
Title: How to make the 'Module Updates' report available again?
I have a 7.18 Drupal site running since a long time without updates. The update manager was deactivated since then as well.

Now I had to move the site to another server and after reactivating the update manager, it does not work properly. I have the status message that there are updates available, but the paths `admin/reports/updates` or `admin/reports/updates/update` only lead to the reports overview page.

Does anyone have a hint about how to fix this?

# Answer
Here is a list of items to check:

* Make sure core module `update` (= Update Manager) is enabled.
* Clear all caches: if you get a WSOD while doing so, it indicates memory shortage.
* Try running `update.php`: if you get a Fatal error like "Allow memory size of ... bytes exhausted", it indicates memory shortage.
* Verify if it is a memory shortage issue: try increasing the memory a bit to check if there is any difference.
> 1 votes

---
Tags: 7, updating, log-messages
---


title: How to make a relationship to two views

text:
# Question
Title: How to make a relationship to two views
I am creating a website in which i am already created two view (1. Category 2. Location) , now i am created the taxonomy for Location and in Category view I am exposed the Location Taxonomy,,, and in Location View here also i am exposed the view-block,,, so the Taxonomy is same in both views,, Now I want to know that if I will select the Category view Location then automatically Location will be select in @nd view (Location view),,,

Plz provide any suggestion ..?

Here is the image of Location View (1st pic):

Checkbox (2nd pic):

So if i will select the Bangalore in Search Menu in 1st pic, then the Bangalore will automatically selected in 2nd pic (View) (i.e. in checkbox).

# Answer
Assuming both views are showing the same page, it could be accomplished using something like this:

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.

* pass the arguments (instructions included in module) to the second view to ensure it is getting the correctly information
* use Views Auto Refresh, Views Flag Refresh or Block Refresh \- depending the exact set up you have and want to refresh the second view
> 0 votes

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


# Question
Title: Drupal 7 + Services : Error 500 on user registration (Integrity constraint violation: 1048 Column 'uid' cannot be null)
I'm still working on user registration with Drupal 7 and Services 3 and I got a weird Error 500 :

> Integrity constraint violation: 1048 Column 'uid' cannot be null

Here is the code I'm using :

```
// REST Server URL for auth
$request_url = SERVER_URL . 'rest/user/register';

// User data
$user_data = array(
  'name' => 'newuser',
  'mail' => 'newmail@mail.com',
  'pass' => 'newpass',
  'field_city' => array('und' => array('0' => array('value' => 'NA'))),
);

$user_data = json_encode($user_data);
// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_VERBOSE, true);

$response = curl_exec($curl);

$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  if ($http_code == 200) {
  return json_decode($response);
}
else {
  $http_message = curl_error($curl);
  return $http_message;
}

```

Is there something I'm doing wrong ?

# Answer
> 1 votes
I think that on the other side of your code you are trying to save the user. So, to create a new user using user\_save() function you have to left the first parameter blank so a new user is created. Also, add the parameter true to your json\_decode($response, true) to obtain an array rather than an object.

$account = user\_save('', $fields);

---
Tags: 7, users, services
---


# Question
Title: Ajax form works on page but not on block
I've created an ajax form with drupal API. The ajax functionality works if I render the form on a page with hook\_menu, but it doesn't when I render it in a block. This is how I create my block:

```
function hook_block_info() {
    $blocks['my_block'] = array(
      'info' => t('Title'),
      'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

function hook_block_view($delta = '') {
    $block = array();

    switch ($delta) {
        case 'my_block':
            $block['subject'] = t('Title');
            $block['content'] = drupal_get_form('my_form');
            break;
    }
    return $block;
}

```

Any idea how I can fix this?

# Answer
> 2 votes
Did you create the form in a separate file? If you did, then it makes a big difference where in the main .module file you put the module\_load\_include() function to bring in the form. I had this problem because my form definition was in a .inc file, but when I moved module\_load\_include() from hook\_node\_view() to hook\_init(), it worked fine.

Edit: Wait, better answer: hook\_init() isn't called on cached pages, so may not be the way to go. Instead, call module\_load\_include() wherever it makes sense (e.g., hook\_node\_view() or hook\_block\_view()), but use form\_load\_include() within your form definition, like this:

```
function my_ajax_test_node_form($form, &$form_state) {
  form_load_include($form_state, 'inc', 'my_ajax_test', 'my_ajax_test.forms');
  $form['my_ajax_test_div'] = array(
    '#type' => 'container',
    '#tree' => TRUE,
    '#prefix' => '<div id="my-ajax-test-form-div">',
    '#suffix' => '</div>',
  );
  return $form;
}

```

Once the file has been loaded with form\_load\_include(), it will be loaded anytime the form is called.

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


# Question
Title: Order product ID field returns "0" in Views
I have a View of type "Orders" for my Ubercart orders. I am trying to display the "Order Product ID" field value for each order product so that I can count those as distinct. I added the relationship "Order: Products", which makes the "Order Product ID" field available; however, that field is returning a value of "0" instead of the actual Order Product ID displayed in the database. How can I resolve this?

Here is an export of my view:

```
$view = new view();
$view->name = 'order_test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'uc_orders';
$view->human_name = 'Order Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Order: Products */
$handler->display->display_options['relationships']['products']['id'] = 'products';
$handler->display->display_options['relationships']['products']['table'] = 'uc_orders';
$handler->display->display_options['relationships']['products']['field'] = 'products';
/* Field: Order: Order ID */
$handler->display->display_options['fields']['order_id']['id'] = 'order_id';
$handler->display->display_options['fields']['order_id']['table'] = 'uc_orders';
$handler->display->display_options['fields']['order_id']['field'] = 'order_id';
/* Field: Ordered product: Order product ID */
$handler->display->display_options['fields']['order_product_id']['id'] = 'order_product_id';
$handler->display->display_options['fields']['order_product_id']['table'] = 'uc_order_products';
$handler->display->display_options['fields']['order_product_id']['field'] = 'order_product_id';
$handler->display->display_options['fields']['order_product_id']['relationship'] = 'products';
$handler->display->display_options['fields']['order_product_id']['link_to_entity'] = 0;

```

Thanks!

# Answer
> 1 votes
I've also experienced this issue by creating hook\_views\_data\_alter adding the following code into it:

```
$data['uc_order_products']['order_product_id']['field'] = array(
    'handler' => 'views_handler_field_numeric',
);

```

I have noticed that the order\_product\_id had no handler so since the return of this field is the ordered product id I just went ahead and used the handler that comes with Views views\_handler\_field\_numeric.

If you'd like, I bunched some additions related to the order product id field in my custom module in Ubercart-Add-ons.

---
Tags: 7, views, ubercart
---


title: Views-based search analytics

text:
# Question
Title: Views-based search analytics
I have a search: search terms field setup in a view in drupal 7. It's exposed to users so they can search nodes.

I know my users are using the search but google analytics isn't capturing that information.

I also looked at reports \> top search phrases and it shows nothing...even though I believe views uses the basic search module.

My question is: is there a way to see statistics on what terms users are using to search with this view?

# Answer
> 0 votes
Looks like I found a possible answer. Use Google Analytics module and make sure to track internal search. Then setup your Google Analytics account like so.

---
Tags: views, search
---


# Question
Title: Adding a 'search tips' link next to the search button in a views-based search
I'm using a Drupal 7 views-based search. I have a search button in there of course. I'd like to add a link next to it called 'search tips' that goes to a 'basic page'. Anyone know how to add a link there?

This is the code I have so far:

```
<?php

  /*
    * Implementation of hook_form_alter()
    */
  function search_tips_link_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == "views_exposed_form") {
    // there's a submit button in here I'd like to add a link after that...
    // not sure how to place a link with this function.
    }
  }

```

# Answer
> 1 votes
You need to:

1. Find the specific view exposed form by using the **#id** array key.
2. Find for the search button array key.
3. Use the #suffix form key to append your link.

A helpful tool to look into the array structure is by using the dsm() function from Devel module.

Additional information for best practice is that use the l() function to structure your link.

So it would look something like:

```
if ($form['#id'] == 'views-exposed-form-test-page') {
  $form['submit']['#suffix'] = l(t('Search tips'), 'link-to-basic-page');
}

```

---
Tags: views
---


title: Need help wiith a Drupal Migration

text:
# Question
Title: Need help wiith a Drupal Migration
I have a task to do a Drupal migration and was given a database backup and a backup of all the web files. It was a Drupal 7 site but I have no further information as to what modules and themes were used. I need to get it up and running on Windows IIS6 enviroment with FastCGI and ISAPI Rewrite running with a MySQL 5 backend. This is a staging environment.

I have 1. rebuilt the database in MYSQL from the sql dump 2. unpackaged the web files into the webroot 3. configured settings.php to point to the DB

and all I got was WSOD so I added

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

to the beginning of index.php to get a better handle on errors

I got "Fatal error: Call to undefined function: user\_access() in menu.inc" so I checked the system table but

```
system.module
node.module
user.module
filter.module
block.module

```

All check out- with status="1" and correct filepaths in data- e.g. module/system/system.module etc.

I have then tried truncating the cache (went directly in to the DB) and tried

```
TRUNCATE TABLE cache;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_filter;
TRUNCATE TABLE cache_form;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_token;
TRUNCATE TABLE cache_update;

```

this caused a slew of PHP Warnings that eventually righted itself as cache started rebuilding.

Am now in state where the page only shows multiple instances of one warning.

```
Warning: array_merge(): Argument #2 is not an array in theme_get_setting()
(line 1461 of C:\Sites\public_html\includes\theme.inc).

```

But now having finding any info on how to proceed from here. Apologies as this my first time doing a Drupal migration.Do have a copy of all the original backps so I can start agin from scratch as necessary.

# Answer
> 1 votes
I would suggest you to use `drush` and try rebuilding registry using Registry rebuild because there might be modules file path issues (conflicts) while migrating.

After you put all files in place and database imported. try this,

1. Download Registry rebuild module.
2. now run `drush rr` on your drupal installation directory. \[ if it is multi-site then your working directory should be inside sites/example.com/ \]

---
Tags: migrations
---


# Question
Title: unable to link my custom content type nodes to a menu I created
I created a custom content type (pics). I can add this new "pics" content to my site (and if I want to, it can appear on front page, but I don't want to...) with no problem. But I would like those new added contents appear in my new menu (called Photos).

When I created my new content type I got a " machine name" : "pics". Then I created a new menu called "photos" and I put this name into the path field like this: http://www.example.com/drupal/pics

But it doesn't work this way. The menu will be empty with a Page not found message.

I'm new to drupal, so please bare with me. Please let me know the solution.

# Answer
> 1 votes
By default, Drupal 7 does not create a filtered list of content. You're going to want to use Views Page to create a list of content.

Delete the menu item you created, then install https://www.drupal.org/project/views and its dependency https://www.drupal.org/project/ctools

If you have Drush installed...

`drush dl views
drush -y en views views_ui`

* In your browser, go to /admin/structure/views
* Click "Add new view".
    + View Name: Photos
    + Show \[Content\] of type \[Pics\]
    + \[X\] Create a page
        - Page title: Photos
        - Path: pics
        - Display format: Table
    + Click "Continue & edit" to customize

For information on Views, see https://www.drupal.org/documentation/modules/views

# Answer
> 0 votes
# Getting around the error message:

You're getting that error like '*Page not found message*', because when creating a menu item like you tried to do, Drupal expects the path that you enter to exist. If however you would specify node/xyz (with xzy = actual node ID of the node you want the menu item to point to), then Drupal would find that path, and you should not get such error message.

# Possible alternative:

Create a new node, or edit an existing one, and specify these values while in the edit form of that node:

1. the path you want the node to use (= 'drupal/pics' in your case).
2. the menu item you want to be created for it (within menu 'photos').

After saving such node, you should get the desired result also.

Curious to hear if either of both approaches answer your question ...

# Answer
> 0 votes
based on your comments, this works - this code assumes a content type Article, adjust as necessary:

* **create a parent menu item within the main menu (PICS), set Show as Expanded TRUE, set the Parent to Main Menu**

* **in the content type set up, set the Menu Settings to Main Menu, with PICS as the parent**

* **There are modules that will do this, but if all you need is a simple menu entry override, you can use this custom module:**

`custom_menu_entry.info`

```
name = Custom Menu Entry
core = 7.x
description = Automatically Creates an Entry on Node Save
package = custom

```

`custom_menu_entry.module`

```
<?php
/**
*   Custom Menu Entry Module - Force a menu entry to be created on node save
**/
function custom_menu_entry_node_insert($node)
{
    if($node->type == 'article')
    {
        $node->menu['enabled'] = true;
        $node->menu['link_title'] = $node->title;
    }
}

```

This will force the menu entry to be created on node save, but again it is unwise in your particular use case - A view is a more suitable option.

---
Tags: routes, nodes, navigation
---


# Question
Title: User having issue with site being redirected to home page from every link
We have a drupal 7 site hosted on a linux machine. One of our users claims they get redirected to the home page from every link they click on the site. I'm not personally having this experience with the site nor is anyone else I work with. The user hasn't given us any more information, but I'm wondering if you guys have any idea what might be going on here?

I found this thread but it seems to be mostly a Windows-based issue: Why does my drupal 7 redirect me to the home page from any link?. Plus I have clean URLs on and like I said it works fine for everyone else.

Thoughts?

# Answer
> 3 votes
It is possibly an issue with a cookie. Have that user try to use another browser to check if the same problem occurs with that browser.

Or just delete the session cookie in the browser being used, then check if the issue is resolved.

---
Tags: 7, redirection
---


# Question
Title: How to get a same result of Views with Random Sort Criteria
There is a View which it's Sort Criteria is Random.I have to use the following code to implement two different displays of **one** view.

```
print views_embed_view("library","block_0",$term->tid);
$views = views_get_view_result("library","block_0",$term->tid);
//some other codes that retrieve data from $views

```

The problem is, because the View is Random the above two lines return different results while I need to have one. How do I can solve this problem?

# Answer
> 1 votes
Try this way :

```
$views = views_get_view("views_name");
dsm($views->preview('display_id')); // instead of views_embed_view
dsm($views->result); // Instead of views_get_view_result()

```

# Answer
> 1 votes
if its in the same context, you can assign a variable and print it twice

```
$output = views_embed_view("library","block_0",$term->tid);

print $output;
print $output;

```

if that is not the idea, you could simply do what views\_embed\_view() does manually by loading the view first which gives you access to the content, and then calling the preview - here's the code from the function:

```
function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);
}

```

---
Tags: views
---


# Question
Title: create contact form block with prepopulated entity references and send email to content author
I am trying to create 3 forms, 2 of them should be made into blocks to show on specific content types. One for anon users and another for logged in users. The other is just a site wide contact form replacement for core Contact.

Anonymous Contact Form: Name, Email, Entity Reference to Content, Message

Logged In Contact Form: Entity Reference to Content, Message (Pull username and email from account)

Site Wide Contact: Name, Email, Message, Term Reference to Category

The Entity reference is important since I will be pulling data from it to populate the email message (like nid, author, etc...)

When a user submits the non-site wide contact forms, Rules should be able to pull the data from the form and send an email to the node author.

Views Contact Form/Core Contact: Can't add entity reference fields (or any fields) to it to link form submissions to content.

EntityForms: Creating forms is easy, but the notification part is convoluted at best with complex but somehow simple data selectors (raw output?) for Rules. Also, the token support is spotty at best (or so I have come across). The prepopulate part worked perfectly, but can't seem to figure out if it is possible to send email based on an Email field or get entity reference tokens like \[entityform:field\_reference:author:mail\]. Doesn't seem to work in Eforms.

Webform: Can't get fields to prepopulate and hide/disable.

Custom: Thinking about just doing this. But I am unsure as to how I can add a entity reference field to a custom (non UI) created form and hide the form.

Can anyone recommend the best solution or at least which module is capable of what I need?

Thank you.

# Answer
> 0 votes
Consider looking at the Bean module. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

As a bonus, the Bean module also works great in combination with the UUID and UUID Features Integration modules.

On top of that, after you become familiar with the Bean module, you might find other cases in your site where you also want to use the Bean module.

---
Tags: 7, forms, webforms, entities, emails
---


# Question
Title: export views data to text file in the background
I am using views data export module to generate a text file and that works perfectly. but instead of asking me to save it to my local computer.

What I want to do is save it directly on the server, I would like to run this is the background if possible as large amounts of data take time to generate. Ideally I would like to run this for each user in the background on cron run so I presume I will need to setup some batch job to run.

# Answer
> 3 votes
Well, I think you can set a cron job on server. You just need to add a drush command in crontab file. Drush command :

```
drush views-data-export [view-name] [display-id] [output-file]

```

Views data export provides this drush command.

**Edit :**

1. If you don't have drush installed on your server then you can take the idea from code of `views_data_export.drush.inc`.

Or :

2. In simple way you can run the code following in hook\_cron :

$output = views\_embed\_view('ViewName', 'views\_data\_export\_1'); file\_unmanaged\_save\_data($Output , 'private://output.xls', FILE\_EXISTS\_REPLACE);

As per https://www.drupal.org/node/1875456#comment-7524421.

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


# Question
Title: Meta-Tag Module that can use existing fields
On my node, I have several existing fields, such as `field_introduction` and `field_book_tags`. These fields were created by me and do not come with Drupal by default.

I would like to know if there are any modules, which will let me use these fields for the Meta Description and Key word Tags.

The fields I need use for the meta tags will vary between content type, so the Meta tags solution must allow local overrides.

Here are some of the modules I have looked at:

Meta Tag, Custom Meta \- Allows use of default Drupal fields only

Meta Tag Quick \- Allows default Drupal fields only. Doesn't give much flexibility for selecting fields.

Simple Meta \- Doesn't support any existing fields.

Beanstag \- This allows the use of existing fields (via tokens). But, in order to target content types, a "folder" name has to be used in the URL (e.g. `mysite.com/news/my-news` for "news" content types, `mysite.com/info/my-story` for page content types). Although the folder name can be anything, I prefer my urls to be "folder" free (e.g. `mysite.com/my-news`)

It looks like BeansTag will have to make-do, but I thought I would ask in case anyone has better suggestions.

# Answer
You have to go to:

```
/admin/structure/types/manage/[YOUR CONTENT TYPE]/display/token

```

Then make sure:

* All fields are visible (not hidden)
* The format should be "default", but in some circumstances, you might need to set it to "plain".
> 1 votes

# Answer
It appears to me that the solution currently being worked on in issue 1838554 is going to be a valid alternative to consider ... At least in the long run (and after the issue status reaches status fixed).
> 1 votes

---
Tags: meta-tags
---


# Question
Title: How to restrict field formatter to selected fields?
I created new field *field\_csob\_srcode* in my custom code:

```
<?php
$field = array(
'field_name' => 'field_csob_srcode',
'type' => 'text',
'settings' => array(
  'max_length' => 4,
),
  );
 field_create_field($field);
?>

```

I would need to create custom formatter for this field. I am using such implementation of *hook\_field\_formatter\_info*

```
<?php
function mymodule_field_formatter_info() {
  $info = array(
'csob_webpay_description' => array(
  'label' => t('SRCODE - text description'),
  'field types' => array('text'),
  'description' => t('Displays text description of message from CSOB GP     WebPay'),
),
  );
return $info;
}

```

It works ok, but now, I see my new formatter as option at all fields settings, which have type = 'text'. Is it possible to restrict using of formatter, not only by field type, but also by field? When I try to set field in hook\_field\_formatter\_info:

```
'field types' => array('field_csob_srcode'),

```

then it does not work, formatter disappears from options in field display settings.

EDIT: I have not problem to set formatter for my field, I just need to restrict formatter ONLY for my field. So other text fields cannot use my formatter. So the formatter will not appear as option in selectbox, when selecting format for display

# Answer
> 0 votes
Use default formatter in your field implemention

```
$field = array(
  'field_name' => 'field_csob_srcode',
  'type' => 'text',
  'settings' => array(
  'max_length' => 4,
  ),
  'default_formater' => 'csob_webpay_description',
);

```

it should works.

---
Tags: 7, entities
---


# Question
Title: Devel dsm() function in Drupal 8 page.html.twig
Is Devel module's dsm() function available in page.html.twig? If it is not available, is there a way to make it available?

I am able to use dsm() in .theme file but not in page.html.twig.

I am aware of dump() function in .twig. dump() is similar to var\_dump() of php and the output is not as clean as Devel module's dsm() function.

Using dsm() or dpr() in page.html.twig causes error and site does not load.

# Answer
> 6 votes
Why not just do it in `hook_preprocess_page()` instead.

```
<?php
function MYMODULE_preprocess_page(&$variables) {
  dpm($variables);
}

```

# Answer
> 6 votes
The Kint submodule in Devel 8.x now provides Kint debugging functionality in Twig templates.

```
{{ kint() }}
{{ kint(variable_one, variable_two) }}

```

Enjoy! Screenshots and a bit more info here: https://drupal.org/node/2218949

And I want to add that I hope the contrib space in 8.x ends up with tons of debugging options, for example I'm looking forward to seeing Ladybug implemented!

# Answer
> 1 votes
Use twig method for debugging. first go to sites/default/services.yml

and set debug:true

then you can use twig method for debugging.

{{ dump(attributes) }}

---
Tags: 8, debugging, theming
---


# Question
Title: Views Filters: show published items from the last week or minimum number of items
The homepage on our local newswebsite "Zee-Online" has a view that shows al published content from the last week. How can i change this, to show at least a fixed number of items?

I want a view that gives me all the nodes from the last week OR at least 12 items (if the first filter-criteria doesn't result in at least 12 items)

# Answer
> 1 votes
Since you're trying to create a Views filter using an "OR" relationship, you might want to consider module Views Contextual Filters OR (which only has a dev version today). Excerpt from its project page:

> ... provides a views plugin which modify query to support OR conditions for contextual filters.

Does this help?

---
Tags: views
---


# Question
Title: Which core module provides the default send email action for use in rules?
There is a core module (might be related to core actions) that allows your to send an email via VBO. What is the name or where is that function located in core?

For e.g. When I am modifying the system mail settings, what "module" in core provides this functionality? (See screenshot)

# Answer
It appears to be a part of the system.module; precisely the system\_send\_email\_action() function.
> 0 votes

# Answer
There is no "module", at least not one that can be turned on and off like other modules. Emails are normally handled by drupal\_mail() and a bunch of other functions found in the `system.mail.inc` file under /modules/system and `mail.inc` found in /includes . These work together to create the framework, using templates that you can set up in order for other modules (like VBO) to actually send emails.

drupal\_mail():

> Sending an e-mail works with defining an e-mail template (subject, text and possibly e-mail headers) and the replacement values to use in the appropriate places in the template. Processed e-mail templates are requested from hook\_mail() from the module sending the e-mail. Any module can modify the composed e-mail message array using hook\_mail\_alter(). Finally drupal\_mail\_system()-\>mail() sends the e-mail, which can be reused if the exact same composed e-mail is to be sent to multiple recipients.
> 2 votes

# Answer
VBO gets those actions from rules.

The functions are into rules module:

PATH\_TO\_YOUR\_MODULES/rules/modules/system.rules.inc
> 1 votes

---
Tags: views
---