title: Insert webform into content type field

text:
# Question
Title: Insert webform into content type field
At the content type i add some field:

if you want to include or embed block into the body of your node https://www.drupal.org/project/insert\_block

if you want to include or embed view into the body of your node https://www.drupal.org/project/insert\_view

How about webform?

# Answer
> 1 votes
For webform: Use insert block module as well.
Structure --\> block --\> Click configure one of the webform you want to add.--\> look at the URL

Example: http://localhost/example.com/#overlay=admin/structure/block/manage/webform/client-block-5/configure

Type this "\[block:webform=client-block-5\]"

# Answer
> 0 votes
It can be done with Node Embed module

> Node Embed provides an input filter for CKEditor integration allowing a content editor the ability to embed the rendering of nodes within the body/fields of another node. This uses a View to allow for the browsing/preview/selection of a node to embed and provides a set of template suggestions that allow for the detailed control of node rendering when in embedded mode.

---
Tags: 7, webforms
---


# Question
Title: Set a value from one text field from one content type to another text field in another content type using set data value in rules
I have two content types *A* and *B* and I have two rules. I am trying to add the text put in the *A text field* of content type *A* into the *B text field* of content type *B*.

On rule two I am using the set data value but it is not working. Have I missed anything or have I setup my rule incorrectly? If anybody can point out where I went wrong it would be much appreciated.

Rule 1 creates a node from content type B when a node is created with content type A.

Export of Rule 1:

```
{ "rules_ref" : {
    "LABEL" : "Ref",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--a" : { "bundle" : "a" } },
    "DO" : [
      { "entity_create" : {
         "USING" : {
            "type" : "node",
             "param_type" : "b",
             "param_title" : [ "node:type" ],
             "param_author" : [ "node:author" ]
          },
         "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
       }
     }
    ]
} }

```

Rule2 takes the value from A text field in the A content type and adds it to the B text field in the B content Type.

Export of Rule 2:

```
{ "rules_ref2" : {
  "LABEL" : "Ref2",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules" ],
  "ON" : { "node_insert--b" : { "bundle" : "b" } },
  "IF" : [
    { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_a_text" } },
    { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_b_text" } }
    ],
  "DO" : [
     { "data_set" : { "data" : [ "node:field-b-text" ], "value" : "[node:field-a-text]" } }
   ]
} }

```

# Answer
> 1 votes
Here is example

* Content type *Article*: field\_product - Product reference
* Content type *Basic page*: field\_product2 - Product reference

Article creation triggers next actions:

```
{ "rules_on_article_create" : {
    "LABEL" : "On Article create",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "page",
            "param_title" : [ "node:title" ],
            "param_author" : [ "node:author" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-product2" ],
          "value" : [ "node:field-product" ]
        }
      }
    ]
  }
}

```

I think you r trying to operate with non existing object. When you r creating node of type B there is no link to any another node in rules.

---
Tags: entities, rules, nodes
---


# Question
Title: How to add the js files to specfic modules only
I am having a module and am adding the js files which is using on the top of the module file as follows :

```
drupal_add_js(drupal_get_path("module", "notification") . "/js/jquery.js");

```

But the problem is this js file appear in the whole site and makes things messy . I need this file should appear in the notification module only. Another problem is the by default `D6 using the jquery.js (which is an older version 1.2.1)` and by default its taking from the `sites/misc` path .its taking the old $.browser function and all !! . And when am including the latest version it makes conflict with the oldest version . How to solve this ?

# Answer
It is, of course, not possible. The problem is:

* JS files, by the nature of WWW, are added to HTML output
* *All* modules participate in creation of *one* HTML output
* You want to add JS "only to module", but because there is no isolation between parts of HTML output, it's plainly not doable.

---

To address what you didn't really ask, but probably need to know:

Never just add jQuery on your own. That's pretty dangerous thing to do and pretty much always *will* mess things up. There is jQuery Update module to address this need. It's not perfect, but way better than anything you will be able to create yourself now - because it was tested by hundreds of thousands.
> 1 votes

---
Tags: 6, javascript
---


# Question
Title: Rule to store user's last post date and scheduled rule based 30 day reminder
In this scenario, user's can post 1 node of a specific content type every 30 days (interval changes depending on user role). We are using node\_limit to accomplish this; it's doesn't play with rules.

So, the idea is to schedule an email that will remind the user 30 days later to post a new article AND update a field in the user's account to display the last time the user posted. Once the node is saved, the rule should update the user field with the node's post date.

BUT I'm unable to correctly configure the **set a data value**.

The rule I have created is as follows:

**Fetch entity by property** Parameter: Entity type: User, Property: press\_update\_last\_posted, Value: \[node:created\] Provides variables: Date (entity\_fetched\_pressupdatelastposted)

**Set a data value** Parameter: Data: \[entity-fetched\] ..., Value: \[entity-fetched\] ...

And then of course it would fire up the scheduled email and display a message on the site.

Any suggestions?

# Answer
> 2 votes
Use the Rules module together with `Rules Scheduler` (a sub-module of it), as explained in the 3 steps below. These steps are based on these assumptions:

* content type = article.
* interval 30 days.

In this case, a date field is added to the user profile, so that for each user you can indicate an appropriate date for the "next article".

### Step 1: Create a field to store the "next article" date

Add a field to the "user" entity with machine name (say) `field_next_article`. Allow only 1 date (to store when the "next" article is allowed).

### Step 2: Create a Rules "Component"

Here is the Rules **Component** to be created (in Rules export format, just import it in your own environment via copy-paste):

```
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Friendly reminder about your next article",
          "message" : "This is a reminder about your next article on [user-to-notify:field_next_article] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Obviously, the ***Subject*** and ***Content*** of the eMail may need review / tuning, while you might also want to use some other ***From*** eMail ID.

### Step 3: Create a "Rule" using the Rules Component

Here is the **Rule** to be created, in Rules export format (just import it in your own environment via copy-paste):

```
{ "rules_user_reminder_after_30_days" : {
"LABEL" : "User Reminder After 30 Days",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_scheduler" ],
"ON" : { "user_login" : [], "node_insert--article" : { "bundle" : "article" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_article" } }
],
"DO" : [
  { "schedule_delete" : {
      "component" : "rules_send_email_notification",
      "task" : "[account:name]"
    }
  },
  { "data_set" : { "data" : [ "account:field-next-article" ], "value" : "+30 day" } },
  { "schedule" : {
      "component" : "rules_send_email_notification",
      "date" : {
        "select" : "account:field-next-article",
        "date_offset" : { "value" : 2592000 }
      },
      "identifier" : "[account:name]",
      "param_user_to_notify" : [ "account" ]
    }
  }
]

```

} }

Note that the above rule refers to the *Rules Component* from the previous step.

The `schedule_delete` that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).

---
Tags: 7, users, entities, rules, emails
---


# Question
Title: Does a template override require a subtheme?
Feels like a silly question to ask, but I can't find a definitive answer anywhere.

## Background

My project is a multi-site that features several themes that our users can choose from. These are all installed in /sites/all/themes. For one site in particular, I wanted to simply use a different page.tpl.php file. I tried copying the theme's page.tpl.php file into /sites/my\_site/themes, but this didn't seem to work. This leads me to the question:

In order to override a template, must I use a sub-theme?

# Answer
> 1 votes
The correct answer is *no* since you can also override templates in a module (example). It doesn't sound like you want to do that, though.

At minimum you would have to create an \*.info file that includes the dependency:

```
name = My Theme
description = Just a basic theme
core = 7.x
base theme = base_theme_name

```

# Answer
> 1 votes
There are multiple ways you could do this. As othermachines writes you can create a subtheme, however, you could also create a custom module and implement hook\_theme\_registry\_alter:

> Alter the theme registry information returned from hook\_theme().
>
> The theme registry stores information about all available theme hooks, including which callback functions those hooks will call when triggered, what template files are exposed by these hooks, and so on.
>
> Note that this hook is only executed as the theme cache is re-built. Changes here will not be visible until the next cache clear.

In this way you can overwrite (the location of) your .tpl.php file, which will be used instead to create the output.

---
Tags: theming
---


# Question
Title: Commerce Stripe and 2.0 version of library with namespace?
I am working on an integration with Commerce Stripe and the new Connect functionality. This however requires the 2.0 version of the library which can be found here https://github.com/stripe/stripe-php/releases.

I have downloaded the source code for this and put this in my stripe-php directory. The stripe-php library has a namespace of Stripe. I have defined my `hook_libraries_info` as follows

```
function bh_test_namespace_libraries_info() {
  return array(
    'stripe-php' => array(
      'name' => 'Stripe API Client Library for PHP',
      'vendor url' => 'https://stripe.com/',
      'download url' => 'https://github.com/stripe/stripe-php',
      'dependencies' => array(),
      'version arguments' => array(
        'file' => 'VERSION',
        'pattern' => '/(2.\d+(\.\d+)?)/',
      ),
      'files' => array(
        'php' => array(
          'init.php',
        ),
      ),
    'xautoload' => function($api) {
        $api->namespaceRoot('Stripe', 'lib');
    },
),
);

```

}

I have installed the xautoload module. However, the classes are still not loaded. Does anyone have an idea as to what I am doing wrong?

# Answer
Download the 2.x uc\_stripe version of the gateway for Stripe - it has code that works (https://www.drupal.org/project/uc\_stripe) as you are seeking - the version 2.0 library uses \Stripe\Action-to-Take:: instead of Stripe\_Action-to-Take:: Stripe Connect however is a whole other issue requiring a OAuth2 flow and JSON working with the Stripe Webhooks to get it working initially and THEN one can use the API for the rest of the issues for nmaintainance
> 1 votes

# Answer
My code works above. However, when you access the classes, it must be in the form of \Stripe\Stripe class::method, not Stripe\_Stripeclass::method. This code uses the init.php that is mentioned in stackin\_hackin's comment above.
> 0 votes

---
Tags: commerce, theming
---


# Question
Title: How to programmatically set views format?
On install I'm trying to set my `commerce_products` view from table to list. Where and how do I do this? I also need to add a class to the list.

I'm a Drupal noob so if answers could be detailed that would be appreciated.

# Answer
> 2 votes
From your comments it sounds like you want to change the style\_plugin from your theme. You need to implement hook\_views\_default\_views\_alter() in your theme.

Something like this:

```
function themename_views_default_views_alter(&$views) {
 if (isset($views['commerce_products']) {
  $views['commerce_products']->display['default']->display_options['style_plugin'] = 'table';
 }
}

```

I'm not too familiar with commerce so you might not want to target the default display if that display is used elsewhere; you might just want to target the 'page' display.

---
Tags: 7, views
---


# Question
Title: View filtering all records with no argument, empty text with invalid argument
I have a view with a block display that I need to filter by:

* All records when no argument present e.g. /foo
* All nodes with specified valid taxonomy term ID e.g. /foo/bar
* Show empty text when taxonomy term ID is attached to no content e.g. /foo/baz

---

* `WHEN THE FILTER VALUE IS NOT AVAILABLE` is set to `Display all results for the specified field`.
* `WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED` is set to `Specify validation criteria`, `Taxonomy Term`.
* `Filter value type` is set to `term name converted to term ID`.
* `Transform dashes in URL to spaces in term name filter values`.
* `Action to take if filter value does not validate` is set to `Display contents of "No results found"`.

---

* The view preview is working correctly, adding `taxonomy_term_data_field_data_field_VOCAB.tid = 'xx'` to the query but on the front-end it doesn't appear to be working at all.
* I have `Global: Null` as the first entry under `Contextual filters` as the argument needed to filter is the second argument in the URL string.

# Answer
All of the methods below will display:

* Matching results on foo/bar (valid term name with matches)
* Value of "No results found" on foo/norf (valid term name with no matches)
* Value of "No results found" on foo/baz (invalid term name) (Page display) or 404 Page Not Found (Block display)\**See note below.

The following methods will take different actions if a term is not present; e.g. foo/.

### Method 1. Display NO results if term is not present

**Contextual filter:** *Content: Has taxonomy term ID*

```
When the filter value is NOT available .. Provide default value
                                  Type .. Raw value from URL
                        Path component .. 2
                        Use path alias .. checked

```

```
                 When the filter value
 IS available or a default is provided .. Specify validation criteria
                             Validator .. Taxonomy term
                          Vocabularies .. (select vocabularies)
                     Filter value type .. Term name converted to term ID
     Transform dashes in URL to spaces
            in term name filter values .. checked

```

```

   Action to take if filter value does
                          not validate .. Display contents of "No results found"

```

---

### Method 2. Display ALL results if term is not present (using PHP filter module)

**Note:** For this method the core module *PHP filter* must be enabled.

**Contextual filter:** *Content: Has taxonomy term ID*

```
When the filter value is NOT available .. Provide default value
                                  Type ..  Raw value from URL
                        Path component .. 2
                        Use path alias .. checked

```

```
                 When the filter value
 IS available or a default is provided .. PHP code
                     PHP validate code .. (see below)

```

```
if ($argument) {
  $vocabulary = 'vocabulary_name'; // The machine name of the  vocabulary.
  $terms = taxonomy_get_term_by_name($argument, $vocabulary);
  if (!empty($terms)) {
    $term = array_shift($terms);
    $handler->argument = $term->tid;
    return TRUE;
  }
  else {
    return FALSE;
  }
}
else {
  $handler->argument = 'all';
  return TRUE;
}

```

```
   Action to take if filter value does
                          not validate .. Display contents of "No results found"

```

---

### Method 3. Display ALL results if term is not present (using Views hook)

**Contextual filter:** *Content: Has taxonomy term ID*

```
When the filter value is NOT available .. Provide default value
                                  Type ..  Raw value from URL
                        Path component .. 2
                        Use path alias .. checked

```

```
                 When the filter value
 IS available or a default is provided .. Specify validation criteria
                             Validator .. Taxonomy term
                          Vocabularies .. [select]
                     Filter value type .. Term name converted to Term ID
   Action to take if filter value does
                          not validate .. Display contents of "No results found"

```

Add this function to a custom module and clear the caches:

```
function MODULENAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'view_name') { // You can optionally also check the display ID.
    if (!empty($args)) {
      $argument = $args[0];
      $vocabulary = 'vocabulary_name'; // The machine name of the  vocabulary.
      $terms = taxonomy_get_term_by_name($argument, $vocabulary);
      if (empty($terms)) {
        $args[0] = FALSE;
      }
    }
    else {
      $args[0] = 'all';
    }
  }
}

```

---

### Method 4. Display ALL results if term is not present (no coding required!)

On your first block display, use the contextual filter in Method 1, then limit the block visibility\*** to 'foo/\*'. Create a new block display that outputs all results and limit the block visibility to 'foo'.

---

\**There's an important caveat when using URL arguments with a block display: the URL must be a valid path. In other words, foo/bar must be an actual page or you will get a 404.

\*** In the *Pages* fieldset on the block configuration form (Administration \> Structure \> Blocks), select "Only the listed pages", then enter the suggested values.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Change allowed file types based on certain criteria
An admin comes onto the website and creates an **assignment** which is a content type. Students come onto the website and create **submissions** that point to the certain **assignment**. There is a **file upload field** where students can upload their submission. I want to make it so when the admin creates the **assignment**, he/she can choose which **file types are allowed**. Is there a field that will automatically process what file types the admin chose so that a student can only upload that specific file type?

# Answer
So, it's the rough instruction step by step as Matt asked:

1. Add new field where you can specify the allowed extensions of the files.
2. Alter the form of your submission via hook\_form\_alter() and find your file upload field
3. Specify your allowed extensions from your field with extensions into this point
> 1 votes

---
Tags: entities, nodes
---


# Question
Title: Is there a way to assign an html ID automatically to a field in a content type?
I am using **JavaScript** in my **custom module** and the field is inside an div, but that div only has a class tag. Is there a way to automatically give an **ID** to the **field** so that whenever it shows up, it's easier to manipulate it with an **ID** tag? The field belongs to a content type.

# Answer
Since I was only displaying the content with a view, in the view settings
\- I edited the specific field
\- clicked **REWRITE RESULTS**
\- checked "Rewrite the the output of this field"
\- and wrote:

`<p id="file-types"> [field_file_type_text] </p>`

This solved the problem
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: PDO Exception Error - How to resolve this?
After integrating Google Custom search in Drupal 7, I am getting this error page. What should I do to resolve this error?

# Answer
Could be a MySQL configuration issue - see http://dev.mysql.com/doc/refman/5.5/en/too-many-connections.html

Or, quoting after http://drupal.org/node/930876#comment-4519490:

> If MySQL connections are not closed properly, then you might have an error within the code somewhere, that leads the script to end prematurely.
>
> In standard cases, connections are properly closed.
>
> Look at the detailed error log of your server, or activate on page error reporting if you're on a develpment site. You might find something useful, such as a forgotten dsm() somewhere with the devel module not being activated.
>
> The error might not be displayed and leads the site to look as usual, but the PHP process is not ended properly, leaving MySQL connections opened.

Start with checking your error logs and try to find out why this could be happening there.
> 3 votes

# Answer
This should also help:

## DEADLOCK

Reading/surfing I found that InnoDB tables can have this problem. One of the causes is the very high traffic and loss of connections (but deadlock is even something different). Combined you may easily reach the max\_users\_connection limit and this will render your site useless.

Some Hints:

* use cache, if you can
* use throttle
* use bad behaviour module (as this should shield you against spammers)
* set interactive\_timeout so that your connections expire quickly

I have made these changes to the **database.mysql.inc** \- to the function `mysql_connect`

the old version:

```
$connection = mysql_connect($url['host'], $url['user'], $url['pass'], TRUE) or die(mysql_error());

```

the new version:

```
 $connection = mysql_connect($url['host'], $url['user'], $url['pass'], TRUE, MYSQL_CLIENT_INTERACTIVE) or die(mysql_error());
 mysql_query("SET SESSION interactive_timeout=120", $connection);

```

To get the timeout run `phpinfo()` and watch for the connection timeout inside your MySQL, and also timeout of your apache process (or IIS if you use IIS).

Basically, after the timeout, your script will be cut off, BUT the opened connection will be there eating out of your `max_users_connections`. If you set the `interactive_timeout` limit, it will be closed automatically (note: mysql has a global `wait_timeout` limit, but as a default there is often 28800 = 8 hours, the connection will expire in 8 hours!)
> 0 votes

# Answer
Try to edit your php.ini/php configuration in your cpanel. I moved up to php5.5 from 5.4 and this problem was gone.
> 0 votes

---
Tags: 7
---


title: Where place spyc library dependencies

text:
# Question
Title: Where place spyc library dependencies
I have a issue trying to activate REST SERVER from services. I need to add this library. I'm using drupal 7.19 on Ubuntu.

Reading this question, I add the spyc.php in 'servers/rest\_server/lib/'

But where I must place the rest of files?

Reading the issue, #2 suggest that the best solution will be allow to place the library on 'sites/all/libraries', this doesn't work in my version.

# Answer
The problem was I hadn't the dependency `libraries` . Just downloading this module, updating, and adding the spyc.php in 'servers/rest\_server/lib/' Rest server will work.
> 4 votes

# Answer
I placed the spyc.php file in /sites/all/libraries/spyc/ and it works.
> 3 votes

# Answer
You have to place it in `sites/all/libraries/spyc` folder.

For example, download Spyc.php by the following drush (\>7.x) one-liner:

```
drush --no-core -y make <(printf "core = 7.x\nlibraries[spyc][directory_name] = spyc\nlibraries[spyc][download][type] = file\nlibraries[spyc][type] = library\nlibraries[spyc][download][url] = https://raw.github.com/mustangostang/spyc/master/Spyc.php")

```

or manually:

```
mkdir sites/all/libraries/spyc
wget -P sites/all/libraries/spyc https://raw.github.com/mustangostang/spyc/master/Spyc.php

```
> 2 votes

---
Tags: services, 8, theming
---


# Question
Title: How to send a newsletter to all email addresses attached to a content type?
I have a content type (customers) having an email field (field\_email). I need to create a newsletter using those emails that every certain period increase.

I try to use the module Newsletter but I must to re-enter all emails again and new email every time a new customer is registered. Is there a way to import all emails from my content type, to list the newsletter module?

# Answer
Unfortunately, it doesn't look like Newsletter supports that.

On the other hand, the Simplenews module has decent Rules support which may make managing your subscribers easier. As far as I know a user account isn't required to subscribe.

Off the top of my head, here is an example of a rule that might automatically add an email address to a subscription list when a new 'Customer' node is created:

```
IF
  (condition) 'After saving new content' (node is created)
AND
  (condition) 'Entity is of type' (node is 'Customer' type)
AND
  (condition) 'Entity has field' (node has 'email' field)
THEN
  (action)  'Set a data value' (get value of email field)
THEN
  (action)  'Subscribe an e-mail address to a newsletter'

```

(The full implementation is beyond the scope of this answer but there are plenty of other posts dealing with Rules.)

As for importing email addresses, in both of the 7.x branches there is a "mass subscribe" option at *People \> Subscriptions*.
> 0 votes

---
Tags: 7, entities, emails
---


title: i18n - Not translating Menu's or Blocks

text:
# Question
Title: i18n - Not translating Menu's or Blocks
# The Problem

Using the i18n module, node translations are working, however *Menu* and *Block* translations are not showing up.

For example: I created 2 identical blocks. For one i set the *Show this block for these languages* to English and the other to Bulgarian. When i then go mysite.com it shows me the English block, but when i go to mysite.com/bg it still shows me the English block.

I have also tried the *Make this block translatable* but that doesn't work either.

# The setup

**Drupal version:** 7.14

**Related modules:** i18n (all enabled apart from Multilingual Forum), pathauto, localization update, administration language, locale

# Background

This is my first Drupal 7 website. The website im working on is a multilingual, multi-country website which is near completion. Hopefully that gives some idea of my exerpience, so if you could tailor your answers to that please.

Thanks in advance.

# Answer
> 1 votes
For those that encounter this issue, the problem is being caused by another module. Disabling the below module fixed the issue.

Drupal 7 - Admin Language Module

# Answer
> 7 votes
if anyone else is experiencing this issue, notice that it can also be caused by your configuration in *yoursite/admin/config/regional/language/configure*, even if you are not using Admin Language Module.

Menus are part of your interface, not of content. So, for example, if you set your interface language detection to default (only use site default language), because you want your interface to be only in english, you are not going to see your translated menu blocks when you navigate to *yoursite/anotherlanguage*!

Hope this helps someone!

# Answer
> 0 votes
One thing to check regarding menu items being translated or not. Make sure that your menus are not themed via CSS with images that contain a specific language.

---
Tags: i18n-l10n
---


# Question
Title: How can I validate a path used to create a page?
I'm in the process of creating my first D7 module, partly based on the tutorial found here. It's a pretty simple module that creates both a block and a page to show some content.

To go a little further, I want to allow the user to **change the path** of this page, via a configuration page.

This raises two questions regarding the validation of this data:

1. how to **avoid collision with already existing paths**. I already use two function calls (see code below) to check if the alias is already used, but I'm wondering if I'm doing it right because it feels a little bit like a hack, and I'm not sure I'm covering every possible cases.
2. more importantly, how should I **validate the data entered by the user**? I suppose some (a lot of) characters are not allowed in a URL (or a least strongly advised against). Is there a Drupal function for that, or should I do it from scratch?

Here is the code I have (simplified, and only the parts relevant to the question) :

```
<?php

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();

  // config page
  $items['admin/config/services/mymodule'] = array(
    'title' => 'mymodule',
    'description' => 'Configuration for the mymodule module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  // public page
  $m_title = variable_get('mymodule_title', 'My module');
  $m_title = $m_title ? $m_title : 'mymodule';

  $m_path = variable_get('mymodule_path', 'mymodule');
  $m_path = $m_path ? $m_path : 'mymodule';

  $items[$m_path] = array(
      'title' => $m_title,
      'page callback' => '_mymodule_page',
      'access arguments' => array('access mymodule content'),
      'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Page callback: mymodule settings
 *
 * @see mymodule_menu()
 */
function mymodule_form($form, &$form_state) {
  $form['mymodule_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title displayed on the mymodule page'),
    '#default_value' => variable_get('mymodule_title', 'My module'),
    '#required' => TRUE,
  );
  $form['mymodule_path'] = array(
    '#type' => 'textfield',
    '#title' => t('Path for the mymodule page'),
    '#default_value' => variable_get('mymodule_path', 'mymodule'),
    '#description' => t('<p>Relative path to your Drupal installation. Default value: <code>mymodule</code><br>Do not include a trailing slash. In case of multilingual sites, do not enter the language prefix either.</p>'),
    '#required' => TRUE,
  );

  return system_settings_form($form);
}

/**
 * Implements validation from the Form API.
 *
 * @param $form
 *   A structured array containing the elements and properties of the form.
 * @param $form_state
 *   An array that stores information about the form's current state
 *   during processing.
 */
function mymodule_form_validate($form, &$form_state) {
  // page path validation
  $m_path = $form_state['values']['mymodule_path'];
  $m_path_db = variable_get('mymodule_path', '');
  if ($m_path_db != $m_path) {

    if (drupal_lookup_path('source', $m_path) || menu_get_item($m_path)) {
      form_set_error('mymodule_path', t('This path is already used.'));
    } else {

      // check if value contains non-standard characters
      // while still allowing for path fragments separators ("/")
      $m_path_parts = explode('/', $m_path);
      $has_invalid_chars = false;
      foreach ($m_path_parts as $key => $part) {
        if (urlencode($part) != $part) {
          $has_invalid_chars = true;
        }
      }
      if ($has_invalid_chars) {
        form_set_error('mymodule_path', t('This path contains invalid characters.'));
      } else {
        variable_set('menu_rebuild_needed', TRUE);
      }
    }
  }

  $m_title_db = variable_get('mymodule_title', 'My module');
  $m_title = $form_state['values']['mymodule_title'];
  if ($m_title_db != $m_title) {
    variable_set('menu_rebuild_needed', TRUE);
  }
}

?>

```

**Edit**: In the meantime, I tried to implement some kind of "manual" validation based on the `urlencode` function. If a part of the path contains characters that are modified by `urlencode`, then it is considered not valid. I've updated my code. Of course I'm still curious to know if there's a better way of handling that.

# Answer
You could use `drupal_valid_path()` to determine if the URL exists in Drupal. I would recommend running this as user 1 to avoid any weird permissions issues with the URL.

Link: https://api.drupal.org/api/drupal/includes%21path.inc/function/drupal\_valid\_path/7
> 1 votes

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


# Question
Title: Where to insert .js code using the webform module for google tracking a submit button?
I am trying to insert a google tracker to a form submit button/form using the webform module (drupal 7). Here is my code:

`Drupal.behaviors.basicWorks = function(context) {
 // Track submission events.
 $('#webform-client-form-198', context).submit(function() {
 ga('send', {'hitType': 'event', 'eventCategory': 'PDTestlinktoDrupal', 'eventAction': 'clickAction', 'eventLabel': 'PDConversionTest' });
 });
};`

My question is:

Where do I place this code? Inside the webform.js inside the /js folder? Or do I create my own file inside the /js folder and upload?

Been working on this issue for a few days now and I could really use some insight.

# Answer
> 0 votes
1. Create the script.js file in to your theme folder
2. Copy paste the above code into it
3. Specify the script.js path in the .info file of the theme as `scripts[] = script.js`

# Answer
> 2 votes
you have 2 option: 1- using #attached to the $form element. use `hook_form_alter`

```
function YourMODULE_form_webform_client_form_1_alter(&$form, &$form_state) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'YourMODULE') . '/js/your_script.js',
  );
}

```

2- add it in your custom module with drupal\_add\_js() function, Also it will be much better if you just load the js on only that page (web form page) so you will avoid loading it on every page.

---
Tags: webforms, forms
---


# Question
Title: allow user to set some css settings through UI
The user wants to be able to choose some sizes and colors for the look of the site. These are css rules. I have a vague vision how this could be done by a module, but maybe there is already something like this?

What I need is to have some form with fields as combo boxes, allowing the user to choose from several values. E.g. allow him to choose from {red, blue, yellow} for the "Background of the News title", which happens to be .news-header-background class.

After he saves, the module would re-create a user.css file which is loaded as the last file in the theme (so it overrides my theme settings).

So the tasks for each role are as follows:

* the user fills the fields on a form choosing from pre-defined values
* the administrator pre-defines these values and also assigns a css selectors to each field in the form (directly in files, no need for GUI for this)
* the module re-creates the css file

One important point is that the interface exposed to the user must be **dead simple**. No technical jargon, no options, only text that he fully understands, like "Background color of the News title". Second point is that the values he can choose are presented as combo boxes, so they are **limited**. Third point is that the module should enable **validation hook** for the values he enters (or be written so that it's easy to hack and validate).

# Answer
> 3 votes
Since the solution I reference in my first answer was created, I have learned new things. If I were to do the same things again, I would base it on a similar principle, but I would use Panels per pane "CSS Settings", to add CSS classes instead. See: How does one theme a panel (or add a style)

This should allow for much broader customization of content. A problem with this approach is that Panels UI is hardly "customer friendly". I would solve that by a custom form, on a dedicated admin page, that simply loads the pane settings from the database, overwrites them, and saves them back.

# Answer
> 3 votes
Coming a bit late to the party but from project page of the Style (CSS) Settings module:

> Configure CSS values from the UI for any module, theme or custom CSS just by wrapping CSS values in a code comment. The CSS is functional even without the module being installed (soft-dependency). Form API elements are provided to have a color picker or a slider (e.g. for opacity).

Apart from the form API elements offered by the module, to have predefined field values you can use the Drupal core form API fields select or checkboxes.

For a **site's custom CSS**, rename the existing dedicated file '*sites/all/modules/style\_settings/css/example.custom.css*' to *'custom.css*' (at time of writing use the dev version). This file gets scanned for CSS values wrapped in comments and will be rewritten if so. In any case, it gets loaded as last stylesheet so you can be sure your custom CSS will not get overridden by module or theme CSS. Neither it will be overwritten when you upgrade the module.

You still have to define the form yourself by writing some code but the module takes care of rewriting the desired values in your CSS. Furthermore it offers form API elements especially for CSS property values (including validation) so that task is made as easy as possible.

The module has a demo and documentation.

# Answer
> 2 votes
When we did something similar in Drupal 6, we solved it by adding a textfield with a few selectable colors in it, "red", "green", and so on. In the css, we then had rules like

```
.red { color: red; }
.green { color: green; }

```

For displaying this node, we then used Views, together with Semantic Views, to take the *field value*, and put it into the markup. \<p class="\[field\_color\]"\>\</p\> becomes

```
 <p class="red"></p>

```

Since the data is in a field attached to a node, validation is simple, and it's easy to understand for the user. That may be a problem in your case, depending on what exactly the customer wants to control.

---
Tags: 7
---


# Question
Title: Ignoring accents/diacritics in apachesolr
I have a site that's in English, but there's a fair amount of French text on it. So, there are some special characters like è, é, á, etc.

I don't want to worry about those diacritics at all when searching (using solr 4), so that, say "any e gives you every e"

Right now, I have it so if you search for non-diacritics, you get all the related diacritics (search for "siecle", and get "siècle"), but if you search using diacritics it won't find anything (search for "siècle" returns nothing.)

I've been up and down between playing around with mapping-ISOLatin1Accent.txt and using:

```
<charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>

```

and

```
<filter class="solr.ASCIIFoldingFilterFactory" preserveOriginal="false"/>

```

But nothing I've tried seems to have any change to this. I assume I have to add this to both AND in schema.xml, but I'm not sure which fieldtypes to do that in. There are fieldtypes of:

* text\_ws
    + "text field that only splits on whitespace for exact matching of words"
* text
    + "A text field that uses WordDelimiterFilter to enable splitting and matching of words..."
* text\_und
    + "An unstemmed text field - good if one does not know the language of the field"

I've tried every combination I can think of, and cleared/rebuilt the index each time, but nothing. A search including diacritics always fails.

After looking through the admin site for Apache, it looks like the ASCIIFoldingFiltorFactory is being added to the index analyzer, but NOT the query analyzer for the fieldtypes of text, but I don't know why; I added it the same way to both analyzers.

# Answer
So, I think it was a mixture of problems/issues that arose, but they were more broad/were somewhat indirectly related to the symptoms. I'll mention the steps to fix it/figure it out:

1. On the web amin interface, I selected the core from the dropdown, then "Schema Browser" below it.
2. From there, I could tell which ACTUAL filters/tokenizers were getting loaded. The ASCIIFoldingFilterFactory was listed on the index analyzer for the text fieldtype, but not the query analyzer.
3. When I attempted to reload the core, it got an error, and failed. It said something about one of the diacritics already being loaded (it was talking about the mapping-ASCIILatinwhatever.txt file that I'd tried earlier)
4. I cleared that file, since I was trying to use a different filter, and the core was able to reload, reindex, and everything's working great now (and the filter is on the query analyzer.)

So, anyone else dealing with this issue, in suhort: Check your "Schema Browser" in the web gui for Solr on the core you're having trouble with!
> 0 votes

---
Tags: search
---


# Question
Title: How to force a selection in one field if another webform field is a certain value
I know it is quite simple with Conditionals to show and hide fields based on another fields value in a Webform -- is it possible to change values of fields based on another field's value?

For example, if someone selected a certain membership type in a field at the top, could a field lower down automatically have certain selections disabled automatically (or a single selection selected, and the entire second field disabled)?

This is a bit of an oversimplified example, but:

> **Membership type** (select) \> Single person
>
> **How many t-shirts** would you like (select)? *\[Preselect "One" and disable the field from edits\]*

and

> **Membership type** (select) \> Two people
>
> **How many t-shirts** would you like (select)? *\[Option to select "One" or "Two"\]*

# Answer
You could use normal conditional fields for that. Simply create two "How many t-shirts" fields, one with only one enabled option, second with both available. Then, make them visible depending on value in "Membership type". It is possible since Webform version 7.x-4.0-alpha2, and earlier using this module.

Sure, this will create two separate entries in results, and only one filled, but if your traffic is low, it will be easy to read. And if it's high, you can aggregate easily in your warehouse handling software. Or in spreadsheet of your choice, after export.
> 1 votes

---
Tags: webforms
---


# Question
Title: How to attach a module to a drupal article?
I have a php function in a drupal module. This function outputs some random text. I want to attach this module to a Drupal article so that each time someone creates an article, random text will appear in it. How can I do this?

# Answer
For example, my module named **custom2**, so:

```
<?php

function custom2_random_text(){
    return 'random-text';
}

function custom2_node_presave($node){
    //check for our node type if needed
    if($node->type == 'article')
        //assign value
        $node->body['und'][0]['value'] = custom2_random_text();
}

```
* hook only works for *Article* content type
* **custom2**\_random\_text - returns random text
* **custom2**\_node\_presave - implementation of hook\_node\_presave

> function **hook\_node\_presave**
>
> 7 node.api.php hook\_node\_presave($node)
>
> Act on a node being inserted or updated.
>
> This hook is invoked from node\_save() before the node is saved to the database.

Note how hooks in Drupal works. You are implementing *hook\_node\_presave* in your\_module.module via replacing *hook* word by your module's name.

If you in doubt about structure of some entity on your site I should recommend you to use Devel module.

For first step you can implement hook\_node\_view and in code of your implementation use dpm($node) - it is Devel module function that will display node structure when node is displaying.

For my example:

```
function custom2_node_view($node, $view_mode, $langcode){
  dpm($node);
}

```
> 1 votes

---
Tags: hooks
---


# Question
Title: JavaScript errors with 'Add collection', 'Select media' (Media, Field Collection)
I drupal 7 site that I did not build but now maintain has developed an odd error. About a month ago the site lost the ability to add an image to a Media field inside a new addition of field collection. Looking into it, this is what I find:

The first few warnings are nothing that I can see would harm things. The media.popup.js error is nonsense:

```
dialogOptions.buttons[ok] = function () {
  alert('hell yeah');
  return "poo";

  var formattedMedia = this.contentWindow.Drupal.media.formatForm.getFormattedMedia();
  if (!formattedMedia) {

```

I have yet to see that code be reached, though it looks a little unprofessional to have such things in a contrib module.

When I scroll down the node edit form I see see the next segment. The Bulletin error has to do with Google Syndication code linked in, and can be ignored for now.

The piece of the screenshot after that is when I try to trigger the field collection's "Add Additional Item" button from the console. Nothing happens. I am not sure if I did it right, but I included it in this screenshot in case it helps identify anything.

The final segment shows the messages that appear when I click the Add Additional Item button. A new field collection instance is actually added to the form, and if the console was not open I would not know that something was wrong yet. I get from 2 to 5 instances of that "object is undefined" error any time I do this. The "too much recursion" error occurs about 1 in 15 tries, so I do not know if it is relevant. I have all cache and compression turned off, and this is a local virtual box copy of the live site so I do not have to worry about killing it in the investigation.

**The problem** is these "object is undefined" errors block the use of the Media module's Select Media button for a field on the node. First time this problem was noticed was when a new slide show entry was being added to an Article node. The Add collection button causes the error, and the Media button then does not respond but throws some "this.hoverable" error. I went over to another content type that has a field collection that contains only text, but also has a Media field on the node itself. The field collection generates the same error, I switch vertical tabs to get to the Media field and it behaves the same as the media field inside the collection. JQuery Update is used to keep the admin screens on jquery v1.5 because it is needed for the Media module.

Modules involved:

* Drupal 7.38
* Field collection (field\_collection) Module Enabled 7.x-1.0-beta8
* Chaos tools (ctools) Module Enabled 7.x-1.7
* jQuery Update (jquery\_update) Module Enabled 7.x-2.4
* Media (media) Module Enabled 7.x-1.5

# Answer
OK, this was sort of entertaining.

The trail begins with this silliness in *media.popups.js*:

```
dialogOptions.buttons[ok] = function () {
  alert('hell yeah');
  return "poo";

```

Just as it stuck out for @DeveloperWeeks, it stuck out for me because I'm familiar with the work of Media module's primary maintainer, and I know him (by reputation) to be pretty meticulous. So in checking it out I discovered that it was removed long ago (like, in 2013) in this commit: Removed inappropriate JS code.

(I am sure he would be thrilled, by the way, to know that this bit of code will now live forever after on StackExchange. :-P)

Since the OP lists as part of his installation the latest production release of Media (7.x-1.5), this didn't mesh. *The errors were originating from a two-year-old file*.

With this compelling clue in hand, @DeveloperWeeks was able to locate **an extra copy of the Media module** hidden away in his installation. That's when the sun rose, the flowers bloomed, and things just generally started to make more sense.

As for those pesky errors, well...

> "This is why "duplication of data" is such a horrible thing." - @DeveloperWeeks

Hell, yeah. ;-)
> 1 votes

---
Tags: 7, entities, media
---


# Question
Title: Drush: --yes-if-newer behavior with pm-download?
I'm writing an Acquia Cloud Hook where I install Registry Rebuild. In the interest of performance, I'd like to only install it if it's not already at the latest version. In other words, `--yes` unless it's already the current version.

Is there a simple way to do this in current Drush or shell?

# Answer
> 1 votes
I'm afraid there is no easy way: as the command version isn't stored in any file, there is nothing to compare with. If you really want to do it, you can download the command and run a diff with the version you have, and install it if it differs, but I doubt the efficiency of such a check compared to install it in any case

---
Tags: drush
---


# Question
Title: Under what circumstances should a site be placed into maintenance mode
I was recently ask to deploy a set of changes to a production server. The changes included Drupal core and contrib module updates, as well as, updated custom theme related code.

In preparation for deployment, I placed the site into maintenance mode. Then took a database backup (using `drush sql-dump`). I then pulled in the latest changes with git and updated the database (using `drush updatedb`). In this case there were several updates which were executed. Finally I took the site out of maintenance mode.

The site owner was not so keen on the fact that the site was placed into maintenance mode for this procedure. He mentioned that in general they don't use maintenance mode when updating a site.

This got me wondering under what circumstances, when updating a site, should one use maintenance mode? Are there any situations when one could get away with updating a site without using maintenance mode?

# Answer
> 1 votes
In my experience working on some very high profile D7 installations, maintenance mode is always required during updates. The steps you took to perform your update are essentially the same as I've experienced. The reason for using maintenance mode is to essentially lock out users from making database changes that might corrupt the DB when update.php(drush updb) is run. I can't think of any good reason why you would do a production update without maintenance mode, unless you like playing Russian Roulette with a production DB. I also hope you're doing the updates during non-business hours or during a scheduled maintenance time.

---
Tags: updating, deployment, maintenance-mode
---


# Question
Title: Is there any module to create a set of field without creating new entity field for each one?
My objective is to have a module which gives me the option to create a entity field that can have multiple field values.

For example, the location module. It creates an entity field of type 'location' which can have a set of field values (country, province, city, address, etc.). In the database this module creates a table 'location' which stores all these values with a key 'lid'. The main entity field has a 'lid' value to connect with the set of values. And we are able to used tokens for all these field values.

I have tried Field Collection, Multifiefld, Composed Field modules, but none of those actually do this.

# Answer
If the objective is to have one entity field that stores a primary key into a custom table schema, the answer is probably no. Location (and its associated Location CCK module) achieves this by its own widget form (via hook\_field\_widget\_form) & element type (via hook\_element\_info). It creates various processing functions to store the data in its custom data schema. I think such a module you're describing would need to dynamically generate data schema and hook callbacks to achieve what you're wanting.
> 2 votes

---
Tags: 7, entities
---


title: File field upload in modal/dialog

text:
# Question
Title: File field upload in modal/dialog
I have a custom content type with file field as one of the fields. For theming/UI purposes I should make this file field as clickable button. And only when user clicks on it, he/she gets modal window with upload/file browse or file name if there already is a file uploaded.

I've accomplished this with using jQuery Update module and from there with help of jQurey UI Dialog (https://jqueryui.com/dialog/) and custom module with JS code:

```
(function ($) {
Drupal.behaviors.module_custom = {
attach: function (context, settings) {
//appending button
var $inputButton = $('<input type="button" value="Līgums" id="open_modal" />');
$inputButton.insertAfter($(".field-name-field-file"));
//hiding file upload wrapper div
$('.field-name-field-file').hide();

//initializing modal dialog window
$( ".field-name-field-file" ).dialog({
  autoOpen: false,
  show: {
    effect: "blind",
    duration: 1000
  },
  hide: {
    effect: "explode",
    duration: 1000
  },
  width: 500
});

//launching modal dialog when button is clicked
$( "#open_modal" ).click(function() {
  $( ".field-name-field-file" ).dialog( "open" );
});

  });

}
  };
    }(jQuery));

```

This all works from UI/theming perspective but it brakes file upload. When modal window opens and file is uploaded I got error "An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (8 MB) that this server supports." no matter how small file is (event if it is 1 KB). I suppose this issue is related how AJAX upload is handled. Any ideas what is issue here?

# Answer
> 0 votes
For sure this is due to some problem with your sever setting, contact your web hosting company and talk with them regarding the issue.

It could be due to ModSecurity that scans incoming *http* requests for any malicious scripts. There may be an issue with the script causing mod\_security to stop the script. ModSecurity is an is an open sourceweb application firewall Apache module, which help in providing an external security layer that increases security, and help in preventing attacks.

In the event that mod\_security is causing the error, you will need to contact tech support to have them look at the logs to see what is exactly causing mod\_security to flag the uploaded file. You may need to Disable mod\_security via cPanel Modsec Manager on your specific domain if there is no work around. Otherwise, tech support will need do this for you.

The other reason could be the size you are allow to upload that can be change in your server setting. It is also important to check apache max\_execution\_time.

If you have control over your server then you can try to change your php file

post\_max\_size = 128M upload\_max\_filesize = 32M max\_execution\_time = 5000 max\_input\_time = 5000 memory\_limit = 1000M

Source

If not solved then Other Reason May be :
**Check the .htaccess or settings.php for conflicting Code**
Edit the .htaccess file to see if there are any overrides in the code. Some server configurations allow .htaccess settings to override your file upload size. Comment any code that controls the files upload size and save the changes.

The settings.php file also can hold overrides for the file upload size. Edit the settings.php directly on the server or you can change the settings through the Drupal dashboard by going to **Administer \> Site configuration \> File uploads** and updating the settings from there.

---
Tags: 7, ajax, files
---


title: users online status issue

text:
# Question
Title: users online status issue
it is a Author Status Issue: let's to show either a user is online or offline. If a user is online then it will show `>Online` if offline then like this `>Offline`
So how to show it?

# Answer
> 1 votes
User Stats is a good basic plugin that provides this functionality within Views and Rules. Install the plugin, then add a field or filter to your views results.

# Answer
> 1 votes
Author Pane is a block of information about a given user, like those typically found on a forum post, but can be used in other places as well. From core, it collects the user picture, name, join date, online status, contact link, and profile information. In addition, any module or theme can feed it more information via the preprocess system. All of this information is then gathered and displayed using a template file.

---
Tags: views, users
---


# Question
Title: How to create views of nodes and all revisions in?
As it is obvious form the title I am want to create a views which has all contents of a given type and all its revisions under it.

I tried these ways but none of theme gave all I need:

1. Create a views from contents with relation to revision `NID`. It just give the last revision.
2. Create a views from contents with relation to revision `ID`. It has no difference with the previous one.
3. Create a views from content revision. Again just the latest version appeared.

So what will be solution to do that?

# Answer
Simple step by step instruction:

1. Try to create view by content revisions.
2. Remove relation to actual revision (added by default).
3. Also be sure that filter by published node isn't enabled.
4. It should work.
> 3 votes

# Answer
I think you can solve it by using a patch. This patch was useful for a number of users with similar issues. Also check this link out to see if it can help you out.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Best way to enter(insert) the content in drupal, so a non techie can edit the content
I am some what new to drupal tho familiar with CMS tho drupal way is to put into views tho i dont see how best a non techie can edit such content what am i missing thank you

# Answer
> 1 votes
Do you have a WYSIWYG editor installed for your end-users?

You can use CKEditor, or a number of other editors, and install as a module. Here is a walkthrough for installing CKEditor: CKEditor Quick Start, Or you can install the WYSIWYG module and choose from a handful of WYSIWYG editors to use on your site. By doing so, you would give your content editors a way to create content similarly to how we enter our answers and code examples here on StackExchange and your users will not need to know any html or code to get the job done.

---
Tags: nodes
---


# Question
Title: How to prevent edit or delete of some content by its author depending on an approval status field?
Here is a screenprint to illustrate part of my current implementation:

This is what I want to achieve:

* If the value of 'Admin Status' is not "Approved", then the author can still edit or delete his/her own content.
* If the value of 'Admin Status' is "Approved", then the content can not be edited by the author.

I have tried a lot, even using the Rules module, but nothing works for me.

Any suggestions about how to get this to work?

# Answer
You can get this to work with the Rules module by using Event ***System \> Drupal is initializing***, combined with a Rules Condition related to the URL for the *edit* or *delete* operation.

# Disallow edit

The rule you'd need for disallowing 'edit', is a variation of the rule I included (in export format) in my answer to the question about How to restrict access to a node via node/12 and allow access via a path like content/sometitle?

These are the changes to that rule to make it work this case also:

* The paths containing `node` should be extended by adding `/edit` at the end (I'm assuming that's how the URL for your edit link looks like).
* Add a (1st) Rules '*Condition*' like "If `Author id` matches the `uid`".
* Add a (2nd) Rules '*Condition*' like "If `Admin Status` is `Approved`".
* Change the "Message" (in the Rules '*Action*' to something to indicate that the edit is not allowed because `Admin Status` is `Approved`.
* Modify the Rules '*Action*' to fit your own requirements, e.g. to issue a redirect to some 'help page' with more details about this.

# Disallow delete

Should you also want to disallow 'delete' by the author for "Admin status" = 'Approved' (which is not what your question currently says however ...), then create another rule in which you use a similar approach as for 'edit' (as described above), just replace all 'edit' by 'delete'.

# Combine both rules

It should be possible to consolidate the 2 suggested rules above, using "OR" within Rules. Know however that this is a very little harder to get it to work. So learn to walk (= get it to work with 2 separated rules) before you want to learn to fly ...

# Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.

**Note**: your question does not say what should happen (what is allowed or not) when a user who is not the author tries to edit or delete something with 'Admin Status' = Approved. If such scenario is possible in your setup, then you might have to further enhance the Rules Condition I suggested accordingly ...
> 2 votes

# Answer
The first thing that comes to my mind is changing the content type of the node. A module that you could use to change content types at least manually would be Node Convert. However I don't know if this can also be triggered by the Rules or Flag modules, or the like.

Anyways – changing the content type of a node would enable you to give permissions accordingly:

1. `content-type-not-approved` –\> author ***can*** still edit
2. `content-type-approved` –\> author ***can not*** edit any more
> 0 votes

---
Tags: entities, rules, users
---


# Question
Title: Create custom path alias when new user is added in drupal 7
I've created contents using `custom form`. I don't use content types. I could add, update and delete that content by access `test`, `test/id/edit` and `test/id/delete`.

I've displayed content lists for a user by `tests/uid`. Now I want to use **user name** instead of **uid**. I have to replace space by '-' and also replace all special characters. So my choice is both url alias and path auto.

But I couldn't add custom url pattern into pathauto pattern. There is only available for content types, taxonomy term, user and file path. But I want to custom url pattern for custom content inside the user path.

# Answer
If I understand your question correctly, you're wanting to implement Pathauto's API. Here's a tutorial on how to do so. Basically, you need to implement `hook_pathauto()` and make use of `pathauto_create_alias()` & `path_delete()` when you're performing your Create/Update/Delete operations. It looks like you can use the `token_type` of `user` for your token replacement.
> 1 votes

---
Tags: path-aliases
---


# Question
Title: How to force a menu parent link to be non-clickable?
I want the parent link in the menu to not be clickable. As a path is mandatory, I have created a blank node, and in my module I substitute the link by a "#" char.

I used custom code in module because I have a multidomain/multilanguage site, and a mixture of Drupal and database own tables content for the links. Many solutions for custom menus could not be used as they were not compatible with Domain Access or there was some problem in customizing.

The code I use is:

```
$a = menu_tree_output( menu_tree_page_data("main-menu") );
if(in_array($value["#href"], array("node/123", "node/456"))) $nolink = true;

```

I wonder if there is a workaround to this problem, as the typical behavior for a parent menu is to be non-clickable, not to load another page, which would be, IMHO, less typical.

# Answer
You can take look at Special menu items.

**User can create a new menu item and place either "nolink" or "separator" to the Path field, without quotes. Nolink item will be rendered similar to a normal menu link item but there will be no link just the title.**

Here is another module you can check: Content Menu

You can create a new menu item as

* URL – With the traditional menu item form
* Dummy – As a dummy menu item (with simple dummy link target)
* New NODETYPE – directly create a new content for the new item
> 4 votes

---
Tags: 7, routes
---


title: qTips and removing inline styles

text:
# Question
Title: qTips and removing inline styles
Okay, I am using the qTip (Stylish jQuery Tooltips) module to add tooltips to my page that has been laid out using inline styles (due to a consistency across browsers issue with the original theme css).

Question: Is there a way to apply complex html inside of qtips tooltips?

I tried inserting HTML and destroyed my page, with just text qtips works perfectly.

# Answer
Okay for the noobies looking for tooltips like me... The documentation for qTip (Stylish jQuery Tooltips) is a bit misleading and on first read you might think that **must** implement the tooltip via input filter. While implementing via input filter is "quick & dirty", it doesn't allow you to enter any html in the tooltip and also inside your wysiwyg editor you see the tooltip text displayed in the textarea, which destroys the W-Y-S-I-W-Y\_G experience.

From the project page if you want to see demos, you are taken to the qTip2 plugin page, which shows great demos, which are programmatically implemented are 100% NOT useful to implement qtip styled tooltips on your page. You can implement programmtically, but then you have to CSS style the tip on your own.

**My Solution:**

1.) Install the qTip (Stylish jQuery Tooltips) and create an instance (style) of tooltip that you want to use.

2.)After you save your style, you will be taken back to landing page of the module, which lists the qtip instances (styles) that you have saved.

3.) right-click on this page and select "view-source". In the source code of the page find the name of your saved qtip instance (for example, "test\_tip\_top\_left"). It should look something like this:

```
<span class="qtip-link">Sample text</span><span class="qtip-tooltip" data-qtip-instance="test_tip_top_left">This is an example of how this qTip instance will look and function throughout the website.</span>

```

4.) attach the class="qtip-link" attribute to your desired page element, then immediately following the element add a div with the attributes class="qtip-tooltip" data-qtip-instance="test\_tip\_top\_left" and add your desired html content inside the div.

5.) Via theme's style.css (assuming it is used inside your wysiwyg content editing area), create a style to hide the display of the div containing your html tooltip content (if you don't, your tooltip will work, however in your wysiwyg editor the div html tooltip content will be displayed again destroying the WYSIWYG experience), something like:

```
.qtip-tooltip { display: none; }

```

6.) Attach the tooltip to an element in your page:

```
<a class="qtip-link" href="#">Text Users See</a><div class="qtip-tooltip" data-qtip-instance="test_tip_top_left"><strong>HTML Content</strong>inserted here</div>

```

7.) BANG - cool tooltip ;-)
> 2 votes

---
Tags: tooltips
---


# Question
Title: Multiple field Settings not appearing on an entity referenced field
I have a content gallery with a multiple selection entity referenced field to a biblio content. I added the image field to the biblio. Created a view for the gallery, and I'm able to display all the images form the referenced entity.

But for the gallery to work, I need the first image to display only, and when user selects an image a popup appears.

What I'm missing is for the first image to appear only.when configuring the entity referenced field, the multiple field settings is not appearing. Is there another way to do the following or am I missing something?

# Answer
You could create a relationship to the referenced entity and then add a filter where field\_FIELD\_NAME:delta = 0. Then either add fields that belong to the referenced entity using the relationship or add a "rendered entity" field using the relationship.
> 1 votes

---
Tags: entities
---


# Question
Title: How to programmatically stop a migration?
Say I want to stop a migration that I'd like to stop on preImport under similar circumstances as a dependency not being fulfilled, is there a way to do this?

I would like to stop the migration and prevent postImport from running, preferably from preImport().

```
public function preImport() {
  parent::preImport();
  if($this->externalDependency == 0){
  // Stop the migration, and maybe even throw an error.
  }
}

```

# Answer
> 0 votes
MigrateException is the answer (kudos to Clive).
postImport() still runs even after the exception was thrown, so I just have to do the same check on postImport like so.

```
public function preImport() {
  parent::preImport();
  if($this->externalDependency == 0){
  throw new MigrateException('Dependencies were unfulfilled.');
  }
}

public function postImport() {
  parent::postImport();
  if($this->externalDependency == 0){
  return false;
  }
  // My code here
}

```

# Answer
> 2 votes
According to my comment on Luke solution, here is the complete code to interrupt you Migration in Migrate these days.

```
public function preImport() {
  parent::preImport();
  if($this->externalDependency == 0){
  throw new MigrateException('Dependencies were unfulfilled.');
  }
}

public function postImport() {
  parent::postImport();
  if($this->externalDependency == 0){
  return false;
  }
  // My code here
}

public function processImport(array $options = array()) {
  try {
    $result = parent::processImport($options);
    return $result;
  }
  catch (MigrateException $e) {
    $this->endProcess();
    drupal_set_message($e->getMessage(), 'error');
    return MigrationBase::RESULT_STOPPED;
  }
}

```

---
Tags: migrations
---


# Question
Title: Can I run the 'Toolbar' and 'Admin Menu' at the same time for different roles?
I have three extra roles and I would like to use the **Toolbar** to use the menu for the *Editor* role, but the **Admin Menu** for the roles *Adminstrator* & *SuperAdmin*. The one problem I run into is that the higher level roles will inherit the permission to also display the **Toolbar** menu, which is redundant as the **Admin Menu** is already taking care of.

Thanks for your advice.

# Answer
I recommend you to disable **Toolbar** module and use Administration Menu Source with Administration menu and enable **Admin Menu Toolbar** which will give you the same look as Drupal Toolbar.

**Administration Menu Source:**

> Use a different menu as the Administration Menu. Configurable per role.

**Custom Solution:**

Create a custom module add the following `hook_page_alter` function:

```
function mymodule_page_alter(&$page) {
  global $user;

  if(!in_array('editor', array_values(array_map('strtolower', $user->roles))) &&
     !empty($page['page_top']['toolbar'])) {
    $page['page_top']['toolbar']['#access'] = FALSE;
  }
}

```

The above code will check the role of current user and will hide **toolbar** if current user is not editor.

Note: make sure to replace **editor** to whatever editor role you named.
> 1 votes

# Answer
You can use instead the admin menu module along with the admin menu source module. That should be it.

What is does is, you can allow admin menu for different user roles to display different set of menus.

i.e.

* Create different menus for different roles.
* choose the menu for different roles using admin menu source.
* disable toolbar completely.

Check this video, which shows, how this can be achieved https://www.youtube.com/watch?v=txEDvQTTNXc

Hope this helps.
> 0 votes

---
Tags: users, toolbar
---


title: Changing Webform's submit button's text

text:
# Question
Title: Changing Webform's submit button's text
The famous Webform module gives a beautiful nicely designed "Submit" button.

How can I change its text from "Submit", to anything else? I want to change it to another language but I found no way to do it by the UI, or by the Translation mechanism.

# Answer
> 5 votes
Well, normally the webform provides you the facility to edit the submit button form text at

Go to webform-\>form settings-\>Submit button text

Or either way you can use the string override module

Hope it may help you!

# Answer
> 4 votes
You can change the submit button text of a webform very easily. Follow these steps :

1. Edit specific webform of which you want to change the submit text.
2. Go to `Webform -> Form` Settings.
3. Go to `Advanced Settings -> Submit Button Label` field.
4. Here you can add the desired text you want to appear on the submit button.

---
Tags: webforms
---


title: Pager missing in View

text:
# Question
Title: Pager missing in View
I have a view with navigation set to paged, 12 items. I can see 12 items (there are way more available), but no pager. Googling this problem I found the following solutions that didn't work:

View uses Global: PHP fields (my view doesn't do that)

View is displayed in a block (my view is displayed in a page)

Changing pager id (tried everything from 0 to 5, also, this is the only pager on this page)

It's also not a styling issue, the pager is not in the markup. I didn't override any templates related to the view.

In other views, the pager works and I can also see it in the views preview. In this view, I can't even see it in the preview - this should prove that it's not a theming issue as well, am I right?

I tried displaying a "more" link, but that didn't work as well. Changing the navigation to "mini pager" also doesn't help.

The view is using a relationship to an entity reference, but that shouldn't be an issue IMO. Other than that it's a pretty ordinary view displaying some fields. Anyone have any ideas?

(Drupal 7, Views 3)

# Answer
> 0 votes
I found the issue, the View was set to display as a Display Suite Layout and the pager field was hidden in the settings of the Layout.

# Answer
> 0 votes
I'm guessing you have caching enabled for this view. You can disable caching for this view or, better, you can apply this patch: https://www.drupal.org/node/1819538

# Answer
> 0 votes
This is a bug in `Views Php` module,there is a patch for that: Pager disappears when Global: PHP used in Views 3.8

> After upgrading from Views version 7.x-3.7 to 7.x-3.8, the pager was missing from all views that used Global: PHP fields.

I had the same problem and #6 worked for me ,If patch#6 does not work for you, just follow the links in #27

---
Tags: views, paging
---


# Question
Title: How to insert a hashed password into table users?
I'm using services module, but i've created my own resource 'login', I'm using $data to store username + password.

When i use postman, I put a text plain for password, and in my service code i've added the hash function (see my code please)

this is my resource declaration :

```
'user_connexion' => array(
  'actions'=> array(
    'login'=> array(
      'help'=> t('Permet de se connecter'),
      'file'=>array('type'=>'inc','module'=>'my_module','name'=>'my_module.resource'),
      'callback'=>'my_module_connexion_login',
      'access arguments' => array('connexion resource login'),
      'access arguments append' => FALSE,
      'args'=> array(
        array(
          'name' => 'username',
          'type' => 'string',
          'description' => 'username du client',
          'source' => array('data'=>'username'),
          'optional' => FALSE,
        ),
        array(
          'name' => 'password',
          'type' => 'string',
          'description' => 'password du client',
          'source' => array('data'=>'password'),
          'optional' => FALSE,
        ),

```

and this is the function callback :

```
function my_module_connexion_login($username, $password){
//hasher (pour le moment pour tester) password
module_load_include('inc', 'services', 'includes/password');
$password_h= user_hash_password(trim($password));
var_dump($password_h);
}

```

the var\_dump result change every time i send a post request (example for the same password text plain i've got this) :

```
string(55) "$S$DV5cPYQpTqX94qlY9jiYSsCkMCE7AZldfHbXx7qm1ju1aA6AQxRv"
string(55) "$S$DMM2YDpjJ6R0q8.QxLTVjMrIw2dslnt.fBTRGUK6Q8RWEls.vEjy"..ect

```

this is the complete function :

```
function my_module_connexion_login($username, $password){
//hasher (pour le moment pour tester) password
module_load_include('inc', 'services', 'includes/password');
$password_h= user_hash_password(trim($password));
//var_dump($password_h);
$log = db_select('users','u');
$log->addfield('u','uid','id_user');
$log->addfield('u','name','username');
$log->condition('name',$username,'=');
$log->condition('pass',$password_h,'=');
$login = $log->execute();
$connexion = array();

foreach ($login as $co) {
    $connexion [] = array(
        'uid'=>$co->id_user,
        'username'=>$co->username
        );
}
if($connexion == null){
    $response = array(); // error, so no login
    return func_succes(3,$response);
}
else{

    $response = $connexion; //no error and login
    return func_succes(0,$response);
}
 }

```

If i create a valid user and i choose a password, there is no way to login with this password (using my custom resource) because my function that take text plain from postman as THE password and hash it with MY RESOURCE will not returns the same hashed password as the real drupal hashed password for the password i've created before

How to use my resource to login, with taking the username (works now) and a text password, hash it and have the same hashed password stored on users table, to be able to compare it ?

Thank you.

# Answer
> 0 votes
I solved it by using `user_authenticate($name, $password)` (see https://api.drupal.org/api/drupal/modules!user!user.module/function/user\_authenticate/7)

Now my code is :

```
function my_module_connexion_login($username, $password){

$authentification = user_authenticate($username, $password); <======

$log = db_select('users','u');
$log->addfield('u','uid','id_user');
$log->addfield('u','name','username');
$log->condition('name',$username,'=');
$login = $log->execute();
$connexion = array();

foreach ($login as $co) {
    $connexion [] = array(
        'uid'=>$co->id_user,
        'username'=>$co->username
        );
}
if($authentification == false){ <==================
    $response = array();
    return func_succes(3,$response);
}
else{

    $response = $connexion;
    return func_succes(0,$response);
}
}

```

Thanks

---
Tags: 7, services
---


# Question
Title: Drupal.settings.basePath is not giving the base_url in js
When I alerted the `Drupal.settings.basePath` it's just giving me a `/`. I have a full `$base_url` in settings.php. which I'm expecting to see instead of `/`.

How can I get the correct value of the base URL in javascript?

# Answer
> 6 votes
You need to pass it manually like this.

```
global $base_url;
drupal_add_js(array('baseUrl' => $base_url), 'setting');

```

Then call like this `Drupal.settings.baseUrl`.

`Drupal.settings.basePath` value is coming from `base_path()` api. See this documentation about base\_path.

---
Tags: 6, javascript, uri
---


title: Can I truncate users table?

text:
# Question
Title: Can I truncate users table?
For some reason, I need to truncate the *users* table, but I don't want to remove the user with ID equal to 1.

Is there any way to do it?

# Answer
> 8 votes
No, you can't truncate a table and leave data in it at the same time. That would be a contradiction in terms.

You'll need to do a standard delete

```
DELETE FROM users WHERE uid NOT IN (0, 1)

```

(it's important to make sure the anonymous user, ID 0, remains there too).

If you use the direct approach, be 100% sure that you know what you're doing. Unless you know different, there will probably be related data that doesn't get cleared out by simply removing an entry from the users table.

The best way to delete users is through the API: `user_delete_multiple()`

---
Tags: database
---


# Question
Title: How to resolve the warning on my homepage, after deleting mini panel?
I deleted a mini panel and then created a new one and on the homepage I keep getting a warning message and I don't understand why.

> Warning: Creating default object from empty value in panels\_renderer\_ipe-\>render\_pane\_content() (line 145 of E:\inetpub\wwwroot\modules\panels\panels\_ipe\plugins\display\_renderers\panels\_renderer\_ipe.class.php)

Please can someone explain why this happens? This is quite confusing ...

# Answer
It seems like your problem is caused by what is detailed in the issue about PHP 5.3.9 Strict Warning on Panels Empty Value. It was first reported in Panels 3.2, and has status 'Closed (Fixed)'.

The patch in comment # 15 of it should help you resolve the error. And according to comment # 26, this patch is included as of Panels 3.4.
> 1 votes

---
Tags: panels
---


# Question
Title: how to alter notification email in search api saved search module. I want to add more details about the search
I m using search api saved search module to save my search selected using facets. In the notification email i want to add selected search options which i saved, Ex: country or city name which i selected while saving the search.

# Answer
> 1 votes
hook\_mail\_alter is your best friend, just keep in mind this hook fired on all emails so make sure you check if your are targeting the search-API emails. Here is a snippet of code copied from the mail\_example module:

```
function email_example_mail_alter(&$message) {
  // For the purpose of this example, modify all the outgoing messages and
  // attach a site signature. The signature will be translated to the language
  // in which message was built.
  $options = array(
    'langcode' => $message['language']->language,
  );

  $signature = t("\n--\nMail altered by email_example module.", array(), $options);
  if (is_array($message['body'])) {
    $message['body'][] = $signature;
  }
  else {
    // Some modules use the body as a string, erroneously.
    $message['body'] .= $signature;
  }
}

```

---
Tags: search
---


# Question
Title: How to auto submit only after typing at least three character in view exposed filter
I have a view with exposed filters using AJAX and auto-submit feature.

The problem is it reacts to every char I type but what I want is that when a user type at least three character in the text field then it should auto submit and display search result. But Cant figure out how to implement this. Please help

# Answer
> 0 votes
* Attach ***custom\_form\_validate*** for that form using ***form\_alter***
* Do what ever you want in this custom\_validation.
* Reference

---
Tags: views
---


# Question
Title: Adding indexed field to Search API query in code
I want to add an indexed field to a Search API query in code. My query currently looks like this:

```
$index = search_api_index_load("default_node_index");
$query=new SearchApiQuery($index);
$query->condition('type', 'answers_question', '=');
$filter = $query->createFilter('OR');
$filter->condition('title', $text, '=');
$filter->condition('body:value', $text, '=');
$query->sort('search_api_relevance', DESC);
$query->fields(array('title'));
$query->filter($filter);
$query->keys($text);
$data=$query->execute();

```

This returns the correct results, however the result set is composed of an array of arrays with an 'id' and a 'score'. I want the indexed node title to be returned as well. I cannot do a join to the node table as -\>join is not available on SearchApiQuery.

The statement:

```
$query->fields(array('title'));

```

does not seem to do anything.

I have this same query set up in a view where it is working properly. When I inspect the query at hook\_search\_api\_query\_alter I cannot see where or how the title is added.

How do I add the indexed title as a field to be returned in the result set?

# Answer
```
$query->fields(array('title'));

```

Doesn't do what you think it does/should, this tells Search API that this is one of your fulltext fields that you want querying against the string you passed to keys()

```
$query->keys($text);

```

What backend are you using for Search API, in my experience Solr returns all indexed non empty fields. Make sure the Title is indexed so that it is available to your Search API's backend.
> 0 votes

---
Tags: search
---


# Question
Title: Programmatically created list_boolean checkbox field value won't get saved
I've added a lot of fields and field instances via a custom module to some prepared content types. `field_create_field()` and `field_create_instance()` work like a charm, not a single error. Every field then works as expected, EXCEPT for the checkbox field.

It appears at the right place, has the right label, BUT when it comes to node saving the checked checkbox simply won't save. Next time I edit the node it's unchecked again, no value got written to the database. What do I miss here?

```
$field = array(
  'field' => array(
    'field_name'  => 'MYFIELD',
    'label'       => 'Set as default',
    'type'        => 'list_boolean',
  ),
  'instance' => array(
    'field_name'  => 'MYFIELD',
    'entity_type' => 'node',
    'bundle'      => 'MYBUNDLE',
    'label'       => 'Set as default',
    'widget'      => array(
      'type'      => 'options_onoff',
      'settings'  => array(
        'display_label' => TRUE,
      ),
    ),
    'display'     => array(
      'default'   => array(
        'label'   => 'hidden',
        'type'    => 'hidden',
      ),
    ),
  ),
);

field_create_field($field['field']);
field_create_instance($field['instance']);

```

# Answer
> 4 votes
Thanks @Clive, all that was missing were `'allowed_values'` in `$field['field]`:

```
$field = array(
  'field' => array(
    'field_name'  => 'MYFIELD',
    'label'       => 'Set as default',
    'type'        => 'list_boolean',
    // It's mandatory to add at least two empty values here,
    // Drupal will do the rest then:
    'settings'    => array(
      'allowed_values' => array(
        '',
        '',
      ),
    ),
  ),
  'instance' => array(
    'field_name'  => 'MYFIELD',
    'entity_type' => 'node',
    'bundle'      => 'MYBUNDLE',
    'label'       => 'Set as default',
    'widget'      => array(
      'type'      => 'options_onoff',
      'settings'  => array(
        'display_label' => TRUE,
      ),
    ),
    'display'     => array(
      'default'   => array(
        'label'   => 'hidden',
        'type'    => 'hidden',
      ),
    ),
  ),
);

```

You simply have to declare empty On/Off values. Which may not seem too obvious, but logical at least since when you create `options_onoff` checkbox from the backend there's written:

> **On value** \[\_____\] If left empty, "1" will be used.
>
> **Off value** \[\_____\] If left empty, "0" will be used.

---
Tags: 7, entities
---


title: Custom 404 error page issue

text:
# Question
Title: Custom 404 error page issue
I want to have a custom 404 page that displays some additional information. I need to display the requested path that was not found and some pages suggestions based on that path (this is based on some internal logic that I don't think is relevant to my question).

Here is what I did:

I defined the default 404 page to be `page-not-found` in `admin/config/system/site-information`

Then in my module I used `hook_page_alter()` to define my pages suggestions (if `drupal_get_http_headers("status")` is `404 Not Found`), and the `request_uri()` to be shown on the 404 template page I created.

I have tried to save these values in different ways (session variable, ctools cache, everything I have tried leads to the same issue — see below).

In **mymodule.module**:

```
/**
 * Implement hook_menu
 * @return mixed
 */
function mymodule_menu() {
  $items['page-not-found'] = array(
    'title' => '',
    'page callback' => 'mymodule_page_not_found',
    'file' => 'inc/functions.inc',
    'access callback' => TRUE,
  );
  return $items;
}

/**
 * Implement hook_theme
 */
function mymodule_theme() {
  return array(
    'mymodule_page_not_found' => array(
      'template' => 'templates/404',
    ),
  );
}

```

In **inc/functions.inc**:

```
function mymodule_page_not_found() {

  return theme('mymodule_page_not_found');
}

```

Problem is, if I request a non existing URL for example `mysite.com/not-found-page-1` then request `mysite.com/not-found-page-2` the information displayed on the 404 page template when I query the *not-found-page-2* corresponds to the values I saved when requesting *not-found-page-1*.

Any idea why I always get the data of the previous query?

# Answer
The trouble is, `hook_page_alter()` is called after your theme function is called. So if you're setting things there it's too late.

I don't know why you're doing it this way. Why not generate your suggestions in your page callback: `mymodule_page_not_found()`. Then pass them to the theme function.

Something like this:

```
/**
 * Implement hook_theme
 */
function mymodule_theme() {
  return array(
    'mymodule_page_not_found' => array(
      'template' => 'templates/404', // Not relevant to your question, but you should consider renaming this to mymodule-page-not-found because of a "bug" in D7; see discussion here: https://www.drupal.org/node/342350
      'variables' => array('suggestions' => array()),
    ),
  );
}

function mymodule_page_not_found() {
  // ... generate list of $suggestions ...
  return theme('mymodule_page_not_found', array('suggestions' => $suggestions));
}

```
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Drupal 7, hook permission for view published content only for certain content type/blog
I disabled the view published permission for anonymous user. but I wanted to allow anonymous user to view the blog section with views on it, and I cant seem to hook permission on that particular blog.

is there any clue for this?

thank you

# Answer
You can use content\_access module, you can control any content type permissions individually. here is a nice video tutorial
> 0 votes

---
Tags: hooks, users
---


# Question
Title: Paypal express checkout doesn't add taxes
I am creating a site where they only want to use paypal express checkout (using drupal 7 /Ubercart 3.1). The problem is that it doesn't display the taxes when processing the order. I know it doesn't have the address info when it goes to the express checkout but when it comes back, it adds the shipping price but no taxes. Is there a way to add the taxes in?

I have been through all the options and don't see anything related to this.

I have also tried modifying inside the paypal module itself:

In the function uc\_paypal\_ec\_review\_form\_submit I see that they add the shipping info if it is not there but when I try to add taxes the same way, the tax functions don't work.

I do see the line "subtotal excluding taxes" which I believe is being generated by the taxes module but no tax is actually applied.

If I use the paypal standard checkout, the tax is applied once the address info is filled in.

Any help would be appreciated.

# Answer
> 0 votes
It seems that Ubercart doesn't set the billing address properly after making the API call. See uc\_paypal.pages.inc around line 240.

The original snippet looked like this:

```
$order->delivery_street1 = check_plain($nvp_response['SHIPTOSTREET']);
$order->delivery_street2 = isset($nvp_response['SHIPTOSTREET2']) ? check_plain($nvp_response['SHIPTOSTREET2']) : '';
$order->delivery_city = check_plain($nvp_response['SHIPTOCITY']);
$order->delivery_zone = !empty($zone_id) ? $zone_id : 0;
$order->delivery_postal_code = check_plain($nvp_response['SHIPTOZIP']);
$order->delivery_country = !empty($country_id) ? $country_id : 840;

$order->billing_first_name = check_plain($nvp_response['FIRSTNAME']);
$order->billing_last_name = check_plain($nvp_response['LASTNAME']);
$order->billing_street1 = check_plain($nvp_response['EMAIL']);

```

You can see that the billing address is never added. I would assume that most people who experience this issue have the tax calculating by the user's state. Since there's no state, no tax is added. Since the billing address and delivery address will be the same on Paypal, simply add the delivery info into the billing info like so:

```
$order->billing_street1 = check_plain($nvp_response['SHIPTOSTREET']);
$order->billing_street2 = isset($nvp_response['SHIPTOSTREET2']) ? check_plain($nvp_response['SHIPTOSTREET2']) : '';
$order->billing_city = check_plain($nvp_response['SHIPTOCITY']);
$order->billing_zone = !empty($zone_id) ? $zone_id : 0;
$order->billing_postal_code = check_plain($nvp_response['SHIPTOZIP']);
$order->billing_country = !empty($country_id) ? $country_id : 840;

```

Hacking core/contrib modules like this sucks and I don't recommend it, but sometimes, you gotta do what you gotta do.

Enjoy your taxes!

---
Tags: ubercart, payment-gateways
---


# Question
Title: How can I make form_alter work with Ajax Comments?
I did some manipulation (with JavaScript and CSS) on my comment form. It works good. Then I needed to install the Ajax Comments module *because I don't want visitors to go another page while replying a comment*.

My customization on the comment form doesn't work after enabling the Ajax Comments module.

This is the custom code that works without Ajax Comments:

```
function mytheme_form_alter(&$form, &$form_state, $form_id) {

      if($form_id == 'comment_node_blog_form') {
        $form['comment_body']['#weight'] = -100;
        $form['#attached']['js'][] = drupal_get_path('theme', 'mytheme') . '/js/jquery.validationEngine-en.js';
        $form['#attached']['js'][] = drupal_get_path('theme', 'mytheme') . '/js/jquery.validationEngine.js';
        $form['#attached']['js'][] = drupal_get_path('theme', 'mytheme') . '/js/scripts.js';
      }
    }

```

And this is the JavaScript code:

```
(function ($) {
    $(document).ready(function(){
        $("#comment-form").validationEngine();
        $('#comment-form').find('.form-type-textfield').hide();
        $('#edit-comment-body').click(function() {
                $('#comment-form').find('.form-type-textfield').slideDown();
        });
    });
})(jQuery);

```

*I tried the code above with behavior format but it also didn't work.*

How can I make this code work with Ajax Comments?

# Answer
> 2 votes
AJAX Comments replaces the core comment form with its own version, so `#comment-form` is the wrong selector. It'll be something more like `#ajax-comments-reply-form-751661-0-0`. The numbers break down as `[node-id]-[parent-comment-id]-[ajax-iterator]`. The parent comment ID comes into play when you're replying to an existing comment.

Because the module uses the core AJAX API, that ID will also change for the new form that appears after a new comment is posted, so using an ID for your jQuery selector isn't a good option.

Without knowing exactly how your markup looks some of this is guess work, but the code to grab a reference to the comment form will look something like this:

```
var $commentForm = $('#main-body-selector').find('.ajax-comments-form-add');

```

---

**EDIT**: The Ajax Comments module adds an `ajax-comments-form-reply` class to all reply forms and adds an `ajax-comments-form-add` class to all comment add forms.

So, instead of `#comment-form` you should use `ajax-comments-form-add` and/or `ajax-comments-form-reply` to effect the comment form.

```
(function ($) {
Drupal.behaviors.comment = {
  attach: function (context, settings) {
        $(".ajax-comments-form-reply").validationEngine();
        $('.ajax-comments-form-reply').find('.form-type-textfield').hide();
        $('.text-full').click(function() {
                $('.ajax-comments-form-reply').find('.form-type-textfield').slideDown();
        });

        $(".ajax-comments-form-add").validationEngine();
        $('.ajax-comments-form-add').find('.form-type-textfield').hide();
        $('.text-full').click(function() {
                $('.ajax-comments-form-add').find('.form-type-textfield').slideDown();
        });

  }
};
}(jQuery));

```

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


title: Transform PDF to image place text on it

text:
# Question
Title: Transform PDF to image place text on it
I am hoping to find a drupal module that can transform a PDF to image and merge that image with another one. Use case scenario is basically placing an endorsement stamp on an image.

Thanks

# Answer
> 0 votes
It sounds like you want PDF to ImageField.

> The PDF To ImageField module provides automatic conversion of uploaded PDF files to images. It can be used either to create a snapshot of the front page to use as a preview thumbnail, or to generate a gallery of images from each page in the document.
>
> The module is implemented as an additional widget for File Field where PDFs are uploaded to. It places generated images into a Image Field on the same content type.

That will get you half way there. As for the 2nd requirement of image merging, you'll likely have to implement your own solution via Drupal's node API/hooks to manipulate the converted PDF image with your stamp.

---
Tags: files, media
---