# Question
Title: Complex View with Contextual Filter and Relationships
I have a View of taxonomy terms. I use the Relationship: **Content using Categoria Secciones** to show, with Aggregation, the listing of the category terms, and next to it, the number of products in that category. That works perfectly. But this is the part where I am stuck: I want to add a contextual filter of Fabricante, so I can filter by another Taxonomy. I have previously, in other ocassions, used contextual filter with a Content View, but not in a Taxonomy View. I have tried to add another Relationship in my Taxonomy View: **Content using Fabricante** and use this relationship in a contextual filter of type **Has taxonomy Term id** but it doesn't work.

In summary, I want a listing of taxonomy related to a product (which works) and add the contextual filter of another taxonomy which is assigned to the same product (this is where I am stuck).

Here, if it is of help, the SQL, with the correct TID of the additional taxonomy term, which is 32619. The listing is empty, even if the product is assigned to that taxonomy term.

```
    SELECT taxonomy_term_data.tid AS tid, taxonomy_term_data_taxonomy_term_hierarchy.tid AS    taxonomy_term_data_taxonomy_term_hierarchy_tid, taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name, field_fabricante_taxonomy_term_data.nid AS field_fabricante_taxonomy_term_data_nid, MIN(taxonomy_term_data.tid) AS tid_1, 'taxonomy_term' AS field_data_field_imagen_categoria_taxonomy_term_entity_type, COUNT(DISTINCT field_taxonomia_taxonomy_term_data.nid) AS field_taxonomia_taxonomy_term_data_nid
    FROM
    {taxonomy_term_data} taxonomy_term_data
   LEFT JOIN {taxonomy_term_hierarchy} taxonomy_term_hierarchy ON     taxonomy_term_data.tid = taxonomy_term_hierarchy.tid
    LEFT JOIN {taxonomy_term_data} taxonomy_term_data_taxonomy_term_hierarchy ON taxonomy_term_hierarchy.parent =    taxonomy_term_data_taxonomy_term_hierarchy.tid
    LEFT JOIN {field_data_field_taxonomia} field_data_field_taxonomia ON taxonomy_term_data.tid = field_data_field_taxonomia.field_taxonomia_tid AND (field_data_field_taxonomia.entity_type = 'node' AND field_data_field_taxonomia.deleted = '0')
   LEFT JOIN {node} field_taxonomia_taxonomy_term_data ON field_data_field_taxonomia.entity_id = field_taxonomia_taxonomy_term_data.nid
   LEFT JOIN {field_data_field_fabricante} field_data_field_fabricante ON taxonomy_term_data.tid = field_data_field_fabricante.field_fabricante_tid AND (field_data_field_fabricante.entity_type = 'node' AND field_data_field_fabricante.deleted = '0')
   LEFT JOIN {node} field_fabricante_taxonomy_term_data ON field_data_field_fabricante.entity_id = field_fabricante_taxonomy_term_data.nid
   LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
INNER JOIN {taxonomy_index} field_fabricante_taxonomy_term_data__taxonomy_index ON field_fabricante_taxonomy_term_data.nid = field_fabricante_taxonomy_term_data__taxonomy_index.nid
   LEFT JOIN {field_data_field_imagen_categoria} field_data_field_imagen_categoria ON taxonomy_term_data.tid = field_data_field_imagen_categoria.entity_id AND (field_data_field_imagen_categoria.entity_type = 'taxonomy_term' AND field_data_field_imagen_categoria.deleted = '0')
WHERE (( (field_fabricante_taxonomy_term_data__taxonomy_index.tid = '32619') )AND(( (taxonomy_vocabulary.machine_name IN  ('secciones')) )))
GROUP BY tid, taxonomy_term_data_taxonomy_term_hierarchy_tid, taxonomy_term_data_name, taxonomy_term_data_vid, taxonomy_vocabulary_machine_name, field_data_field_imagen_categoria_taxonomy_term_entity_type, field_fabricante_taxonomy_term_data_nid

```

# Answer
I have been able to completely solve it. Using a contextual filter, but somehow I had no the options listed in the first edit, so I needed to create the filter first, and then edit again, maybe because I was using a relationship (not very user intuitive, BTW). So here it is important to use the relationship and complete the values below (all outlined in red). Now it works perfectly, the taxonomy terms are listed with the grouped count of items, and filtered by a different taxonomy, with the content Producto joining both taxonomies.
> 1 votes

# Answer
All you have to do is click on your contextual filter, then scroll all the way down, click on the blue MORE button and checkmark allow multiple values.

Yeah, it's hidden, lol.
> 0 votes

# Answer
I have almost solved it, using a Filter instead of a contextual filter. I understand that I can call the view with Drupal API and set the filter to what I want... that would be similar to a contextual filter. I will try, though still not the most elegant way of solving it. I have tested it and works as I want, but I would like to have it as a contextual filter instead of just a filter. For some reason is not working there.
> 0 votes

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


title: How to migrate to translatable fields

text:
# Question
Title: How to migrate to translatable fields
I am using the latest Entity Translation module in order to provide a couple of translatable fields for some of my content types. I have a content type which has a translatable field which is called "title\_field".

I am using the Migrate module (version 2.0) in order to fill in the Drupal scheme with data from an old database. Normally, in a single language, the line would be:

```
$this->addFieldMapping('title_field','name')

```

Now the problem is that I have two translations of this field in my old database, which I want to create through the migration API.

```
$this->addFieldMapping('title_field','name_el')->arguments(array('language','el'));
$this->addFieldMapping('title_field','name_en')->arguments(array('language','en'));

```

Unfortunately this last one does not work. Any idea how I can go further with this?

# Answer
I solved the problem by first doing the field translation manually for one node, and then using Node Export to see the actual code describing the node. Finally, I used the prepare function of the Migrate api to do the work manually.

```
function prepare($entity, stdClass $row){

    $entity->language = 'el';
    $entity->title_field['el'][0]['value'] = $row->name;
    $entity->title_field['en'][0]['value'] = $row->name_en;
    $entity->translations = (object) array(
                    'original' => 'el',
                    'data' => array(
                            'el' => array(
                                    'entity_type' => 'node',
                                    'entity_id' => $entity->nid,
                                    'language' => 'el',
                                    'source' => '',
                                    'uid' => '0',
                                    'status' => '1',
                                    'translate' => '0',

                            ),
                            'en' => array(
                                    'entity_type' => 'node',
                                    'entity_id' => $entity->nid,
                                    'language' => 'en',
                                    'source' => 'el',
                                    'uid' => '1',
                                    'status' => '1',
                                    'translate' => '0',

                            ),
                    )
            );
 }

```
> 0 votes

# Answer
lefterav solution has a problem: in `prepare()` function, `$entity` is not yet saved, so `$entity->nid` is not set.

To solve this problem, I used `complete()` function:

```
public function complete($entity, stdClass $row) {
$entity->translations = (object) array(
  'original' => 'it',
  'data' => array(
    'it' => array(
      'entity_type' => 'node',
      'entity_id' => $entity->nid,
      'language' => 'it',
      'source' => '',
      'uid' => '1',
      'status' => '1',
      'translate' => '0',
    ),
    'en' => array(
      'entity_type' => 'node',
      'entity_id' => $entity->nid,
      'language' => 'en',
      'source' => 'it',
      'uid' => '1',
      'status' => '1',
      'translate' => '0',
    ),
  )
);
entity_save('node', $entity);

}

```
> 0 votes

# Answer
Import data in multiple languages

> This tutorial will explain, step-by-step, how to import multilingual data into Drupal. This is important for projects that require data to be imported, whether it's new data, data from an old site, or even from a desktop application.
> 0 votes

---
Tags: i18n-l10n, migrations
---


# Question
Title: ImageCache action: How do I set the width as 500px and the height will constrain propotion to width?
I use ***ImageCache Action*** to add watermark and resize image.

How do I set the width as **500px** and the height will constrain propotion to width?

# Answer
***Found solution*** Use "Scale" in Action, Width:500, Heigth:0, Select "Allow Upscaling" Then update action.
> 1 votes

---
Tags: media
---


# Question
Title: feed import on node reference doesn't add language in database
I got a XML import witch imports new nodes, in this nodes there is a node reference field. When I run the import I get the message "does not match an existing node" when I look at the nodes they got the node reference, but when you edit the field is empty.

If you look in the database I see that language stays on UND when I change this and update the database it works but when the import runs again its ruined again.

Any solution?

# Answer
I turned off the translation on the node reference with entity translation; this fixed the problem for me.
> 0 votes

# Answer
The issue you have run into looks like it may be identified here: https://www.drupal.org/node/1183440. I walked through this issue queue and was able to get my feed processor to specify the language it was importing. The comment #193 was particularly useful. I'll elaborate on his directions a little bit.

For the record, this patch applies only to the feeds module, but you will need to have Feeds Entity Translation installed as well (which you probably already do).

1. `drush dis feeds -y`
2. `rm -rf feeds` \- remove feeds directory entirely
3. git-pull the feeds repo and checkout older commit:

`git clone --branch 7.x-2.x http://git.drupal.org/project/feeds.git`

`cd feeds`

`git checkout 006234fc3cc859e4fec0cb261675577efcf389b8`
4. enable all feeds modules that were disabled from step 1:

`drush en feeds, feeds_ui, feeds_tamper, feeds_tamper_ui, feeds_et, feeds_ex -y`
5. patch feeds:

`wget https://www.drupal.org/files/issues/feeds-field_translations-1183440-191.patch`

`git apply < feeds-field_translations-1183440-191.patch`
6. confirm patch by building new feed. you should see a language option under the processor settings.

There is a little bit of work to do on this patch before it can be incorporated in the Feeds trunk, but I'm hopeful it will be in place within a few months.
> 1 votes

---
Tags: feeds, nodes, i18n-l10n
---


# Question
Title: How to store information in session for anonymous user in a site without a user with uid=0?
In our system for some reason, we have deleted user with 0 uid. But for now I have to store some information in session for anonymous users. But Drupal is not allowing me to save the information in session.

Can someone suggest another way around?

I am trying

> session\_start();
>
> $\_SESSION\['some\_param'\] = 'value';

for retrieving

> session\_start();
>
> echo $\_SESSION\['some\_param'\];

But the values are not available after reload.

PS: It is working fine if I create a user with uid=0. But I need solution without uid=0.

# Answer
If you "***have to store some information in session for anonymous users***", then you will have to make `uid=0` available to Drupal. Because that's the `uid` that Drupal always uses for anonymous users.

So you'll have to re-create that ***user with uid=0*** (again) if you want this to work. If you would combine this with not granting any permissions to role anonymous, there is not a lot that anybody can do in your site if they are not logged in (apart from things like performing login). Maybe an acceptable work around?

About your "*for some reason we have deleted user with id=0*": it might be that the user with id=0 never got created before (so that it was never deleted). E.g. if the database of your site was created via some type of database copy (backup and restore) from a dev site to a prod site (using PhpMyAdmin). Forgot the exact scenario, but I've ran in such sites before, which caused problems for anonymous users (which is how we discovered such cases). The solution we used was to simply use PhpMyAdmin, and insert the user with uid=0 in the Drupal database (using PhpMyAdmin).
> 2 votes

---
Tags: sessions
---


# Question
Title: changing role wen opening a confirmation link but auto login with logintoboggan
We are using logintoboggan to login new users after registration. After the registration the users get the role 'unconfirmed user' with limited permissions. The users need to open the confirmation link to get another role 'confirmed user' with more permissions.

Logintoboggan disables the option to send a confirmation link to the user.

How can I send an email with a confirmation link to the new user and how can I switch his role when opening the link?

# Answer
> 0 votes
If using rules module, then you will have an event: when user account is activated. when rule fires you can define action add role.

For sending email even: when user account is created and then as action send email.

There is more possibilities. I like to do it with custom modules so I can simpletest the code. If so, use hook\_user\_insert() and hook\_user\_login(). In hook\_user\_login() check for user roles.

# Answer
> 0 votes
Rules isn't a solution for us. I found user email verification. A small module which generates a verification link after registration. Also with the possibility to delete not verified accounts after a time x. We pimped this module a little. Now we can select a role to which we change the account after opening the verification link. The select excludes the role which is defined as 'Admin'.

Now we can send a verification link and change the role after opening to the one we selected in settings. If anyone ist interested - feel free to contact me.

Note. LoginToboggan does actually the same. But it changes the role only to 'authenticated user'. There's no possibility to select the verified role.

---
Tags: users, authentication-authorization
---


# Question
Title: How to make a sticky post on appear on top within a view
I've created a view which is organised by date. All works fine, however I'd like to add the sticky functionality to it, where whenever a node is marked as sticky, it'll go to the top of the list regardless of the date. How can I achieve that?

# Answer
> 6 votes
Just sort by sticky and after that sort by date.

As simple as that, it should do the trick for what you want to do.

---
Tags: 7
---


# Question
Title: How to change the order of banners using the weight module?
I have add banners. I want to change the banners order. I have installed the Weight module. I have also added weight in content type but it does not reflect in node.

So how can I change the order of banners?

# Answer
> -1 votes
Check out these modules :

weight

> This module adds a weight option to enabled node types. Nodes with lower weight will float to the top of lists, while heavier items will sink.

Field\_weight

> Customise the weight/order in which fields on nodes can be displayed on a per node basis and not just globally per type. Individual fields can also be hidden from display.
>
> For any node types that are enabled, a 'Field display weights' tab will appear on nodes (for users with adequate permissions). From this page administrators can customise the order in which fields are displayed on each node by using a draggable table (or manually select weights).

Nodequeue

> The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:
>
> 1. A block listing teasers for the five top news stories on a site
> 2. A user’s favorite music albums
> 3. A group of favorite from which one is randomly displayed
>
> Nodequeue provides a simple drag-and-drop interface to manually order any queue. Additionally, it allows nodes to be added and removed from queues without needing edit permissions to the node. Nodes can be added to queues either from a queue management tab or by links on the node teaser.

---
Tags: nodes, 7
---


title: Install a module in Linux

text:
# Question
Title: Install a module in Linux
I am looking to download and install a module using the Linux command line.

How can I do this?

# Answer
* You can install Drush (see Installing Drush on Ubuntu or How to install Drush server-wide in less than one minute); after, you can install a module with drush:

+ to download a module

    ```
    drush dl modulename

    ```
    + to enable the module

    ```
    drush en modulename

    ```
* Also, you can use wget to download the module, and make a directory inside the modules directory (in this case the modules directory is /home/youruser/public\_html/sites/all/modules/).

```
    wget http://ftp.drupal.org/files/projects/modulename-6.x.tar.gz
    mkdir -p /home/youruser/public_html/sites/all/modules/modulename
    tar -zxf modulename-6.x.tar.gz -C /home/youruser/public_html/sites/all/modules/modulename

```

Enable the module in "Administer \> Site building \> Modules."
> 7 votes

# Answer
To install Drupal modules using command line, you have to install `Drush Composer` on your machine.

So use this link to install Drush using composer : https://github.com/drush-ops/drush

After installing it, open your terminal and go to your project/drupal directory into which you want to download modules.

To download and enable modules using a single command, run following command:

```
drush en -y your_module_name

```

Note : your\_module\_name should be the name present on the url of the module name like `https://www.drupal.org/project/your_module_name`
> 6 votes

# Answer
The best way to do this is via the Drush project. This will allow you to download and enable modules via the command line similar to the code below.

```
# Download the Views module
drush dl views

# Enable the Views module
drush en views

```
> 1 votes

# Answer
If you don't have (or don't want) drush, you can also just do something like this:

```
$ cd $MY_DRUPAL_SITE_ROOT/sites/all/modules
$ wget http://ftp.drupal.org/files/projects/querypath-6.x-1.6.tar.gz
$ tar -zxvf querypath-6.x-1.6.tar.gz

```

(the -z flag to the tar command does a "gunzip" of the file before untarring)

From there, you can go to the Site Building -\> Modules screen and install the module there.

That said, if you are going to be doing this a lot, Drush is very helpful
> 1 votes

# Answer
Install drush, which is a command line tool for Drupal. Downloading and installing a module would just need you to execute two commands. (The first command download the module, and the other one installs it.)

```
drush dl <modulename>
drush en <modulename> -y

```

These commands will take care of module dependencies too.
> 1 votes

# Answer
1- By using cyber duck tool we can import any thing into linux server from windows.using ip,username,password,port. http://www.v3.co.uk/v3-uk/download-review/2032496/cyberduck-windows-v401

2- wget http://ftp.drupal.org/files/projects/modulename-7.x-1.0-rc2.tar.gz

```
 mkdir -p /home/force_password_change-7.x-1.0-rc2.tar.gz -C /home/www/html/transgenic/sites/all/modules/modulenmae

```

procedure -open terminal and give the download link adrress(above format) it will download save on desktop and follow second command and you can able to see your module,in modules.
> 0 votes

---
Tags: 7
---


# Question
Title: Redirect SimpleTest queries to a different database
How can I tell SimpleTest to use a different database than the default connection? I want to be able to run the tests against an in memory database while keeping the local data on disk.

UPDATE:

So far the answers I'm getting are on how to set up tmpfs and move mysql data to that folder. That's great and super helpful. However this is missing the specific answer that I am looking for. I'm most interested in how to run SimpleTest against a different connection than the default database connection. You can see above that my question reflected by both the title and the first line of my original submission. I apologize for the confusion caused by my mention of an in memory database, I provided that only as context, but it is not the root of my question.

# Answer
It's not possible to do this on a storage engine level. You can't install Drupal on top of the HEAP storage engine, there are various missing features, the most obvious one being: "MEMORY tables cannot contain BLOB or TEXT columns." (copied from the link in the comments).

The qa.drupal.org testbot's have the complete MySQL data directory in a tempfs that is stored in memory, which is copied from the real file system during startup and back during shutdown. I don't think that's a doable setup for a development environment because, at least in my case, databases of real sites quickly get too big for something like this (Working on large sites with multiple GB of data). http://drupal.org/node/466972 has some more tipps and scripts for the tempfs thing. Make sure to read the comments.

Not sure what exactly takes 2,5m in your case, I can run a single test in ~10s (Note that every test method is a separate test that runs in a new installation).

I'm quite sure that I've already written quite a list of tipps on how to speed up tests in an answer somewhere but I'm unable to find it. The most important thing is defining `$profile = 'testing';` in your test class, that will only install the absolutely required modules for Drupal to run. Speeds up test runs by ~50%. Another way is prefixing your different test methods with anything other than `test` and having a single public test method that calls all other. Downside is that your tests then run in the same environment and might affect each other. You e.g. can't have hardcoded node id's and things like that.

Another thing is optimizing your mysql configuration, than can speed up tests quite a bit as well, see http://techblog.md-systems.ch/blog/improve-mysql-performance for a start.

To actually override the used database connection, you need to completely overwrite the setUp() method where the connection is created and activated and instead use whatever connection you want, see DrupalWebTestCase::setUp().
> 4 votes

# Answer
I am now running SimpleTests with MySQL on a tmpfs folder, and the execution time went from 27 seconds to 5 seconds. I'll explain how I did it.

* Create a tmpfs folder

```
mkdir /var/tmpfs
mount -t tmpfs -o size=1G tmpfs /var/tmpfs
chown -R mysql:mysql /var/tmpfs/mysql

```
* Copy your MySQL data into the tmpfs directory

```
sudo service mysqld stop
cp -Rv /var/lib/mysql /var/tmpfs/
chown -R mysql:mysql /var/tmpfs/mysql

```
* When you want to run some tests, configure my.cnf to use tmpfs.

```
#/etc/my.cnf
[mysqld]
datadir=/var/tmpfs/mysql

```
* Start mysqld

```
sudo service mysqld start

```

The data won't be persistent but it shouldn't be a problem since the website used for testing should not be in a production environment. Anyway you can always switch back to datadir=/var/lib/mysql when you need to save data.

Note that it still worth adding the 'testing' profile to the DrupalTestCase class

```
protected $profile = 'testing';

```

Indeed, on the same without the above it went up to 12 seconds, instead of 5 seconds.
> 3 votes

# Answer
If you want to perform tests on the current database (usefull to test your specific cases of data migration) you could override `DrupalWebTestCase::setUp()` and also `DrupalWebTestCase::tearDown()`. Here some exemple by Trellon.com http://www.trellon.com/content/blog/forcing-simpletest-use-live-database

As for me I use something like this:

```
abstract class DwCurrentDbBasedTestCase extends DrupalWebTestCase {

  /**
   * Override setUp().
   *
   * Avoid creating a new database and install for testing.
   * We want to use current. Our CI will check project build.
   */
  protected function setUp() {
    global $conf;

    $conf['error_level'] = 2;

    $this->originalFileDirectory = variable_get('file_public_path', 'sites/default/files');
    $this->public_files_directory = $this->originalFileDirectory . '/simpletestFiles';

    // Use the test mail class instead of the default mail handler class.
    variable_set('mail_system', array('default-system' => 'TestingMailSystem'));

    // Simpletest needs this to run any tests
    $this->setup = TRUE;

    // @see drupal_web_test_case.php
    $modules = func_get_args();
    if (isset($modules[0]) && is_array($modules[0])) {
      $modules = $modules[0];
    }
    if ($modules) {
      $new_modules = array();
      foreach ($modules as $module) {
        if (!module_exists($module)) {
          $new_modules[] = $module;
        }
      }
      if (count($new_modules) > 0) {
        $success = module_enable($modules, TRUE);
        $this->assertTrue($success, t('Enabled modules: %modules', array('%modules' => implode(', ', $modules))));
      }
    }
  }

  /**
   * By default this method will remove testing env, avoid this in below code.
   */
  function tearDown() {
    // In case a fatal error occurred that was not in the test process read the
    // log to pick up any fatal errors.
    simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE);
  }
}

```
> 1 votes

---
Tags: database, testing
---


title: Raw menu data in block.tpl.php

text:
# Question
Title: Raw menu data in block.tpl.php
I need to access the raw menu data in a menu block, but `$content` only stores the rendered markup. How can I gain access to this object from within the `block--sidebar_second.tpl.php` file?

I've looked into creating a View but I couldn't figure out how to select menu nodes. Either solution will work for me...

Here is the output of the `$block` object:

```
stdClass Object
(
    [bid] => 196
    [module] => menu_block
    [delta] => 7
    [theme] => theme-name
    [status] => 1
    [weight] => 0
    [region] => sidebar_second
    [custom] => 0
    [visibility] => 0
    [pages] =>
    [title] => Services Menu
    [cache] => -1
    [subject_array] => Array
        (
            [#markup] => Services
        )

    [subject] => Services
    [last_in_region] => 1
)

```

# Answer
If you need the menu array structure in your block theme template, you need to implement a `template_preprocess_block()` in your theme's **template.php**:

```
//@TODO: replace MYTHEME with your theme name
function MYTHEME_preprocess_block(&$variables) {
  //Only add on sidebar_second region
  if($variables['block']->region == 'sidebar_second') {
    //Replace "my-menu" with the machine name of your menu
    $variables['menu'] = menu_tree_all_data('my-menu');
  }
}
//after flushing caches $menu should be available in your block template.

```
> 1 votes

# Answer
It sounds like you are using Menu block module, and you would have already successfully placed the menu-tree in your region. If your desire is to access raw menu data from a menu block, just use TEMPLATE\_preprocess\_block(&$variables).

$variables\['content'\] is rendered.
**$variables\['elements'\]\['#content'\]** is raw.
> 2 votes

---
Tags: 7, routes, blocks
---


# Question
Title: Get the node count by its node type and node status in Drupal 8
I was wondering how to get the number of nodes I have, filtered by the node count and status.

For example: how many published articles I have.

I was thinking about using Entity Query to get the node count.

# Answer
> 6 votes
This function will give you the count of the node by its status and content type.

Example: if nodeCountState(1,'article');

the count of number of nodes in the article content type which is published will be displayed.

```
 public function nodeCountState($status, $type) {
    $query = \Drupal::entityQuery('node')
            ->condition('status', $status)
            ->condition('type', $type);
    $result = $query->count()->execute();
    return $result;
  }

```

Hope this help some one :)

---
Tags: nodes, 8
---


# Question
Title: programatically find unpublished node count in drupal
I have a task to find how many node are **unpublished** in a particular **content type**. Have to use the count for some other purposes.

How can I do that?

# Answer
You just want to query the node table for example

here a sample function sent the content type machine name to this function will give you unpublished node count:

```
function get_unpublish_node_count($type){
            $db_query = db_select('node','n')
            -> fields('n',array('nid'))
            -> condition('n.status',0,'=')
            -> condition('n.type',$type,'=')
            $result = $db_query->countQuery()->execute()->fetchField();
            return $result;
}

```

Same function you can use this for published node count

```
function get_publish_node_count($type){
            $db_query = db_select('node','n')
            -> fields('n',array('nid'))
            -> condition('n.status',1,'=')
            -> condition('n.type',$type,'=')
            $result = $db_query->countQuery()->execute()->fetchField();
            return $result;
}

```

just change the status to "1" will give you published node count

Hope this helps :)
> 3 votes

# Answer
```
$result = db_query("SELECT COUNT(*) FROM {node} WHERE type = :type AND status = 0", array(':type' => 'YOUR_NODE_TYPE'))->fetchField();

```
> 1 votes

# Answer
> The Node Type count module do the same as you require.
>
> ```
> This module is used to Show a count of nodes of a particular content-type and also number of Users of particular role type.
>
> ```

This module will be used for statistical and dev purposes only.

```
function node_type_count_published($content_type, $status = NODE_PUBLISHED) {
  $query = new EntityFieldQuery();
  // Grab nodes.
  $query->entityCondition('entity_type', 'node')
     // Filter by type.
    ->entityCondition('bundle', $content_type);

  if ($status) {
    // Filter by published.
    $query->propertyCondition('status', NODE_PUBLISHED);
  }
  else {
    // Filter by unpublished.
    $query->propertyCondition('status', NODE_NOT_PUBLISHED);
  }
  // Count.
  $query->count();
  $result = $query->execute();
  return $result;
}

```
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Is there a way to add content templates for blog
I've been asked to add templates (where a blog post is pre-created with certain content) and the user simply selects it and make minor changes. Please note this is not a visual template, but a content one.

Thanks!

# Answer
Go to Manage fields

Ex: `/admin/structure/types/manage/article/fields`

Then **click on edit**, for example, the body field. Look for **Default Value** and put whatever you want there.

Now when a user tries to add a new article, it will have the body pre-filled-out and they can change it if they wish.
> 1 votes

# Answer
You can theme template by content type. You need to create a node--blog.tpl.php and write your code in here. Check out this link for more info.

https://www.drupal.org/node/17565
> 0 votes

---
Tags: 7
---


# Question
Title: How to add crumb for each search result item?
I want to add crumb/breadcrumb on each of search result item.

For example, if I search keyword **"dog"**, the search result should return results as follow.

---

Dog's Life ($title)
Dog is life. Dog is love... ($snippet)
Home \> Article \> Dog's Life (the crumb)

---

Dog Dog Who's There ($title)
Who's there dog? Dog dog dog... ($snippet)
Home \> Tips Trick \> Dog dog Who's There (the crumb)

---

Usually I construct the crumb using variable $url from `search_result.tpl.php` via function `mytemplate_preprocess_search_result()`, implemented in `template.php`.

I create a new variable, $breadcrumb, based on variable `$url` and then I call it on `search_result.tpl.php`. Then I copy `search_result.tpl.php` into my theme folder.

The problem arises when it is no longer achievable to construct crumb from `$url` due to circumstances, mostly because of custom breadcrumb that is not related with URL.

Please guide me to achieve that goal, a different approach is welcome. Thanks.

# Answer
> 1 votes
If you already have a function to get breadcrumb from URL and assuming breadcrumb is, when is it, customize by hook\_menu\_breadcrumb\_alter hooks, you just have to call this hook :

```
// Allow modules to alter the breadcrumb, if possible, as that is much
// faster than rebuilding an entirely new active trail.
drupal_alter('menu_breadcrumb', $active_trail, $item);

```

If this isn't enough to fix your problem, you can also see this contribution on github which seems great regarding the default breadcrumb construction in Drupal : https://gist.github.com/arshad/5490042#file-gistfile1-php-L12

Hope that helps :)

---
Tags: 7, search, breadcrumbs
---


# Question
Title: Rule to create a new view when a node is created
I have an event registration site that uses the Entity Registration module for its registration forms. There is also an admin section that uses the Views Data Export module to export all of the registration details. The trouble is there is no views field (like there is with Webform) that says get all fields from this registration. As the site hosts multiple events throughout the year, it means that I have to create a new view for each event.

Is there a way to use rules to create a new view or (preferably) view display when saving a node of the Event type.

# Answer
> 2 votes
I think a better solution would be to use a single view with a contextual filter here. I don't have experience with the Entity Registration module but since it's entity based it should have an Registration id contextual parameter which you can give a default from the url.

---
Tags: views, rules
---


# Question
Title: White screen after installing on Ubuntu 15.04
I got the following error while installing Drupal 8 on Ubuntu 15.04.

> Uncaught PHP Exception Drupal\Core\Database\DatabaseExceptionWrapper: "SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'checksum' in 'field list': INSERT INTO {cache\_config} (cid, expire, created, tags, checksum, data, serialized)

I downloaded Drupal via `drush dl drupal-8 --select` and used the beta15 branch. The web facing install screens ran perfectly. It was only after pressing either link for visiting the site or running the update script did this error occur.

How might I begin trying to fix this?

The output of `php -v` is the following.

> PHP 5.6.4-4ubuntu6.2 (cli) (built: Jul 2 2015 15:29:28)
> Copyright (c) 1997-2014 The PHP Group
> Zend Engine v2.6.0, Copyright (c) 1998-2014 Zend Technologies
> with Zend OPcache v7.0.4-dev, Copyright (c) 1999-2014, by Zend Technologies
> with Xdebug v2.2.6, Copyright (c) 2002-2014, by Derick Rethans

MySQL version is *14.14 Distrib 5.6.25, for debian-linux-gnu (x86\_64) using EditLine wrapper*.

# Answer
> 0 votes
I think that this error is recoverable if you drop the `cache_config` table because cache tables are created dynamically at run time if they do not exist when using a database backend.

Like Brady suggested there may be a bug in the Drupal installer where that table was not created correctly. To dig more into this bug, if you're interested, you would need to look at the MySQL log to see what happened and try to reproduce it.

---
Tags: 8
---


title: How can I create an image gallery?

text:
# Question
Title: How can I create an image gallery?
Currently I am running in D7 with the following modules:

* Media 7.x-2.0
* Views 7.x-3.7
* Colorbox 7.x-2.4

I am trying to create an image gallery using these modules with the following steps. Please note problems I am running into will be in bold.

1. Go to admin/structure/views
2. Click Add new view
3. Select File for show, and image for type
4. Unchecked Create a page, and check Create a block
5. Select Grid of File for Display Format
6. Click Continue and Edit

This is where things go off the rails for me, what I would like to do is have ALL images that are tagged display in a custom image style I already created (200x200) in a 4 column grid, and when you click on them they open up into a normal sized image colorbox.

Now I have seen this done when you create a image content type, but that way is clunky compared to using the media module, and I have to believe that there is an easy way to do this with these modules, and I am simply missing it.

I have read about Media Gallery module, but there seem to be a lot of errors with it and I am not thrilled with the idea of it.

Any help on how to get what I am trying to do done would be greatly appreciated as this is becoming a bother.

# Answer
I don't see anything in bold but is the issue showing the image in your custom style or having it open in a modal?

For the latter, opening the image in a modal, you would need to set one field item to be the colorbox trigger.

The trigger needs to be a field you have already added, in your case the image field which you will use the custom display format with. Then you add the image field again with the desired popup format. You set this field to display within the colorbox trigger.

There are several related screencasts on drupal.org that may help:

https://drupal.org/project/colorbox
> 0 votes

# Answer
When you add image field in your view there in settings you will have to make **colorbox(formatter)** and for on click pop up select **Colorbox image style** Configure your view settings.
> 0 votes

---
Tags: 7, views, javascript, media
---


# Question
Title: How to customize home page layout according to the user?
I have a site with more than 2000 users. Users can log in to the site, can see the content, make it as his favorite etc. My home page (Dashboard of user) has different blocks created of views.

How can I allow users to customize the position of these blocks?

They can show/hide blocks, change the position (region) of blocks, can select which content need to show from the view results, change the sort criteria.

# Answer
> 0 votes
It would be quite hard to provide an exact answer as I don't know how you can affect the view results in your setup. In terms of the rearranging the content and even to save the settings I would suggest that you create a new 'textarea' user field which will be hidden in the front end and use a jquery plugin like this: https://github.com/troolee/gridstack.js to update the value of the field using AXAX when the onchange event fires. That way when you load the homepage you can request that user field and arrange your blocks in the order they wanted. You could use a similar approach for which content is shown and then read it back on page load and pass it to the view as an argument.

# Answer
> 0 votes
# Option 1: Homebox

The Homebox module might be a possible fit (only an RC1 release for D7 though, but about 4.500 reported installs). Here are some details about it, from its project page:

> Homebox allows site administrators to create dashboards for their users, using blocks as widgets. Blocks in a Homebox page are resizeable, and reorderable by dragging.
>
> Homebox is currently used on Drupal.org for the 'Your Dashboard' feature.

Summary of its features (also from its project page):

> * Create as many homebox pages as needed.
> * Each homebox pages as its own access permissions by role.
> * Block layout and status is saved per-user, so each user can reorder, resize, add and remove blocks to meet their specific needs.
> * Layout settings autosaved via AJAX.
> * Users can set color (manually or via Color Picker) for each block (available colors are defined per homebox pages).
> * Integrated with Views 2 and its exposed Ajax filters. Exposed filter settings are saved between sessions.
> * All Homebox pages are alias-able via the core Path module.
> * Uses the block system, so anything that can be exposed in a block can be made available to Homebox.
> * Comes with documentation through the excellent Advanced help module.
> * Homeboxes may be placed in code via hook\_homebox().
> * Import/export homebox pages.
> * Optional block title overrides.
> * Option to have a Homebox appear on a user profile tab.
> * Easily create custom region layouts (easier than Panels).
> * User-added custom blocks.
> * Option to disable theme block regions so homebox can go full-width.

# Option 2: Dashboardify

The relatively new Dashboardify module (which has an official D7 release, but only about 50 reported installs) is a possible alternative. Here are some details about it, from its project page:

> Dashboardify is a module for creating complex dashboards.
>
> Each user with proper permissions can add any block to dashboard and rearrange blocks order on his or her dashboard page. There is one dashboard with predefined regions available for each user. User can add unlimited instances of the same block which can be useful for views blocks with different contextual filters applied. Along with block information module stores data what contextual filters were used while adding block to dashboard. Block order is autosave via AJAX.

---
Tags: views, dashboard
---


# Question
Title: Why dropdown menus does not work with all themes?
I am testing few drupal-6 themes for my blog and I observe that the drop-down menus in one theme does not show in another theme. I am specifically testing with Blogbuzz and Jackson. In my case, Blogbuzz shows the drop-down menus whereas Jackson does not. I have ticked the expanded options in the menues primary links in both cases, but I dont see the dropdown menus in Jackson. How can i make the jackson theme to show me the dropdown menus?

# Answer
> 0 votes
The Jackson project page says:

> jQuery for Superfish and pngFix (optional): In order to use the styles created for the Superfish drop-down menus and to fix the IE6 transparent png issue, you will need to download the following files and add them to the Jackson \> scripts folder which you will need to create.
>
> Please note primary links can be created and are styled to work without drop-down navigation.
>
> The following scripts are to be added only if you would like to use drop-down navigation on your website, or if you would like transparent images to display correctly for IE6.
>
> jQuery pngFix Plugin by Andreas Eberhard jQuery Superfish Plugin by Joel Birch

By default, it is set not to use drop-downs.

# Answer
> 0 votes
I tested several modules and finally opted by writing the menu in PHP, which reads directly from the Drupal system. You can check the following object and its properties:

```
$a = menu_tree_output( menu_tree_page_data("main-menu") );
foreach($a as $key => $value){ ... modify... write...each link ... }

```

---
Tags: theming, routes, navigation
---


title: Views conditional filter

text:
# Question
Title: Views conditional filter
Is it possible for me to apply a filter in a view on a field only if that field is not empty? In other words if the field is empty the filter is not applied (and the row is shown), and if the field is not empty the filter is then applied and determines whether to show the row or not based on the field value.

My particular use case is a job expiry date. If no expiry date is entered I want the job to show, but if an expiry date is entered, then this determines if the job is displayed or not based on the current date.

# Answer
It's possible to set up 2 filters:

1. Filter operating on date (as you described)
2. Filter "job expiry" field is empty

Then use the drop-button right of `Filter crieria`, go to `And/Or, Rearrange` **and change the operator for group to OR**

Let me know, if you need further assistance.
> 1 votes

---
Tags: views
---


# Question
Title: Language switcher with country code and title
For my responsive site i try to override the language switcher block to get both, the long title of the country and the short code. So I can change the display for smartphone or desktop.

I dont know whats the best solution, print a second block or gives out an array with 2 links in a list element. These code overrides only the title.

```
   function mytheme_links__locale_block(&$vars) {
      foreach($vars['links'] as $language => $langInfo) {
        $vars['links'][$language]['title'] = $vars['links'][$language]['language']->language;
      }
      $content = theme_links($vars);
      return $content;
}

```

# Answer
> 1 votes
You have to copy and paste the entire theme\_links function and rename it like you did `mytheme_links__locale_block`

```
function theme_links__locale_block($vars) {
  $links = $vars['links'];
  $attributes = $vars['attributes'];
  $heading = $vars['heading'];
  global $language_url;
  $output = '';

  if (count($links) > 0) {
    // Treat the heading first if it is present to prepend it to the
    // list of links.
    if (!empty($heading)) {
      if (is_string($heading)) {
        // Prepare the array that will be used when the passed heading
        // is a string.
        $heading = array(
          'text' => $heading,
          // Set the default level of the heading.
          'level' => 'h2',
        );
      }
      $output .= '<' . $heading['level'];
      if (!empty($heading['class'])) {
        $output .= drupal_attributes(array('class' => $heading['class']));
      }
      $output .= '>' . check_plain($heading['text']) . '</' . $heading['level'] . '>';
    }

    $output .= '<ul' . drupal_attributes($attributes) . '>';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = array($key);

      // Add first, last and active classes to the list of links to help out themers.
      if ($i == 1) {
        $class[] = 'first';
      }
      if ($i == $num_links) {
        $class[] = 'last';
      }
      if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
         && (empty($link['language']) || $link['language']->language == $language_url->language)) {
        $class[] = 'active';
      }
      $output .= '<li' . drupal_attributes(array('class' => $class)) . '>';

      if (isset($link['href'])) {
        // Pass in $link as $options, they share the same keys.
        $output .= '<div class="desktop-only">';
        // This will give the native name of the lang like 'Français'
        $output .= l($link['language']->native, $link['href'], $link);
        // This will give the name of the lang like 'French' if the website is in English
        // $output .= l($link['language']->name, $link['href'], $link);
        $output .= '</div>';
        $output .= '<div class="mobile-only">';
        $output .= l($link['title'], $link['href'], $link);
        $output .= '</div>';
      }
      elseif (!empty($link['title'])) {
        // Some links are actually not links, but we wrap these in <span> for adding title and class attributes.
        if (empty($link['html'])) {
          $link['title'] = check_plain($link['title']);
        }
        $span_attributes = '';
        if (isset($link['attributes'])) {
          $span_attributes = drupal_attributes($link['attributes']);
        }
        $output .= '<div class="desktop-only">';
        // This will give the native name of the lang like 'Français'
        $output .= '<span' . $span_attributes . '>' . $link['language']->native . '</span>';
        // This will give the name of the lang like 'French' if the website is in English
        // $output .= '<span' . $span_attributes . '>' . $link['language']->name . '</span>';
        $output .= '</div>';
        $output .= '<div class="mobile-only">';
        $output .= '<span' . $span_attributes . '>' . $link['title'] . '</span>';
        $output .= '</div>';
      }

      $i++;
      $output .= "</li>\n";
    }

    $output .= '</ul>';
  }

  return $output;
}

```

Inside the code you will find the version for mobile and desktop with class added.

```
    $output .= '<div class="desktop-only">';
    // This will give the native name of the lang like 'Français'
    $output .= l($link['language']->native, $link['href'], $link);
    // This will give the name of the lang like 'French' if the website is in English
    // $output .= l($link['language']->name, $link['href'], $link);
    $output .= '</div>';
    $output .= '<div class="mobile-only">';
    $output .= l($link['language']->language, $link['href'], $link);
    $output .= '</div>';

```

Then you'll have to hide the link (`display:none;`) in CSS depending on the resolution of you screen (with media queries)

---
Tags: theming, i18n-l10n
---


# Question
Title: Add HTML to Page Title for Entity (Profile2)
I have a Profile2 page where I want to add some HTML into the page title (I want to insert a fontawesome icon). I am using Display Suite to layout the Profile2 page with a custom view mode.

I have succeeded in over-writing the title using the function hook\_profile2\_view\_alter() and drupal\_set\_title(), but drupal\_set\_title() uses check\_plain, which strips out all the extra html. I tried using hook\_preprocess\_page, but there is no title variable available. I think this is because Display Suite takes over the title variable, and renames it as label. I also tried the html\_title module without any luck, as I'm pretty sure this is because it only works on nodes and not on entities. I also tried hook\_preprocesss\_profile2 (having first used mymodule\_preprocess\_entity(&$variables, $hook) to create the function suggestion), but this function doesn't seem to be running on the page. I'm not sure if this is because I'm using display suite or a custom view mode.

Any help much appreciated, as I seem to be running out of options.

# Answer
> 0 votes
I solved this by adding the HTML to a custom page template based on the user role and profile. I used the following code to create the template suggestion in the template.php file:

```
function MYTHEME_preprocess_page(&$variables) {
  global $user;
    if(arg(0) == 'profile-carer' && in_array('my custom role', $user->roles)) :
      $variables['theme_hook_suggestion'] = 'page__profile_carer_my_custom_role';
    endif;
}

```

I was then able to use the custom template `page--profile-carer-my-custom-role.tpl.php` based on the page.tpl.php

# Answer
> 0 votes
I have also since found another method explained at Display Suite and HTML node titles

---
Tags: theming, entities, users, display-suite
---


# Question
Title: How to count number of field collection items for a row in a view?
I just want to count the number of field collections items in a row. I am working on a view. In the view I am able to show the field collection items value, but I do not want the value I just want to count number of items per row.

I am trying view aggregate but its showing sql errors.

# Answer
While it may be possible with just using Views. I find it easier to do this type of 2-step logic in Drupal with additional information.

For example use Computed Field module to store an `integer` value in the field on `node save` for a custom computed field called `number_of_fc_values` or whatever you want to call it. You then just count the number of field collection items on save using PHP.

For example your PHP could look like the following for the computed value PHP field, this example API usage is taken from https://drupal.stackexchange.com/a/84282/3279

```
$node_with_fc = node_load($node->nid);
$items = field_get_items('node', $node_with_fc, 'NAME_OF_FC_FIELD');
return count($items);

```

Now in your View you simply add your `number_of_fc_values` field to the field values for the row display.
> 1 votes

---
Tags: views, entities
---


title: Local site not working

text:
# Question
Title: Local site not working
I've pulled down a site using dev desktop but none of the styles are working. I think it's a problem with the settings file.

There are multiple sites on this environment. In Dev Desktop, I chose to clone an environment, specified a specific site, and cloned it locally. I am able to view the site and images but the stylesheets are loading. I also can't access the admin area. Drush seems to work fine.

The only error I'm seeing is "The file could not be created." In the past I've had to create a settings.local.php file but that doesn't seem to be working, either.

Any thoughts as to what I'm doing wrong?

# Answer
The message `The file could not be created` indicates a permissions issue to me. Make sure that the webserver has the ability to create files in all the places in needs.
> 0 votes

---
Tags: 7, acquia-dev-desktop
---


title: How to trigger Ajax forms machinery

text:
# Question
Title: How to trigger Ajax forms machinery
I'm working on ajaxifying a form which uses Hierarchical Select widget. I need to update a text field based on the value of HS and a couple of other fields. I want to use Drupal forms Ajax API. I followed the http://drupal.org/node/752056. Now the form is updated when user fills in the text fields. But I can't cope with HS.

I was told http://drupal.org/node/1630186 HS doesn't support regular Drupal #ajax mechanism. I can easily attach the handler to HS update event. So all I need now is to manually trigger Drupal Ajax machinery from my own handler. How it's best to be done?

I see there is a global Drupal.ajax object but can't figure out how to make use of it.

# Answer
> 6 votes
There is a really simple work around for this. You can add a button or a hidden input field with an ajax callback and trigger this callback by jQuery.

So declare your button:

```
$form['my_button'] = array(
   '#type' => 'button',
   '#ajax' => array(
     'callback' => 'my_callback',
     'event' => 'hs_changed',
   ),
   // hide the button and set a unique id:
   '#prefix' => "<div style='display:none' id='my_ajax_button'>",
   '#suffix' => "</div>"
);

```

In your javascript you can then easily trigger the event with jQuery.trigger:

```
jQuery("#my_ajax_button input").trigger('hs_changed');

```

This will trigger your ajax callback.

http://api.jquery.com/trigger/

http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#ajax

# Answer
> 2 votes
To piggy back on the answer above (I can't comment without 50 reputation...), you can attach a click handler with jQuery and trigger the namespaced event.

```
$form['my_button'] = array(
   '#type' => 'button',
   '#ajax' => array(
     'callback' => 'my_callback',
     'event' => 'hs_changed',
   )
);

```

And create a click handler with custom trigger.

```
(function($) {
  Drupal.behaviors.buttonSubmit = {
    attach: function(context, settings) {
      $('button', context).on('click', function(e) {
        $(this).trigger('hs_changed'); // Fires the AJAX submit
        // Add other button effects or changes below.
      });
    }
  };
})(jQuery);

```

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


# Question
Title: What causes 'Invalid form POST data' when removing an attached file from a node?
I have an attached PDF file on a file field. When I click the 'Remove' button, the AJAX throbber appears and then the file remains unremoved. Adding an file to a new node still works.

I checked the error logs; it states "Invalid form POST data."

What is causing this problem?

# Answer
I can confirm, increasing 'max\_allowed\_packet' in our MySQL config solved this problem. MySQL's default of 1 megabyte was too small. Increasing it to 16M, then restarting MySQL has resolved this issue.

Info on our solution was found here: https://www.shift8web.ca/blog/2014/11/drupal-problem-an-ajax-http-request-terminated-abnormally/
> 2 votes

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


title: Show parent taxonomy term in view

text:
# Question
Title: Show parent taxonomy term in view
I have *taxonomy* **countries list** with cities

```
Czech Republic
 - Prague
 - Brno
Germany
 - Berlin

```

Then I have content type **position** where I am using this taxonomy as select list. Now I need to create table with list of this content type.

Wanted result:

```
Country       || City
--------------||------
Germany       || Brno
Czech Republic|| Prague

```

I have created view for that, but I am not sure how to show parent of taxonomy term.

I have found that How to show the parent and child taxonomy term? but I do not see **Taxonomy term: Term ID**, **Taxonomy term: Parent term** at all

# Answer
* First you need to create a *Taxonomy term on node* relationship to your vocabulary and name the identifier *term*
* Then create a *Taxonomy term: Parent term* relationship using the previous identifier (*term*) as relationship and name the identifier *parent*
* Create a *Taxonomy term: Parent term* contextual filter using *term* as identifier
* Lastly, add a *Taxonomy term: Name* and use the *parent* relationship
> 7 votes

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


title: Conditional View Output?

text:
# Question
Title: Conditional View Output?
A view I'm working on has a linked Title field. By default, this field should link to an internal page with the `[nid]`. E.g. http://www.example.com/node/\[nid\]

However, there is a second link field where, if filled in, the link should be re-written to go to the specified link.

So, if the link field is blank, link to a URL with the `[nid]`. If the link field is filled in, link to the specified URL. I'm unsure of how to have a default behavior and then override it.

How could I accomplish something like this from within Views? Thank you!

# Answer
Views Conditional module, can help you.

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include:
>
> Equal To Not Equal To Greater Than Less Than Empty Not Empty Views conditional allows you to output text based on the result of the condition.

Example screenshots

1. Added Fields in view

2. Views Conditional Field configuration
> 1 votes

---
Tags: 7, views
---


# Question
Title: Changing from a Profile to Standard profile after the installation
Its possible from moving from a custom profile or a Distro and move to a the Standards profile ?

The reason, I'm asking this is because I build a website with the Recruiter distro. At first everybody likes the workflow of the recruiter, then after a while my client ask me to change the entire workflow of the website. I have change some many things from the distro that is not longer useful to have the recruiter profile. I'm running issues with some incompatibility with some modules that the distro is not running the latest version. And I do not think that I need the distro any more.

I have try to move some modules from the `profile/recruiter/module` to `sites/all/modules` and the module does not seem to be working.

So my goal would be to remove the `/profile/recruiter` and move everything to `/sites/all/modules` & `/sites/all/themes`

# Answer
> 0 votes
I figure out how to do it. You will need to use the Profile Switcher module in order to achieve moving from one profile to another one.

---
Tags: 7, updating, distributions, installation-profiles
---


title: Views rewrite results: div in anchor

text:
# Question
Title: Views rewrite results: div in anchor
I am trying to accomplish the following in a views accordion style.

> Here is what I am putting in the rewrite field

```
<div class="session-date">[field_event_date_1]</div>
<div class="session-title">[title]</div>
<div class="session-timeslot">[field_time_slot_1]</div>

```

> Here is what gets rendered

```
<div class="panel-heading">
    <h4 class="panel-title">
      <a class="accordion-toggle views-ajax-processed-processed" data-toggle="collapse" data-parent="#views-bootstrap-accordion-1" href="#collapse0">
        Tuesday, November 3, 2015
Example title description goes here
1A - 10:00 - 11:30 AM
      </a>
    </h4>
  </div>

```

HTML5 spec allows div styling in anchors. Can anyone point me in the right direction?

# Answer
> 1 votes
If this was purely about just views accordian, then the rendering output you show would not be showing a div with a class of panel-heading. I see this as more likely about trying to have a views accordian rewrite into a panel and probably panels accordian at the same time and having the anchor tag reduced to a single line output when the html is stripped out. So without knowing what the full details are I can only suggest trying the rewrite as:

```
[field_event_date_1]
[title]

[field_time_slot_1]

```

or if only the div tags are being stripped out then try:

```
<div class="session-date">[field_event_date_1]</div><br/>
<div class="session-title">[title]</div><br/>
<p><div class="session-timeslot">[field_time_slot_1]</div></p>

```

# Answer
> 1 votes
I was using bootstrap accordion which the module strips out any markup. Although I could hardcode the example, it was pointless to do so in that module. I ended up changing my styling and using views accordion which allowed more grouping options.

---
Tags: views, navigation
---


# Question
Title: Image grid from view with randomly inserted colored squares
I've got a creative challenge here. I've got a view that creates a grid of images linking to their respective content, but my designer threw in a bit of a twist. He wants me to randomly insert colored squares between every 2-3 images. I was looking into creating a custom template for this view to do the inserting, but he'd also like these colors to be editable through the admin. While there are many ways to accomplish this I'm curious to hear your solutions. I could create a "Grid Color" content type, but I'm not sure I want to clutter my content types with such an obscure type.

# Answer
My solution was fairly simple. I created a new content type called "Homepage Grid Spacer" and used auto\_nodetitle to suppress the title. I created a single field of the jQuery Colorpicker type and deleted the body. Now the admin can insert these decorative squares between actual flagged content by creating and flagging them in the same fashion.

I updated my view to select the color code and suppress the image field of the actual content and I used the rewrite to add a div with the color in a data field. I couldn't add the field in a style because Drupal doesn't allow this. Then I added a couple lines of JavaScript to take the data color and make that the CSS background color.
> 0 votes

---
Tags: views
---


title: Plugin versus Module

text:
# Question
Title: Plugin versus Module
Drupal has many specific terms that can have different meanings depending on usage (e.g. view vs. a Drupal View). It looks like another in Drupal 8 is plugin & module. Generically, both seem to imply extending functionality to existing code (e.g. FireFox plugin, WordPress plugin, Drupal module, Angular module, etc.). However, it seems like they are 2 different things in Drupal 8.

As I understand it, D8 plugins (the incorporation of CTools plugins in D8?) are reusable components like a form widget, while modules are extensions to Drupal 8 core code ***that can implement or create plugins***. Is this correct?

# Answer
Yes, you're right: Modules are still modules, the equivalent of what WordPress calls *plugins*. Each module can implement one or more plugins.

For example, the Voting API module has a plugin for each of the methods to show the result: `Average`, `Sum` and `Count`.

Plugins also needs a plugin manager, which is the responsible for actually calling the plugins.

You can see this on:
> 8 votes

---
Tags: 8, plugins
---


# Question
Title: Ajax not output to Ctools modal when using pager
So in my continuing quest to display a form with Solr search results in a Ctools modal window and use a pager, I've managed to get everything to display fine after the initial search, but when I use the pager, I get a white screen with the data in json format instead of everything displayed in the modal again. Here is the relevant code:

```
function imgsearch_page($ajax, $id, $a, $b) {
  if ($ajax) {
    //Load the modal library and add the modal javascript.
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('Image Search Form'),
      'next_field_id' => $id,
    );

    // Use ctools to generate ajax instructions for the browser to create
    // a form in a modal popup.
    $search_form = ctools_modal_form_wrapper('imgsearch_form', $form_state);

    if (($form_state['executed'] && $form_state['ajax']) || isset($_GET['page'])) {
      // If the form has been submitted, there may be additional instructions
      // such as dismissing the modal popup.
      if (!empty($form_state['ajax_commands'])) {
        $output = $form_state['ajax_commands'];
      }

      if ($form_state['values']['search_terms'] != '' || isset($_GET['search_terms'])) {
        $page_num = isset($_GET['page']) ? $_GET['page'] : 0;

        if ($_GET['search_terms']) {
          $form_state['values']['search_terms'] = $_GET['search_terms'];
        }
        $results = nb_image_search_search($form_state['values'], $page_num);

        if (is_array($results['images']) && count($results['images'] > 0)) {
          $next_field_id = $form_state['next_field_id'];
          // Create object to store file and target field info. To be stored in ctools cache.
          $file_info = new stdClass();
          // Generate the field name.  field_images is a multivalue field collection, so we just need the next available option
          // in the $field_images['und'] array. The second number (for field_image) will always be 0 since it
          // is a single value field.
          $file_info->fieldname['url'] = '#edit-field-images-und-' . $next_field_id . '-field-image-und-0-imgsearch-file-url';
          $file_info->fieldname['person'] = '#edit-field-images-und-' . $next_field_id . '-field-person-und-0-value';
          $file_info->fieldname['organization'] = '#edit-field-images-und-' . $next_field_id . '-field-organization-und-0-value';
          $file_info->fieldname['year'] = '#edit-field-images-und-' . $next_field_id . '-field-year-und-0-value';

          $file_info->fids = array();

          // Theme the results as a table.
          $header = array(t('Image'), t('File Name'), t('Add to field'));
          $rows = array();
          foreach ($results['images'] as $image) {
            // Create image style derivative for each image.
            $imagestyle = array(
              'style_name' => 'thumbnail',
              'path' => $image['filepath'] . $image['filename'],
              'width' => '',
              'height' => '',
              'alt' => '',
              'title' => $image['filename'],
            );
            $styled_image = theme('image_style', $imagestyle);
            $fid = $image['fid'];

            $rows[] = array(
              'image' => $styled_image,
              'name' => $image['filename'],
              'add' => ctools_ajax_text_button("select", "imgsearch/nojs/imgadd/" . $fid . '/' . $next_field_id, t('Select')),
            );

            $file_info->fids[$fid] = $image['filename'];

            // Cache values for Person, Organization, and Year if they exist.
            foreach (array('person', 'organization', 'year') as $field) {
              if (isset($image[$field])) {
                $file_info->meta[$fid][$field] = $image[$field];
              }
            }
          }
          //Cache image name in ctools object cache so it can be used later in nb_image_search_image_add()
          ctools_include('object-cache');
          ctools_object_cache_set('imgsearch', 'imgsearch_' . $next_field_id, $file_info);

          // Create a render array ($build) which will be themed as a table with a
          // pager.
          $build['search_form'] = isset($search_form[0]) ? drupal_build_form('imgsearch_form', $form_state) : $search_form;
          $build['imgsearch_table'] = array(
            '#theme' => 'table',
            '#header' => $header,
            '#rows' => $rows,
            '#empty' => t('There were no matching results found'),
          );

          // Attach the pager theme.
          $pager = pager_default_initialize($results['total_found'], $results['rows']);
          $build['imgsearch_pager'] = array(
            '#theme' => 'pager',
            '#parameters' => array(
              'search_terms' => $form_state['values']['search_terms'],
              //TODO: add params for Person, Organization, and Year.
              ),
          );

          $form_state['values']['title'] = t('Search Results');
          $output = ctools_modal_form_render($form_state['values'], $build);

          print ajax_render($output);
          drupal_exit();
        }
        else {
          $build['no_results'] = array(
            'markup' => '<div class="no-results>No images found</div>',
          );
        }
      }
    }
    elseif (!isset($output)) {
      $output = ctools_modal_form_wrapper('imgsearch_form', $form_state);
      // Return the ajax instructions to the browser via ajax_render().
      print ajax_render($output);
      drupal_exit();
    }
  }
  else {
    return drupal_get_form('imgsearch_form', $id);
  }
}

```

The only real difference is that since form field values are removed somehow when the form is submitted via ajax, I use the #parameters element in the pager array, which puts it in $\_GET\[\], allowing me to access it in the search function (nb\_image\_search\_search()). The page argument is also there, put there by the pager. Since ctools\_modal\_form\_wrapper() returns the form in rendered mode, I have to rebuild it again to pass it to ctools\_modal\_form\_render().

Other than that, I don't see any differences. I've stepped through the code all the way to the call to drupal\_json\_encode() in ajax\_render(), but can't get any farther than that.

What would be causing the json to just be displayed on a white screen instead of displaying in the modal, but only when I'm using the pager link?

Thanks.

# Answer
The answer turned out to be a missing class in my pager links. Whenever you use CTools Modal, you have to add the ctools-use-modal class to the link. My first thought was to add the class as a link attribute in the link themeing functions, since the theme\_pager\_link() function accepts attributes (via $values\['attributes'\]). However, the functions that actually call theme\_pager\_link() (e.g. theme\_pager\_previous(), theme\_pager\_next(), and theme\_pager\_last()) don't bother to actually pass attributes, so there's no way to get them to the link function. Sigh.

So, to work around this, I just created a quick jQuery behavior that adds the ctools-use-modal class to the pager links:

```
(function ($) {
    Drupal.behaviors.addCtoolsModalClass = {
        attach: function (context) {
          $('#modalContent .pagination ul li a').addClass('ctools-use-modal');
    }
  }
})(jQuery);

```

and voila!, it works as it should.
> 2 votes

# Answer
use array\_chunks after pager\_default\_initialize.

A small example from my code, hope it will help you.

```
$per_page = 10;
$current_page = pager_default_initialize(count($result['node_ids']), $per_page);
$chunks = array_chunk(node_load_multiple($result['node_ids']),$per_page, TRUE);

```
> 0 votes

---
Tags: 7, ajax, paging, chaos-tool-suite, javascript
---


# Question
Title: How to enable/disable Billing Information in Commerce depending on the payment method
Till now, I have been using only PayPal checkout on my Commerce site, and I have configured the checkout flow so all of the customer's information is collected over on PayPal's site.

However, I am now trying to add Stripe as an alternate payment method. I need to collect the customer's billing info on my site when using Stripe, so I need to add **Billing information** to the checkout pane.

Goal

* Show **Billing information** if the customer selects Stripe as the payment method. If the customer selects PayPal, do not show **Billing information**.

I looked through the various commerce events and actions available in the Rules module, but I couldn't find anything that is helpful for this case.

# Answer
There is no way just through Rules to influence the visibility of a checkout pane. Instead, you'll need to use hook\_form\_alter() and hook\_commerce\_checkout\_pane\_info\_alter(). Why both?

You have to use the form alter to remove or disable the billing information checkout pane when you detect PayPal has been selected, which means you also need the payment method selection to be first (and, in the most simplest case, on its own page).

You have to use the checkout pane info alter to set your own validate and submit callbacks for the billing information checkout pane. These should also check the payment method and only invoke the default callbacks if the proper payment method was selected. The reason for this step is that the checkout form validates / submits checkout panes based on where they're configured to appear in the checkout form, not based on whether or not they were actually present on the finally rendered form. You can alter a pane out of the checkout form's array, but its default validate callback will still process it as if it had been there.

To determine what payment method was selected, look in $order-\>data\['payment\_method'\].
> 3 votes

# Answer
This would need to implement hook\_form\_alter() on your checkout form. You should be able to toggle hidden or not for that pane. From my own experience, you may need to wrap the div you're hiding in another div to have it reappear after hiding it. EG: when a customer is toggling between those two payment methods.
> 2 votes

# Answer
Go to checkout settings page, drag "Billing information" to the disabled section.
> 0 votes

# Answer
There is actually a way to set checkout pane visibility via rules.

You can use the Commerce Rules Extra module.

You then should be able to use the "Process checkout pane" event and have a condition to check the payment method that has been selected (stolen from Ryan's post this should be in the data array - `$order->data['payment_method']`) and an action to change the pane visibility settings.

This is only really going to be user friendly if your payment type checkout pane comes early in the checkout process. In this case having that first up seems logical.
> 0 votes

---
Tags: commerce
---


# Question
Title: Pager not working when $form['table'] is called with AJAX
For a statistics page I let users select the right file in a select list. After that I generate a table with stats. This table also has a pager (that worked without the ajax part).

Now I did everything in an ajax callback, when I now want to click on next page the URL is: http://localhost/drupal2/system/ajax?page=1 and that doesn't work ofcourse.

My code:

```
function push_notifications_theme() {
return array(
'push_notifications_form_table' => array(
  'render element' => 'form',
),
);
}

function push_notifications_form_table_form($form = array(), &$form_state) {
$form = array();
// $id = $_GET['id'];

$qry = db_select('push_notifications_api', 'pt');
$qry->distinct();
$qry->fields('pt', array('app_name'));
$qry->orderBy('app_name', 'ASC');
$names = $qry->execute();
foreach($names as $record) {
$options[$record->app_name] = $record->app_name;
}

$form['title'] = array(
'#type' => 'fieldset',
'#title' => t('Application statistics'),
'#description' => t('Select an application below to see the statistics.'),
'#tree' => TRUE,
);

$form['title']['changethis'] = array(
'#title' => t('Application Name'),
'#type' => 'select',
'#options' => $options,
'#required' => TRUE,
'#ajax' => array(
  'callback' => 'push_notifications_form_table_form_callback',
  'wrapper' => 'replace_textfield_div',
),
);

$form['replace_textfield'] = array(
'#prefix' => '<div id="replace_textfield_div">',
'#suffix' => '</div>',
);

if(!empty($form_state['values']['title']['changethis'])) {

$appname = $form_state['values']['title']['changethis'];
$id = db_query('SELECT app_id FROM push_notifications_api WHERE app_name = :app_name', array(':app_name' => $appname))->fetchField();

$form['replace_textfield']['id'] = array(
'#type' => 'fieldset',
'#title' => t('@appname: Push notifications', array('@appname' => $appname)),
'#description' => t('Newest push notifications are on top.'),
'#weight' => 10,
);

$go_back_link = array(
'!link' => l(t('go back to the overview'), 'http://localhost/drupal2/admin/config/services/push_notifications'),
);

$form['replace_textfield']['goback'] = array(
'#type' => 'fieldset',
'#title' => t('Go back'),
'#description' => t('If you want to view stats from other application you can !link', $go_back_link),
'#weight' => 25,
);

// $query = db_query('SELECT * FROM push_notifications_messages WHERE msg_appID = :app_id ORDER BY msg_timestamp DESC', array(':app_id' => $id));
// $qCount = db_query('SELECT * FROM push_notifications_messages WHERE msg_appID = :app_id', array(':app_id' => $id))->rowCount();

$query = db_select("push_notifications_messages", "n");
$query->fields("n", array('msg_id', 'msg_message', 'msg_receiver', 'msg_device', 'msg_appID', 'msg_timestamp'));
$query->orderBy('msg_timestamp', 'DESC');
$query->condition('msg_appID', $id);
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(15);
$result1 = $query->execute();

$form['replace_textfield']['table'] = array(
    '#theme' => 'table',
    '#header' => array(t('Message'), t('Device'), t('Token'), t('Date')),
    'rows' => array(),
    '#weight' => 15,
    );

foreach($result1 as $key => $result) {
    $form['replace_textfield']['table']["#rows"]["'r$key'"] = array(
        'c1' => array(
            'data' => array('#type' => 'item', '#markup' => t('@message', array('@message' => $result->msg_message))),
          ),
        'c2' => array(
            'data' => array('#type' => 'item', '#markup' => t('@device', array('@device' => $result->msg_device))),
          ),
        'c3' => array(
            'data' => array('#type' => 'item', '#markup' => t('@token', array('@token' => substr($result->msg_receiver, -50)))),
          ),
        'c4' => array(
            'data' => array('#type' => 'item', '#markup' => t('@timestamp', array('@timestamp' => date("d F Y H:i:s", $result->msg_timestamp)))),
          ),
      );
}

$form['replace_textfield']['pager'] = array('#markup' => theme('pager'), '#weight' => 20);

}

  return $form;
}

function push_notifications_form_table_form_callback($form, $form_state) {
// The form has already been submitted and updated. We can return the replaced
// item as it is.
return $form['replace_textfield'];
}

function theme_push_notifications_form_table(&$variables) {
// Get the userful values.
$form = $variables['form'];
$rows = $form['rows'];
$header = $form['#header'];

// Setup the structure to be rendered and returned.
$content = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => array(),
);

// Traverse each row.  @see element_chidren().
foreach (element_children($rows) as $row_index) {
$row = array();
// Traverse each column in the row.  @see element_children().
foreach (element_children($rows[$row_index]) as $col_index) {
  // Render the column form element.
  $row[] = drupal_render($rows[$row_index][$col_index]);
}
// Add the row to the table.
$content['#rows'][] = $row;
}

// Redner the table and return.
return drupal_render($content);
}

```

Screenshot of result:

# Answer
> 0 votes
This sounds like a known bug in core:

Pager, tablesort links in a form point to system/ajax when reloaded via AJAX

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

Someone has offered up a "quick fix" in comment #22:

> As a quick fix I overrode theme\_pager\_link() to set the url of my AJAX-loaded pager to the page url instead of $\_GET\['q'\] (which was system/ajax).

---
Tags: forms, paging, theming
---


# Question
Title: How can i set a pagination in detailed page
How can i set a pagination in detailed pages? for example i have 10 pages in common blogs and the main page contain only the description about the content.When we click on the title of the page or readmore then it will displaying the detail of specified content here i want to set the pager how is it possible?

# Answer
> 0 votes
What you're describing is one of Drupal's most commonly used modules, Views. Views lets you:

* Select any content you want of your choice (in your case blog posts)
* Show only the fields you want on that content (in your case a title link & description).
* Display it in a form of your choice (in your case a dedicated page with a pager).

You shouldn't have any trouble finding tutorials on Views. For example, here is one from Acquia.

---
Tags: paging
---


title: Set option value in a select field

text:
# Question
Title: Set option value in a select field
The array generated gets me the information that I need, but it's created a keyed array where the key is numeric (0..length-1). How do I change it so that key is equal to the value, so that the option value is equal to what is displayed?

```
$page = $sql->execute();
$pages = array();

    // Populate page dropdown
    foreach($page as $p)
    {
      $pages[] = $p->title;
    }
// Display only unique values in the array
$paged = array_unique($pages);

// Sort the array in ASC Order
sort($paged);

$form['group_owner_filter']['select'] = array(
    '#type' => 'select',
    '#title' => t('Filter by Name'),
    '#default_value' => t('Make a selection...'),
    '#options' => $option
  );

```

This generates:

```
<select id="edit-pages" name="pages" class="form-select">
    <option value="0">About Davenport</option>
    <option value="1">Academic Support Center</option>
    <option value="2">Academics</option>
    <option value="3">Adjunct Insurance Scholar Opportunity</option>
    <option value="4">Admissions</option>

```

# Answer
So here is the corrected code. I've changed some variable names to make it easier to understand.

* `$option` and `$pages` became `options`
* `$page` became `$pages`
* `$paged` was retired

As @Sujith-Nara mentions you don't need `array_unique` as the keyed approach will make them unique by default. This does presume that the page titles are unique across the site (which is *not* enforced). You could replace the key with `$p->nid` or `$p-name` if the titles aren't unique.

Because the keys are now strings you can use `ksort` instead of `sort` to order them on the key.

```
$pages = $sql->execute();
$options = array();

// Populate page dropdown
foreach($pages as $p)
{
    $options[$p->title] = $p->title;
    // $options[$p->name] = $p->title;
    // $options[$p->nid] = $p->title;
}

// Sort the array alphabetically in ASC Order
ksort($paged);

$form['group_owner_filter']['select'] = array(
    '#type' => 'select',
    '#title' => t('Filter by Name'),
    '#default_value' => t('Make a selection...'),
    '#options' => $options
);

```
> 0 votes

# Answer
You can also use `drupal_map_assoc()` function to convert a linear array into an asscoiative array.

```
$pages = drupal_map_assoc($pages);

```

> Forms an associative array from a linear array.
>
> This function walks through the provided array and constructs an associative array out of it. The keys of the resulting array will be the values of the input array. The values will be the same as the keys unless a function is specified, in which case the output of the function is used for the values instead.
> 0 votes

---
Tags: forms
---


title: How to create date remainder e-mail?

text:
# Question
Title: How to create date remainder e-mail?
HI i have date field in user profile,after user has been registered based upon current date for every one week i want trigger a mail to user. example-you are one week old,two week old,like that i want to trigger a mail to user,thanks in advance.

# Answer
> 0 votes
This can be done using the power of Rules Module and exactly **Rules Scheduler** which is a part of rules.

1. Create a Rule component with the condition "User has role: Role A" and the action "Send email".

> Events: After saving a new user account
>
> Conditions: None
>
> Actions: Schedule component evaluation

In that Action, I chose these options:

```
Component: the component from step 1
Scheduled evaluation date: account:created
Add offset: 7 days
User > Data Selector: account

```

For an in-depth tutorial on how to set this up please see this blog post on how to use Rules Scheduler to send emails

You also need to likely have your drupal cron job properly configured as well.

---
Tags: rules, emails
---


# Question
Title: How to get nid from URL alias in drupal 7?
I have a URL alias `sitepath/john/video/nature-beauty` where `john = user`, `video = content type` and `nature-beauty = node`. I am trying to get `nid` of node `nature-beauty`. Node title is `"Nature beauty"` actually. I have set node title in URL alias.

Can anyone tell me where am I wrong in below code?

```
   $last_page_visited = $_SERVER['HTTP_REFERER'];
   $alias =$last_page_visited;
   $path = drupal_lookup_path("source", $alias);
   $node = menu_get_object("node", 1, $path);
   $nid=$node->nid;
   print $nid;

```

# Answer
The `$_SERVER['HTTP_REFERER']` will return the full URL, but the function `drupal_lookup_path()` takes only the alias as argument, so parse you URL and pass only the alias, `john/video/nature-beauty` then it will work.

```
$url = $_SERVER['HTTP_REFERER'];
$path = preg_replace('/\//','',parse_url($url,PHP_URL_PATH),1);
$org_path = drupal_lookup_path("source", $path);
$node = menu_get_object("node", 1, $org_path);
$nid=$node->nid;
print $nid;

```
> 6 votes

# Answer
There are number for of ways to get nid but its depend how your page is build. If its a direct node page then you can get using `$_GET["q"]` or using `arg()` function. You can also use `menu_get_object()` function directly and get the `$nid=$node->nid;`.

* `$_GET["q"]` would return like `node/2345` 2345 is your node nid.
* `arg(1)` would return node nid.
> 0 votes

# Answer
There is nothing wrong in your code. Just use `drupal_get_path_alias` instead of `$_SERVER['HTTP_REFERER'];` to get url alias.

If you want to use `$_SERVER['HTTP_REFERER']` you need to parse the it like follows.

```
   $path = $_SERVER['HTTP_REFERER'];
  $filter = preg_replace('/\//','',parse_url($path,PHP_URL_PATH),1);
   $path = drupal_lookup_path("source", $filter);
   $node = menu_get_object("node", 1, $path);
   $nid=$node->nid;
   print $nid;

```
> 0 votes

# Answer
```
$path = drupal_get_path_alias($_GET['q']);
$path = explode('/', $path);
echo $nid = $path[1];

```

Or simply arg(1) will return the node id of the page By using this, you can get the nid of any node. But it should be the detail page of any node
> 0 votes

# Answer
```
global $base_url;
$referrer = substr($_SERVER['HTTP_REFERER'], drupal_strlen($base_url));
$referrer = drupal_get_normal_path($referrer);
$referrer = trim($referrer, '/');
if (arg(0, $referrer) == 'node' && is_numeric(arg(1, $referrer)) {
  $nid = arg(1, $referrer);
}

```

That's it. $base\_url includes subdirectory, if your site is not in server root: http://example.com/drupalsite. drupal\_get\_normal\_path transforms alias into drupal internal path, that is, article/marvelous into node/101. It is actually a wrapper around drupal\_lookup\_path, so the use of the latter is discouraged. And then you get your nid.
> 0 votes

---
Tags: 7, path-aliases
---


# Question
Title: Alphabet sorting does not work properly with unique characters
I've a view with sorting by first character and it does not work properly for unique characters (f.x. danish characters: ø å æ).

What should I do in order to sort they properly?

Thanks.

# Answer
I ended up with writing my own module. It uses hook views\_query\_alter and change SQL query little bit. Module does not have any settings in UI but hardcoded variables so you need to adjust it in order to solve issue with sorting.

```
<?php

/**
 * @file
 * Implements hook_views_query_alter().
 *
 * it adds 'COLLATE utf8_language_ci' to languages that are not supported by default
 * so far there are only few languages we have issues with.
 */
function views_collate_sorting_views_query_alter(&$view, &$query) {
  // views where we want to enable collation
  $views = array(
    'dictionary_overview'
  );

  // exit if the current view is not specified
  if (!in_array ($view->name, $views)) {
    return FALSE;
  }

  // define list of languages we support
  $map = array(
    'da' => 'utf8_danish_ci',
    'sv' => 'utf8_swedish_ci',
    'nb' => 'utf8_danish_ci',
    'es' => 'utf8_spanish_ci',
    'pl' => 'utf8_polish_ci',
  );

  // get current utf8
  $l = $GLOBALS['language']->language;

  if (!array_key_exists ($l, $map)) {
    return FALSE;
  }

  // get current utf8 language which we are going to add to all sort fields
  $utf8 = $map[$l];

  // add COLLATE utf8_xx_ci to all sort criteria
  $orderby = &$query->orderby;
  foreach ($orderby as &$order) {
    $order['field'] .= ' COLLATE ' . $utf8;
  }
}

```
> 1 votes

---
Tags: views
---


title: Use separately the links of $links

text:
# Question
Title: Use separately the links of $links
How to separate the links of the variable $links (in nodes and comments) to be able to place them in various places?

# Answer
You can add variables in `hook_node_preprocess` in the `template.php` file in your theme. Something like:

```
function MY_THEME_node_preprocess(&$vars) {
  // EXAMPLE: add variable according to view mode.
  switch ($vars['elements']['#view_mode']) {

    case 'teaser':
    $link_text = t('Add new comment...');
    // Build render array for link.
    $link = array(
      '#theme' => 'link',
      '#text' => $link_text,
      '#path' => "comment/reply/" . $vars['nid'],
      '#options' => array(
        'html' => FALSE,
        // Make sure it jumps to the right anchor point
        'fragment' => 'comment-form',
        'attributes' => array(
          'class' => array('add-comment'),
        ),
      ),
    );
    $vars['add_comment'] = $link;
    break;
  }
}

```

And then in your `node.tpl.php` you can check for `$add_comment` and print it out using `render()`:

```
    <?php if (!empty($add_comment)): ?>
        <?php print render($add_comment); ?>
    <?php endif ?>

```

You can probably split out the comment link from `$vars` if that is neater.
> 0 votes

---
Tags: 7, theming, hooks, navigation
---


title: Entity_Token breaks token my tokens

text:
# Question
Title: Entity_Token breaks token my tokens
I've got an issue after I installed entity\_token module (Drupal 7)

Now I can't really open admin interface in Drupal that contains tokens.

That is how tokens are displayed without entity\_token

That what happens after I install this module

I've google a bit about it and what I only found is that: https://www.drupal.org/node/1203018 https://www.drupal.org/node/1058912 https://www.drupal.org/project/token\_tweaks \- sounds like a module that fix this issue (which logically for me sounds really wrong, module that fix another module).

My question is what to do :) Please suggest if I've to go with module or patch or there is better way to fix it.

# Answer
I ended up with decreasing Token's limit (see images below)
> 0 votes

---
Tags: entities
---


# Question
Title: How to call disclaimer page on all media files in Drupal?
I want to display a **terms n condition** page on every **media** of website. I collect all media from `file managed` table of database. I also convert `fid` to `url`. Now for each **media url** I need a **disclaimer page**.

My issue is something related to this link.

**For example:**

When I click on *each report of news table* shown below, on clicking of (say) `linux-minimal.pdf` , it first redirect to **some node which is my disclaimer url**, and then **pdf open**.

**How can I achieve this?**

I have tried some code which is actually not working. It is:

```
function hook_init(){
    $get_current_path_media = $GLOBALS['base_url'].'/'.current_path();
    if($get_current_path_media == 'http://my-website/sites/default/files/569338.pdf'){
        drupal_goto('disclaimer');
    }
}

```

# Answer
> 1 votes
Here is an example

```
<a class="test" href="https://bitcoin.org/bitcoin.pdf">bitcoin.pdf</a>

<script>
    $('.test').click(function() {
    alert('Your disclamer goes here');
});
</script>

```

SEE A DEMO HERE

**In Drupal to use jQuery you need to wrap it in**

```
(function ($) {

    //code goes here

})(jQuery);

```

so your code should look like this

```
(function ($) {
  $( document ).ready(function() {
    $('.test').click(function() {
        alert('your disclamer goes here');
    });
  });
})(jQuery);

```

PS: If your div class is outside the `<a>`

```
<div class="test"><a href="https://bitcoin.org/bitcoin.pdf">bitcoin.pdf</a></div>

```

then use it like this

```
<script>
(function ($) {
  $( document ).ready(function() {
    $('.test a').click(function() {
        alert('your disclamer goes here');
    });
  });
})(jQuery);
</script>

```

---
Tags: media, hooks
---


# Question
Title: How to hide tabs, depending on the role of editing using menu_alter
I have 3 types of accounts: **Admin**, **Student** and **Tutor**.

After I turned on the path `user / %user / edit / tutor`, I see two tabs editing: **Student** and **Tutor**. But I want to only display the tab tutor when I edit tutor.

I'm using module profile, which adds tabs unknown way.

Any suggestions?

# Answer
Using hook\_menu\_alter you put restriction by passing role in access argument like "tutor" or "student".

```
function MYMODULE_menu_alter(&$items) {
  $items['menu_item']['access callback'] = 'user_has_role',
  $items['menu_item']['access arguments'] = array('tutor'),
}

function user_has_role($roles) {
  if (user_is_logged_in()) {
    global $user;
    if (in_array('administrator', $user->roles)) {
      return TRUE;
    }
    foreach ($roles as $role) {
      if (in_array($role, $user->roles)) {
        return TRUE;
      }
    }
  }else {
    return FALSE;
  }
}

```
> 0 votes

---
Tags: routes
---


title: Dynamic webforms workflow

text:
# Question
Title: Dynamic webforms workflow
I know how to setup a multi-page webforms (basically add page breaks' between each page). I also know how to use the conditionals to skip certain questions based on the values or state of previous questions.

However, I would like to do this dynamically. So instead of using conditionals to change the workflow, I would like to use my own logic (code) to decide what the next question should be. The reason is I have a webforms with 42 questions (pages) and the actual workflow can change significantly.

All I am really asking is how do I tell webforms what the next question is that should be shown.

I guess it is similar to this question (How to jump to a specific page in a multipage Webform) but the solution quoted (Webform steps Module) does not solve my problem.

# Answer
> 0 votes
Solved.

I added hook\_form\_alter and checked if I am working with webforms (I suppose you can check if you are working with a specific webform), and then added a custom validation call-back:

```
  if (strstr($form_id, 'webform_client_form') !== FALSE) {
    if (empty ($form['#validate']['_set_next_page'])) {
      $form['#validate'][] = '_set_next_page';
    }
  }

```

In the \_set\_next\_page function I get the value of the submitted component. In my case there is only one question per page, but you can easily adapt that

```
$submitted = array_keys($form_state['values']['submitted']);

```

Remember if this is the first page (question), the array looks slightly different, so:

```
  if ($form_state['webform']['page_num'] == 1) {
    $Q = $submitted[0];
  }
  else {
    $Q = $submitted[1];
  }
  // Get the value that was submitted
  $value = $form_state['values']['submitted'][$Q];

```

Assuming $destination holds the 'form\_key' of the question you want to jump too:

```
   if ($destination) {
    foreach ($node->webform['components'] as $component) {
      if ($component['form_key'] == $destination) {
        $nextPage = $component['page_num'] - 1;
        if (($nextPage > 1)
          && ($nextPage < $form_state['webform']['page_count']))
        {
          $form_state['webform']['page_num'] = $nextPage;
          break;
        }
      }
    }
  }

```

I set the page\_num to the page\_number for the destination component to one less, because webforms will increment this value once the submission is processed.

I am sure the code needs some re-finement (make sure that I do not crash and burn while accessing array elements / objects that does not exist) - but you get the idea.

Hope this helps someone else.

---
Tags: webforms, workflows, forms
---