title: How to render a poll within a node?

text:
# Question
Title: How to render a poll within a node?
I'm trying to embed a poll into the body of a node with PHP code:

```
$node = node_load(123);
print node_view($node, 'full');

```

That won't work. What's the trick?

# Answer
> 4 votes
I would add a node reference field to the content type you want to add a poll to, and choose the formatter that renders the referenced poll node (instead of rendering just a link). I must add that I never tried this with poll nodes, but I expect it to work just like it does with other nodes.

# Answer
> 1 votes
If I am looking at the poll.module correctly, you would use `$node=poll_view($node, 'full')` instead of `node_view($node, 'full')` and then run that through `drupal_render()` to display it. If that doesn't work, this is pulled from/based upon the latest poll block\_view:

```
$poll = node_load($nid);
$poll = poll_block_latest_poll_view($poll);

```

and might format it a bit nicer for drupal\_render().

# Answer
> 0 votes
`$poll_node = node_load($poll_nid);`

`$poll_view = node_view($poll_node);`

to render the form use `echo render($poll_view['poll_view_voting']);`

to render the results use `echo render($poll_view['poll_view_results']);`

---
Tags: nodes
---


# Question
Title: Results of autocomplete field in form depending on another field - Drupal 7
I have an **autocomplete** field in a Drupal form made with **Form API**. It works great, suggesting the data from a **db\_query**.

However, I would like to alter this db\_query depending on the selection made in another field of the form (a select field).

But I don't know how to do it, as I would need to change the db\_query parameters *on-the-fly* (Javascript) but they are hard-coded in PHP!!

Is what I want possible at all? (it can be done in pure HTML + Javascript + AJAX PHP but I cannot imagine how to do it in Drupal).

# Answer
Keep a wild card in your autcomplete menu path something like

```
function mymodulename_name_menu() {
  $items['example/autocomplete/%/%'] = array(
    'page callback' => '_mymodulename_autocomplete_callback',
    'page arguments' => array(2, 3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
}

```

In your form

```
function mymodulename_my_form($form, &$form_state) {
// Your select field.
  $form['select_field'] = array(
    '#type' => 'select',
    '#options' => array(
      'option1' => 'Option1',
      'option2' => 'Option2',
    ),
    '#ajax' => array(
      'callback' => '_mymodulename_ajaxcallback',
      'wrapper' => 'replace_autocomplete_field',
    ),
  );
  // A container field
  $form['autocomplete_field_container'] = array(
    '#type' => 'container',
    '#tree' => TRUE,
    '#prefix' => '<div id="replace_autocomplete_field">',
    '#suffix' => '</div>',
  );
  $query_parameter = isset($form_state['values']['select_field']) ? $form_state['values']['select_field'] : 'default_value_to_start_with';
  // Your autocomplete field.
  $form['autocomplete_field_container']['autocomplete_field'] = array(
    '#title' => t('My autocomplete field.'),
    '#type' => 'textfield',
    '#autocomplete_path' => "example/autocomplete/$query_parameter",
  );
}

```

You Automcomplete menu callback

```
function _mymodulename_autocomplete_callback($query_parameter, $string) {
  // Use $query parameter to decide autocomplete field behavior.
}

```

Basically I am trying to update the autocomplete field by attaching '#ajax' behaviour to select field, and while updating the autocomplete field we will change the query parameter which db\_query will use.
> 1 votes

# Answer
I have found this reference: How to dynamically reconfigure Drupal's jQuery-based autocomplete at runtime? However, I see it somehow complicated. I prefer this approach of mine that I am using right now (and working for an exposed filter):

I create a hook to add a Javascript Ajax call to the select list. In that Ajax call, I use a cookie associated to the user, and the value of the selected value in the select list, and insert both in a database table.

Now when I make the Autocomplete call, in the db\_query I use the user cookie and read the value inserted, so I can restrict the suggestions based on that value.

The only problem is that the call is asynchronous, but if the autocomplete function cannot find the cookie value in the table, will yield a warning in the suggestion list, indicating to type more letters or type again, giving time to the first Ajax call to complete.
> 0 votes

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


# Question
Title: Reloading a page from selecting a taxonomy term from a views filter
## general

I have a book containing docs for multiple versions of software.

I want the pages of those books to be searchable and sorted per version.

## specifically

I have a node override provided my panels of a certain content type.

One of those panels is a view displaying the content type that has been tagged with a taxonomy term.

How can I

1. Create an exposed filter that provides a dropdown selection of terms, in this case, version numbers?

and

2. Have the page reload the view after a new term, in this case, the version number, is selected and then submitted via a submit button?

This would preferably be done with contrib modules.

# Answer
No need for contrib modules: it's all in Views.

So firstly you'll need to add a Filter criteria in your View.

1. *Add*
2. Select the term field (Topic in my case)
3. Configure extra settings: *Dropdown*
4. Configure filter criterion: *Expose this filter to vistors*

Secondly you'll need to enable AJAX submits.

1. *Advanced \> Other \> Use AJAX \> Yes*

There are a couple of contrib modules that may be useful however.
> 1 votes

---
Tags: views, panels
---


# Question
Title: How to do multiple file uploads from a block's form?
In the hook\_block\_configure of my block, I'm defining the form for my block. I want it to have multiple file uploads, so I'm using "cardinality", but the following code isn't working for me. I only get the one file field.

```
$form['background_image'] = array(
  '#type' => 'managed_file',
  '#title' => t('A Background Image'),
  '#description' => t('An image file.'),
  '#cardinality' => -1,
);

```

Any ideas?

I'm using Drupal 7.

Note: I don't want to just upload multiple files at once. I want the user to be able to upload "one more file" or delete one of the existing ones.

# Answer
> 1 votes
I think the '#cardinality' it's not a form attribute, I couldn't find on the docs.

But I could find it on the field\_multiple\_value\_form().

I suggest you to take another approach and use the AJAX framework, I found a couple of guides (guide\_1 and guide\_2) that might be helpful.

---
Tags: 7
---


# Question
Title: Download development releases of modules with Drush Make
How do I get a development release of a module in the .make file of my installation profile?

I am writing this now to get the development release of better\_exposed\_filters.

```
projects[better_exposed_filters][version] = "3.0-beta3+31-dev"

```

When I run the .make file I get the following message:

> Could not locate better\_exposed\_filters version 7.x-3.0-beta3+31-dev, will try to download latest recommended or supported release.

# Answer
> 2 votes
I tried generating a Drush make file with http://drushmake.me/, and the generated file contained the following lines.

```
projects[jquery_ui][version] = 1.x-dev
projects[jquery_ui][type] = "module"
projects[libraries][version] = 2.1
projects[libraries][type] = "module"
projects[xmlsitemap][version] = 2.0-rc2
projects[xmlsitemap][type] = "module"

```

I think that in your case you should use the following lines.

```
projects[better_exposed_filters][version] = 3.x-dev
projects[better_exposed_filters][type] = "module"

```

That would select the development snapshot for 3.x; in the case you want to select the 7.x-3.0-beta3 version, then you should use the following lines.

```
projects[better_exposed_filters][version] = 3.0-beta3
projects[better_exposed_filters][type] = "module"

```

The make file needs to contain the following line, which select Drupal 7 as Drupal version to use. This alters the version used for the modules; for example, the following line used with the latter lines I shown, would pick-up version 7.3.0-beta3 of the Better Exposed Filters module.

```
projects[drupal][version] = 7

```

# Answer
> 0 votes
If you need a specific dev version, you need to specify the Git commit ID on the branch you're looking for:

```
; Schema.org
projects[schemaorg][type] = module
projects[schemaorg][download][type] = git
projects[schemaorg][download][revision] = f860c7cc49e95d8420980d0dadd706172cc7955d
projects[schemaorg][download][branch] = 7.x-1.x

```

You can find the commit ID you need by doing the following:

1. Surf to the project page.
2. Click on *Browse code repository*.
3. In the Branch section, click on the branch you want.
4. From the "X.Y-betaZ+A-dev" string, find the Ath commit after the X.Y-betaZ release, and click on it.
5. You'll find the ID in the *commit* row and in your URL address bar.

---
Tags: drush
---


# Question
Title: How to copy current directory into Drupal profile folder via drush?
I've this yml file in my current folder:

```
$ cat profile.yml
api: 2
core: 7.x
projects:
  drupal7:
    type: "copy"
    download:
      url: "file://."

```

and 3 empty files (just for now): `drupal7.info`, `drupal7.install`, `drupal7.profile`.

And I've downloaded fresh Drupal:

```
$ drush -y dl drupal
Project drupal (7.39) downloaded to drupal-7.39.

```

Now I'm trying to copy my profile into Drupal directory via:

```
$ drush make --no-core profile.yml drupal-7.39/
Beginning to build profile.yml.
Non-existent project type copy on project drupal7.

```

and the same with:

```
$ drush make -r drupal-7.39/ --yes --no-core profile.yml

```

This is based on this example:

```
projects[example][type] = "profile"
projects[example][download][type] = "copy"
projects[example][download][url] = "file://./example"

```

but I'd like to achieve that in yml format.

What is the correct syntax then? Or how does it work?

# Answer
I actually had to specify extra `type: "profile"` (to follow this example), so `type` is specified twice (type of project, and type of download), as below:

```
api: 2
core: 7.x
projects:
  drupal7:
    type: "profile"
    download:
      type: "copy"
      url: "file://."

```

Then this would work fine:

```
$ drush make --no-core profile.yml drupal-7.39/
Beginning to build profile.yml.
drupal7 copied from file://..

```

To avoid copying `docroot/` it-self, it's good to actually create a separate folder for profile (as specifying wildcard won't work).
> 0 votes

---
Tags: drush, installation-profiles
---


# Question
Title: Host blocked website due to sending spam from website
My hosting provider has blocked my Drupal website due to: sending spam using local e-mail sockets /var/www/vhosts/site domain/httpdocs/sites/all/themes/chaymae/css/mailer.php.php

I am currently not using the mentioned theme, but this is a standard theme in Drupal. I also have installed the BOTCHA module on the website and it's active. Can anyone help to solve this problem?

# Answer
> 1 votes
Your hosting provided blocked your website, because it was used for sending the spam from using PHP scripts which were suspiciously uploaded to your Drupal installation folder (by using some vulnerabilities).

---

### Why this happened?

There could be many issues, including contrib modules or Drupal core vulnerabilities.

Please follow Drupal Security advisories to be up-to-date.

If your Drupal version is 7.32 or below, there is Highly Critical issue (SA-CORE-2014-005) which people call Drupalgeddon. See FAQ and Drupalgeddon project for more details. Also my GitHub repo (drupageddon) for educational purposes (to understand how it works).

---

### What to do

To prevent that from happening, first of all, check Status/Reports in Administer page to see if you've any Security warnings and your site needs some upgrades.

Then you may consider to log-in to the website (ssh) and scan for suspicious files.

You should look into these tools to help you with restoring your Drupal security:

* Security Review
* Site Audit
* Hacked!

> If you use `drush` (and you've alias set-up to your environment), check for Hacked! module. It can find which core files or modules were hacked, but it could find only modified one, not the one which are extra.

---

If you're using drush, other trick can be to generate your make file (`drush generate-makefile`) from your current Drupal site (however this is probably not necessary, but it keeps track of your old version of modules), then run `drush up`. This will upgrade your Drupal core and all contrib projects and apply any pending database updates. How would that help? It'll actually upgrade all core/module files by replacing old directories with fresh version of stable release files (so any extra files which aren't part of the module would be automatically removed).

### Finding suspicious files

To fix your infected website installation, you need to find files which were hacked and malware files in your Drupal installation folder.

You actually found one at (which is a good start):

> /var/www/vhosts/site domain/httpdocs/sites/all/themes/chaymae/css/mailer.php.php

which needs to be removed as soon as possible. Probably you have more of them.

If there is no access to shell, transferring over FTP (`ncftpget -R`) and checking locally would help. Or find other way to backup your whole site and test it locally for any extra files or hacked files.

If you don't use git, I would suggest you to download your Drupal site into folder and create git repository, so you can track the changes.

For example:

```
git init
git add -A .
git commit -m 'My original files.' -a

```

Then upgrade all your core and modules and review the changes (`git diff`), and commit all again.

Here are few commands which can be useful to find suspicious files (in your webroot):

```
grep -R return.*base64_decode  .
grep --include=\*.php -rn 'return.*base64_decode($v.\{6\})' .
find . -name \*.php

```

Above results doesn't mean necessary suspicious files, but you need to use your common sense to identify which files aren't Drupal. Usually these files are obfuscated.

Please find the following repository with common php-exploit-scripts to give you some idea what you could deal with. See also: What does this malicious PHP script do?

### Unblocking your site

Once you find your problem and identified malware files, then remove these files from the server and upgrade your core and modules to the recent secure version and inform your hosting provider that you've removed malware so they can unblock your site.

---
Tags: 7
---


# Question
Title: How to import a Text File from feeds CSV and map it to a File upload field with multiple values?
> **EDIT:** This issue is directly related to how the Acquia hosting Platform handles private files, not webforms / feeds or feeds tamper.

I've got a site where I need to Migrate the users from a webform they were using, and convert those submissions into user accounts.

I am using Feeds (7.x-2.0-beta1+8-dev) and Webform (7.x-4.8) and feeds Tamper.

I've managed to map all the fields except the Attachment field which is of type `File`. The Attachment field has the ability to attach unlimited files. Here are the three options I have when using the **Mapping** section in Feeds importer:

When I export my CSV from webforms, my Attachment field becomes the parent of every field in my CSV, and won't run until I modify it by removing the Attachment key from the start of the CSV file. (This makes no sense to me.)

After removing the Attachments field I am left with:

> "Email","Name","Filesize (KB)" "testemail@example.com","http://dev.website.ca/system/files/webform/permits/genericfile.txt|http://dev.local488.evsite.ca/system/files/webform/permits/94ufos.txt","55"

In this CSV there is the **Attachment** field and the **Email** field. When the run the CSV import, the user is created but nothing is added to the `file` field. I've tried mapping the **Name** value to all the possible options and it doesn't seem to be outputting anything for me.

When there is multiple values in the **Name** field I am using the `explode` plugin, using `|` as a string separator. I'm just not sure if i'm suppose to pass in an array or values or am I missing a module or something? I've browsed several similar questions but they have to do with `Image` i'm just using text files.

**I am just wondering how can I can use the Feeds `User Importer` to import a regular text file from a CSV file and have it uploaded to the `File` widget in the user's Account page?**

Any tips in the right direction are highly appreciated.

# Answer
The reason I can't get to my files is because i'm using the Acquia platform.

Files in `system/files` are aliased from `/mnt/files/[site]dev/sites/[sitename]/files-private`.

By default drupal webforms output the CSV file with: `http://dev.website.ca/system/files/webform/permits/genericfile.txt`

So when I mapped to the `File` field in the profile page, nothing happened because it couldn't find the file.

I did a quick `Ctrl + F` and replaced the `http://dev.website.ca/system/files/` with `/mnt/files/[site]dev/sites/[sitename]/files-private` inside the CSV file.

(you can find your path with `/admin/config/media/file-system`)
> 0 votes

# Answer
It looks like you're on the right track from: https://www.drupal.org/node/1116130#comment-6827626

I believe you to set it to use an array of values (that's what `explode` returns). The file type itself, image vs text file, is largely irrelevant as you simply want it to work with a multiple item field.
> 0 votes

---
Tags: 7, webforms, importing-exporting, feeds
---


title: Help on error Notice on Modules page

text:
# Question
Title: Help on error Notice on Modules page
I have the following Notices and Warning on the Modules page:

> Notice: Undefined index: name in system\_sort\_modules\_by\_info\_name() (line 951 of /var/www/vhosts/site name/httpdocs/modules/system/system.admin.inc). Warning: uasort() \[function.uasort\]: Array was modified by the user comparison function in system\_modules() (line 802 of /var/www/vhosts/site name/httpdocs/modules/system/system.admin.inc). Notice: Undefined index: name in \_system\_modules\_build\_row() (line 988 of /var/www/vhosts/site name/httpdocs/modules/system/system.admin.inc).

I have searched on the internet for examples of this issue and found some, but the answers didn't help me, because it was about an error in a module i didn't have installed or the answer was too complex for me. Could anyone help me with above error?

I don't even know to which module it is related.

# Answer
> 0 votes
This seems to be related to this issue and there is available patch file for Drupal 7 and UTF-8 file encoding.

So your options are:

* Disable the notice in site settings or in PHP configuration.
* Wait until patch is committed and upgrade your Drupal core.
* Disable faulty module.
* Apply the patch your-self.
* Apply patch manually by opening it and check the changes:

```
--- a/includes/common.inc
+++ b/includes/common.inc
@@ -7369,7 +7369,8 @@ function drupal_parse_info_format($data) {
   $constants = get_defined_constants();

   if (preg_match_all('
-    @^\s*                           # Start at the beginning of a line, ignoring leading whitespace
+    @^(?:\xEF\xBB\xBF)?             # Check for UTF-8 byte order mark and remove it
+    \s*                             # Start at the beginning of a line, ignoring leading whitespace

```

where on the top is the file to edit which is `includes/common.inc` (ignore `a`/`b`), 3rd line is the line number, then remove the lines which starts with minus and replace them these with pluses (without plus signs). If you got the error, then double check your syntax or revert your file to the previous version.

---
Tags: 7
---


# Question
Title: How can I make db_select recognize an empty field?
I am writing a `db_select` in D7 to get various user fields, including the URI's of user's avatars (if it exists).

My initial attempt looked this:

```
$query = db_select('node', 'n');
$query->join('users', 'u', 'n.uid = u.uid');
$query->join('file_managed', 'f',
  'f.fid = u.picture OR u.picture = :null', array(':null' => 0));
$query->fields('f',array('uri'));

```

This *almost* do the job. The only glitch is that if the user has no avatar, the field `uri` always contains the uri pointing to `f.fid` #1. In that case, I want it be missing or empty.

As a workaround, I now execute two db\_selects: First one for all users that have an avatar:

```
$query->join('file_managed', 'f', f.fid = u.picture);

```

Then one for all users without:

```
$query->join('file_managed', 'f', u.picture = :null', array(':null' => 0));

```

I then just concatenate the results. This produces the desired result, but is a bit clumsy.

I would like to do it with one db\_select if that is possible.

# Answer
Just do a left join on 'files\_managed' table

```
$query = db_select('node', 'n');
$query->join('users', 'u', 'n.uid = u.uid');
$query->leftjoin('file_managed', 'f', 'f.fid = u.picture');
$query->fields('f',array('uri'));
$query->fields('n',array('nid'));
$query = $query->execute();
dpm($query->fetchAll());

```
> 1 votes

---
Tags: database
---


title: Views generating JSON output

text:
# Question
Title: Views generating JSON output
I want to pull a JSON file out of a view that has images. This is similar to the way views\_datasource works in D6. I am not a drupal coder, but I would like to give this a try. but I am guessing that is would be something like http://mearra.com/blogs/juha-niemi/drupal-7-custom-node-view-modes#comment-218

but I would like to make this a module as much as possible. any sample code, examples would be great. thanks

# Answer
There is now a Drupal 7 version of Views Datasource. Here is a quote about it (from the module's project page):

> ... is a set of plugins for Drupal Views for rendering content in a number of shareable, reusable formats based on XML, JSON and XHTML. These formats allow content in a Drupal site to be easily used as data sources for Semantic Web clients and web mash-ups. Views Datasource plugins output content from node lists created in the Drupal Views interface in a variety of formats - XML data documents using schemas like OPML and Atom, RDF data documents using a vocabulary like FOAF, JSON data documents in a format like Exhibit JSON, and XHTML data documents using a microformat like hCard.
>
> The project consists of 4 Views style plugins (and related row plugins):
>
> * views\_xml - Output as raw XML, OPML, and Atom;
> * views\_json - Output as Simile/Exhibit JSON, Canonical JSON, JSONP/JSON in script;
> * views\_rdf- Output as FOAF, SIOC, and DOAP;
> * views\_xhtml - Output as hCard, hCalendar, and Geo.
> 4 votes

# Answer
The referenced article is about *view mode* which have nothing to do with Views and almost none with the output format of a page.

Note there is an ongoing effort to port Views Datasource to Drupal 7 with a dev. version available outside of Drupal.org.
> 1 votes

# Answer
views json

> This module is meant for people doing heavy-duty JS work. Knowledge of JSON, jQuery, and a bit of Views internals is needed to fully utilize this module.

views datasource

> Views Datasource is a set of plugins for Drupal Views for rendering content in a number of shareable, reusable formats based on XML, JSON and XHTML. These formats allow content in a Drupal site to be easily used as data sources for Semantic Web clients and web mash-ups. Views Datasource plugins output content from node lists created in the Drupal Views interface in a variety of formats - XML data documents using schemas like OPML and Atom, RDF data documents using a vocabulary like FOAF, JSON data documents in a format like Exhibit JSON, and XHTML data documents using a microformat like hCard.
>
> Views Datasource can be thought of as a userland complement to the work going on in the Services and RDF APIs as a site operator only needs to know Views to be able to create datasources in the different formats.
> 0 votes

---
Tags: 7, views
---


title: Feeds tamper find and replace

text:
# Question
Title: Feeds tamper find and replace
Is it possible with Feeds Tamper to find something in a string and replace all the string with something ?

```
Ex : I've got a .csv file and column 23 can contain something like:
"XL SSR FR RB" or "XL TL RB"

```

I need to find if this column contains SSR, and rewrite everyting to 1 or 0

```
Ex : "XL SSR FR RB"  => "1"
     "XL TL RB"      => "0"

```

Is this something the tamper module can do ?

If it's possible to convert it to boolean it's even better.

Thanks.

# Answer
So you'll need two tampers for that field. From the manual:

1. **Find replace REGEX** Find and replace a user-specified string using REGEX with an option to limit the number of replacements. See the PHP Manual on PCRE Pattern Syntax for a complete reference, or RegexPal for a quick tester.
2. **Convert to boolean** Convert a user-specified string to boolean, with the option of specifying what to do in the case of no match.

Here is a regular expression that will find `SSR` and replace the entire string with it.

https://regex101.com/r/aO0uG3/2

`/\b(SSR)\b/\1/`

Then match `SSR` in the Convert to boolean tamper. (**Note:** The regex in the screen shot is now out of date. Use `/\b/(SSR)\b/` instead)
> 2 votes

# Answer
**Step 1.** Install the Feed Tamper php module and enabled it. https://www.drupal.org/project/feeds\_tamper\_php

**Step 2.** Now select the Excute php code option from add plugin regarding the required.

**Step 3.** Paste the following code there...

```
    //$field contains the value whatever value you are passing by required column

    $required_column_value = $field;
    $find_str = "SSR";

    $pos = strpos($required_column_value, $find_str);
    if($pos){
       return 1;// now $field value would be 1
    }else{
       return 0;// now $field value would be 0
    }

```

**NOTE :: Here don't confuse due to field name username in screen shot it would be your required field name.**
> 0 votes

---
Tags: commerce, feeds
---


# Question
Title: Cron is not working - leading to user/0/edit instead
When I was trying to migrate my site and export the database I realised that the cache\_form field is enormous. According to suggestions I have found online the proper way to solve this is to run cron. So I try to run cron by going to the admin/config/system/cron page, and in there it said that cron was last run 3 weeks ago.

When I press run cron or when I visit the link with the cron key provided in that admin/config/system/cron page, they have both led me to user/0/edit instead of running cron. I did a quick search among the files I have made changes to in the site directory in these three weeks and none of them are leading to user/uid/edit. I wonder what else can I do to solve this properly?

Thanks!

# Answer
> 1 votes
I think your not logged in, that's why going to " user/0/edit " path because you have not permission to run cron. Please check it.

---
Tags: cron
---


# Question
Title: How to create a glossary page in Drupal 7?
I tried to create glossary page like this. I've used Glossary module version 7.x-1.x-dev.

But i couldn't make it work. How to create glossary page in Drupal 7?

# Answer
Option 1: Install https://www.drupal.org/project/views module. Go to Structure \> Views, then enable the 'Glossary' view. View module provide 'Glossary' view by default.

Option 2: Also you can achieve your requirements by installing https://www.drupal.org/project/views\_glossary module.
> 3 votes

# Answer
Here are quite some contributed modules for creating a glossary in a D7 site (quotes are from their project pages):

* Lexicon:

> A lexicon is a stock of terms used in a particular profession, subject or style; a vocabulary. The Lexicon module generates one or more Lexicon pages based on terms in taxonomies and optionally marks terms in the content and links them to the appropriate Lexicon page.
>
> The Lexicon module started out as a fork of the Glossary module project that was changed to suit the needs of a project for the Dutch government and later ported to Drupal 7. The main reason for forking the Glossary module was compliancy with the web guidelines of the Dutch government.
* Glossify:

> The Glossify module provides filters that scan and parse content and replace terms in the text with links to their pages. The d7 version is a complete rewrite of the module to be as simple and performant as possible.
* G2:

> Glossary2 (G2) is an alternative glossary module written for Drupal 4.7 to 7.0, designed for high-volume glossary / dictionary sites.
* Glossary:

> The Glossary module helps newbies understand the jargon which always crops up when specialists talk about a topic. Doctors discuss CBC and EKG and CCs. Web developers keep talking about CSS, P2P, XSLT, etc. This is all intimidating for newbies.
>
> The glossary module scans posts for glossary terms (including synonyms). The glossary indicator is inserted after every found term, or the term itself is turned into an indicator depending on the site settings. By hovering over the indicator, users may learn the definition of that term. Clicking the indicator leads the user to that term presented within the whole glossary or directly to the detailed description of the term, if available.
>
> The glossary uses Drupal's built in taxonomy feature, so you can organize your terms in a Drupal vocabulary. This allows you to create hierarchical structures, synonyms and relations. Glossary terms are represented with the taxonomy terms in the glossary vocabulary. Descriptions are used to provide a short explanation of the terms. You can attach nodes to the terms to provide detailed explanation on the keywords.

Refer to Comparison of Glossary-type modules for lots of information about these modules.
> 2 votes

---
Tags: 7, views
---


title: Render Drupal variable in CKeditor

text:
# Question
Title: Render Drupal variable in CKeditor
im trying to render/display a breadcrumb in a mini panel using both with text format 'PHP code' and 'Display suite code' but it display nothing. it works when i tried with common php code;

```
<?php echo date("Y"); ?>

```

but when i tried with

```
 <?php print render($breadcrumb); ?>

```

nothing is displayed. and

```
<?php var_dump($breadcrumb); ?>

```

return NULL. meaning it cant read drupal variable right? any workaround for this?

# Answer
First thing is this its not a good practice to write the php code in CKeditor because it impact the execution of page and increase the page load time. So it would be better to create the specific page tpl and and render all the drupal variable there.

**Reason ::** Why its not rendering the drupal in CKeditor because after the complete page load its execute the content section of CKeditor and at that page has not page drupal variable (now page has only html content).

Thanks
> 1 votes

---
Tags: panels, wysiwyg
---


# Question
Title: What does it take for field in an entity to be able to be used in cotexetual filter, or relationship?
I am using a view for an entity. I had it working until I changed the cardinality of a taxonomy field. Now that field is no longer available for relationships, or contextual filters. Every other field defined is available as a contextual filter.

So this makes me wonder what determines whether a field can be used in a contextual filter?

# Answer
Since you changed the cardinality to more than 1.

Add a contextual filter of Has Taxonomy Term ID, then scroll all the way down, click on the blue MORE button and checkmark allow multiple values.

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

---
Tags: views
---


# Question
Title: How to automate the transfer of a registered user from Drupal to LimeSurvey?
I have a Drupal site which is using the LimeSurvey Sync module. All is working fine.

Now I want to automate import user in LimeSurvey when user registered in my Drupal site.

Is there any option to do it?

# Answer
I think you are looking for Rules. There you can check events like "After saving a new user account". And your action would be "Page redirect".
> 1 votes

# Answer
You can follow the rules module to redirect the user on specific page by setting the rule after user registration and also you can alter user registration form and set the user redirect after successfully registration.

Thanks
> 1 votes

---
Tags: users
---


# Question
Title: How can I inspect $element variable in theme function?
I would like to change formatter of Field Collection Table, so that class added to a table row corresponds to a value of field of field collection item. As a first step, I would like to inspect theme function of that module. However, if I modify it to:

```
function theme_field_collection_table_multiple_value_field($variables) {
  $element = $variables['element'];
  $header = array();
  $cells = array();

  // Order field widgets by their widget weight.
  $instances = field_info_instances($element['#entity_type'], $element['#bundle']);
  uasort($instances, '_field_collection_table_sort_items_widget_helper');
  foreach ($instances as $field_name => $instance) {
    if (empty($element[$field_name])) {
      continue;
    }

    $header[] = _field_collection_table_get_title($element[$field_name]);
    $cells[] = array('data' => $element[$field_name]);

    // Remove the original field to prevent duplicate printing.
    unset($element[$field_name]);
  }

  $element['field_collection_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => array($cells),
    '#weight' => 0,
  );

  $element['#sorted'] = FALSE;
  dpm($element);
  return drupal_render_children($element);
}

```

no krumo element is displayed. I cleared both opcache and drupal cache several times, but the problem persists. Also, I did deliberate error to make sure, that theme function applies. Do you know, what am I doing wrong?

# Answer
If `dpm($element)` isn't returning output at that stage, you can log the data instead (temporarily) to the watchdog log.

e.g:

```
watchdog('dev', '<pre>' . var_export($element, 1) .'</pre>');

```

You can then view it at *Admin \> Reports \> Recent log entries*
> 1 votes

# Answer
I think you should initialize the $element variable as a array element before this part of code..

```
   **$element = array();**
     $element['field_collection_table'] = array(
        '#theme' => 'table',
        '#header' => $header,
        '#rows' => array($cells),
        '#weight' => 0,

```

);
> -1 votes

---
Tags: theming, debugging
---


# Question
Title: How to display upvoted posts by user in a view?
I want to display nodes upvoted by user in userprofile page in a view. I have number up/down rate widget with nodes, and user can take back votes by clicking on vote arrows.

I tried this:

**Relationship**:

* node:votes
* node: vote results

**Contexual Filters**

* votes:user = -node-votes(user)

**Filter criteria**

* (Vote results) Vote results: Value (\> 0)

**Problem**

first problem is, whenever a user take an upvote back, and upvote again on same node, it duplicates on view result.

second problem = absolute value of vote result in field criteria is greater than 0. and this also brings downvoted posts on this view.

# Answer
> 2 votes
Hi Please check the data filters and widget type, for more details read readme file of module, there is (Views integration section)

Its working great if you configure according to documentation. Thanks!

---
Tags: views, rating
---


# Question
Title: What's the difference between the 2 different Rules pages in admin?
What's the difference between the Rules shown under `Structure > Content Types > My type > Rules` and `Config > Workflow > Rules`? The first one is from Entity Rules (= "*Instead of adding entity related events to Reaction Rules you are able to select which Rules will fire from the bundle management page*").

These pages don't look the same. When do I use one instead of the other (to send emails when nodes are added/edited)?

# Answer
**Entity Rule is not alternate to Rules**

* It simply acts as component which is, it allows you to set certain conditions and action on it and then this component can be picked by rule to run on certain event.
* It gives another interface for rules action on "Entities" so you do not have to have rule administration permission if you belong to a role who has administration permission for certain entities.

> When do I use one over the other (to send emails when nodes are added/edited)?

* If you want a user role with administration permission of content, and you do not want to confuse or simply give them permission to see all rules on site but you still want them to configure their entity specific rule, use entity\_rule module.
* You can also it for sanity of configurations, as it will bundle rules specific to entity on entity page, keeping default rules page more cleaner.
> 5 votes

# Answer
The *Rules* located at `Config > Workflow > Rules` are from the typical Rules module.

The *Rules* you see under `Structure > Content Type > My type > Rules` are related to the fairly new Entity Rules module (great module, though only an alfa version for D7 for now). Refer to this video for a great introduction about it.
> 3 votes

---
Tags: 7, rules
---


title: How to theme content edit page

text:
# Question
Title: How to theme content edit page
I themed page to create custom type node and named it `page--node--add--book.tpl.php` It works well, but when I tried to theme content edit page and named it `page--node--edit--book.tpl.php` nothing happening. Help to fix this.

Tried suggestions:

```
function bookhive_theme() {
  return array(
    'book_node_form' => array(
        'arguments' => array('form' => NULL),
        'template' => 'book-node-form',
        'render element' => 'form',
    ),
  );
}

```

and suggestion from here

```
http://www.wdtutorials.com/how-to-override-forms-using-custom-template-drupal-tutorial/7

```

# Answer
> 2 votes
Ok, I find an answer. In my case the proper theme suggestion was html--node--edit.tpl.php I used theme debug mode to find it.

Also, to make page--node--edit.tpl.php works I need to delete my page--contenttype.tpl.php file. To customize my content type page I just used simple check in page.tpl.php `if($node->type == 'book'):`

```
<!-- THEME DEBUG -->
<!-- CALL: theme('html') -->
<!-- FILE NAME SUGGESTIONS:
   * html--node--edit.tpl.php
   * html--node--209.tpl.php
   * html--node--%.tpl.php
   * html--node.tpl.php
   x html.tpl.php
-->

```

# Answer
> 1 votes
**page--node--edit--book.tpl.php** isn't a valid theme template suggestion. From the d.o. D7 Template docs for **page.tpl.php**...

> The list of suggested template files is in order of specificity based on internal paths. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, "http://www.example.com/node/1/edit" would result in the following suggestions:
>
> 1. page--node--edit.tpl.php
> 2. page--node--1.tpl.php
> 3. page--node.tpl.php
> 4. page.tpl.php

If you're looking to theme a node edit page, use **page--node--edit.tpl.php**.

---
Tags: theming
---


# Question
Title: i18n-Frontpage: inconsistent links to non-default language
I am running across some inconsistent behaviour regarding the links to the frontpage of my multilingual site. The following is happening:

`mysite.com` -\> English frontpage, correct

`mysite.com/en` -\> English frontpage, correct

`mysite.com/en/node` -\> English frontpage, correct

`mysite.com/de/node` -\> German frontpage, correct

`mysite.com/de` -\> **English content** but language switcher says it's German, should display German content

Did anyone experience something similar? I have an idea why this is happening but no clue how to fix it.

I didn't find anything here. The closest one was this, but I already have a working link to the German frontpage, so it doesn't really apply to me. https://stackoverflow.com/questions/5168289/multiple-frontpages-in-mutiple-languages.

Best regards, Christoph

P.S.: All my images with relative links in Blocks or Pages get the language tag set in front of them. Is this a corresponding thing or default i18n behaviour? I just hotfixed it with softlinks from `en/images` and `de/images` to `images`.

# Answer
What eventually worked for me:

**Disable the module "admin\_language"**

I tried many different configurations of this module but it just kept on giving me English content on the German Frontpage. Views however displayed the correct language.

Should I report this bug to the module maintainers?
> 1 votes

---
Tags: i18n-l10n, navigation
---


title: Simple newsletter not diplaying images

text:
# Question
Title: Simple newsletter not diplaying images
I am using Simplenews module for sending newsletter to users. I have created a view and the view will be the newsletter body. The view has title and images. When I send email to users, images in view are breaking. But other iamges such and footer images are displaying. When inspected the URL `itok=''` is missing from the image. I am using Mime Mail for email sending. Is any configuration to be made in Mime Mail for displaying the images. Thank You

# Answer
Please set **E-mail format** Plain Text to Full HTML in Mime Mail Settings
> 0 votes

# Answer
I have same issue few days back. My images breaks in the email. After searching, I found the solution in drupal issue queue. After apply the patch mentioned in #9, image break issue resolved for me. I don't know whether it is correct approach there may be some other approach but it solves my problem. Thank You.
> 0 votes

---
Tags: media, emails
---


title: Show password button

text:
# Question
Title: Show password button
I'm developing a module and in the settings page I've inserted a `text` field to allow users to insert a key.

I thought to change this into a `password` field but I want to also create a **Show password** button or a checkbox. How could I implement this functionality?

# Answer
> 9 votes
Password Toggle is already doing something of this sort. Code is simple and straight

Its basically a JS to be added at the right time.

```
function password_toggle_add_js_and_css() {
  $path = drupal_get_path('module', 'password_toggle');
  drupal_add_js($path . '/password_toggle.js');
  drupal_add_css($path . '/password_toggle.css');
}

```

You can borrow the module's js code for your module.

# Answer
> 4 votes
That's the kind of functionality you'd want to implement with jquery.

If you google up "jquery show password" you'll get over a million results.

First on the list you get this fiddle http://jsfiddle.net/herdiansc/dnznh/8/ which does the trick with a checkbox.

Do you see how you can adapt that jquery script to your module ?

---
Tags: 7, javascript
---


# Question
Title: want to create custom rule for like post or comment?
I want to write a code for custom rule.I want to that when some one post a comment then one can able to like his/her post or comment i.e a single click on the Like will 'like' pieces of content and a message is send to that user who posted that comment . Is it possible with rules ??

# Answer
You can use flag module.

> Def: Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity.

Once you install the module, its very simple. Goto structure-\>flag-\>add new flag. Give title for the flag and use the count option to display the like-count.

In my example, 'Node Like' is the title of the flag, the flag count can be achieved in token

```
[node:flag-node-like-count]

```

*To answer your question, its possible but complex to achieve just using rules.*
> 1 votes

---
Tags: rules
---


# Question
Title: How to get field collection value in tpl file in drupal 7?
I have created a content type and take field collection for some field. Within field collection I have taken 4 select box. Now I need to get these select box value in content type tpl file. For this I am using this code : `$wrapper = entity_metadata_wrapper('node', $node_data);`

but its not giving me select box option value.

# Answer
> 2 votes
Use `entity_load('field_collection_item', array($item_id))` or `field_collection_field_get_entity($item)`

Sample

```
$node = node_load($id);
$items = field_get_items('node', $node, 'field_fc');
foreach ($items as $item) {
$fc_value = field_collection_field_get_entity($item);
// Do something.
}

```

For reference link 1, link 2

# Answer
> 1 votes
Simple render the field on the `node.tpl.php` with field machine name:

```
print render($content['field_collection']);

```

It's work for me.

---
Tags: nodes, theming, entities
---


title: Drupal link inside bootstrap thumbnail

text:
# Question
Title: Drupal link inside bootstrap thumbnail
I inserted this with a new created Text format

```
    <div class="col-sm-6 col-md-4 ">
   <a href="#" target="_blank" class="thumbnail">
      <img alt="test" src="#" />
     <h3>test</h3>
     <div class="mail"><a href="mailto:test@test.ch">E-mail</a></div>
   </a>
</div>

```

but drupal outputs this when i save the content

```
<div class="col-sm-6 col-md-4 ">
   <a class="thumbnail" target="_blank" href="#">
      <img src="#" alt="#">
     <h3>Test</h3>
   </a>
<div class="mail"><a class="thumbnail" target="_blank" href="#"></a><a href="#">E-mail</a></div>
</div>

```

I want that the div mail is inside the anchor thumbnail but drupal strips out the anchor automaticly out of the anchour thumbnail.

Can anybody tell me how i can fix that?

# Answer
Nested `<a>` elements (anchor tags) are forbidden in HTML syntax.

Nested links are illegal by w3.org rules.
> 1 votes

---
Tags: theming
---


# Question
Title: hook_form_alter with nested field collections to add #prefix?
I'm struggling with adding $ prefix to fields within nested, multi-value field collections. I'm not sure how to build this loop. I've tried to add each field to an array then using foreach to add '#prefix' = '$'. It's not quite working. When I add additional field collections, only the last instance gets the prefix:

Any ideas?

```
$dollar_fields = array(
        &$form['field_estimated_value'],
        &$form['field_down_payment'],
        &$form['field_amount_new'],
        &$form['field_appraisal_cost'],
        &$form['field_credit_report'],
        &$form['field_lender_s_inspection'],
        &$form['field_processing_fee'],
        &$form['field_underwriting_fee'],
        &$form['field_wire_transfer'],
        &$form['field_closing_costs'],
        &$form['field_lender_finders_fee'],
        &$form['field_property_tax_holdback'],
        &$form['field_lien_hold_back'],
        &$form['field_bonus_discount_paid_by_bor'],
        &$form['field_brokerage_fee'],
        &$form['field_evaluation_fee'],
        &$form['field_inspection_costs'],
        &$form['field_insurance_fees'],
        &$form['field_participant_tax_amount'],
        &$form['field_agent_commission'],
        &$form['field_appraisal_amount'],
        &$form['field_total_asset_dp'],
        &$form['field_total_prior_to_advance'],
        &$form['field_total_from_proceeds'],
        &$form['field_total_payments_remaining'],
        &$form['field_capped_payments'],
        &$form['field_legal_fees_disbursments'],
        &$form['field_total_closing_costs'],
        &$form['field_1st_mortgage'],
        &$form['field_2nd_mortgage'],
        &$form['field_3rd_mortgage'],
        &$form['field_assets_value'],
        &$form['field_liabilities_limit'],
        &$form['field_liabilities_balance'],
        &$form['field_liabilities_payments'],
        &$form['field_total_assets'],
        &$form['field_total_liabilities'],
        &$form['field_net_worth'],
    );

    foreach ($form['field_applicant_property']['und'] as $delta => $field) {
        if (is_numeric($delta)){
            $app_property = array(
                &$form['field_applicant_property']['und'][$delta]['field_property_value'],
                &$form['field_applicant_property']['und'][$delta]['field_original_value'],
                &$form['field_applicant_property']['und'][$delta]['field_annual_taxes'],
                &$form['field_applicant_property']['und'][$delta]['field_annual_taxes_m'],
                &$form['field_applicant_property']['und'][$delta]['field_condo_fees_m'],
                &$form['field_applicant_property']['und'][$delta]['field_heating_m'],
                &$form['field_applicant_property']['und'][$delta]['field_rental_income_m'],
                &$form['field_applicant_property']['und'][$delta]['field_hydro_m'],
                &$form['field_applicant_property']['und'][$delta]['field_management_m'],
                &$form['field_applicant_property']['und'][$delta]['field_repairs_m'],
                &$form['field_applicant_property']['und'][$delta]['field_other_m'],
                &$form['field_applicant_property']['und'][$delta]['field_insurance_m'],
                &$form['field_applicant_property']['und'][$delta]['field_interest_m'],
                &$form['field_applicant_property']['und'][$delta]['field_total_monthly_expenses'],
            );

        foreach ($form['field_applicant_property']['und'][$delta]['field_property_mortgage']['und'] as $delta2 => $field2) {
            if (is_numeric($delta2)){
                $mort_field = &$form['field_applicant_property']['und'][$delta]['field_property_mortgage']['und'][$delta2];
                $app_mortgage = array(
                    $mort_field['field_mortgage_balance'],
                    $mort_field['field_payments'],
                    $mort_field['field_early_discharge_penality'],
                );
            }
        }
    }
    }

    foreach ($form['field_employment']['und'] as $delta => $field) {
        if (is_numeric($delta)){

            $emp_field = &$form['field_employment']['und'][$delta];
            $app_employment = array(
                &$emp_field['field_gross_revenue'],
                &$emp_field['field_income_amount'],
                &$emp_field['field_self_declared_income'],
            );
        }
    }

    foreach ($form['field_assets']['und'] as $delta => $field) {
        if (is_numeric($delta)){

            $ass_field = &$form['field_assets']['und'][$delta];
            $app_assets = array(
                &$ass_field['field_asset_value'],
                &$ass_field['field_asset_down_payment'],
            );
        }
    }

    foreach ($form['field_mortgage']['und'] as $delta => $field) {
        if (is_numeric($delta)){

            $mort_field = &$form['field_mortgage']['und'][$delta];
            $app_new_mortgage = array(
                &$mort_field['field_annual_taxes'],
                &$mort_field['field_condo_fees_m'],
                &$mort_field['field_hydro_m'],
                &$mort_field['field_management_m'],
                &$mort_field['field_interest_m'],
                &$mort_field['field_total_monthly_expenses'],
                &$mort_field['field_insurance_m'],
                &$mort_field['field_repairs_m'],
                &$mort_field['field_other_m'],
                &$mort_field['field_purchase_price'],
                &$mort_field['field_estimated_value'],
                &$mort_field['field_appraisal_amount'],
                &$mort_field['field_recommended_value'],
                &$mort_field['field_heating_m'],
                &$mort_field['field_mortgaeg_amount_new'],
                &$mort_field['field_total_loan_amount'],
                &$mort_field['field_monthly_payment'],
                &$mort_field['field_property_tax_in_arrears'],
                &$mort_field['field_dp_total'],
                &$mort_field['field_improvement_value'],
                &$mort_field['field_property_value_new'],
                &$mort_field['field_down_payment_new'],
                &$mort_field['field_1st_mortgage'],
                &$mort_field['field_2nd_mortgage'],
                &$mort_field['field_3rd_mortgage'],
            );
        }
    }

    foreach ($form['field_liabilities']['und'] as $delta => $field) {
        if (is_numeric($delta)){

            $liability_field = &$form['field_liabilities']['und'][$delta];
            $app_liabilities = array(
                &$liability_field['field_liability_limit'],
                &$liability_field['field_liability_balance'],
                &$liability_field['field_liability_payment'],
            );
        }
    }

    foreach ($form['field_investor_s']['und'] as $delta => $field) {
        if (is_numeric($delta)){

            $invest_field = &$form['field_investor_s']['und'][$delta];
            $app_investors = array(
                &$invest_field['field_investment_amt'],
            );
        }
    }

    $percentage_fields = array(
    &$form['field_mortgage']['und'][0]['field_ltv'],
    &$form['field_mortgage']['und'][0]['field_interest_rate'],
    &$form['field_mortgage']['und'][0]['field_secondary_rate'],
        &$form['field_mortgage']['und'][0]['field_buy_down_rate'],
        &$form['field_mortgage']['und'][0]['field_net_rate'],
        &$form['field_mortgage']['und'][0]['field_variable_to_prime'],
        &$form['field_mortgage']['und'][0]['field_escalation_rate'],
   );
    $all_dollars = array_merge($dollar_fields, $app_property, $app_mortgage, $app_employment, $app_assets, $app_liabilities, $app_new_mortgage, $app_investors);

    foreach ($all_dollars as &$field) {
        //dpm($field);
        $field['und'][0]['value']['#field_prefix'] = '$';
    }

    foreach ($percentage_fields as &$field) {

        $field['und'][0]['value']['#field_suffix'] = '%';
    }

```

# Answer
> 0 votes
The reason for prefix not setting is,

Firstly, you are setting the values in the `foreach` loop which is not affecting the actual `$form` array.

**Your code:**

```
foreach ($all_dollars as &$field) {
  $field['und'][0]['value']['#field_prefix'] = '$';
}

```

**It should have been:** `$form[field_name]` instead of `$field`.

Secondly, field\_prefix can be applied to the form field not to the value of the form field.

Finally, array\_merge is not going to help here. You have to apply the value directly to the $form.

```
$form['field_mortgage']['#field_prefix'] = '$';

```

---
Tags: forms
---


# Question
Title: Module to easily insert link to other content into textarea?
Title pretty much says it all. I want a button or something next to the textarea that will let you link selected text to a particular node.

I am guessing that I should be using the WYSIWYG module with a particular editor, and happy to hear suggestions as to which combination.

# Answer
CKEditor with CKEditor Link does the trick.
> 2 votes

# Answer
Well it's not a button, but node\_link creates links to a given node number.
> 0 votes

# Answer
How about Linkit?

"Linkit provides an easy interface for internal and external linking with editors and fields by using an autocomplete field. Linkit links to nodes, users, managed files, terms and have basic support for all entities by default. Linkit has three major advantages over traditional linking"

https://www.drupal.org/project/linkit
> 0 votes

---
Tags: 7, wysiwyg
---


# Question
Title: Unable to delete feature content type after uninstalling feature
## Issue

Uninstalling a feature which creates a content type hides the "Delete" link on the `admin/structure/types`.

Issue on Drupal.org

# Answer
> 15 votes
## Solution

Using a `hook_uninstall()` in FEATURE\_NAME.install file and changing the status of the content type, so the system thinks it is an unlocked, custom content type.

I posted this also on d.org.

```
<?php
/**
 * Implements hook_uninstall().
 */
function FEATURE_NAME_uninstall() {

  // List custom content types added by this feature
  $custom_ctypes = array(
    'blog',
  );

  // Go through each and unlock the content type
  foreach ($custom_ctypes as $ctype) {
    db_query("UPDATE {node_type} SET `custom` = 1, locked = 0 WHERE type = :ctype", array(':ctype' => $ctype));
  }

  // Clean Drupal cache; this is necessary for the "Delete" link to appear
  // next to the content type created by the feature.
  drupal_flush_all_caches();

}

```

This will make the "Delete" button appear for that content type, so you can delete it from the admin.

Hope this helps someone!

# Answer
> 12 votes
For me, the solution was to load the delete page manually since there is no "delete" link on the content types page. To do this, you just need to construct the URL yourself by following the same URL structure as the delete page for other content types:

admin/structure/types/manage/YOUR\_CONTENT\_TYPE\_MACHINE\_NAME/delete

This brought up the content type delete confirmation page, which then allowed me to delete the content type.

For reference, see this thread on Drupal.org:

https://drupal.org/node/1055460#comment-7297680

Regards,

@cmsdave

# Answer
> 3 votes
The above method does not delete taxonomies, but this can be achieved by appending the following after disabling and uninstalling the module:

```
// Delete taxonomies.
$machine_names = array('taxonomy_a', 'taxonomy_b');
foreach ($machine_names as $machine_name) {
  $taxonomy = taxonomy_vocabulary_machine_name_load($machine_name);
  taxonomy_vocabulary_delete($taxonomy->vid);
}

```

# Answer
> 1 votes
Another solution that worked for me directly to the database in my development site. Remember to always backup your database.

To manually delete a content type that was created by a feature #16 what Nedjo suggests is the following:

> * Disable the feature. I've sometimes run into problems with this--a feature won't disable. In this case, remove the feature module code.
> * Determine the machine name of the content type to be deleted, e.g., 'mytype'.
> * In the database, revert the node\_type table values to the defaults as if the content type were created manually through the UI:
>
> `mysql> UPDATE node_type SET module = 'node', custom = 1, modified =
>  1, locked = 0 WHERE type = 'mytype';`
>
> * Clear caches to ensure the content type change is available.
> * Through the UI at admin/structure/types, delete the content type.

# Answer
> 0 votes
If you use admin\_menu module, you will still see the delete links in pull-down menu Structure / Content types / \[content type name\] / Delete, even if they are not displayed on the content types page.

I would say it's pretty safe to use this delete link if you assure there are no other references to this content type anymore.

---
Tags: 7, nodes, features
---


title: Add multiple nodes at the same time?

text:
# Question
Title: Add multiple nodes at the same time?
I've got a requirement to allow Users the ability to create multiple nodes within a single experience.

All this content the Users are adding share much of the same data, so the idea is to give them a more convenient way to add multiple nodes without all the Save and Add Content clicking.

They don't necessarily need to be able to edit the nodes in the same single experience.

Any modules, and/or case studies you recommend?

# Answer
Maybe the Multi Node Add will cover what you require :

> This module provides a new interface for creating nodes where the users are able to select the fields what they want to use for creating the nodes.
> **It is designed to create multiple nodes in one round,** it's possible to add more node input rows on-the-fly.

See if it does it for you. But also beware that it's a beta release.
> 2 votes

---
Tags: nodes
---


# Question
Title: Is it possible to get node alias during hook_node_insert()
I need to get the node alias during a hook\_node\_insert() when creating a brand new node. Function drupal\_lookup\_path() returns blank because the node actually isn't created yet per hook\_node\_insert() docs.

Does anyone know of a way to accomplish this or of an alternative to hook\_node\_insert().

# Answer
> 2 votes
@David Thomas pointed me in the right direction with his answer. By passing 'return' as the operation to the pathauto\_create\_alias() function you can get the alias without saving the alias.

Here is my code:

```
/**
 * Implements hook_node_insert().
 */
function hcp_sync_node_insert($node) {

  module_load_include('inc', 'pathauto');
  $language =  pathauto_entity_language('node', $node);
  $uri = entity_uri('node', $node);
  $alias = pathauto_create_alias('node', 'return', $uri['path'], array('node' => $node), $node->type, $language);
  ......
  ......
}

```

# Answer
> 3 votes
A couple of options there, if `drupal_lookup_path` isn't returning the alias yet.

1. Get the alias using `pathauto_create_alias` without the `_pathauto_set_alias` save part ( update: can use the 'return' option)
2. Add the node id to a cron queue defined with `hook_cron_queue_info` and get/process the alias in a worker\_callback a little later.

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


# Question
Title: Highlight autocomplete suggestions Drupal 7
I have a text field in a form, with autocomplete on. It works very well, but I cannot manage to find a way to highlight the letters in the suggested works. I found this hack in the autocomplete library (general, no Drupal related), but don't know if it applies or how to apply it. I would like the same effect:

http://output.jsbin.com/ezifi/4

# Answer
> 1 votes
Try Autocomplete Deluxe Module. May b this help you

# Answer
> 0 votes
I have found this tutorial. It is a small gem in which I have found the solution to this problem and this another one.

Basically, I use the hook callback function **mymodule\_formName\_autocomplete ($type, $text)** and there I can do **drupal\_json\_output($output\_string)** where *$output\_string*, based on the string query *$text* accepts any HTML label, so I can highlight at convenience by just using PHP, which is very powerful.

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


# Question
Title: How to use drop tables on target when via drush sql-sync?
I'm using the following command::

```
drush sql-sync @prod @dev

```

As I experienced, it does not drop tables on target (@dev) machine.

Is there a way, while syncing this way, to drop tables on target, so databases match completely? Or I must manually first drop tables on target?

# Answer
Drush sql-sync will not drop tables on the target unless you specify --create-db. Note that the later drops and recreates the entire database; if you do not have permissions to do this, you could run drush sql-drop on the target first.

There has been a feature request to add this functionality (drop before sync) in the Drush issue queue for years: http://drupal.org/node/716412. Patches welcome.

**Important update:** On Drupal 7, if you drop tables on the target prior to sql-sync, you could run into trouble unless you have http://drupal.org/node/1996004#comment-7419764. This is fixed in 8.x-6.x-dev, but is not part of 5.9, 7.x-5.x-dev or 8.x-6.x-beta1.

**Update 2:** This fix has now also been committed to 7.x-5.x-dev.
> 8 votes

# Answer
Here is the bash script that deletes all tables that are exist on @live, but do not exist on local:

```
drush sqlq "DROP TABLE $(comm -13 <(drush @live sqlq 'SHOW TABLES') <(drush sqlq 'SHOW TABLES') | paste -sd ',' - | sed 's/,/, /g');"

```

It assumes that you execute it after updating local database from @live, so after:

```
drush sql-sync @live default

```

It is helpful if you have no permissions to use --create-db.
> 1 votes

# Answer
This works on Drush 8 with Drupal 7:

```
drush @dev sql-drop -y && drush sql-sync @prod @dev

```

**Careful, this will drop all tables on @dev without prompting (the -y flag).**
> 0 votes

---
Tags: database, drush
---


# Question
Title: Views filter of date - complicated relative format
Looking for some suggestions on how to best accomplish this. We want to set up a filter on a date field to display just content with a date within the current (or next or previous) academic year, defined as May 1-April 30.

Using the great Views between dates filter (https://www.drupal.org/project/views\_between\_dates\_filter) we can do the filter, but the exact relative format string elludes us, and quite likely can't be achieved without writing some code.

What we have so far is a start set to "first day of may" and end set to "last day of april +1 year", but of course as soon as we hit January 1st that blows up.

Can anyone recommend a different approach or even better module that makes this happen?

# Answer
> 0 votes
There's no need for views\_between\_dates\_filter for this use-case. You might consider turning on the date\_views module because it provides some niceties, but if you're using core date properties (like Post Date or Updated Date) then you don't even need that. Just add 2 filters to your view:

* One set to only show content where the date field is greater than or equal to your specific desired start date (`2015-05-01 00:00:00` for instance)
* One set to only show content where the date field is less than or equal to your specific desired end date (`2016-04-30 23:59:59` for instance).

You don't need relative dates at all since you're setting up distinct views for each year.

---
Tags: views, datetime
---


# Question
Title: How to update block with step links based on AJAXified multipage entity form state?
### Brief

I'm using Entityform with Field group configured as Multipage with AJAX enabled for multipage groups provided by Field Group Ajaxified Multipage. So there are multiple steps and user can access (jump into) these steps through provided Multipage jumplist block.

See some sample images (to give you some visual idea):

### Problem

The problem is that form is AJAX (dynamic) and jumplist block is static (which is unaware of form context and links doesn't work) with some basic jQuery code (so it's not reloaded when user goes to next pages).

As result this is what happens:

* when field\_group multipage is AJAX, the form validation works per step, but jumplist doesn't work (jQuery events are not attached to the links and other steps are not available as it needs to be loaded via AJAX),
* when field\_group multipage is not AJAX, the jQuery events works, so you can switch between pages, but the server-side validation doesn't work as nothing is submitted on Next button

but I need both to work (server-side validation and jumplist links).

### Further info

See also the following related issue.

I'm thinking to do:

* jQuery, but I'm not sure how to access the step the user is in,
* rendering navigation block (or jumplist it-self) with the AJAX form (dirty and tricky), e.g.

```
// Implements hook_form_alter().
$block = module_invoke('multipage_jumplist', 'block_view', 'd07d74b8ad268f8c');
$rendered_block = theme('block', $block);
$theme_code = theme('multipage_jumplist', $foo);
$form['navigation'] = array('#markup' => $rendered_block);

```
* not to use AJAX, but I need it for step-by-step server-side validation (FGAM+IFE),
* create a session variable and pass to the JS (but the page won't be reloaded), or override jumplist theme hook, e.g.

```
// hook_form_alter - Get step we're in.
$step = empty($form_state['storage']['field_group_ajaxified_multipage_step']) ? 1 : $form_state['storage']['field_group_ajaxified_multipage_step'];
$curr_step = &$_SESSION[end((arg())) . '-step'];
$curr_step = max($step, $curr_step);
// theme_multipage_jumplist_item - Parse the jumplist
$visited_steps = &$_SESSION[end((arg())) . '-step'];
if ($variables['counter'] <= $visited_steps) {
    // return either clickable item or not.
}

```
* customize/patch the module (where to start),
* find some alternative solution

### Question

How do I alter/update my multipage jumplist block (unaware of form context) based on the current step user is in having AJAXified form?

By updating I mean either knowing which element is active, or have ability to extend the behaviour and disable further steps (from being clickable) which weren't visited yet.

What's your suggestion? What would be the Drupal-way?

# Answer
> 1 votes
This was implemented by patching/extending FGAM module and the following jQuery code:

```
/**
 * @file
 * Connect jumplist to their corresponding multipage panes.
 */
(function ($) {
  Drupal.behaviors.multipageJumplistFix = {
    step: 1,
    maxStep: 1,
    attach: function(context) {

      // Wrapper changes its id but it's id must be static!
      $('div[id^="foo-entityform-edit-form"][id$="form-ajax-wrapper"]').attr('id', 'foo-entityform-edit-form-form-ajax-wrapper');

      this.step = $('.multipage_step_change.active').attr('step');
      this.numSteps = $('.multipage-jumplist > li').length;
      this.maxStep = Math.max (this.maxStep, this.step);

      this.updateActive ();

    },
    updateActive: function () {
      $('.multipage-jumplist a').removeClass('active');
      $('.multipage-jumplist a[step=' + this.step + ']').addClass ('active');

      for (var i = 1; i <= this.numSteps; ++i) {
        if (i > this.maxStep + 1)
          $('.multipage-jumplist a[step=' + i + ']').addClass ('disabled');
        else
          $('.multipage-jumplist a[step=' + i + ']').removeClass ('disabled');
      }
    }
  };

  $(function () {
    $('.multipage-jumplist').html($('.multipage-jumplist').html());

    $('.multipage-jumplist a').each(function (index, el, e) {
      el.step = index + 1;
      $(this).click (function (e) {
        console.log (this.step);
        if (!$(this).hasClass('disabled')) {
          $('.multipage_step_change[step=' + this.step + ']').trigger('mousedown');
          return false;
        }
      });
    });

    Drupal.behaviors.multipageJumplistFix.attach();
  });
})(jQuery);

```

which is loaded from the theme and then few enhancements in `template.php`:

```
/**
 * Implements hook_form_alter().
 */
function theme_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'entityform_edit_form') !== FALSE) {
    drupal_add_js(drupal_get_path('theme', 'foo') .'/js/eforms.js');

    $step = empty($form_state['storage']['field_group_ajaxified_multipage_step']) ? 1 : $form_state['storage']['field_group_ajaxified_multipage_step'];
    $curr_step = &$_SESSION[end((arg())) . '-step'];
    $curr_step = max($step, $curr_step);

    unset($form['actions']['prev']);
    unset($form['actions']['next']);

    if (!empty($form['#multipage_jumplist_instances'])) {
      $num_steps = count($form['#multipage_jumplist_instances'][0]['panes']);

      for ($i = 1; $i <= $num_steps; ++$i) {
        $active = $step == $i;
        $is_prev = $i == ($step - 1);
        $is_next = $i == ($step + 1);
        $form['actions'][$is_prev ? 'prev' : ($is_next ? 'next' : ('step' . $i))] = array(
          '#type' => 'submit',
          '#value' => $is_next ? t('Continue') : ($is_prev ? t('Previous') : ('Step' . $i)),
          '#id' => 'step' . $i,
          '#attributes' => array('step' => $i, 'style' => (($is_prev || $is_next) ? '' : 'display: none'), 'class' => array('multipage_step_change', ($active ? 'active' : ''))),
          '#submit' => array('theme_multipage_step_change_submit'),
          '#ajax' => array(
            'wrapper' => 'foo-entityform-edit-form-form-ajax-wrapper',
            'callback' => '_field_group_ajaxified_multipage_form_callback',
          ),
        );
        if ($i < $step) {
          // We don't want validation when going back.
          $form['actions']['step' . $i]['#limit_validation_errors'] = array();
        }
      }
    }

  }
}

function theme_multipage_step_change_submit(&$form, &$form_state) {
  $step = substr($form_state['triggering_element']['#id'], 4);

  $form_state['triggering_element']['#array_parents'] = array('actions', 'step' . $step);
  $form_state['triggering_element']['#parents']       = array('actions', 'step' . $step);

  _field_group_ajaxified_multipage_form_submit($form, $form_state);

  $form_state['rebuild'] = TRUE;
}

```

This can be also extended by theme overrides for: `theme_multipage_jumplist()` and `theme_multipage_jumplist_item()`.

Hope that helps.

---
Tags: ajax, javascript, entities, navigation
---


# Question
Title: hook_breadcrumb() doesn't show breadcrumb
Hello Drupal community,

I am trying to alter the breadcrumb in my site with the hook\_breadcrumb($variables). I've used drupal\_set\_breadcrumb() function without any result. Here's my function in template.php :

```
/**
 * implements theme_breadcrumbs
 * @param unknown $variables
 */
function MYFUNCTION_breadcrumb($variables) {
  // On récupère les items de la page s'ils existent
  dpm($variables['breadcrumb']);
    if ($item = menu_get_item ()) {
      if (isset ( $item ['page_arguments'] )) {
        foreach ( $item ['page_arguments'] as $argument ) {
          // Keeping the name of the taxonomy in $field_name
          if (isset ( $argument->field_article_type )) {
            $field_name = "field_article_type";
          } elseif (isset ( $argument->field_type_remontee_document )) {
            $field_name = "field_type_remontee_document";
          } elseif (isset ( $argument->field_lien_type )) {
            $field_name = "field_lien_type";
          } elseif (isset ( $argument->field_type_de_contenu )) {
            $field_name = "field_type_de_contenu";
          } else {
            $field_name = "  ";
          }
          // retrieving the field and then the link to the taxoomy in the form term/taxonomy/%
          if ($field = field_get_items ( 'node', $argument, $field_name )) {
            foreach ( $field as $taxonomy ) {
              $taxo = taxonomy_term_load($taxonomy['tid']);
              $nom_taxo = $taxo->name;
              foreach ( $taxo->field_taxo_list as $taxo_link ) {
                foreach ( $taxo_link as $link ) {
                  $lien_taxo = $link ['value'];
                  $title = $item ['title'];
                  $crumbs = array ();
                  $crumbs [] = l ( t ( 'Accueil' ), '<front>' );
                  $crumbs [] = l ( $nom_taxo, $lien_taxo );
                  $crumbs [] = l ( $title );
                  dpm($crumbs);
                  drupal_set_breadcrumb ( $crumbs );
                }
              }
            }
          }
        }
      }
    }
}

```

Can anyone help ?

Thank you,

# Answer
I finally figured out how to alter the breadcrumb. The function needed to return a string

```
  function MYFUNCTION_breadcrumb($variables) {
    // On récupère les items de la page s'ils existent
    if (drupal_is_front_page ()) {
      return '';
    }
    if ($item = menu_get_item ()) {
      $title = (isset ( $item ['title'] ) ? $item ['title'] : false);
      $last = '</div>';
      $separator = '<span class="crumbs-separator">' . $variables ['crumbs_separator'] . ' </span>';
      $first_crumb = '<div class="breadcrumb"><a href="/" title="Display the homepage">Accueil</a>' . $separator;
      $key = count ( $variables ['breadcrumb'] ) - 2;
      $final_temp = ($variables ['breadcrumb'] [$key]);
      $final_crumb = ((isset ( $title ) && $title != "") ? ('<span class="crumbs-current-page">' . $title . '</span>') : ($final_temp));
      if (isset ( $item ['page_arguments'] )) {
        foreach ( $item ['page_arguments'] as $argument ) {
          // Keeping the name of the taxonomy in $field_name
          if (isset ( $argument->field_article_type )) {
            $field_name = "field_article_type";
          } elseif (isset ( $argument->field_type_remontee_document )) {
            $field_name = "field_type_remontee_document";
          } elseif (isset ( $argument->field_lien_type )) {
            $field_name = "field_lien_type";
          } elseif (isset ( $argument->field_type_de_contenu )) {
            $field_name = "field_type_de_contenu";
          } else {
            $middle_crumb = "";
          }
          // retrieving the field and then the link to the taxoomy in the form term/taxonomy/%
          if (isset ( $field_name ) && $field = field_get_items ( 'node', $argument, $field_name )) {
            foreach ( $field as $taxonomy ) {
              $taxo = taxonomy_term_load ( $taxonomy ['tid'] );
              $nom_taxo = $taxo->name;
              foreach ( $taxo->field_taxo_list as $taxo_link ) {
                foreach ( $taxo_link as $link ) {
                  $lien_taxo = $link ['value'];
                  $lien_taxo = (substr ( $lien_taxo, 0, 1 ) == "/") ? substr ( $lien_taxo, 1 ) : $lien_taxo;
                  $middle_crumb = '<a href="/' . $lien_taxo . '" title="Display ' . $nom_taxo . '">' . $nom_taxo . '</a>' . $separator;
                }
              }
            }
          }

          $crumbs = isset ( $final_crumb ) ? $first_crumb . $middle_crumb . $final_crumb . $last : '';
          // And here is returned a string
          return $crumbs;
        }
      }
    }
  }

```
> 0 votes

---
Tags: breadcrumbs, taxonomy-terms
---


# Question
Title: How to override field collection field title?
I have created field using field collection. I need to override field title and and incremented by 1 every field title. For this I am using this code. But its not working for me.

```
function previewcustom_form_alter(&$form, &$form_state, $form_id) {
  $x = 1;
  if($form_id =="article_node_form"){

  foreach($form['field_ingredientsf']['und'] as $k => $v) {

    if(is_numeric($k)) {

      $form['field_ingredientsf']['und'][$k]['field_steps']['und'][0]['#title'] = $form['field_ingredientsf']['und'][$k]['field_steps']['und'][0]['value']['#title'].' '.$x;
      $form['field_ingredientsf']['und'][$k]['field_steps']['und']['#title'] = $form['field_ingredientsf']['und'][$k]['field_steps']['und']['#title'].' '.$x;
      $x++;
    }
  }
}

```

Note I cleared the cache.

# Answer
Maybe just a typo. It should be `['value']['#title'] = ...`. Also you'ld rather use `LANGUAGE_NONE` instead of `'und'`.

```
$form['field_ingredientsf'][LANGUAGE_NONE][$k]['field_steps'][LANGUAGE_NONE][0]['value']['#title'] .= $x;

```
> 4 votes

---
Tags: 7, forms
---


# Question
Title: Values from $node object in Views Contexual Filter
I'd like to create a PHP contexual filter for a view.

This code isn't right, but I want something like this:

```
global $node;
if ($node->type=="ABC") {
return 5880;
}

if ($node->type=="XYZ") {
return 6200;
}

```

How do I access the $node object in a PHP contexual filter?

Also, is there a better way to debug/troubleshoot this? I feel like I'm operating in complete darkness.

# Answer
> 0 votes
You can access the $node object by doing this in the filter:

```
$node = menu_get_object()

```

---
Tags: 7, views
---


# Question
Title: How to move installed modules from /sites/all/modules/* to /sites/all/contrib/modules/*
I have been searching for the answers to this question with no luck at all. From what I observe in the database structure, the location to the modules are specified in the 'system' table. The only solution I have is to write an SQL query to update the 'filename' column.

Is there a better/cleaner solution in solving this, for eg., a contrib module?

# Answer
You only need to move your modules to the your new location and rebuild the regisry. When the registry rebuilds the path to the modules will be updated. Check `registry_rebuild()`.

> Rescans all code in modules or includes directories, storing the location of each interface or class in the database.

Although, I would recommend you to backup you database before testing this.

If you are using drush you could also rebuild the registry using the following command:

```
drush cc registry

```

You can also install the `registry_rebuild` command for drush:

```
// install registry_rebuild
drush dl registry_rebuild
// rebuild the registry
drush rr

```
> 28 votes

# Answer
Try the cool tool from Mark Sonnabaum: Drush Rebuild Project Paths. It automates the process; worked great for me. Uses Drush, of course.

I will second the suggestion that you try this on a copy of your site database, though.
> 10 votes

# Answer
I restored a backup from production locally and tried to just move things and hit admin/modules or to run registry\_rebuild() but it didn't stop fatal errors from being thrown. This makes sense to me since some modules may use includes or whatever in their hook\_init(), or you may have a menu router path set that depends on a module or include that Drupal can't find on bootstrap. Ultimately, this is what I did (your paths may be different):

**Step 1: Replace sites/all/modules with sites/all/modules/contrib**

```
UPDATE system SET filename = REPLACE(filename, 'sites/all/modules', 'sites/all/modules/contrib');
UPDATE registry SET filename = REPLACE(filename, 'sites/all/modules', 'sites/all/modules/contrib');
UPDATE registry_file SET filename = REPLACE(filename, 'sites/all/modules', 'sites/all/modules/contrib');

```

**Step 2: Replace sites/all/modules/contrib with sites/all/modules/custom for custom namespaced modules**

```
UPDATE system SET filename = REPLACE(filename, 'sites/all/modules/contrib', 'sites/all/modules/custom') WHERE name LIKE 'my_custom_namespace_%';
UPDATE registry SET filename = REPLACE(filename, 'sites/all/modules/contrib', 'sites/all/modules/custom') WHERE name LIKE 'my_custom_namespace_%';
UPDATE registry_file SET filename = REPLACE(filename, 'sites/all/modules/contrib', 'sites/all/modules/custom') WHERE filename LIKE '%my_custom_namespace_%';

```

**Step 3: Move dev modules into sites/all/modules/dev**

```
UPDATE system SET filename = REPLACE(filename, 'sites/all/modules/contrib', 'sites/all/modules/dev') WHERE name LIKE 'devel%';
UPDATE registry SET filename = REPLACE(filename, 'sites/all/modules/contrib', 'sites/all/modules/dev') WHERE name LIKE 'devel%';
UPDATE registry_file SET filename = REPLACE(filename, 'sites/all/modules/contrib', 'sites/all/modules/dev') WHERE filename LIKE '%devel%';

```

**Step 4: Clear caches so that things will bootstrap properly**

```
TRUNCATE TABLE cache
TRUNCATE TABLE cache_bootstrap
TRUNCATE TABLE cache_menu
TRUNCATE TABLE cache_page
TRUNCATE TABLE cache_path

```

**Note:** If you use a custom module or a contrib like LoginToboggan to handle 403 (access denied) and you've gotten logged out during this process, you may need to update the `include_file` column in the `menu_roter` table to use the new path for the include file. This is probably a rare occurrence.

`UPDATE menu_router SET include_file = 'sites/all/modules/custom/my_custom_namespace/includes/foo.inc' WHERE path = 'access-denied'`

Once these queries have run – which will only take a split second – hit up admin/config/development/performance and clear the cache so that menu paths rebuild.
> 10 votes

# Answer
For the record, there's a great drush command to rebuild the registry: http://drupal.org/project/registry\_rebuild

There's plenty of information in the project's page.
> 7 votes

# Answer
Firstly, **always** backup your database, so simple to do you'll kick yourself if something goes wrong and you didn't backup.

I'm not sure if it matters if you disable the modules or not; you might want to do it, just in case. Then do this:

1. Put your site in maintenance mode at (sitename)/admin/config/development/maintenance
2. Physically move your modules in the file system.
3. Clear your caches at (sitename)/admin/config/development/performance, or just re-save your modules page.

All done! Drupal will re-search for all installed modules.
> 5 votes

# Answer
Why don't you try the Registry Rebuild module. It worked every time for me.

Here is a quote about it (from the module's project page):

> There are times in Drupal 7 when the registry gets hopelessly hosed and you need to rebuild the registry (a list of PHP classes and the files they go with). Sometimes, though, you can't do this regular cache-clear activity because some class is required when the system is trying to bootstrap.
> 4 votes

# Answer
You can use the Registry Rebuild module, which integrates with Drush via the `Drush RR` command.

Basically what you do are these steps:

1. Move your modules to another directory, and
2. Registry Rebuild will then rebuild the system table to get the modules in the right place.

I first learned/discovered it via DrupalEasy Podcast #133, which further explains how this module / drush cmd can be used.

PS: Of course, first perform a backup of your site ...
> 3 votes

# Answer
Visit /admin/build/modules it will rebuild the paths in the system table. Sometimes drupal can't bootstrap anymore so this solution does not work in this case. If it does not work you can use Drush Rebuild Project Paths as said in a previous answer. You have to add the new drush command before breaking bootstrap though. To add the new command check out the readme's COMMANDS section
> 2 votes

# Answer
I had some trouble with `drush dl` not working because of the module directory issues. Generally I like stack answers that I can simply paste in to get things working. Here you find a couple of lines that will install Drush Rebuild Registry and run it on your site if you're already in the proper site directory.

```
pushd ~  # good if drush on your site is broken because of moved modules
drush dl -y registry_rebuild
popd
drush rr

```
> 2 votes

# Answer
I'm not 100% sure on a true drupal-esk answer but in my experience:

I accidentally moved one of my custom module folders into another custom module folder when FTPing to the server. They both still worked. Drupal seemed to have recognized it as a separate module even while it was in another module's folder. I did not have to disable the module.

\**This module that I moved did NOT have an .install file so I'm not sure if that matters.
> 2 votes

# Answer
Drupal distributions don't handle this well, so recently after accidentally ending up with a copy of Entity API in `sites/all/` on a Panopoly site, none of this worked. Registry rebuild, loading the modules page and everything else caused a fatal error.

Disabling the module isn't simple either if you have to move something like Entity API which is required by tons of other modules in Panopoly.

To solve this, for Entity API you would do something like this:

1. Update the path in the system table:

```
UPDATE `system`
  SET `filename` = REPLACE(
    `filename`,
    'sites/all/modules/entity',
    'profiles/panopoly/modules/contrib/entity'
  );

```
2. Then rebuild the registry:

```
drush rr

```
> 1 votes

# Answer
**Drupal 7**

First of all try `drush rr`.

If it won't work, after moving the files, try the following Drush commands in your Drupal root dir:

```
drush sqlq "TRUNCATE cache; TRUNCATE cache_bootstrap;"
php -r "define('DRUPAL_ROOT', getcwd()); require_once DRUPAL_ROOT . '/includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION); registry_rebuild(); registry_update(); cache_clear_all();"
drush -y cc all

```

---

If above doesn't work, find the table which still have the old information about the path by:

```
drush --ordered-dump sql-dump | grep "sites/all/modules" # Change the path to the old one.

```

If none is found, that means it's your external cache.

If so, don't forget to restart them, e.g.:

```
killall -HUP memcached
drush eval "function_exists('xcache_clear_cache') && xcache_clear_cache();"

```

See more: What method is used to clear caches in the Drupal?

---

Alternatively you may try the following MySQL queries after moving the files:

```
UPDATE system SET filename = REPLACE(filename, "sites/all/modules", "sites/newplace/modules") WHERE
       filename LIKE "sites/all/modules/%" AND type = "module"
       AND name IN ("my", "module", "whose", "path", "changed");

UPDATE registry SET filename = REPLACE(filename, "sites/all/modules", "sites/newplace/modules") WHERE
       filename LIKE "sites/all/modules/%"
       AND module IN  ("my", "module", "whose", "path", "changed");

```
> 1 votes

# Answer
Moving your modules into contrib/dev/patched/custom subfolders is recommended. There are no performance gains however, this is done for practical and aesthetic reasons. This will make the lives of future developers easier.

You can move most of the contrib modules to subfolders without a problem on a live site. You should clear the caches afterwards. If you don't use drush and find you cannot access the cache clearing page anymore, you will have to visit /update.php or manually truncate the cache tables. I only ever had to do the last bit when moving the entity API module.

Moving core modules is technically possible, but I would not recommend it nor do I see any valid reason for doing this.

Update: Moving modules like entity API may require rebuilding of the registry. Check out the registry\_rebuild page.
> 1 votes

# Answer
You could just add a sym link in the sites/all/modules diretory pointing to sites/all/contrib. I'm not sure if it solves your problem. There are other solutions too, including the installation profile, or a drush make file. I don't know enough to provide details on them but at least it's a direction you can look at.
> -4 votes

---
Tags: 7, installation
---


# Question
Title: How to resolve my 404 error when using hook menu?
I've a custom module named workingmodule. I get a 404 when visiting domain.com/workingmodule.

My module is enabled, and I cleared the cache. This id the code I am using in workingmodule.module.

```
/**
* Implements hook_menu().
*/
function workingmodule_menu() {
  $items = array();
  $items['workingmodule'] = array(
    'page callback' => 'workingmodule_blank_page_callback',
    'page arguments' => array(),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
* Display the tagboard/custom content for page.
*/
function workingmodule_blank_page_callback() {
  print_r("test");
}

```

Why does domain.com/workingmodule return a 404 error?

# Answer
> 9 votes
I tested the code by adding that path and it works.

I suggest the following steps debug:

1. Make sure that Drupal is able to flush the cache without any problem by checking if there is any errors at admin/reports/dblog
2. If you didn't find any errors when you flushed the cache, try to add a `die('checking hook_menu')` on your hook\_menu implementation to see if the hook is being executed.
3. If you are not going to pass any arguments to that callback I suggest you to remove the line `'page arguments' => array(),`
4. Check your Apache/NGINX settings, it could contain something that is affecting that path.

# Answer
> 3 votes
Remove the `'page arguments' => array(),`

You're passing an array to a function that does not accept any arguments. Otherwise make your callback function function `workingmodule_blank_page_callback($arg)`

# Answer
> 2 votes
Had the same problem but got an `500`. Had to uncomment the `RewriteBase` in Drupal's `.htaccess`:

```
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

```

---
Tags: routes
---


# Question
Title: Drupal + Moodle SingleSignOn logout issues
**Does anyone know how to set cookie\_domain to use an IP-Address and not a domain name?**

I recently put together a SSO solution between Drupal and Moodle. Drupal is acting as the users repository with Moodle as a subdirectory.

To get the sso working I'm using the moodle-sso module to good effect.

**The only problem is that logging out of moodle does not log a user out of drupal.**

After much googling, I found articles indicating cookies are the key to solving this problem.

I attempted following moodle-sso cookie\_domain instructions but then I can't log into my site anymore because I access my dev site via IP address and not a domain name.

I set cookie\_domain as follows: `$cookie_domain = 'http://128.79.128.44/drupal-site';`

The project structure is `http://128.79.128.44/drupal-site/moodle`.

Any help is appreciated.

**UPDATE:**

I added the following data to my */etc/hosts* file on my Linode server:

`128.79.128.44/drupal-site/ dev.drupalsite.com`.

When I visit *dev.drupalsite.com* I receive the following error:

```
Forbidden

You don't have permission to access / on this server.

```

**Clearly, *dev.drupalsite.com* is not a globally recognised URL but how do I use it to access my website on a LIVE Linode server?**

# Answer
> 1 votes
`$cookie_domain` can only be set to a domain that you want the `Set-Cookie` header to specify. This doesn't include protocol or path, just the domain with a leading dot (e.g. ".example.com"). If you leave `$cookie_domain` commented out, the browser will default to the domain that you requested it on.

If you need to access a Drupal site by IP when its cookie is set to another domain, you can create a subdomain on your hosts file that maps to the IP.

```
128.79.128.44 dev.example.com

```

Once that's saved to your hosts file, you should be able to browse to http://dev.example.com/ and have your web browser send the relevant cookies (assuming the cookies of domain are set to "example.com").

---
Tags: 7, authentication-authorization, cookies
---


title: Template for custom form not working

text:
# Question
Title: Template for custom form not working
I am trying to theme a custom using a template file but unfortunately I am not getting it by using the below method. listing.module

```
function listing_menu() {
  $items['ad-listing'] = array(
    'page callback' => 'adlist_template',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,

  );
      return $items;
    }
function listing_form($form, &$form_state) {

$form['title'] = array(
    '#type' => 'textfield',
    '#attributes' => array('placeholder' => t('Title')),
);
$form['category'] = array(
    '#type' => 'select',
    '#options' => array(
        'default' => '- Category -',
        'Car' => 'Car',
        'Van' => 'Van',
    ),
);
 return $form
}

function listing_theme($existing, $type, $theme, $path){
return array(
  'listing_form' => array(
    'render element' => 'form',
    'template' => 'adlisting',
    'path' => drupal_get_path('module', 'listing') . '/form',
  )
    );
}
function adlist_template(){
    return theme('listing_form');
}

```

listing/form/adlisting.tpl.php

```
<div class="row">
  <div class="small-12 medium-12 large-8">

      <div class="row">
          <div class="small-12 columns">
              <h5 class="">Contact Information</h5>
          </div>
      </div>

      <div class="row">
          <div class="small-12 large-6 medium-6 columns">
              <?php print render($form['title']); ?>
          </div>
      </div>

      <div class="row">
          <div class="small-12 medium-6 large-6 columns">
              <?php print render($form['category']); ?>
          </div>

  <div class="row">
      <div class="small-12 medium-12 large-8 large-offset-2 columns">
          <?php print render($form['ad_submit']); ?>
      </div>
  </div>

```

I tried to follow this thread How to a use a template file to theme a form? but did not help me, neither other solutions

# Answer
There were 2 major changes on the code above

1. I changed the form name to listing\_adform()
2. I changed the hook\_menu to call my form not theme

> ```
>   $items['ad-listing'] = array(
>     //'page callback' => 'adlist_template',
>     'access callback' => TRUE,
>     'type' => MENU_CALLBACK,
>     'page callback' => 'drupal_get_form',
>     'page arguments' => array('listing_adform'),
>   );
>
> ```

Flushed the cache, and I saw my fields rendering using my template in form/adlisting.tpl.php
> 2 votes

---
Tags: 7, forms, theming
---


# Question
Title: How to prevent users with negative balance of user points from viewing nodes?
I have a rule that deducts 1 point from users viewing a node, however the problem is that users with a negative balance can still view a node. So I would want to prevent this.

I'm using Drupal 7 with modules Rules and User Points.

Any suggestions?

# Answer
> 1 votes
Your question actually contains 2 challenges:

1. Which Rules Event to use?
2. Check the current balance of user points of the user?

Read on for an answer to address each of those challenges.

### 1. Rules Event to use

If you'd use Rules event `node_view`, then you're too late, because the node is already being viewed (which is exactly what you want to prevent). Instead you need to use (System) event "Drupal is initializing" (= `init`), which is actually BEFORE the node is actually being viewed.

### 2. Check current balance of user points

However, you also want to disallow viewing nodes for users who have a negative user points balance. The challenge with that is that there is no out-of-the-box Rules Condition to check that balance.

Have a look at this Rules example (in Rules export format):

```
{ "rules_stop_node_access_for_user_with_negative_points" : {
    "LABEL" : "Disallow node/* access for a user with negative points",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "rules_conditional" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "0" } },
            "DO" : [
              { "drupal_message" : { "message" : "You have insufficient points (you only have [total-points:value] points ...)." } },
              { "redirect" : { "url" : "no_access" } }
            ]
          }
        ]
      }
    ]
  }
}

```

The Rules Condition added here, is to only perform the Rules Action for attempts to browse a path like `node/*` (adapt to what fits for your case).

This rule retrieves, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If it is negative, it will display an appropriate message starting with "You have insufficient points ...", and it redirects to a relative path like `no_access` (adapt to what fits for it).

This rule uses the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module.

The clue to make this rule work is the very first Rules Action "***Load user points of a user***". Refer to my answer to "How to access current amount of earned userpoints in a Rules Condition?" for more details on this.

# Answer
> -2 votes
Add rule for node\_view with custom php as condition. In condition check for negative points. If negative points, condition returns true. Execute custom php with `drupal_access_denied()`

---
Tags: 7, rules, userpoints
---