# Question
Title: Webform, let data expire after a period of time
How might I expire data collected in Webform? That is, I'd like to purge data after a period of 6 to 18 months.

Alternatively, I'd be happy to find a module that cleans up old data in a Drupal 7 database.

# Answer
Try the Webform auto-delete sandbox project.

> Automatically delete webform submissions after a set period of time.
> 1 votes

# Answer
You can try the Webform Scheduler module

also.

> It adds an optional start date and end date field to the webform form settings. If the current date and time falls outside the specified window, the webform is disabled.

or create a rule with Webform Rules
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: Wordpress Migrate Inline Images looking in wrong folder
I've recently used the Wordpress Migration module to bring over a lot of posts into drupal. The images get moved, and the text comes in fine. The problem is when the images get brought over they are put in one location on the server, but the inline media tags tell them to use view\_mode: media\_large the images don't show in the post because it's looking in the '/sites/default/files/styles/large/public' folder instead of where they actually got imported to. How do I either import these posts so that the images go there, or so that the media tags that are created don't look in the large folder but where the files actually are?

# Answer
Turns out the styles folder inside /sites/default/files was the only folder in there that was not writable by the server so it put the images elsewhere. I rolled back the wordpress import, fixed the permissions, and ran the import again. Everything seems to be good now.
> 1 votes

---
Tags: 7, migrations, media
---


# Question
Title: Drupal Commerce | Hide or set an alias to the order number in the checkout path
Is there any DC module or configuration that would allow me to set an alias for the order number that is shown on the checkout path.

i.e.

Instead of example.com/checkout/10

Something like example.com/checkout/order or just plain example.com/checkout

An alias module would have similar functionalities as the me module.

# Answer
> 0 votes
I just realized that my goal is not feasible because the system could not distinguish orders of an unique user who has more than one order in the system.

I will encrypt the order number bit by implementing hook\_url\_outbound\_alter() and hook\_url\_inbound\_alter().

# Answer
> 1 votes
I to went that road, did not want customers to see an on each order incrementing ID in URL's. In `hook_url_outbound_alter()` *any* path can be encrypted by altering the regular expression.

```
/**
 * Implements hook_url_inbound_alter().
 */
function mymodule_url_inbound_alter(&$path, $original_path, $path_language) {
  // Decrypt paths that are encrypted by our hook_url_outbound_alter() to hide possible id's in paths.
  if (preg_match('#^ENC:(.+)#', $path, $m)) {
    $path = _mymodule_mcrypt('decrypt', $m[1]);
  }
}

/**
 * Implements hook_url_outbound_alter().
 */
function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  // To hide id's in paths, we encrypt them.
  if (preg_match('#^checkout/.*#', $path, $m)) {
    $path = 'ENC:' . _mymodule_mcrypt('encrypt', $path);
  }
}

/**
 * Helper function to encrypt and decrypt strings, ie. paths to hide containing id's.
 * NB: We replace forward slashes for exclamation marks, otherwise trailing
 *     slashes in the URL will be ignored by Drupal.
 */
function _mymodule_mcrypt($action, $string, $key = null) {
  if (!$key) {
    $key = $GLOBALS['drupal_hash_salt'];
  }

  $mcrypt_method = MCRYPT_RIJNDAEL_128;
  $iv_size = mcrypt_get_iv_size($mcrypt_method, MCRYPT_MODE_CBC);

  // Make key exactly as long as long as $iv_size.
  $key = substr(str_repeat($key, CEIL($iv_size / strlen($key))), 0, $iv_size);

  if ($action == 'encrypt') {
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $encrypted_string = base64_encode($iv . mcrypt_encrypt($mcrypt_method, $key, $string, MCRYPT_MODE_CBC, $iv));
    return preg_replace('#/#', '!', $encrypted_string);
  }
  elseif ($action == 'decrypt') {
    $decrypted_string = base64_decode(preg_replace('#!#', '/', $string));
    $iv = substr($decrypted_string, 0, $iv_size);
    $decrypted_string = substr($decrypted_string, $iv_size);

    return rtrim(mcrypt_decrypt($mcrypt_method, $key, $decrypted_string, MCRYPT_MODE_CBC, $iv));
  }

  return false;
}

```

# Answer
> 0 votes
Hopefully there is a new Drupal module for that named Commerce\_Checkout\_Paths.

---
Tags: 7, commerce
---


# Question
Title: Drupal Commerce : Shopping Cart Checkout for Orders
What I'd like to do is have an order page where the user see's a list of all products.

They'll then fill out the quantities they want and click on 'checkout' .

So it'd look like how the Cart looks once you've added products

Has anyone done this or anything similar. I'm currently looking at using Drupal commerce on Drupal 7.

Much Appreciated.

# Answer
My initial thought is for you to check out the commerce\_add\_to\_cart\_extras module. Granted, it's still in its dev version, but you can create a view with products, specify quantity, and bulk-ly add to cart.

To go straight to checkout, you may need to add a little redirect in the submit handler for that button.
> 1 votes

---
Tags: 7, commerce
---


title: drush fails to install drupal properly

text:
# Question
Title: drush fails to install drupal properly
I installed Debian 7 in a VM, there is nothing there except for web server apache2, mysql, webmin, phpmyadmin, and drush.
Drush fails to install Drupal, gives me admin and password but it fails to log me in.
Error: Not Found
The requested URL /phurst/node was not found on this server. Apache/2.2.22 (Debian) Server at xx.xx.xx.xx Port 80
Weird thing is that it works flawlessly on my localhost, my computer is more advanced, I use Debian testing branch in it. I cannot figure out what is causing this, I added my user to group www-data, chowned web root (/var/www) to myuser:www-data.
I noticed that perms were not set, that is weird because drush set perms correctly, I set all perms on the site to 775 recursively, but I am still locked out of the admin area.
Another weird thing: I can install Drupal manually, but I need to use drush to go fast. Thanks in advance.

# Answer
Here is the answer to the riddle. My live VM is on an older version of Debian, different document root, different apache2.conf. It is much easier to edit apache2.conf in the newer version, and that is why it was working: Options Indexes FollowSymLinks

# AllowOverride None

```
AllowOverride All
Require all granted

```

In older version, I copied apache2.conf to something else and replaced Deny for Allow, like so: Order allow,deny Allow from all Satisfy all . Completely different, I am mulling to move server to testing version, in spite that everybody advices against it.
> 0 votes

---
Tags: drush, installation
---


title: View: Comparison taxonomy terms

text:
# Question
Title: View: Comparison taxonomy terms
I have a content type = news and 5 normal page. Content type news have 5 taxonomy term that the user can select and chose when write a news. Each of the 5 normal page have 1 taxonomy term on it.

I want do a view (block) that show only the news that have the same taxonomy term.

My previous solution was to do a view for each taxonomy term but i don't like it because i have 5 block.

Thanks

# Answer
> 1 votes
I believe that Contextual Filters are what you are looking for. The example should be pretty close to your use case from the sound of it.

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


title: Remove field data in submit function

text:
# Question
Title: Remove field data in submit function
Drupal 7. On form validate, I want to:

* check the value of one of the form fields \[field-1\]
* based on that value, completely remove another field \[field-2\] together with its values, from the form

If it makes any difference, \[field-2\] is a multiple-value entity-reference field.

I think I need to do something like --- get hold of $form\_state\['values'\]\['field\_2'\] and set it so that it is in the same state it is before any data was entered by the user.

Am I on the right lines? I haven't been able to find examples or documentation on this.

EDIT:

This is what worked for me in the end:

In the submit function (not the validate function):

```
// Start with a clean array for the field we want to change.
$form_state['values']['field_2'] = array();
// Restore the array values that correspond to 'empty' for this field.
// In my case this was as follows:
$form_state['values']['field_2']['und'][0]['target_id'] = '';

```

# Answer
Short answer is yes you are on the right track. Altering form values on validation can get a little tricky and complex depending on the form. You might want to check out form\_set\_value if you haven't already.
> 1 votes

---
Tags: 7, forms
---


title: use taxonomy for organic groups

text:
# Question
Title: use taxonomy for organic groups
To lock down access to nodes based on OG's, I have implemented a taxonomy as a group. The users can then can select that taxonomy and access level for each content. Is anyone aware of pitfalls I need to watch out for doing it this way?

I apologize if this is out of scope for this site.

# Answer
I apologize, but I am trying to do something similar.

OG\_Menus, taxonomy\_menu have seemed to provide a solution. nodeone.se provides a warning, it's unclear if it's been fixed or not. also look at simpleaccess and taxonomy access control.
> 0 votes

---
Tags: organic-groups
---


# Question
Title: Is there an automated way to create another multisite inside of an existing multisite Drupal install?
I have an existing instance of D7 in a multisite configuration on RedHat.

Can I use `drush si` to create a new database and /sites/ instance -- without altering any existing subsite? Is there a way to automate this?

I'm envious of Wordpress Networks' ability to spawn up a new site inside the admin console.

In my current process, I create a database on local systems.

```
mysql> create database nominations;
Query OK, 1 row affected (0.01 sec)

mysql> grant usage on nominations.* to nomnom@localhost identified by 'Sup3rS3cr3tP455w04d';
Query OK, 0 rows affected (0.00 sec)

mysql> grant all privileges on nominations.* to nomnom@localhost;
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;

Query OK, 0 rows affected (0.00 sec)

```

Sudo and edit the alias.conf file

```
$ sudo su
# vim /etc/httpd/conf.d/alias.conf

```

In that file add the alias. The current file reads as such. The idea is to point all aliases to the drupal root. Let drupal handle routing based on folder entries inside its /sites/ folder.

```
 Alias /nomination /var/www/html

```

Once this file is saved. Restart the server.

```
# service httpd restart

# exit

```

Now the database is created and apache has a new alias. Create a new folder inside of /sites/ in the fashion drupal routing will recognize (server.name.path). Create a symlink to make drush maintenance easier.

```
$ mkdir nomination
$ cp default/default.settings.php nomination/
$ cd nomination
$ mv default.settings.php settings.php

```

At this point I go to server.com/nomnination and run the typical install process. After and back on the command line, coordinate a bit of module goodness:

```
$ drush en -y coffee module_filter jquery_update bootstrap

$ drush dis -y overlay

```

# Answer
A lot can be done with just drush si:

--sites-subdir: install in a subfolder of /sites (defaults to 'default')

--db-url: if the database is not found, it will try to create the database

--db-su and --db-su-pw to supply a user who can create the database, but will not be set in settings.php

```
$ drush si --db-url=mysql://nomnom:Sup3rS3cr3tP455w04d@localhost/nominations --db-su=root --db-su-pw=dbrootpwd --sites-subdir=nomination

```

And then do the general module goodness.
> 0 votes

# Answer
If you configure multisite instances to use https://www.drupal.org/project/dslm, you can use a command like 'drush dslm-new mynewsite drupal-7.34' to provision a new site. @btopro has taken DSLM a step further calling DSLM and Drush commands from the CIS install profile to completely automate the process from within Drupal for Penn State and the growing number of schools using ELMS. This configuration allows schools to generate several new Drupal sites from different ELMS install profiles from a centralized Drupal site. \[This screencast\]\[1\] explains how the ELMS CIS implementation works. There is also a vagrant version of this configuration you can spin up from https://github.com/btopro/elmsln-vagrant

CU Boulder also uses a Drupal front end to DSLM to spin up new sites, but we don't use a true multisite configuration and our backend for this service is more complicated and CU specific leveraging Eve (http://python-eve.org) and F5 server (https://f5.com/products/modules/global-traffic-manager).

I doubt either of these solutions is a good fit for you out of the box, but if the "automated way" you are only looking for only needs to automated this process at a commandline level, DSLM will get you most of what you need. You can also use code from the ELMS CIS project to create your own front end.

If you looking for a graphical front end that works "out of the box", you might want to consider using the Aegir Project (http://www.aegirproject.org/) with an install profiles like Hostmaster (https://www.drupal.org/project/hostmaster). Installing Aegir on your own server can be complicated (http://community.aegirproject.org/installing/manual), but there are several hosted Aegir options. Converting an existing site to Aegir is also more complicated than DSLM. Aegir is really an "all in decision" while DSLM can be used along side existing, non-DSLM sites and includes a command to convert an existing site to use the DSLM symlink structure.
> 1 votes

---
Tags: multi-sites
---


# Question
Title: Create view to display a Gmap for locations on node you are currently viewing
I am using Gmap 7.x-2.9 and Location 7.x-3.6 on my Drupal 7.34 site. I have setup a custom content type for "Locations". So if I, for example, added a new Location called "California" I could add in all of our California locations so when I go to the California page, I will get a Gmap displaying all of our CA locations. I am currently using the default block that comes with the Location module and set it up to display in the content area for my "Locations" custom content type nodes. This works and it indeed displays markers for all of the CA locations. The problem is nothing happens when I click a marker. I would expect to get a popup bubble with the address information for the clicked location. I see nowhere in any of the configuration for that block to change this behavior. You just don't get a popup. SO I figured what I could do is make my OWN view block and set it up where the content type is Location and only display it on the Location content type nodes. This also works, but when I go to any Location node, like California for example, it displays ALL of my locations in the entire system (other states). I want it to only display the locations for the location node I am currently viewing. I am thinking contextual filters? I just can't seem to figure out the right combination of settings in the view to display locations for the location node I am currently viewing. If I could figure this out, I can use the settings in the view to add the popup and decide what goes in the popup when you click a marker.

Thanks in advance for any help on this one.

# Answer
> 0 votes
* Filter on 'Content: Nid' in contextual filters.
* Under 'WHEN THE FILTER VALUE IS NOT AVAILABLE', choose 'Provide default value' and 'Content ID from URL'

This will look for a node id in the url and filter your view on that id.

---
Tags: location, google-maps
---


# Question
Title: Point visitors to directory depending on Drupal site visited
I am in the process of completing a transition from my client's old sites to a Drupal installation with multiple sites (this is my first experience with Drupal). Some of their older migrated content contains links to files available for download, which were previously located at an address in a format like **firstsite.com/files/foo.zip**.

They are insistent that these links not be changed, but since all of their sites are now in the same installation and there is overlap between file names (multiple sites may have a foo.zip to download), they cannot simply put all of their files in a /files subdirectory of the root (as these links would deliver a visitor to).

Is there a way I could deliver incoming requests for /files to the public files directory of each site? For example, if **firstsite.com/files/foo.zip** is requested, take them to **/sites/firstsite.com/files/foo.zip**?

I have attempted using .htaccess matched redirects but these apply universally and I cannot seem to capture the part of the request that precedes /files/foo.zip, and am not familiar enough with RewriteCond/RewriteRule pairs to build a working set for each site. Does Drupal have inbuilt functionality for this kind of legacy adaptation, or are there specific .htaccess rules that are suited to this procedure?

# Answer
> 0 votes
If you used a drupal multi-site installation for the various websites. Then each site may have it's own dedicated `Files` directory which may be set in `Admin -> Media -> File System` per subsite.

# Answer
> 0 votes
.htaccess is the way to go, add this to your rewrite section for every domain you need:

```
RewriteCond %{HTTP_HOST} ^www.domain1.com$
RewriteCond %{REQUEST_URI} ^/files
RewriteRule ^files/(.*) sites/folderofdomain1/files/$1 [R]

```

---
Tags: redirection, .htaccess, files
---


# Question
Title: Priority of execution of hooks in different modules
Let's say that there is a contributed module installed in Drupal 7. It alters a SQL statement from the core. Now I have a custom module of my own which alters the same SQL statement in a different way. Now, depending on the alteration, I could have different SQL strings depending on which module hook applies before the other. For example, the first hook deletes a table "field" and the other adds the same table "field". If the first hooks executes earlier, the final SQL has the field added. If it is now the second hook which executes earlier, the extra field is added and later removed, so the SQL is completely different. How can I now the priority, any other conflicting issues and is there a way to override this apparent difficulty?

# Answer
The system table has a 'weight' field. The hooks are executed in that order.

You can change during install with this code:

```
function your_module_name_install() {
  db_update('system')
    ->fields(array('weight' => your_preferred_weight))
    ->condition('name', '[your_module_name]', '=')
    ->execute();
}

```

Source: https://www.drupal.org/node/110238
> 2 votes

---
Tags: 7, database
---


# Question
Title: Using migrate module to import to a list_boolean field
I'm trying to use the migrate module to import data from a mysql table to Drupal 7. I've created a content type with a field type of boolean and used "single on/off checkbox" as the widget. So in the migration destinations the field is (list\_boolean).

The data in the database is integer (0/1).

I set the field mapping: $this-\>addFieldMapping('field\_my\_event', 'my\_event');

However, none of the 1's get stored as 1 in the field\_my\_event table when migrated.

I tried also forcing the value to a boolean value of TRUE/FALSE in the prepareRow hook, but that didn't make a difference.

versions I'm working with: Drupal 7.33 and Migrate 7.x-2.6-rc1

Can someone steer me in the right direction?

# Answer
> 0 votes
See this comment on this issue: https://www.drupal.org/node/1729996#comment-9511751

"I found a way to import, you must set the "on" and "off" values.

I went to my field in my content type and set the "on" value to 1 and the "off" value to 0.

In the migration mapping I made a callback function for this field and convert my true value to 1 and the false value to 0, you could do this instead creating a new feature.

This way worked perfectly here.

I don't know if it is a really necessary feature."

---
Tags: migrations
---


title: "More like this" for a view

text:
# Question
Title: "More like this" for a view
I know how to get a "more like this" block for an individual piece of content (as a block in a panel, or whatnot), however these functions don't seem to work with the results of a View.

My site has a few pages that list the content of a specific taxonomy term (Industry). Each content type listed has an additional taxonomy term associated (Focus Area).

The view that is presented on the site allows the visitor to select the Focus Area, which when selected, limits the content on the page to matched terms.

I'm trying to get a "more like this" block for the results of the view. There may be other content that matches the Industry and Focus Area (such as an Event or a Career) that we would like presented.

Bonus points if you can help me make the Focus Area selection persistant across the site (so that when the visitor navigates to a different Industry page, their selection for Focus Area is remembered and applied).

Use of Solr is a possibility as well. We haven't turned it on while in development, but is part of the plan.

Thanks in advance.

# Answer
I think what you are looking for is https://www.drupal.org/project/global\_filter. There is a good README on how to use it: http://drupalcode.org/project/global\_filter.git/blob\_plain/refs/heads/7.x-1.x:/README.txt
> 1 votes

---
Tags: 7, views
---


title: Can't disable or enable any module

text:
# Question
Title: Can't disable or enable any module
I recently moved a project from one server to another. the server is running on nginx.

I noticed some issues like that I cant upload any picture to ckeditor using imce module (I can upload images via filefield) then while trying to fix this issue I encountered this problem that I cant enable or disable any module.

It's like when I check/uncheck a module and hit submit on module's list page, it refreshes but nothing change afterwards.

the other thing is Im running another website on this server with the same version of drupal and it just works fine, I wonder what could be wrong? is it a server issue or a drupal problem?

I'd really appreciate any help and tips.

# Answer
Well I tried alot of approaches, the last thing that I would think of was the solution, it was because clean-url , I just enabled it in server and it start working just fine again.
> 3 votes

# Answer
Enabling `mod_rewrite` solved this problem for me.

Here is a link for how to enable it: https://stackoverflow.com/questions/869092/how-to-enable-mod-rewrite-for-apache-2-2
> 0 votes

---
Tags: 7
---


# Question
Title: How to create variations in commerce file?
I am creating a ecommerce site selling downloads. Currently, I am trying to get product attributes to work with commerce file. I have created a select list taxonomy for operating systems, so the user uploading the file would be able to select operation systems. I need a way for users to be able to upload different files depending on operating systems they selected, for the same product. Thanks in advance! (I am using a normal Drupal with commerce installed I.e. Not kickstart 2, just a standard Drupal installation)

# Answer
The set up should be: a single product display whose product reference field has both the (I'm assuming) Windows file and Mac file. The relevant product attribute being that taxonomy term. So, in your product type, place that taxonomy term. It sounds as if you put that taxonomy term on your product display, which is a node type. Note: products entities = variations in Kickstart 2. Products I believe refer to product displays.
> 0 votes

---
Tags: commerce
---


title: How to get the base url?

text:
# Question
Title: How to get the base url?
(Drupal 7.22) We need to create a menu link to an external site, "https://example.com/some/path" `/some/path` is static, whereas "https://example.com" depends on site instance, such as

web-dev.example.com

web-qa.exmple.com

web-rc.example.com

I would think that this could be accomplished with `$GLOBALS['base_root']`; for example: `$url = $GLOBALS['base_root'] . '/some/path';`

On local (laptop) `$GLOBALS['base_root']` resolves correctly, but on CentoOS `$GLOBALS['base_root']` resolves to `[http://default]`

How do we dynamically get the actual current site domain?
This can't be so hard, what are we missing?

# Answer
> 9 votes
If this is a fully bootstrapped Drupal site, the superglobal `$base_url`, should get you what you want. See: https://api.drupal.org/api/drupal/developer!globals.php/global/base\_url/7

However, these globals are not initialized until Drupal is fully bootstrapped.

If you need to sniff the base URL before Drupal is fully bootstrapped you can use the PHP `$_SERVER` superglobal.

For example:

```
function _get_base_url(){
  $protocol = ($_SERVER['HTTPS'] && ($_SERVER['HTTPS'] != "off")) ? "https" : "http";
  return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

```

# Answer
> 1 votes
For the case when Drupal is fully bootstrapped, that is when `$base_url` works, the `url()` function is a potentially more elegant alternative:

```
$make_absolute = array('absolute' => TRUE);
$url = url("some/path", $make_absolute);

```

---
Tags: uri
---


title: delete a product that added to an order

text:
# Question
Title: delete a product that added to an order
I want to delete an order,but when I try to delete it notify me "This product is referenced by a line item on Order 40 and therefore cannot be deleted. Disable it instead" but I want delete it completely in my product list, It is not important delete an order item that is used in.

# Answer
Commerce is protecting its own data integrity - if you were able to delete a product that's referenced by an order line, the next time you view the associated order something would break.

You'll need to remove the product from all associated orders before deleting it; I think the easiest way to do so would be to construct a View using Views Bulk Operations, select Line Items filtered by the relevant product ID, and bulk delete them. Obviously this will have an effect on existing orders, but since the product is attached to the line item by its ID, there isn't really an alternative (short of rewriting a bunch of stuff in Commerce).
> 6 votes

# Answer
I have also run into this problem with test products during a site build, and/or products in a large dataset that needed to be deleted post-import. Once the product is associated with orders or nodes, it is painful to get rid of them. Even after orders or shopping carts are deleted, the database records remain. Even Views Bulk Operations will not get around those.

So, here is my **Product Removal Toolkit**:

Install the fantastic module: https://www.drupal.org/project/commerce\_prodnodelink

This will put a very handy box on your product pages that will tell you what node the product is referenced on so you don't have to go searching for it. Use the info there to delete the product references.

Now you have to go into the DB and do some SQL queries:

1. commerce\_line\_item table:

delete from commerce\_line\_item where line\_item\_label = '*the-sku-of-the-product-here*';

2. field\_data\_commerce\_product table:

delete from field\_data\_commerce\_product where commerce\_product\_product\_id = '*product-id-of-the-product-entity*';

3. field\_revision\_commerce\_product table:

delete from field\_revision\_commerce\_product where commerce\_product\_product\_id = '*product-id-of-the-product-entity*';

Once you do these things, you should be able to delete that product!

Now, if you really have a lot of items to get rid of, you could make arrays with your errant line item data and funnel it all through a PHP function. :P
> 3 votes

---
Tags: 7, commerce
---


title: Replace Standard Node Path in Drupal 8

text:
# Question
Title: Replace Standard Node Path in Drupal 8
I am still new to all the Symfony semantics. What would be the easiest way to change node canonical urls to be `/article/[node-title]` instead of `/node/[node-id]`? Following this documentation I tried the code (which I expected to produce at least a url structure like `/article/[node-id]`)

```
<?php
/**
 * @file
 * Contains \Drupal\example\Routing\ExampleRoutes.
 */

namespace Drupal\example\Routing;
use Symfony\Component\Routing\Route;
/**
 * Defines dynamic routes.
 */
class ExampleRoutes {

  /**
   * {@inheritdoc}
   */
  public function routes() {
    $routes = array();
    // Declares a single route under the name 'example.content'.
    // Returns an array of Route objects.
    $routes['entity.node.canonical'] = new Route(
      // Path to attach this route to:
      '/article/{node}',
      // Route defaults:
      array(
        '_controller' => '\Drupal\node\Controller\NodeViewController::view',
        '_title' => 'Hello'
      ),
      // Route requirements:
      array(
        '_permission'  => 'access content',
      )
    );
    return $routes;
  }

}
?>

```

But unfortunately it is not changing anything…

# Answer
While theoretically now supported, that is not possible not like this.

You can not reliable load a node based on the node title, it is not guaranteed to be unique, and to become a practical URL, a number of replacements should be made, like replacing spaces, lowercasing it and so on.

Use the path alias system for this, just like in Drupal 7. We're maintaining an inofficial port of the pathauto module, that allows you to configure token patterns to automatically generate an alias for each node. You also need token.module, which you can get from here.
> 2 votes

---
Tags: nodes, uri, 8
---


title: Meta tags on Drupal blog home page

text:
# Question
Title: Meta tags on Drupal blog home page
How can I overwrite meta tags on the Drupal blog homepage? I'm using a "Blog" module ( which creates a blog homepage with the URL www.mysite.org/blog ) and a "Metateg" module for generating and overwriting title, description and keywords meta tags. The problem is that I can't find a way to overwrite the default generated meta tags for the blog home page since Metatag module doesn't provide this functionality. Is there any other way to do it?

# Answer
You need to use the metatag\_context sub module of Metatag, which means you need the Context module.

I was thrown for a loop on this as well. It'll create a default Context for a few of these oddball situations. Your metatag information is then controlled through Context.

See source for export handling blog: http://cgit.drupalcode.org/metatag/tree/metatag\_context/metatag\_context.context.inc#n251
> 2 votes

---
Tags: meta-tags, nodes
---


title: Hook into Panels content form submit

text:
# Question
Title: Hook into Panels content form submit
I'm writing a routine to track inline image usage in panel panes every time the panels content form is submitted. The *hook\_panels\_pane\_update* hook works, but only after the second time the form is saved. Is there a hook that will trigger the first time the form is saved?

# Answer
Correct, according to the `panels.api.php` file, hook\_panels\_pane\_update() is for *changed* panes. There's one just above it for new panes called hook\_panels\_pane\_insert().

If you want the same function to happen every time regardless of whether the pane is new or not, combine them like this:

```
function mymodule_panels_pane_insert($pane){
  mymodule_act_on_panels($pane);
}

function mymodule_panels_pane_update($pane){
  mymodule_act_on_panels($pane);
}

function mymodule_act_on_panels($pane){
  //Do the things here
}

```
> 1 votes

---
Tags: hooks, panels
---


# Question
Title: How to manage editing and publication of content
The scenario is this:

1. Content is created or edited:

At that point, the content should be marked or moved to a state of "edited" If the content is new, it should not be published. If it is an existing node, it the **ORIGINAL** version should **REMAIN** published until it is "approved".

2. Content is approved:

If the approved node is preexisting, the edited version replaces the old version. Otherwise, it is new content and it is moved from not published to published.

I'm looking for suggestions on how to accomplish this. My hope was to use the module *Workflow* and integrate it with *Triggers*.

So far, I'm not seeing an obvious path to making this work as described above.

# Answer
I think you're looking for the Workbench Moderation module. From the project page:

> Workbench Moderation adds arbitrary moderation states to Drupal core's "unpublished" and "published" node states, and affects the behavior of node revisions when nodes are published. Moderation states are tracked per-revision; rather than moderating nodes, Workbench Moderation moderates revisions.
> 4 votes

# Answer
You can also try the Revisioning module which describes itself:

> ... for the configuration of workflows to create, moderate and publish content revisions. You use it in scenario's like this:
>
> Authors write content that prior to being made publicly visible must be reviewed (and possibly edited) by moderators. Once the moderators have published the content, authors should be prevented from modifying it while “live”, but they should be able to submit new revisions to their moderators.
> 3 votes

---
Tags: workflows, nodes
---


# Question
Title: Multisite or multiple sites setup with Open ID server
I am working on a project where I have a basic site with a sets of modules and configurations. Currently when I get a new client for this project in order for him/her to use their own site, I setup a subdomain, load a basic DB and copy the basic site files over.

This setup has work for me, but now I am having to deal with more clients and the manual process will just make it hard to manage and maintain. Ideally I will love to have it a single set of files will connect each user DB and I don't care if instead of subdomains (they are nicer) I have to use sub-directories.

What will be best for this setup multisite or multiple sites, and will it make sense to have a centralize account (open id) server?

> **Note:** I was thinking in register the users in a single place and then they can login into their private sites using this centralize account system. Otherwise each site will have to have a user 1 account with a password to be manage for each site.

Thank you

# Answer
> 1 votes
I use multisite to run about 50 Drupal sites from a single code base, but each site has its own database.

To be able to manage all the site, I use the Drupal Remote Dashboard Server module and its corresponding Drupal Remote Dashboard module. These modules let me out all the servers into maintenance mode, or run update.php.

# Answer
> 1 votes
I think multisite would work well if you're keeping all of the same code. I know you can do it with subdomains (or even completely different domains) using the sites.php file, I'm not so sure about sub-directories.

Have a look at the Features module which will allow you to import all of your standard settings as a single module on new sites.

---
Tags: 7, multi-sites, authentication-authorization
---


# Question
Title: Views Load More: Showing X number of item initially
I have a view which shows 6 items per page using Views Load More (Ajax). However what I would like to do is, on the very first page I would like to show 6 items and when clicked on Load More button it should show 3 items and so on. Is it possible?

# Answer
> 1 votes
Well you could use this workaround.

Have a view with the initial 3 (#1-3). Then add another view below it with an offset of 3, so it shows #4-6. Thus, it will load 3 rows at a time.

You could just show the views back to back on the page or you could use the Insert View module, and have it load the #1-3 view at the header of the 2nd view.

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


# Question
Title: Panels Everywhere and missing Page Title
I am new to using Panels Everywhere and noticed that once I applied PE to my site the page titles went missing. I have site name and slogan and such set up. I can't figure out where the problem is. Has anyone run across this before?

# Answer
> 1 votes
I think page title is a pane you can add to your PE master.

In the region you want to put it:

Add content -\> Page elements -\> Page title

---
Tags: panels
---


title: Insert an ad into Views Grid?

text:
# Question
Title: Insert an ad into Views Grid?
I'm using the Views Grid layout and I'm looking for a way to place Google Adsense ads randomly within the grid. Here is the code in views-view-grid.tpl.php:

```
<?php if (!empty($title)) : ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<table class="<?php print $class; ?>"<?php print $attributes; ?>>
  <?php if (!empty($caption)) : ?>
    <caption><?php print $caption; ?></caption>
  <?php endif; ?>

  <tbody>
    <?php foreach ($rows as $row_number => $columns): ?>
      <tr <?php if ($row_classes[$row_number]) { print 'class="' . $row_classes[$row_number] .'"';  } ?>>
        <?php foreach ($columns as $column_number => $item): ?>
          <td <?php if ($column_classes[$row_number][$column_number]) { print 'class="' . $column_classes[$row_number][$column_number] .'"';  } ?>>
            <?php print $item; ?>
          </td>
        <?php endforeach; ?>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

```

Is editing the template file the correct way to do this? I'm not a programmer so a lot of this is beyond me but I am willing to learn.

# Answer
> 1 votes
Nice attempt, but no the template file is not the best place for that.

I would work on including the ads in your View result rather than trying to hack the template file.

Does your view show rendered content? Easy, make a new content type that contains your ads and include that content type in your filter.

Does your view show fields? Same thing, just make sure the ad content type has the same fields as the content you're showing in the grid.

# Answer
> 0 votes
The template is the correct place to print it. However, you should just print a pre-populated variable in the template, and actually populate the variable in a preprocess function for the template.

First, you need to rename your views-view-grid.tpl.php by using an appropriate suggestion, unless of course you want your code to run on every view of grid format.

Your preprocess function will be named HOOK\_preprocess\_views\_view\_grid. The same preprocess function is used for all suggestions of the template. In this preprocess function you will need to test the view object's name and display\_id so that it runs for your specific view (unless of course you want it to run on all views of format grid). Then you need to add a variable containing a single/array of Google Adsense scripts/html you want to include.

You then print the already populated variable in your template (if it is an array you will have to print individual items).

Install devel module and use dpm statements in your code to help you drill down into the structures.

Another possible way to add your adds into the output of a view is hook\_views\_pre\_render, or hook\_views\_post\_render if you are prepared to do some search and replace on the assembled views string. This last option might actually be the easiest as you will get all occurrences of a pattern (`</tr><tr`), select a few randomly, then replace it (`</tr><tr><td colspan="X">adcode</td></tr><tr`)

---
Tags: views, advertising, theming
---


# Question
Title: Group Audience field in Group Content does not show any values other than None
I am a OG newbie and followed examples and created a new content type called "Team" and a new content type called "Item" and associated it as a Group Content Type for "Team".

I created a new "Team" called "Team 1" and when I try to create a new "Item", in the Group Audience field I only see "None" as an option. When I change the Group Audience field setting in "Item" to "Select List" instead of "OG Reference", I see the "Team 1" as part of the list.

The problem is that this workaround is not sufficient because I want to get the "Create Item" link in the Team's page using Entity Reference Prepopulate module. However, not having it as "OG Reference" causes issues with using entity reference pre-populate field setting for the Group Audience field (getting an AJAX 500 error when I select entity reference pre-populate checkbox).

Any idea what I am doing wrong? I am using OG 7.x-2.7, Entity Reference 7.x-1.1 and Entity Reference Prepopulate 7.x-1.5

# Answer
> 0 votes
Making sure the Group is published solved the issue for me.

---
Tags: 7, organic-groups, entities
---


# Question
Title: How 2 set up a bunch of modules for sell per node access?
I need to sell some nodes on my site, not type of content (subscription alredy exist) - only per node acess. I think, that it is not cost-effective to create type of content for every good, cause number of goods can reach 100 units per day. I know, that https://www.drupal.org/project/uc\_node\_access can resolve my trouble, but I develop my site under 7 version of Drupal, and uc\_node\_access for 7 has only sanbox now. Dear experts, help me if u can, I'm not a professional developer. P.S. - sorry if my post has grammar mistakes, I'm Russian.

# Answer
I have done it successfully. Resolving my problem on https://www.drupal.org/node/2407311
> 0 votes

---
Tags: ubercart, users
---


# Question
Title: Workflow for Entity relationship / relations
I have a content type called Blog. I want the end users to be able to add new relations between the blogs, so that we can build a network of related blogs. But the challenges I am facing are

1. Users should be able to add the relations without having the access to edit blogs.
2. The relations(references) added by the users should be monitored. I need to have a workflow around it. Eg : If more than 2 users with the role moderator upvote this relations/reference then it should become public.

I have searched quite a bit for workflow and entity relationship but nothing worthwhile seems to come up. Currently the only option seems to be a combination of relations and workflow module. I haven't used in relations in any projects earlier and would try to avoid it if possible.

Any suggestions or inputs are greatly appreciated. TIA

# Answer
How about a content type with two Entity Reference fields? One for each of the two blogs.

Each node of that content type will then be a connector, and you can use the workflow module or perhaps Workbench Moderation to manage the connections.
> 0 votes

---
Tags: 7, workflows, entities
---


title: Create Content Type from code

text:
# Question
Title: Create Content Type from code
Following this post: http://www.sitepoint.com/creating-a-new-drupal-node-type/

I have tried to create a custom content-type from code like here:

**Update code** https://github.com/jmvelasco/drupal

But the way, after install/activate it I get these warnings:

```
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 270 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 274 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in FieldInfo->getField() (line 291 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 270 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 274 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in FieldInfo->getField() (line 291 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 270 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 274 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in FieldInfo->getField() (line 291 of /users/gen00/web/html/modules/field/field.info.class.inc).

```

Although the content-type is apparently created.

**EDIT the content could be created once I update the base value**

But when go to Create Content of this new content-type, I have the following error

```
array
  'error' =>
    array
      0 => string '<em class="placeholder">Warning</em>: Missing argument 3 for node_form(), called in /users/gen00/web/html/modules/node/node.pages.inc on line 161 and defined in <em class="placeholder">node_form()</em> (line <em class="placeholder">107</em> of <em class="placeholder">/users/gen00/web/html/modules/node/node.pages.inc</em>).' (length=324)

```

Also, when uninstall the module I get this notice:

```
Notice: Trying to get property of non-object in content_access_node_type_delete() (line 524 of /users/gen00/web/html/sites/all/modules/contrib/content_access/content_access.module).

```

I can't figure out where is my mistake and I have come here wondering if any drupal-ninja could help me to understand my mistake and create this content-type correctly. Anyone?

Thanks in advance.

# Answer
> 0 votes
The errors are produced inside the file **slider.install**, line 99, replace:

```
 if (!field_info_field($field)) {
            field_create_field($field);
}

```

By

```
field_create_field($field);

```

The reason is that the function **field\_info\_field()** calls to `$cache->getField($field_name);`

For more information, go to Drupal: field\_info\_field()

# Answer
> 0 votes
In your hook\_node\_info, 'base' should not be node. It has to be something else and generally your module name is advised.

Explanation from the node\_example.module

```
// 'base' tells Drupal the base string for hook functions.
// This is often the module name; if base is set to 'mymodule',
// Drupal would call mymodule_insert() or similar for node
// hooks. In our case, the base is 'node_example'.

```

# Answer
> 0 votes
Can you use features module - Drupal.org/project/features ? It will be very easy for you to export the content type in code.

---
Tags: nodes
---


# Question
Title: Can drush show list all available modules?
With yum you can do `yum list available ...`, and know the name of the package you want to install.

For example, there is the Mime Mail module in Drupal. What name should I use with `drush dl`, mime\_mail, or mimemail?

So does drush have something like `yum list available`?

# Answer
No, drush can't do that.

Why should it when you can see the entire list yourself on drupal.org.
> 10 votes

# Answer
Yes, you can. based on this feature request, I build the functionality, and created a sandbox module.
> 9 votes

# Answer
Correct me if I'm wrong but I think you should use the last segment of the URL When I was trying to find out what to use for the "Redirect 403 to User Login" module Example: http://drupal.org/project/r4032login

use: drush dl r4032login
> 0 votes

# Answer
```
function get_list_of_drushable_modules(){
$url = "https://www.drupal.org/project/project_module/index";
$content =  get_url_data($url);
$start = '<div class="view-content">';
$end ='</ol>';

$start_i = strpos($content,$start);
$content = substr($content,$start_i);

$projects = explode("</li>",$content);
$new_projects = array();

foreach($projects as $i => $project){
    $st = '<a href="/project/';
    $strlen = strlen($st);
    $st_i = strpos($project,$st);
    $project = substr($project,$st_i+$strlen);
    $project_character = str_split($project);

    $new_project = "";

    foreach($project_character as $char){
        if($char == '"') break;
         $new_project .= $char;
    }

    $new_projects[] = $new_project;
}

return $new_projects;
}

function get_url_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

```
> 0 votes

# Answer
No drush does not have this feature
> -1 votes

---
Tags: drush
---


title: Drupal commerce "family group"

text:
# Question
Title: Drupal commerce "family group"
Is there a way to create "familly group" in drupal commerce, like with an image and a description ( looks like a product ) and when you select it in shop you've got a list with all the product with this image in different shape ( with price, ... )

I guess there must be a module for that, i don't think this is very special.

If someone know what I can do, please tell me.

Thank you

# Answer
> 1 votes
I think what you are talking about is the concept of product variations introduced by Commerce Kickstart 2.0. Product variations allow you to group together commerce products based on choices like size and color and price. So for example say you create a Product Variation Type called T-Shirt. You can group together the different sizes.

There are a few ways to get this done. You can install Commerce Kickstart 2 and follow their tutorials.

You can install their stand alone module called commerce\_backoffice and its dependencies. I recommend the book Getting Started With Drupal Commerce by Richard Jones for an explanation of how to use back office.

As a note, I started out trying to get all of the functionality I wanted from the stand alone, but found that it was better to use Commerce Kickstart 2.0

---
Tags: commerce
---


# Question
Title: AutoSKU and Commerce Kickstart 2.0 or Commerce backoffice
I would like to use the AutoSKU module with the functionality provided by commerce backoffice. Right now what I have done is installed the module commerce\_backoffice with my commerce module which is the functionality from Commerce Kickstart 2.0 from my understanding.

I then installed the AutoSKU module. However, since the software design has changed there are no longer product types, there are product variation types. It doesn't seem that AutoSKU works with the new functionality.

Has anyone ported AutoSKU to work with Commerce Kickstart 2.0?

# Answer
The AutoSKU that works with product variations is part of Commerce Kickstart 2.0. You will have to enable the module of AutoSKU once you have installed Commerce Kickstart 2.0.
> 0 votes

---
Tags: commerce
---


# Question
Title: Public and temporary files error in my "Status Report"
I just upgraded to 7.25 from 7.19, and now in my Status Report I have a red X on my "Public Files" and "Temporary Files".

> See http://drupal.org/SA-CORE-2013-003 for information about the recommended .htaccess file which should be added to the sites/default/files directory to help protect against arbitrary code execution.

I go to the address above, but I don't have any user friendly explanation of what to do to fix this. Thanks in advance.

## Update: (1/8/14)

The answer below fixes the `Public files` problem 100%.

It does not fix the `Temp files`. To fix temp files, I go to `admin/config/media/file-system` and change the path from `/tmp` to `../tmp`

I will update this if this is fixed in a newer version of drupal, or if there is another fix available. I'm not sure if the `../tmp` is the correct solution, but it works.

# Answer
> 7 votes
The easiest method is in the fine print. If you haven't edited these files, then

* browse to admin/config/media/file-system
* delete sites/default/files/.htaccess
* delete wherever/your/private/files/are/.htaccess as indicated on the page you just browsed to
* delete wherever/your/tmp/files/are/.htaccess as indicated on the page you just browsed to
* click **SAVE**

This will recreate the two .htaccess files. Then visit the status report and double check things.

Otherwise, edit sites/default/files/.htaccess to be

```
# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

and wherever/your/private/files/are/.htaccess and wherever/your/tmp/files/are/.htaccess to be

```
Deny from all

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

Note the difference on line 1 for the private files. This is what prevents files from being browsed to from the outside world. It is also beneficial to place your private and tmp file directories outside your DOCROOT if you can, as an added precaution.

# Answer
> 0 votes
At first Create a folder "tmp" in sites/"default or whatever/files/". Then Go to Drupal admin "admin/config/file system" and update Temporary path with your tmp directory path.

That's it.

---
Tags: 7, files
---


# Question
Title: How to define multiple blocks in a module?
Thanks to this tutorial, I cam up with this block-generating module:

```
function myblockmodule_block_info(){
    $block['myadblocks'] = array(
        'info' => t('My first ad blcoks'),
        'cache' => DRUPAL_NO_CACHE,
    );
    return $block;
}

/**
 * Define what our block is going to look like.
 * Implements hook_block_view().
 */
function myblockmodule_block_view($block_key){
    $block = array();

    if($block_key == 'myadblocks'){ //We only want to define the content of OUR block
        //This is the title of the block.
        $block['subject'] = t('First ad block comes here');

        //Define the block content.
        $block['content'] = 'some fancy script comes here';
    }

    return $block;
}

```

I am wondering how to extend the module to create 2 blocks instead of one?

# Answer
Simple as:

```
function myblockmodule_block_info(){
    $block['myadblocks'] = array(
        'info' => t('My first ad blcoks'),
        'cache' => DRUPAL_NO_CACHE,
    );

    $block['myadblocks2'] = array(
        'info' => t('My second ad blcoks'),
        'cache' => DRUPAL_NO_CACHE,
    );
    return $block;
}

/**
 * Define what our block is going to look like.
 * Implements hook_block_view().
 */
function myblockmodule_block_view($block_key){
    $block = array();

    if($block_key == 'myadblocks'){ //We only want to define the content of OUR block
        //This is the title of the block.
        $block['subject'] = t('First ad block comes here');

        //Define the block content.
        $block['content'] = 'some fancy script comes here';
    }
    elseif ($block_key == 'myadblocks2') {
      $block['subject'] = t('Foo');
      $block['content'] = 'var';
    }

    return $block;
}

```

And clear the caches.
> 2 votes

# Answer
```
function myblockmodule_block_info(){
    $blocks = array();
    $blocks['myadblocks'] = array(
        'info' => t('My first ad blcoks'),
        'cache' => DRUPAL_NO_CACHE,
    );
    $blocks['myadblocks2'] = array(
        'info' => t('My second ad block'),
        'cache' => DRUPAL_NO_CACHE,
    );
    return $blocks;
}

/**
 * Define what our block is going to look like.
 * Implements hook_block_view().
 */
function myblockmodule_block_view($block_key){
    $block = array();

    if($block_key == 'myadblocks'){ //We only want to define the content of OUR block
        //This is the title of the block.
        $block['subject'] = t('First ad block comes here');

        //Define the block content.
        $block['content'] = 'some fancy script comes here';
    } elseif ($block_key == 'myadblocks2') {

        $block['subject'] = t('Second ad block comes here');

        $block['content'] = 'some fancy script comes here';
    }

    return $block;
}

```
> 2 votes

---
Tags: 7, blocks
---


title: Social links for each user

text:
# Question
Title: Social links for each user
I am looking a module which will give each user an option to create links to various social networks profiles they have.

I found Follow module but for D7 it says it is very unstable.

# Answer
For the profile part, you can just use the profile2 module. It allows you to add any kind of field to user profiles. Install it, enable it, clear caches, and go to structure \> profile types. For the actual fields, you might want to use the url field module, to enable validation of urls, etc. You can then create all the url fields you want, and give them appropriate names, like "facebook page", "twitter page" etc.

To display a block on nodes authored by the user, you could do the following:

* Create a view of profiles.
* Create a block display for the view
* Choose fields (your social media link fields)
* Click on advanced and then "contextual filter"
* Add "profile: user uid" as a contextual filter and click 'apply'
* Under "When the filter value is NOT in the url", select "Provide default value"
* Select "PHP code"
* Paste in the following PHP:

$node = menu\_get\_object(); return $node-\>uid;
* Click "apply" and then save your view.

You can now add your block to the content types your users are allowed to create.
> 0 votes

# Answer
I think you can use Social media module. It has functionality to allow each user to link to their own social media profiles.
> 0 votes

---
Tags: 7
---


# Question
Title: What should a bilingual site look like from the backend?
Suddenly I have lost track on my new build D7 German/English site. Nothing I attempt seems to work. I will tell more about the problems below but I think its hard to help me there as long as I am not sure if the base is correct. So, my concrete question is:

How should the mainmenu of a bilingual D7 site look like, i.e. is there only one main menu and the translations of the links can just be seen after clicking on them?

```
Home
About Us
-Team
-Jobs

```

Or should there be a menu tree for German and another one for English?

```
Home
About Us
-Team
-Jobs
Start
Über uns
-Mitarbeiter
-Karriere

```

(Both is possible and I am still strugelling to understand if this is a bug or a feature. See Why are there so many different ways to translate menus?)

Well, here are some of the problems I thought I overcome and which now seem to be everywhere on my site:

1. Sometimes, a translated site appears as an item on its own in content list, sometimes the translation seems to be stores in the main language item.
2. On some pages I may not click on English although there exists a translated version of the site although it should be linked as far as I see.
3. If a link works, the bread crump path differs from the real path:

German:

```
Start / Über uns / Karriere

```

English:

```
Home / Jobs

```

# Answer
I figured out that a correct localized main menu should be bilingual or multilingual and therefore look like this:

Home About Us -Team -Jobs Start Über uns -Mitarbeiter -Karriere Infographic (EN: Infographic, DE: Infografik)

The possibility to save localizations inside of the node (my possibiliy 1 in the question) are for pages that are not necessary to translate (e.g. they show only a infographic, as in my example above) but the links pointing to them.

Hope this helps other people with this question.
> 0 votes

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


# Question
Title: Is this block safe from code injection exploit?
Thanks good people here, I have create a simple module which generate two blocks as follows:

```
function myblockmodule_block_info(){
    $block['myadblocks'] = array(
        'info' => t('My first ad blcoks'),
        'cache' =>  DRUPAL_CACHE_GLOBAL,
    );

    $block['myadblocks2'] = array(
        'info' => t('My second ad blcoks'),
        'cache' =>  DRUPAL_CACHE_GLOBAL,
    );
    return $block;
}

/**
 * Define what our block is going to look like.
 * Implements hook_block_view().
 */
function myblockmodule_block_view($block_key){
    $block = array();

    if($block_key == 'myadblocks'){ //We only want to define the content of OUR block
        //This is the title of the block.
        $block['subject'] = '';

        //Define the block content.
        $block['content'] = '<script>some ad js comes here</script>';
    }
    elseif ($block_key == 'myadblocks2') {
      $block['subject'] = '';
      $block['content'] = '<script>some other ad js</script>';
    }

    return $block;
}

```

My intention is to user these blocks instead of my current blocks that were volnurable to to script injection.

However, I am not sure the new module-based blocks will be more secure than the old admin-generated blocks. So appreciate your critical review of the module above.

# Answer
> Is this block safe from code injection exploit?

Essentially yes.

You're hardcoding the javascript, so there's no vector by which an attacker can inject code from the client side. This will of course change if you're interpolating variables into the JS code that have come from a potentially insecure source (i.e. the user). Those will need to go through `filter_xss()`.

That's a bit over-simplified, there could of course be other vectors outside of this context which would allow an attacker to manipulate the PHP file itself, which could theoretically be invoked from the client. But in-and-of-itself, the method you've chosen is secure against XSS attempts.
> 1 votes

# Answer
It seems from your older question that your problem with old blocks was mainly the fact that someone was able to log in and edit admin-only things, wasn't it? If so, then no. This will not make you safe. If someone hijacked your admin account, he will be able to switch these off and create new, abused ones.

And if problem was with the JS itself, then switching from Full HTML block to module-provided one, and leaving the same script in it, will not help, either.
> 0 votes

---
Tags: blocks, security
---


# Question
Title: how do I configure a view to make two fields be inline
what format should I use in order to make two fields out of three be inline in a drupal 7 view, and how do I configure this?

# Answer
Hi I decided to use display suite which makes it responsive as well.
> 0 votes

# Answer
Hide the two fields in the views ui, then add a Global: Custom text field (make sure it is below the two hidden fields). In this field's text box you then add the two hidden fields back via replacement patterns (that's why it needs to be below the two hidden fields, else it will not see them), and wrap them in inline html or html that you will style inline.

You can use unformatted list format.

To make two rows out of three inline you will just use CSS with :nth selector. Else you can override the theme template for views (in advanced section). You copy and paste the template, then rename it to a proper suggestion. In that template it uses a loop to write the rows. You can rewrite that so that it loops over three at a time, prints two inline, one as block-level element.
> 5 votes

# Answer
Under the Format section where it says 'Show: Fields | Settings' select settings. There is an inline fields section. Select the fields you want to be displayed inline.

**Note:** If the fields render as block elements simply change the CSS for the fields to `display: inline-block`.
> 4 votes

---
Tags: views
---


# Question
Title: Override a view definition programmatically
I want to override a view definition programmatically (using the code that I get from "view export" in the views admin pages).

I've found examples for creating views using views\_new\_view(), but nothing on modifying views definition programmatically. Are there any examples / tutorials on this ?

Can I do this with views\_get\_view($name) / views\_save\_view() ?

# Answer
> 0 votes
Ok, I got to a working solution :

```
$my_view_name = 'my_test_view';

$view = views_get_view($my_view_name);
if ( $view ) {
  views_delete_view($view);
}

// ... code from view export UI ...

$view->save();

```

If the view exists already then I delete it before recreating it.

Then I throw in the code taken from the views export UI, and add right after a `$view->save();`

And that does it.

---
Tags: 7, views, importing-exporting
---


# Question
Title: Drush installed but all commands could not be found
I have drush installed on a remote server and was able to successfully run commands this morning, however I tried executing `Drush Self-Update` and got a permission error probably because I don't have sudo rights etc and now any drush commands I try run return the error `The drush command 'drush_command_here' could not be found.` when I run `which drush` it returns `/usr/bin/drush` so I know its installed + other users on the server can run drush commands without issue. I tried adding the drush alias in my .bashrc file like this `alias = '/usr/bin/drush'` and also tried using the alias pointing to usr/share/drush but no luck.

# Answer
Ended up uninstalling and re-installing drush and seems to have fixed my problem. Thanks.
> -1 votes

---
Tags: drush
---


# Question
Title: Interface Translation: Separate Drupal interface strings from theme strings?
I want to translate all the t() strings in my theme but there's no way to filter those strings by your theme only. Instead they are bundled with Drupal interface strings which creates an excessively large export to deal with and potentially unwarranted translation requests from core strings such as:

!local-task-title!active

which is located in function theme\_menu\_local\_task of includes/menu.inc

Is there a solution on how to filter your strings by ones in your theme only?

# Answer
> 0 votes
Looks like you are looking for contexts. In `t` documentation:

> Parameters
>
> * $string: A string containing the English string to translate.
> * $args: An associative array of replacements to make after translation. Based on the first character of the key, the value is escaped and/or themed. See format\_string() for details.
> * $options: An associative array of additional options, with the following elements:
>
> + 'langcode' (defaults to the current language): The language code to translate to a language other than what is used to display the page.
>     + 'context' (defaults to the empty context): The context the source string belongs to.

You can have separate translations for separate contexts if you need.

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


title: hook_menu question

text:
# Question
Title: hook_menu question
What is `"access content"` used as access argument in the following code? I don't see it in Drupal permissions.

```
function hook_menu() {
  $items['example'] = array(
    'title' => 'Example Page',
    'page callback' => 'example_page',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );

```

# Answer
> 3 votes
That permission comes from the node module (`node_permission()`). Definition is:

```
'access content' => array(
  'title' => t('View published content'),
),

```

So in the permissions UI you'll be looking for "View published content".

---
Tags: routes
---


# Question
Title: how to set a global variable that is referenced throughout the site?
i'm trying to avoid programming and hoping i could do this with modules:

I have a classified ad's website which has about 100 categories where users can add an advert. The thing is these are all linked to a location. So i use two vocabularies- one of categories and one of locations.

I want to be able to allow the user to select a location when they first land on the site from a dropdown and then when the user moves through the site this is referenced. I have two specific use cases

1. When the user goes to add a listing, their location is pre-selected in reference to the one they already selected at the initial visit.
2. When the user returns they only see adverts relating to their town/city (consider them being already registered)

# Answer
Ok. With next to no programming I would recommend trying to use the Session Cache API. This module allows for simple items to be stored in say a cookie, even for Anonymous users. You may want to try to use it directly, or use a module that already makes use of it, such as:

Views Global Filter, this module allows you to set an exposed views global filter your visitors fill out once -- and it's remembered for the duration of their visit. As they visit throughout your website your other views pages or blocks would query the existing saved off global filter values in cache and be shown the listings you want.
> 0 votes

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


# Question
Title: Saving multipage webforms after each page?
You can create a multipage webform by inserting a pagebreak element. Can you have these webforms save after each page, so that if someone doesn't complete the final page you still get what they entered on previous pages?

# Answer
The webform module does this by default if you enable `Draft` mode per webform and create multi-page forms.
> 3 votes

---
Tags: webforms
---


# Question
Title: Is it possible to restrict the site search module to specific nodes?
I am trying to figure out a way to provide a search for a specific set of nodes. Currently it seems that the site search is not configurable in this way. Is there any way to change this functionality, or other modules that provide a search for a defined group of pages/nodes?

Thanks!

# Answer
> 0 votes
You can use one of these 2 modules, Custom search Or Search restrict. Both these modules allow you to restrict the search on specific content types

---
Tags: nodes, search
---


title: Ajax button in admin

text:
# Question
Title: Ajax button in admin
So I figured I'd create a configuration for my module. I created a normal form with some fields to let the users configure the module with variables. I also added a button which would do an ajax-call to a service. Problem is, this button is within the form, meaning it submits the form aswell.

```
$form['products']['update'] = array(
            '#type' => 'button',
            '#ajax' => array(
                'path' => '/products/update',
                'event' => 'click'
                ),
            '#value' => t('Update Products')
);

```

I just want the button to actually call this service (/products/update) and not act like a submit button. This worked in beta3 but is not an annoying feature in beta4, preventing the actual service call. How do I fix this?

# Answer
> 1 votes
ajax path is not supported anymore I think. It would need to be a route.

Why do you need a path? The common way to do this is to have a #submit callback on that form element, then just that will be called.

---
Tags: ajax, 8
---


# Question
Title: getting error while showing a user online or offline
While setting a user online or offline status with the Views module, I get this error message:

> SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')) \< 30, 1, 0) AS users\_node\_is\_online, 1 AS expression FROM node node LEFT JOI' at line 1

How do I fix it?

# Answer
I believe the field *meh* is referring to is provided by the *user\_stats* module. Indeed, once installed it is possible to add that field in a views. There is also a patch for this error on the user\_stats issue queue.
> 1 votes

---
Tags: views, database
---


# Question
Title: Unable to Search or Sort through Webform Submitted Data
I created an exposed filter for my View that aggregates user-submitted webform data. I was hoping this would allow them to search the View for specific webform entries. Unfortunately, the View remains unsortable by column (although I checked the option to make every column sortable), and whenever I search via my exposed filter, it comes back with 0 results.

I've attached images of my Filter and View settings... am I doing something wrong?

Thanks!

View Settings:

Filter Settings:

Table Settings:

# Answer
> 1 votes
Check your FORMAT -\> Format: Table | **Settings** for a checkbox that says `Override normal sorting if click sorting is used` and turn it on if it is not already.

---
Tags: webforms, views
---


# Question
Title: Clone product display with referenced product
I am using Commerce Kickstart for Drupal 7, and I need to be able to clone products.

In Commerce Kickstart you have all the products just as "reference" of node, product display. I mean, the products themselves are displayed for customers similar like any other page, with "attached" actual products. (this allows you to create more variations of one type)

I am trying to clone both of those by one operation - to clone Product display (as node), and also referenced product by this product display. But when I used basic Node Clone module, it just clones Product display as a node but not the reference. Result is, the same cloned content with "attached" reference product at the very bottom, but when I change that product, It also changes the product of previously cloned product display.

Here is what I mean: http://harmonel.sk/stuff/drupal\_commerce.jpg

I am not sure what to do, I am not very good with coding, maybe I should somehow re-write the Node Clone module to also clone the referenced product? Does anyone had similar or same problem? I am trying to achieve this with Rules but with no success, but maybe that would be the best way to achieve this?

Any advice would be greatly appreciated.

# Answer
Try https://www.drupal.org/project/replicate and https://www.drupal.org/project/replicate\_commerce

The Node Clone module focus on cloning using the administration interface and is designed only for nodes replication, whereas Replicate can clone any entities (nodes, taxonomy terms, users, ...).
> 0 votes

---
Tags: commerce, rules
---


title: Drupal 8 JavaScript and Best Practice

text:
# Question
Title: Drupal 8 JavaScript and Best Practice
I am building a theme for Drupal 8 that I want to make available in the drupal.org theme section. As such, I want it to conform to best practice code wise. When adding JavaScript, I notice there has been some changes. Here is how I do it:

```
function THEMENAME_preprocess_page (&$vars, $hook) {
  $path = drupal_get_path ('theme', 'THEMENAME');
  // Render the main scripts file.
  $local_js = array (
    '#attached' => array (
      'js' => array (
        $path . '/js/THEMENAME.js' => array ('group' => JS_THEME, 'weight' => 9999),
        '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js' => array ('group' => JS_THEME, 'weight' => 9000),
      ),
    ),
  );
  drupal_render ($local_js);
}

```

Is this it? the best-practice way?

Edit:

In accordance to Aneek's answer I am now including JavaScript this way:

First, I created a THEMENAME.libraries.yml:

```
THEMENAME-base:
  version: 1.0
  js:
    //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js: {}
    js/THEMENAME.js: {}

```

Then, in THEMENAME.info.yml I added the libraries:

```
--snip--
core: 8.x
stylesheets:
  all:
    - css/grid.css
    - css/style.css
regions:
  header: 'Header image'
  home_intro: 'Home intro'
  breadcrumbs: Breadcrumbs
  content: Content
  sidebar-main: 'Sidebar main'
libraries:
  - THEMENAME/THEMENAME-base

```

This method includes the JavaScript files to all pages on the site. If one needs to include on specific pages only, the preprocess\_page would probably be the way to do it.

# Answer
> 0 votes
If you follow the best available themes like Adaptivetheme or Omega, they followed the yml structure and placed the JavaScript files in **"omega.libraries.yml"** file.

If you are using template.php then for preprocess HOOKs I think they have implemented a file with .theme extension instead of template.php. See https://www.drupal.org/node/1967614

# Answer
> 1 votes
As of newer versions of Drupal 8, the "js"-key (or "css") is not allowed anymore in the #attached-array. Use "libraries" instead.

---
Tags: theming, javascript, 8
---


# Question
Title: Displaying Database Data Within the Flow the Site
I have a multi-page form that works fine in and of itself (pathfindertool.module). However, once a user clicks submit I want the page to display some records on the page. And it DOES display the records on the page, but NOT within the flow of the page. What I mean by that is, it just puts all the returned results in the top-left of the page in the browser window in and not in a tag in the #content area for example where content is supposed to go.

I tried to use javascript document.getelementbyid.innerhtml, calling that from my php and it just returns no results (well it returned them according to console but it didn't display them):

```
while ($row = $result->fetchAssoc()) {
    echo '<script type="text/javascript">';
    echo 'window.onload(';
    echo 'document.getElementById("pathfinder-primary-form").innerHTML=';
    echo '"<div>';
    echo $row['title'];
    echo '</div>");';
    echo '</script>';
  }
  }

```

I also tried doing drupal\_add\_js inside my .module file and can't get that to work either. Granted my coding here is pretty kloogy:

```
drupal_add_js('document.getelementbyId("pathfinder-primary-form").innerHTML = "', 'inline');

$title = $row['title'];

drupal_add_js('document.getelementbyId("pathfinder-primary-form").innerHTML = "', 'inline');

```

Surely this must be one of the most common workflows ever. What's the best practice for displaying data from a database in Drupal so that it displays within a specific (ie. #main, or perhaps even the form container itself)?

Here's my pretty basic functioning code so far for displaying the results in my .module file:

```
if ($result) {
while ($row = $result->fetchAssoc()) {
    $title = $row['title'];
    echo '<p>' . $title. '</p>';

  }
  }

```

**But of course it displays it in the top-left corner of the body in the browser window right above the Logo! O.O**

What am I doing wrong and how can I fix it?

# Answer
Drupal splits functionality (modules) and layout (themes) to keep everything maintainable.

Instead of echoing everything, you need to pass your output from your module to the theme.

First step is making a menu item. This will give you an url to work with: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu/7

Basic example:

```
function pathfindertool_hook_menu() {
    $items['pathfinderurl'] = array(
      'page callback' => 'pathfindertool_page',
    );
    return $items;
}

```

The page callback point to a function that contains your logic. You can choose the function name, but it's advised to start with your module name.

```
function pathfindertool_page() {
  $output = '';
  drupal_add_js('document.getelementbyId("pathfinder-primary-form").innerHTML = "', 'inline');

  $title = $row['title'];

  drupal_add_js('document.getelementbyId("pathfinder-primary-form").innerHTML = "', 'inline');

  // Do whatever you did to fill result.
  if ($result) {
    while ($row = $result->fetchAssoc()) {
      $title = $row['title'];
      $output.= '<p>' . $title. '</p>';

    }
  }
  return $output;
}

```

Returning the output will make sure it will show in the right place. Never use echo or print, it will show up at the top.

You must always return something, even an empty string is ok, return NULL will result in a WSOD. That's why I always start my function with $output = '';
> 1 votes

---
Tags: forms
---


# Question
Title: When viewing a product node, how to show/ enable the original node title?
I am using commerce in my drupal site, but the node title is not there. Debugging it in the `page.tpl.php` returns an empty string `''`. I know you can enable the title in the display settings of the content type and product variation, but this is rather a field within the node article, that has no influence of the title not being shown within the page template.

Obviously, the title is being set to `''` somehow, but I cant figure out where this happens or, even more importantly, how to change this with my custom module.

Any help is greatly appreciated.

# Answer
I found out that within the `commerce_kickstart_product_ui_preprocess_page` function the node title of product nodes is being set to `''`, for what reason ever. I wrote a custom module with weight higher than 50 and re-enabled the title:

```
function mymodule_preprocess_page(&$vars) {
  // make the title display available again
  $product_display_types = commerce_product_reference_node_types();
  if (isset($vars['node']->type) && isset($product_display_types[$vars['node']->type])) {
    $vars['title'] = $vars['node']->title;
  }
}

```
> 0 votes

---
Tags: nodes
---


# Question
Title: Convert dropdown of exposed sorting of view into Checkboxes
I have created view in that view I exposed **sorting** with dropdown field 'Distance', 'Rating', 'Review', it works fine. Now I want to convert that dropdown into checkboxes with AJAX callback. I used module Better Exposed Filters please suggest me to how to do that.

# Answer
You can achieve this goal by Implementing hook\_form\_alter

e.g:

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page_1') {
       // do your alteration stuff
       $form['sort_order']['#type'] = 'radios';
        //$form['sort_by']['#type'] = 'radios';
    }else
    if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page_2') {
       // do your alteration stuff
    }
}

```
> 1 votes

# Answer
I Suppose this may help you using Better Exposed Filters
> 1 votes

---
Tags: views
---


title: How to get nodeid?

text:
# Question
Title: How to get nodeid?
How to get nodeid in Drupal for the current page without using the information from the page url? I.e.:

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

```

I do not want to use the above approach.

# Answer
> 16 votes
Still comes through the URL indirectly, but this is the easiest way to get it: menu\_get\_object.

```
<?
if ($node = menu_get_object()) {
 $nid = $node->nid;
}
?>

```

Note that if there is a node, it was already loaded by the menu system anyway and this is loaded from the static cache.

# Answer
> 1 votes
Unless there is some technical reason why the arg() method is unavailable (or you NEED to check access as in other posts), the arg() method is the simplest and quickest.

If you then need additional properties you can run a node\_load() to get the ID. Assuming you are trying to get the current node, this has pretty much no performance hit.

# Answer
> 0 votes
You can get the node's ID by calling `$node->nid`. Indeed, getting the ID from the URL is not the best solution because you may some day switch to more SEO-friendly URLs.

From this documentation, it looks like `$node` is defined in `page.tpl.php`, so it should be available to you.

```
<?php
  // In a template file...

  if ($node) {
    echo $node->nid;
  }
  else {
    // you are viewing taxonomy, view, etc
  }
?>

```

# Answer
> 0 votes
Yes, that confused me for ages, but using the arg array should work in almost all circumstances, and Drupal takes care of the conversion from the actual url created by path or pathauto.

# Answer
> 0 votes
Easiest way to do this in Drupal 8:

```
$path_args = explode('/', current_path());
print $path_args[1];

```

# Answer
> 0 votes
Another pretty straight forward and reliable approach in D7 would be

```
<?php
if (isset($node->nid) && count($node->nid) > 0){
  $nodeid = $node->nid;
}
?>

```

Zourtney's suggestion causes an *undefined index* error in my case.

---
Tags: nodes
---


# Question
Title: how to get tinymce value in javascript?+ Drupal7
I am using drupal7 form

```
$form['subject'] = array('#type' => 'textfield',
        '#title' => t('Subject'),
        '#maxlength' => 200,
        '#size' => 100,
        '#required' => TRUE,
);

$form['body'] = array('#type' => 'textarea',
        '#title' => t('Body'),
        '#type' => 'text_format',
        '#base_type' => 'textarea',
        '#format' => 'full_html',
        '#required' => TRUE,

);

```

we used tinymce editor. Posting form with jquery like this

```
$.ajax({
            url: '/myevent/preview',
            data: $('#eventform').serialize(),
            type: 'POST',
            success: function(data){
                $('#eventdata').html(data);
            }
        });

```

At my local its working fine, but on server, I couldn't get value of body textarea.

# Answer
> 2 votes
Try this I suppose this may help.

> tinyMCE.triggerSave();
>
> $('`#textarea-selector-id`).val();

i suppose that your text area would be inline:TRUE; change the text area to a div this may work

or

```
var editor='textarea-selector-id';
var content =tinyMCE.activeEditor.getContent();
alert(content);

```

---
Tags: wysiwyg
---


# Question
Title: Commerce: adding +/- buttons to the Quantity field
I am working on a site that uses the Commerce module for a web store. The design specifies that the user's cart overview page should allow them to increase and decrease the quantity of a particular item using plus/minus buttons. However, as far as I can see the only option for a quantity field is a bare text field (in *commerce/config/line-items/product/fields*). I've searched for solutions online, but apart from the Commerce Extra module (which is in alpha, and does not allow for vertically-stacked buttons as per the design) I'm coming up blank.

Is there an 'accepted' way to add these buttons to the quantity field, or am I missing something in my configuration?

# Answer
Commerce Kickstart has that.

We use the jquery\_ui\_spinner library, extracted in our libraries folder.

We declare the library in a hook\_library implementation:

```
/**
 * Implements hook_library().
 */
function commerce_kickstart_product_ui_library() {
  $libraries['jquery_ui_spinner'] = array(
    'title' => 'jQuery Spinner',
    'website' => 'http://github.com/btburnett3/jquery.ui.spinner/',
    'version' => '1.8',
    'js' => array(
      libraries_get_path('jquery_ui_spinner') . '/ui.spinner.min.js' => array(),
    ),
    'css' => array(
      libraries_get_path('jquery_ui_spinner') . '/ui.spinner.css' => array(),
    ),
    'dependencies' => array(
      array('system', 'ui.widget'),
    ),
  );
  return $libraries;
}

```

Then in our hook form alter we attach the library:

```
function commerce_kickstart_product_ui_form_alter(&$form, &$form_state, $form_id) {
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['#attached']['library'][] = array('commerce_kickstart_product_ui', 'jquery_ui_spinner');
  }
}

```

and finally in our JS file we do:

```
(function ($) {

  // Add a spinner on quantity widget.
  Drupal.behaviors.quantityWidgetSpinner = {
    attach: function ( context, settings ) {
      $('.form-item-quantity input').spinner({
        min: 1,
        max: 9999,
        increment: 'fast'
      });
    }
  }
})(jQuery);

```
> 13 votes

# Answer
This functionality is also provided by the Commerce Extra module, it works just right.
> 1 votes

---
Tags: commerce
---


# Question
Title: How to get select option id value in form api
Hi hello please help how to get dynamically selected option id value (i.e `#options=>0=>'bala',1=>'kumar'`)

for example how to get selected value of ID value in form api in drupal

```
$form['state1']= array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' =>$options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

```

the selected value store in $key value, please help me how to do....

```
$key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

```

is this correct???

# Answer
> 2 votes
You can get the value using:

```
$form['field_name'][#options][$form_state['values']['field_name']]

```

# Answer
> 0 votes
You will get selected value of that select box using $form\_state like this

ex: If you want to use that id in your callback "\_ajaxfunction" then its possible using $form\_state variable.

`$key = !empty($form_state['values']['state1']['und']['value']) ? $form_state['values']['state1']['und']['value'] : 1;`

or

`$key = !empty($form_state['values']['state1']['und']['nid']) ? $form_state['values']['state1']['und']['nid'] : 1;`

still not work then print bellow line and you will get perfect array

`$form_state['values']['state1']['und']`

# Answer
> 0 votes
If you are using fields API:

You can get the Value of the `key => value` pair of a Select List by using `list_allowed_values()` see the docs page for more info.

Your form will always return the key in the result so you can do something like this :

```
$key = $form_state['values']['whatever'];
$options = list_allowed_values("field_whatever");
$value = $options[$key];

```

---
Tags: forms
---


# Question
Title: How to select a node reference field when querying the database
I am using `db_select` to query the database to get some fields, one of the fields is a node reference and I don't know how to select it or join its table.

My content type contains a node reference, and this node reference contains another node reference (nested relationship), how can I from the original content type get the first node reference fields and the fields of its node reference ?

My current query :

```
$query = db_select("node", "n");
$query->fields("n", array("nid", "created", "type"));
$query->fields("f1", array('field_field1_value'));
$query->fields("f2", array('field_field2_value'));
$query->leftJoin('field_data_field_field1', 'f1', 'f1.entity_id = n.nid');
$query->leftJoin('field_data_field_field2', 'f2', 'f2.entity_id = n.nid');
$query->condition('n.type', 'my_content_type', '=');

$query = $query->orderBy('n.created', 'DESC');
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(20);
$result = $query->execute();

```

# Answer
> 1 votes
I was able to join my node references using `db_select`, I just needed to add two relationships for each node reference (I have two node references (nested)), a first relationship to the specific table (which follows the pattern `data_field_THE_NAME_OF_THE_NODE_REFERENCE_FIELD_IN_YOUR_CONTENT_TYPE`) and a second relationship to the node itself with another alias (I mean by relationships JOINs).

Here's my code now :

```
$query = db_select("node", "n");
// joins
// setting up the first relationship
$query->leftJoin('field_data_field_X_ref', 'r', 'r.entity_id = n.nid');
$query->join('node', 'x', 'r.field_X_ref_nid = x.nid');
// setting up the second relationship
$query->leftJoin('field_data_field_Y_ref', 'r2', 'r2.entity_id = x.nid');
$query->join('node', 'y', 'r2.field_Y_ref_nid = y.nid');
// joining other fields
$query->leftJoin('field_data_field_field1', 'f1', 'f1.entity_id = n.nid');
$query->leftJoin('field_data_field_field2', 'f2', 'f2.entity_id = n.nid');
// ...
// fields
$query->fields("n", array("nid", "created", "type"));
$query->fields("f1", array('field_field1_value'));
$query->fields("f2", array('field_field2_value'));
// ...
$query->fields("x", array('title')); // title for the first node
$query->fields("y", array('title')); // title for the second node

// adding conditions
$query->condition('n.type', 'voiture_d_occasion', '=');

$result = $query->execute();

```

note that the two nodes references have a title, and in the `query->fields()` we mentioned that we want the title of both, drupal will return `title` for the first field, while the name of the field will be `y_title` for the second, you can use `dsm` on the query result to see the name of your fields.

---
Tags: nodes, database
---


title: Multisite path issue

text:
# Question
Title: Multisite path issue
Our multisite is having issues.

we have a subsite called /wikifix some of the URLs in this subsite are /wikifix/wiki/...

now we have another subsite called /wiki. as soon as we make our symlink, the pages on /wikifix that have wikifix/wiki/ in their path start giving drupal page not found errors. Testing on another subsite in the multisite /kids shows similar issues, /kids/wiki also gives page not found errors

both sites work and are accessible, the issue is only when the path contains the name of a different subsite.

# Answer
the two issues causing this were both in the .htaccess:

this line was commented out:

```
RewriteBase /

```

and then we had to add this per subsite:

```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} ^/wikifix
RewriteRule ^ wikifix/index.php [L]

```

including the first 3 rules:

```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} ^/wiki
RewriteRule ^ wiki/index.php [L]

```

since both subsites start with /wiki, it was also important to have the RewriteCond for wikifix BEFORE the RewriteCond for wiki
> 1 votes

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


title: Views check access by PHP

text:
# Question
Title: Views check access by PHP
I've got 2 roles on my system -uzman and isveren- and several views that need to be restricted to either uzman or isveren. For that purpose, I have been trying to check access control with PHP. I can't use role based access check because then administrator would see all because he has access to all views. Anyway, I am using

```
<?php
if (in_array("uzman", $account->roles)) {
return TRUE;
}
?>

```

which works, but I see many `undefined offset:4` messages in dblog (4 is uzman's rid). What is the correct way to check access with PHP in Views module?

# Answer
> 1 votes
The correct way is to create a custom module and implement `hook_permission()` to define an appropriate permission:

```
function hook_permission() {
  return array(
    'administer my module' => array(
      'title' => t('Administer my module'),
      'description' => t('Perform administration tasks for my module.'),
    ),
  );
}

```

Grant that permission to the roles that require access to it, and then use `user_access()` to make the access decision:

```
if (user_access('administer my module', $account)) {
  ...
}

```

As AyeshK points out in the comments, you don't actually need the second part - Views has n plugin for access based permissions already, which you can configure through the UI. So once you've added the permission and granted it to the relevant role(s), it'll be easy to get what you're looking for.

---
Tags: views, users
---


title: An URL that is all parameters

text:
# Question
Title: An URL that is all parameters
I'm building a website related to videogames. There's a view that shows all videogames catalogued in the website, using taxonomy terms as arguments, that is:

mysite.com/games/genre/platform

The problem is that the "games" part in the URL is unnecesary: everything is games. For SEO reasons we want to remove this part, so, for example, this...

mysite.com/games/strategy/android

becomes this...

mysite.com/strategy/android

That is, a view with no fixed part in the path, just the parameters. How can I get this working?

# Answer
You can go directly in your **View's settings**, in "Page settings" bloc, configure the **path** manually. Just remove the game part of the path.

**For your information:**

I suggest you to take a look at Pathauto module that allows you to define URL patterns very precisely for all the default pages of your site (but not views apparently): https://www.drupal.org/project/pathauto

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

Maybe it will be helpful for other cases.
> 1 votes

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


# Question
Title: Block loading behaviour in Drupal 8 in a performance sense through the visibility settings
The following scenario: \- i have for example a standard block region through a pages of a site: "highlights" \- for the frontpage i have an additional region: "highlights\_frontpage" \- i put a block into "highlights\_frontpage" \- i have to put into the visibility textarea: ""

If i remember correctly for D7, otherwise the block is loaded everywhere even though he is only shown on the frontpage.

Has Drupal 8 the same behaviour in loading blocks? My page has for each main menu page an own region, but it would be a little bit ugly for the editor if he has to place the block via the administration in one region and also has to set the visibility ...

thanks

# Answer
The block is loaded (otherwise we could not check if he should be shown or not), but we do not call build() unless the block is visible and the user has access.

I'm pretty sure that was already the case in Drupal 7, it is only Drupal 6 AFAIK where it was building the blocks and then checking visiblity.
> 1 votes

---
Tags: performance, 8, blocks
---


# Question
Title: Page not found when there are clean extra parameters in URL alias-
I have a working site which has PathAuto with SubPath setting properly configured. When I try to access the site from localhost in XAMPP, it gives 404 not found at several pages where the clean URL has extra parameters.

For example, this goes perfect: subdomain.example.com/url-friendly/extra-parameters

This, in local PC: www.example2.com/url-friendly/ goes right This, in local PC. fails www.example2.com/url-friendly/extra-parameters

Is there some known issue with XAMPP and Drupal url alias?

# Answer
> 0 votes
I have discovered the problem and the solution. When you change domain, or you add a domain to the list in **Domain Access**, you later have to switch off **SubPath**, save, and later turn on SubPath again. In that way, it refresh "something", and everything works perfectly.

So if you have free parameters passed on the *clean friendly URLs*, you need to make those steps in order to assure that the site will work with the changed or added domains.

---
Tags: path-aliases
---