# Question
Title: How to add Drupal Commerce to an existing Drupal site?
I wonder how to add the Drupal Commerce module to an existing Drupal installation.

I've had problems with the documentation about this topic that I have looked at so far:

I've also looked at the available Community documentation about Drupal commerce and I have installed the required modules. But when I try creating the products I'm having issues.

After following the aforementioned documentation and creating a custom product I get this error when trying to view the newly created product:

> EntityMetadataWrapperException: Unknown data property commerce\_product. in EntityStructureWrapper-\>getPropertyInfo()

Any suggestions about how to resolve this error?

# Answer
> 3 votes
# Option 1: Instructions from the community documentation

You saw the available community documentation about Drupal commerce, where it says (bold markup added here):

> If you're **installing Drupal Commerce on an existing Drupal site** or on a new Drupal site without using Commerce Kickstart, you first need to install the latest packaged release of the following modules: ...

From my quote here, it sounds to me that it "has to be possible" to add Drupal commerce into an existing site.

I wonder however if it'd help to get your error resolved by taking into account this part of the community docu page:

> Installing Drupal Commerce modules
>
> When turning on the sub-modules of Commerce, you will notice that some modules are dependent on other modules. You may wish to turn them on one at a time so as to pinpoint any error messages. This is the order to satisfy dependencies:
>
> * Commerce and Commerce UI
> * Customer and Customer UI
> * Price
> * Line Item and Line Item UI
> * Order and Order UI
> * Checkout, Payment, Product
> * Product Reference
> * Cart and Product Pricing
> * Tax
> * Product UI
> * Tax UI
> * Payment UI

More specific: are you using all these modules? If not, could your error be caused by some dependency as mentioned in the quote above? Alse, does your error remain if you (temporarely) install/enable the modules in the list above that you don't use yet.

If you have all those modules enabled, what happens if (a) you disable them all and (b) re-enable them one at a time (as in the quote above also). It might help to pinpoint the real reason for your error message ...

# Option 2: Use the Commerce Repair module

Other thoughts / approaches / attempts:

---
Tags: 7, commerce
---


# Question
Title: Pass variable to field template from theme_preprocess_field()
I'm stuck trying to pass variables from my theme\_preprocess\_field function to my template file. I want to have a variable for each of the fields I am printing out to my template.

I'm using the Paragraphs module in Drupal 7, so that might be throwing me off, but I feel like I'm really close. Here's a simple example:

Preprocess function in my template.php:

```
function merge_preprocess_field(&$variables) {
    $element = $variables['element'];
  if (isset($element['#field_name'])) {
    if ($element['#field_name'] == 'field_title') {
      $variables['test_title'] = $variables['items'][0]['#markup'];
    }
  }
}

```

The name of the template I am using is `paragraphs-item--full-text.tpl.php`.

`field_title` is the name of a field inside a paragraphs bundle called `full-text`.

Everything that I have read so far indicates that I should be able to access the `$variables['test_title']` variable in my template this way:

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

```

It doesn't print, even after clearing the cache. It's even showing up in the array when I `krumo($variables);`. Am I missing something?

# Answer
Ok, I figured this out. My preprocess function was for a field, but I was trying to access the variable in the wrong template. What I ended up doing was creating individual preprocess functions for each paragraphs-item, and preprocessing the variables in there.

First, I created a function that would allow me to create preprocess functions for entity types:

```
function merge_preprocess_entity(&$vars, $hook) {
  $function = 'merge_preprocess_' . $vars['entity_type'];
  if (function_exists($function)) {
    $function($vars, $hook);
  }
}

```

This allowed me to create a preprocess function for paragraphs items. Then I used this same idea to create preprocess functions for individual paragraphs items:

```
function merge_preprocess_paragraphs_item(&$vars, $hook) {
  $elements = $vars['elements'];

  $function = 'merge_preprocess_paragraphs_item__' . $elements['#bundle'];
  if (function_exists($function)) {
    $function($vars, $hook);
  }
}

```

Now I can set variables that are available in the paragraphs items templates, like so:

```
function merge_preprocess_paragraphs_item__smaller_full_width_text(&$vars, $hook) {

  if ($vars['content']['field_cta']) {

    $field_cta = !empty($vars['content']['field_cta'])? $vars['content']['field_cta'][0]['entity']['field_collection_item']: '';

    foreach ($field_cta as $field_cta) {

        // Make the CTA url available to the rest of the block
        $vars['content']['cta_url'] = $field_cta['field_link'][0]['#markup'];

        // Set character limit for CTA Text
        $vars['content']['cta_text'] = truncate_utf8($field_cta['field_link_text'][0]['#markup'], 24, TRUE, FALSE);

    }
  }
}

```
> 2 votes

---
Tags: theming
---


title: Free Pager and Contextual filter

text:
# Question
Title: Free Pager and Contextual filter
I just can't get my head around the following problem.

* I have two content types. One is **ISSUE** the other one is **ARTICLE**.
* I use the *Node Reference module* to link and **ARTICLE** to an **ISSUE**.
* Then I am using *Free Pager module* to have a pager on every page to click to the next and previous node.

The pager works but for all **ARTICLES** of all **ISSUES**. Now I want it to work for only the **ARTICLES** in the same **ISSUE** as the current node.

I tried to get this to work with the normal Views filter and the Contextual filter but for some reason it doesn't work. Does anyone have a solution for this? Or another option with other modules that do the trick?

Thanks in advance Joost

# Answer
> 0 votes
It can be done using Views:

* set up the view in the format you want so that all Articles show
* create a filter on the Node Reference Field in Content:Articles
* expose this filter
* make the operator: Is one of
* Options: Select all - this should automatically update as new issues are created
* Pager: Mini, Mini pager, 1 item - this will create a simple pager with only one item per page

---
Tags: views, nodes
---


# Question
Title: Fetch data from database and show in custom block
I have created my own simple block.I want to show some data from user table of database of logged in user to the block.I want to show it programmatically and not want to use any module. How can I do that? One more question related to block is, can I add my custom theme to my custom block (like .tpl.php file for custom module)?If yes how can I do that?

# Answer
> 1 votes
depending on the information you want to retrieve, Views is probably your simplest option:

> You need Views if
>
> You like the default front page view, but you find you want to sort it differently. You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically. You use /tracker, but you want to restrict it to posts of a certain type. You like the idea of the 'article' module, but it doesn't display articles the way you like. You want a way to display a block with the 5 most recent posts of some particular type. You want to provide 'unread forum posts'. You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month. Views can do a lot more than that, but those are some of the obvious uses of Views.

Views allows you create a block or a page in order to display formatted data.

---
Tags: blocks, theming, database
---


title: Changing date format in node template

text:
# Question
Title: Changing date format in node template
I have a content type called news which I created a template for, node--news.tpl.php. In my template, I call the date field as follows:

```
<?php print render($content['field_news_date']);  ?>

```

It displays like so:

> 05/01/2015 - 15:25

I would like it to look like this:

> 1 May 2015

I need to be able to do so solely through the node template, as making changes directly in Drupal will affect other sites and that is not an option. Is there a way to do that?

# Answer
Assuming you need a specific template, you could also use template.php. This is the preferred method to keep logic out of the template.

Using template.php, you can do a template\_preprocess\_field()

This overview does a nice job walking you through altering the date. Also, using php date() function you can alter the field to display as `1 May 2015` using `l M Y`
> 1 votes

---
Tags: 7, nodes, theming, datetime
---


# Question
Title: What is the Drupal 6 equivalent or alternative to hook_node_load?
In Drupal 7, there exists the function hook\_node\_load. Does anyone know how I can hook into a node being loaded from the database in Drupal 6? If not, can you suggest an alternative hook? I am simply trying to get my custom module to load my javascript file upon the user visiting a particular node page. Thanks.

# Answer
> 0 votes
I've found that hook\_nodeapi fits my use case: https://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook\_nodeapi/6

---
Tags: 6, nodes
---


# Question
Title: Best way to translate parts of an existing site and retain page aliases
What is the least complicated way to translate parts of an existing and quite big site (few hundreds of thousands nodes), without affecting the page aliases?

I am aware of different translation systems and would prefer to use Entity translation. Unfortunately, it seems that both Entity Translation and Content translation don't make it possible to retain a functioning URL structure. E. g. I have this now:

* Original text's URL (the same pattern should work after translation): example.com/texto-original

After the translation work, it should have this structure:

* Original text's URL (the same pattern should work after translation): example.com/texto-original
* Translated text (has language parameter in the URL): example.com/en/translated-text

What I want to achieve:

1. There's a default language (Spanish in this example) that was used for all of the content so far. Those pages don't have language prefix in the URL (e. g. "es/") at the moment. It should stay that way.
2. Site should always display everything in Spanish, unless a visitor opens an URL with "en/" prefix.
3. On the pages that are translated, there should be a link "English", "View this page in English" or something similar.
4. When a visitor opens such page in English, there should also be a link "Español". If a visitor is on the English page - the interface, blocks and other entities (if translated) should be in English as well.

Sorry if I haven't explained well what I want to achieve, I'll try to explain better if something is not clear.

Thank you for any ideas.

# Answer
I have found the solution and it's quite easy actually. Here are the steps necessary:

1. Go to languages settings: admin/config/regional/language
2. Edit the default language (the one that shouldn't have language prefix).
3. Remove the code from "Path prefix language code" field.
4. Go to detection options (admin/config/regional/language/configure) and select "URL" method.

That's it, it should work as I have described in the question.
> 0 votes

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


# Question
Title: Why doesn't the field table in the Drupal database use entity_id as a primary key?
I'm working on trying to optimize a View SQL query and I noticed that the query being executed is using a join on a the entity\_id field of a field table. I noticed that for some reason unbeknownst to me the entity\_id field is not a primary key. The delta field is a primary key.

Can anyone enlighten me as to why this is the case? Can I safely tag entity\_id as a primary key without incurring a wrath of unintended consequences? Thank you for your help.

# Answer
> 3 votes
The primary key for a field table is compound, consisting of:

* entity\_type
* deleted
* entity\_id
* language
* delta

It's probably just the way your GUI is displaying the data that's confusing. This is Navicat's representation, for example:

If not, then something fishy has happened. Since the entity\_id is supposed to be part of the compound key, if it *isn't*, it should be safe to add it to the rest. Take a backup first just in case.

# Answer
> 1 votes
The field tables store the usages of that field *for all entities* that use that field. In other words, nodes and users could both have the same field on them. In this case, a particular field could be on both nodes and users. In this case, the entity ID may not be unique.

---
Tags: 7, views, database
---


# Question
Title: Can't Update Contrib Modules via Admin UI
I'm having a problem with a new Drupal site I'm working on. I installed Drupal 7.36 and am able to install contributed modules via the admin UI and Drush. However, I cannot update any contributed modules via the admin UI. I can update via Drush however.

The error I'm getting is as follows.

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /wcbvi/batch?id=9&op=do StatusText: Internal Server Error ResponseText:

I'm running Ubuntu Server 14.04.2 (32-bit) in VirtualBox with Apache 2.4.7 and PHP 5.5.9. I've also installed Curl, Composer, and Drush.

# Answer
> 1 votes
No guarantee it will help, but I think it's worth trying (inspired by some of the suggestions in this comment in issue nr 1022558):

* Increase the php memory limits by editing the following lines in the php.ini file as:

+ max\_execution\_time = 30 --\> 60 ;
    + memory\_limit = 32 --\> 128, or even 256M ;
* Add the following lines to the end of .htaccess file:

+ php\_value auto\_append\_file none
    + php\_value memory\_limit 128M

---
Tags: updating
---


# Question
Title: Received "An illegal choice has been detected. Please contact the site administrator" while creating node with taxonomy field via service3 drupal7
I am having an error:

> {"form\_errors":{"field\_category\]\[und":"An illegal choice has been detected. Please contact the site administrator."}}

Field category is a taxonomy field attached to a node. I'm trying to create a node via web services and unable to create taxonomy field. I have also match post array by doing print\_r($obj) on node form validate:

PHP Array:

```
[field_category] => Array(
  [und] => Array(
    [0] => Array(
      [tid] => 6246
    )
  )
)

```

JSON conversion:

```
"field_category": {
  "und": [
    {
      "tid":6246
    }
  ]
}

```

However, in response having an error, the same problem with the other taxonomy field. What I am doing wrong with it.

# Answer
> 1 votes
I was having the same issue. After reading this I was able to figure out the problem by doing a `dsm($_POST)` on hook\_node\_update() and inspecting the array and figuring out what it expects.

In my case my array looked like this:

```
'field_term_subtype[und]' => '166',

```

In your case it would be:

```
{
    "title": "your title",
    "type": "page",
    "field_category": {
        "und": 6246
    }
}

```

# Answer
> 0 votes
You should be able to create a node using a POST request.

For the node fields, you can use something like:

```
$node_data = http_build_query(
  array(
    'type' => 'page',
    'title' => 'This node was created via the API.',
    'field_category[und][0][tid]' => 6246,
  )
);

[...]

curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $node_data);

[...]

```

See also: https://drupal.stackexchange.com/a/72758/7153

# Answer
> 0 votes
Try the following Json format to create node having taxonomy filed

```
{
    "title": "your title",
    "type": "page",
    "field_category": {
        "und": "termname"
    }
}

```

---
Tags: 7, taxonomy-terms, nodes, services
---


# Question
Title: Is there a way to prevent a user from seeing a field on their user profile page?
I'm looking to create a 'Last Updated' field in a user's profile. I was then going to create a rule that filled that field with the current date everytime the user's profile was edited. I want the information for admin purposes and don't want the user to see this info.

Is this possible? I'd prefer not to use a module.

EDIT: I would be fine with the field being on the user-edit page instead (but still hidden) if that's easier.

# Answer
> 1 votes
I recently needed something similar and ended up pre-processing some of the details in `template.php` and then rendering the output in `user-profile.tpl.php`. What I did was like this:

```
function MYTHEME_preprocess_user_profile(&$variables) {

// check if current user has role 'Administrator'

$ok_role="Administrator";

    if ($variables['user']) {
        foreach($variables['user']->roles as $key => $role) {
            $variables['classes_array'][] = $role;
        }
    }

    if(in_array($ok_role,$variables['classes_array']) {
        $variables['visiblebyrole']=TRUE;
    } else {
        $variables['visiblebyrole']=FALSE;
    }

// etc...

}

```

This gives me an extra variable that's `TRUE`for admins and `false`for everybody else. I did then check the fields `user-profile.tpl.php` accordingly similar to this:

```
<?PHP if(($profile_updated)&&($visiblebyrole)) { ?>
    <div class="updated"><?PHP print($profile_updated); ?></div>
<?PHP } ?>

```

You could probably improve the code structure, but for me it worked.

# Answer
> 4 votes
> Is this possible?

Yes, but not out of the box with Drupal.

> I'd prefer not to use a module.

Not an option unfortunately, you need either a contrib or custom module to make this happen. You could theoretically do it in the theme, but that logic doesn't belong there.

Field Permissions is the go-to module for this.

Ah, just noticed your edit.

If you want the field to simply not be rendered, but you're happy for it to exist in the edit form, you can override the user-profile.tpl.php template in your theme, and just hide the field there:

```
<?php hide($user_profile['foo']); ?>

```

Or just hide it through the UI at admin/config/people/accounts/display if that works for your scenario.

# Answer
> 3 votes
This works for D7. You have to do it by a custom module, replace MYMODULE with your module name and field\_YOUR\_FIELD with your field name. It will not hide it for admin user

```
//implement function form_alter

      function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
        global $user;
        $uuid = $user->uid;

  /*  check that user is NOT admin (No1) */
    if ($uuid !='1') {
        //if form id is user_profile_form --> hide fields
         if ($form_id=='user_profile_form') {
            hide($form['field_YOUR_FIELD']);
         }
        }
      }

```

---
Tags: users
---


title: drupal 7 SSL a lot of insecure urls

text:
# Question
Title: drupal 7 SSL a lot of insecure urls
My site is now using a SSL certificate but i have about 300k pages with insecure urls (http) - What is the best and most efficient way of fixing this problem?

The problem is the dynamic content is referencing HTTP content. The site is already forcing SSL.

# Answer
One solution, *if you're wanting to force your site to always to use SSL,* is to do it at the Apache level by adding this to your .htaccess:

```
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

That's probably the *quickest way*. The *best way* is subjective; your needs might be different depending on priorities (e.g. for performance reasons you might want to force many static pages to HTTP).
> 3 votes

# Answer
As Shawn Conn says, the easiest thing to do would be to force SSL for your entire site at the server level. There is minimal performance overhead to SSL encryption for modern processors so if you've already paid for the certificate there's little reason not to do it. Also this will prevent expensive application-level redirects to secure/un-secure pages as the case may be.
> 1 votes

# Answer
You could try the Secure Pages module.

> A small process which will redirect the required pages to a SSL version of the page.
> 1 votes

---
Tags: uri, ssl
---


# Question
Title: Using hook_node_presave to auto-select a reference field from a field list selection
I'm trying to use hook\_node\_presave to select a value in a term reference field based on a selection a user makes in a field list field. The term reference field is hidden from the user. The code I'm working with is problemmatic in at least two ways:

1) I'm not sure I'm referencing the correct theme in my function header because the dpm() is not outputting anything. But it's in the administrative theme 'seven' that this form is running so I assume that's right.

2) I'm getting errors when I run this code saying 'syntax error, unexpected ||' wherever I have those. Am I not using the correct syntax for OR operators? It seems fine to me. I tried OR in place of || and got the same errors.

Here's the code I'm working with:

```
function seven_node_presave($node) {
    $field_type = $form['field_type']['und']['#options'];
    dpm($field_type);
    if (($field_type == 4) || ($field_type == 5)) || ($field_type == 7) ||
($field_type == 6)) {
        $form['field_icon']['und']['#options'][]= '2';
    }
    elseif (($field_type == '9') || ($field_type == '98')) || ($field_type == '8')) {
        $form['field_icon']['und']['#options'][]= '6';
    }
    elseif (($field_type == '3') || ($field_type == '1')) || ($field_type == '2')) {
        $form['field_icon']['und']['#options'][]= '1';
    }
}

```

Note 1: the numbers being compared to (ex: $field\_type == 4) are the 'keys' for those fields, not the actual text the user would select.

Note 2: I'm running this from a module called grouphideandselect, not from template.php...maybe that's my problem?

# Answer
As Darvanen said above, the function name is wrong, replace HOOK by the module's name in HOOK\_node\_presave(). About the || operators, you could use in\_array instead or a single associative array:

```
function grouphideandselect_node_presave($node) {
    $field_type = $form['field_type']['und']['#options'];
    dpm($field_type);

    $field_type_to_icon = array(
      1 => 1,
      2 => 1,
      3 => 1,
      4 => 2,
      5 => 2,
      7 => 2,
      8 => 6,
      9 => 6,
      98 => 6,
    );

    if (isset($field_type_to_icon[$field_type])) {
      $form['field_icon']['und']['#options'][] = $field_type_to_icon[$field_type];
    }
}

```

EDIT: from another question of yours I see that you already tried renaming the function to `grouphideandselect_node_presave`. You need to make sure that: \- the function's name is right \- the module is enabled \- you cleared Drupal's cache afterwards
> 2 votes

# Answer
Ben's answer is correct on getting the code to fire, regarding your OR operators, they're fine, it's the syntax you're using around them that is the problem: you have too many parentheses, or not enough.

Let's look at one of the lines:

```
elseif (($field_type == '9') || ($field_type == '98')) || ($field_type == '8')) {

```

After `elseif` you open two parentheses, fine. You close one after your first comparison, open one, close two. Now you've closed all of the parentheses but you're still adding more criteria.

It might be easier to see if you remove the unnecessary parentheses around each comparison:

```
elseif ($field_type == '9' || $field_type == '98') || $field_type == '8') {

```

Everything after `elseif` needs to be in one set of parentheses, and then you either have a single command (bad practice) or a code block in brackets `{}` (good practice). So you need to either, add one more parenthesis at the very beginning, or remove the one in the middle. I suspect you're after the latter which would look like this:

```
elseif ($field_type == '9' || $field_type == '98' || $field_type == '8') {

```

---

As for your question in comments:

> "Is this the correct way to set a term reference field programmatically (the field\_icon field is a term reference field)?"

The method looks ok to me, that is using a presave function to adjust values is fine. But you need to edit the `$node` variable that is being acted upon or you will not achieve anything, because the code that called the hook is not interested in the form, only the node.

I would use dpm($node) to discover how the node is structured and then adjust those values in your code.
> 1 votes

---
Tags: theming, hooks
---


# Question
Title: FontAwesome tags removed when switching between Source and Wysiwyg
I am using http://fortawesome.github.com/Font-Awesome/ \- popular iconic font

When I insert "i" tag i.e. it is saved only in source mode enabled, but removed from html when saving in wysiwyg mode.

How to avoid removing i tag? (using Ckeditor with Drupal 7 and Wysiwyg module)

# Answer
> 9 votes
As Vic Nicethemer pointed out - the solution (for me) was to add ` ` within the `<i>` and `</i>` like so: `<i class="icon-facebook"> </i>`.

CKEDitor removes elements that do not have any internal content...

# Answer
> 7 votes
Adding `&nbsp` between the tags isn't the greatest since it's adding additional unneeded markup.

To do this a better way I suggest creating a custom WYSIWYG module to tweak the CK Editor settings.

Basically, create a module that adds a `ckeditor-config.js` for extra configuration settings with `hook_wysiwyg_editor_settings_alter()`

Inside the file you add:

```
CKEDITOR.editorConfig = function( config ) {

  // allow i tags to be empty (for FontAwesome)
  CKEDITOR.dtd.$removeEmpty['i'] = false;

}

```

Here is a CK WYSIWYG Tweaks module on Github I created, download and install like a regular module if you have WYSIWYG w/ CK editor already running. Then add any other tweaks you need, the tweak to stop disappearing tags is alread there!

# Answer
> 1 votes
You've probably enabled the "Limit allowed HTML tags" option. In this case You've to enable the "i" tag on the input format filter.

1. Open admin/config/content/formats
2. Click "configure" on the input format you're using
3. Add `<i>` on "Allowed HTML tags" setting

# Answer
> 1 votes
I created an **unrestricted\_html** format under `/admin/config/content/formats/` that I only give to administrators.

I unchecked **\[ \] Limit allowed HTML tags** & **\[ \] WYSIWYG Filter** & was able to use the `<i>` tags successfully.

I also don't have a **Wysiwyg profile** associated with this format. My assumption is that as an administrator, more likely than not, they know how to write raw html.

# Answer
> 0 votes
Here's another method of forcing CKEditor not to strip out empty `<i>` without adding a new text format (or exposing your site to insecure code):

1. Edit your CKEditor profile. *(For me, it was `admin/config/content/ckeditor/edit/Advanced`.)*
2. Scroll down to the bottom and expand the "Advanced options" fieldset.
3. In the "Custom JavaScript configuration" field, add the following: `config.allowedContent = true;
CKEDITOR.dtd.$removeEmpty.i = 0;`

*(These instructions originaled from https://www.drupal.org/node/2385795#comment-9681661 with some minor tweaks.)*

---
Tags: wysiwyg
---


# Question
Title: Link module: Confused about how to use link fields
I got the Link module because I thought it would help me manage links in my pages. But I have the following two problems:

* When I enter links in the "Links" form on the page-editing page (the functionality that appeared after installing the Link module), all this seems to do is put a list of those links at the bottom of the page. It doesn't seem to give me any way to place those links where I need them in the text of the page. Am I missing something?
* I thought that one advantage of using this module was going to be that I could use defined links on different pages, so that when a URL goes bad and I need to update it, all the links to that URL would change automatically. But all I see is the ability to define links separately and independently on any page they need to appear on. Again, am I missing something?

I also installed and enabled CKeditor and File (Field) Paths. From what I read, I thought that at least CKeditor would interact with the Link module to do what I needed. But when I click on the editor's link button after installing the Link module, it still only allows me to manually enter the data for a link.

I thought that managing links data (and other repeated content) from a database would be one of the major advantages of using a system like Drupal. Am I trying to do it the wrong way, or was I mistaken that this can be done?

Thank you.

(Note, I'm not talking about user-entered content here. Although there might be a forum on one of the sites, the vast majority of content will be entered and updated by one or two administrators.)

(And I suppose Views could do what I'm talking about for structured output, like a table, but I'm talking about links that need to appear on arbitrary strings of text anywhere in a page.)

# Answer
> 2 votes
you have mistaken the link module, it doesn't work as you are thinking, it will not place links wherever you want. It is just to add the link with content not within the content body.

CKEditor will provide you with the options to format the content including links, but there is no interaction between CKEditor and Link module.

If you want to set custom URL's, you need to use Pathauto module.

---
Tags: navigation
---


# Question
Title: How to redirect user after form submit in overlay mode?
The following code redirects user to `node/add/article` but doesn't use overlay.

`$form_state['redirect'] = 'node/add/article'`

How do I open `node/add/article` in overlay mode?

# Answer
You could try this,

```
global $base_url;
$custom_url =  (urldecode(url($base_url, array('query' => array('destination' => '#overlay=node/add/article')))));
$form_state['redirect'] = $custom_url;

```
> 0 votes

# Answer
This seems to be the working solution:

Inside your form:

```
$form['somebutton']['#submit'] = array('your_custom_callback');

```

Add a custom callback

```
function your_custom_callback($form, &$form_state) {
  //redirect users to Drupal.org
  $url = "http://drupal.org";

  if (module_exists('overlay') && overlay_get_mode() == 'child') {
    unset($_GET['destination']);
    overlay_close_dialog($url, array('external' => TRUE));
    $form_state['redirect'] = FALSE;
  } else {
    $form_state['redirect'] = $url;
  }
}

```
> 1 votes

# Answer
Code above didn't quite work for me - I had to include *$form\_state\['rebuild'\] = TRUE;* within the overlay clause in the custom callback. The code below works for me:-

```
// the URL of the view I want to redirect to...
$redirect_to = 'manager/dashboard';

if(!empty($redirect_to)) {
    if (module_exists('overlay') && overlay_get_mode()=='child') {
        $form_state['rebuild'] = TRUE;
        unset($_GET['destination']);
        overlay_close_dialog($redirect_to);
        $form_state['redirect'] = FALSE;
    }
    else {
        $form_state['redirect'] = $redirect_to;
    }
}

```
> 0 votes

---
Tags: 7, forms, modal-dialogs
---


# Question
Title: Show node only to node author and author that is referenced by node
Is there a way to allow only a node author as well as an author referenced by a node reference field to view the node and comments.

Example:

A listing content type. (for posting want ads) An Offer content type. (for making an offer for referenced listing ad)

Listing has: Title, pics, description, location, etc... as fields' Offer has: Title, Listing Node Reference, Message, Offered price, etc... as fields

I want to hide the offer nodes (in any view mode) from everyone but admins, the offer node author and the listing node author.

Basically, creating a simple private messaging system. with nodes as messages and comments as replies to the message that only those two accounts can see as well as admins.

Any suggestions on the best way to implement this? Thank you.

# Answer
> 1 votes
You could use Node Access User Reference for this task:

> Gives content access permissions to users for content that references the users with User reference or Entity reference.
>
> This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

Or you could use OG groups for something like this as well: https://www.drupal.org/project/og It may be a little harder to setup at first but certainly more a more flexible option.

---
Tags: 7, users
---


# Question
Title: How to resolve 'Unknown data property commerce_product' when adding a product in Drupal Commerce?
I'm wondering if someone can help: I'm trying to add Drupal Commerce into an existing Drupal site, so I've followed the steps in this video about this topic and managed to install all modules without problems.

The issue I'm having is when I view a product I've added. Please note that I've added the product type. I can also add the node, but every time I try to view it I get this error (in the reports/error):

> EntityMetadataWrapperException: Unknown data property commerce\_product. in EntityStructureWrapper-\>getPropertyInfo() (line 336 of /my/local/server/php/mysite/sites/all/modules/entity/includes/entity.wrapper.inc).

I did follow all the steps in the tutorial. When I tried to view the product like in the video I get the error.

Any ideas?

# Answer
Looks like an answer to "this" question might be similar to what I suggested in How to add Drupal Commerce to an existing Drupal site?, which originally was rather a request for manuals/docu about this topic. It has a comment (from the OPer) like this (bold markup added here now):

> ... After your post I've **uninstalled** all modules and **installed again** and **still had the errors**, however this time when I **run Commerce Repair** the fields were fixed **and everything worked**.

With that it appears to me that "this" question "has an answer" now also.

Ps: The "Commerce Repair" module is "looking for a new maintainer", and used in over 1.000 sites. To me it appears as the best possible alternative to consider, which is not the same as "the module is no longer maintained" I believe (as I read in a comment to the question here).
> 1 votes

---
Tags: 7, commerce
---


title: VBO mass email via local email client

text:
# Question
Title: VBO mass email via local email client
I have a drupal 7 view diplaying nodes containing an email address field. I would like the user to be able to select multiple rows and then execute an action that simply open his own email client with a new message with all the email addresses in the To: field. I don't want to let users send mass emails via my website but give them an easy way to send emails to many addresses at thew same time via their local email client.

# Answer
> 0 votes
try integrating the Views Send Module, the instructions specifically mention VBO:

> Views Send enables you to send mass mailing from a View.

Since you aren't able to install new modules, it could be done this way:

* Create the view as a table of fields, include the email address as EMAIL PLAIN TEXT
* add the VBO field, Save Content (you can choose anything you want, but this seems the least offensive)
* add some css:

```
#views-form-email-test-page #edit-select {   display:none; }

```

This will hide the VBO button since we are overriding its functionality manually
* add a header, Global Text:

```
<button type="button" onclick="emailUsers(); return false;">email users</button>

```
* add a modified version (modified for view and field names) of this JS to your html.tpl.php, or drupal\_add\_js, or by whatever other means you want:

```
function emailUsers()
{
    var toField = '';

    jQuery('#views-form-email-test-page table tbody tr').each(function()
    {
        if(jQuery('.views-field-views-bulk-operations div input', this).is(':checked'))
        {
            toField += jQuery('.views-field-field-address', this).html() + ',';
        }
    });

    if(toField.length > 0) window.location.href = "mailto:" + toField;
    else alert('Please select at least one user to email!');
}

```

This all assumes:

* the View machine name is name `email_test`
* the View is a page
* the field holding the email address is `field_address`

EDIT FROM OP:

> Thank you very much Geoff, your solution works very well, I've learned a few things and I hope it will be usefull for others in the futures, indeed I was quite surprised not to find anything when I searched befor posting. Since my email field was also a link I've used the following code
>
> tmp = jQuery('.views-field-field-applicant-email', this).html(); tmp2 = jQuery(tmp.replace('mailto:','')); toField += jQuery(tmp2).attr('href') + ',';
>
> instead of
>
> toField += jQuery('.views-field-field-address', this).html() + ',';
>
> not very elegant may be (I'm not a programmer) but it works! for some strange reasons I cannot upvote your answer, sorry.

---
Tags: emails, views
---


# Question
Title: Update script fails due to Service capacity
I am trying to update the core of my Drupal site. I neglected updates for some time and the update script had 19 updates pending. Apperently the update script tries to do all of this in one go, and fails miserably. I get an error message like this:

> ```
> StatusText: Service Unavailable ResponseText: 503 Service Unavailable Service
> Unavailable The server is temporarily unable to service your request due to maintenance
> downtime or capacity problems. Please try again later.
>
> ```

and this one:

> An AJAX HTTP error occurred. HTTP Result Code: 503 Debugging information follows. Path: h t t p ://mysite.com/update.php?op=selection&token=7R0M7yvUZR09UsRDFf9FUAYhV9Ui82efUzsZPh61JZU&id=152&op=do StatusText: Service Unavailable ResponseText: 503 Service Unavailable Service Unavailable The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.

I have the following questions:

* Has anyone seen this one before? If so how do I solve it?
* If not, can I run the other 18 pending updates somehow?
* If not, how harmfull is it if I don't run `update.php`?

# Answer
Attempt to answer your questions ...

> Has anyone seen this one before? If so how do I solve it?

I've never seen this error before. But what I don't see anywhere in your question is that you FIRST disabled all modules, prior to upgrading Drupal core. And that is problably where your error originates from.

So if you have not done that, try doing so now as a first step. Note each of the modules you're disabling, so that afterwards you know which one to re-enable again. Note "all" is more then just the 18 modules you mentioned that needed updating (so also those modules which do not require any update).

After all these modules are disabled, try to upgrade Drupal Core. I'd expect that upgrading core then should work just fine.

> If not, can I run the other 18 pending updates somehow?

I would NOT try to do that. Instead first make sure core is upgraded, as explained in my prior item.

After core upgrade completed fine, re-enable all modules again that you disabled to complete the core upgrade. From then on the 18 pending updates should appear also again (of course). Then perform the update of each of those 18 modules, one by one.

> If not, how harmfull is it if I don't run update.php?

NOT running update.php is not something I would consider. In other words: if your Drupal installation shows messages that updates are pending, you better apply them ASAP.

Does this help somehow?

PS: worst case (if everything else goes wrong): restore from your last backup (you have that, right???). Then apply the steps I described above. I'd assume you would not run into similar errors anymore.
> 0 votes

---
Tags: updating
---


# Question
Title: How to display event's views block inside another content type's content section with only events related to that content alone?
I am working on a drupal7 site. The scenario is that, there are 2 content types namely singers and events. When i am adding an event, i need to add an event to a singer, so that when i am viewing a singer's node page, i can see block containing events related to that singer alone.

I have done the events block inside the singer's content page(Using the views block). But it displays all the events and i want to display the only the events related to that singer alone. I have tried to make it using term reference or some other stuff. But nothing have worked out. Can anyone help me out to get this scenario working. Thanks in advance.

# Answer
> 0 votes
You can use theentity reference and rules modules for this.

First, add entity ref fields to both singers and events. Then, create a rule so that, when an event is created, which refers to a singer, the singer gets updated with a reference back to the event.

Your singer nodes should therefore have references to all the events that refer to that singer. In the display settings for the singer nodes, you can render the referenced nodes as, say teasers.

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


# Question
Title: Populate drop down fields according to other fields in Drupal 7
Let's say I have a content type car with content fields brand and model. Now I want to populate the field model according to the value of brand that the user will select. So for example if have:

* BMW
    + series 1
    + series 3
* mercedes
    + a class
    + b class

So if a user chooses BMW as a brand the model field should be populated with series 1 and series 3.

# Answer
May be hierarchical select is what you are looking for.

Use one taxonomy field with hierarchy to store brands and models. hierarchical\_select module will create nice widget for choosing them.
> 1 votes

# Answer
This can be achieved by following this tutorial. It works also in webform 4.x, http://www.ishwor.info/dynamic-dependent-drop-down-list-drupal-7-webform-3x
> 0 votes

# Answer
I used recently https://www.drupal.org/project/reference\_option\_limit , is good, easy and nice but can be a pain in the ass if you try to change forms from code later on.
> 0 votes

---
Tags: entities
---


# Question
Title: hook_form_alter() only firing after cache clear
I have a custom module that I'm using to add a Java applet to some of my admin forms. The applet is necessary to get details about the product being entered.

I'm noticing that after 15 minutes (or more) of site inactivity, my hook stops firing. If I clear the cache, the hook begins firing once again. However, this only seems to last 15 minutes or so.

Is it possible there is some admin form caching happening?

*Possibly salient details:*

* I'm using Seven as the admin theme
* I'm using D7 with Commerce Kickstart install profile (commerce\_kickstart-7.x-1.8)

# Answer
I think your problem stands in **cascading caching logic** : your form must be called by something (a block, a template, a function...) that must be itself cached.

What you have to think about is **"When, and by who, is my cache warmed up, with which conditions ?"** : the most logical answer is that when your cache is created for the first time, conditions in your `hook_form_alter`are not TRUE.

For example, are you searching, in your alter, for infos coming from the session, or user roles, or static variables...

We could do more with your code :)
> 2 votes

# Answer
I was facing the same problem. hook\_form\_alter() was not being called without clearing cache and thus the form incomplete. It was a form at admin panel (module config form).

Then I used the format hook\_form\_FORM\_ID\_alter() and the problem solved.
> 1 votes

# Answer
**I'm noticing that after 15 minutes (or more) of site inactivity, my hook stops firing**: If your `javascript` code does not work, as per my understanding that this is issue related to your `javascript`.

When the system is idle for few minute, `javascript` stopped working and generate the error. I was working in a project, I found the same issue and so I need to refresh browser to make it working after few minute if system is idle.

You can add some debug in your `hook_form_alter` and check that its working or not if system is idle for few minute.
> 0 votes

# Answer
move your hook\_form\_alter() in theme template.php , works each time
> 0 votes

---
Tags: 7, forms, commerce
---


title: Between Query is not working

text:
# Question
Title: Between Query is not working
My query is like so:

```
$result = db_query("SELECT nid as id,created as start,title
          FROM node WHERE (created BETWEEN '1430134906' AND '1430129127')");

 foreach ($result as $record) {
  print_r($record);exit;
 }

```

But it's not working in Drupal 7 running on MS SQL and using the Drupal 7 driver for SQL Server and SQL Azure module. Here's an excerpt of that module's project page:

> Drupal 7 driver for Microsoft SQL Server database engines. It supports both SQL Server (version 2008 and later), and SQL Azure, part of Microsoft Azure cloud platform.

# Answer
> 0 votes
This might be a situation where Drupal's `db_select()` wrapper might be more useful. I've definitely found it readable, if all you're trying to get is an array of nids.

```
$query = db_select('node', 'n')
                ->fields('nid')
                ->condition('created', array('1430134906', '1430129127'), 'BETWEEN');

$nids = $query->execute()->fetchCol();

```

This is based on the assumption that db\_select() properly wraps MSSQL, which I haven't looked into.

---
Tags: database
---


title: PHP code in contextual filter (Views)

text:
# Question
Title: PHP code in contextual filter (Views)
I would like to get a value from the reference node of the node\_id I used this code for PHP code in Contextual filter...

```
$node = menu_get_object();
if ($node->type == 'trailer_videos'){
       $mynode = node_load($node->nid)->field_trailer_video_of[und][0][target_id];
return $mynode;
}

```

The result is CORRECT!! but the page itself throw 2 errors:

* Notice: Use of undefined constant und - assumed 'und' in eval()
* Notice: Use of undefined constant target\_id - assumed 'target\_id' in eval()

Whats wrong with my code above????

# Answer
> 1 votes
Why don't you use entity metadata wrapper? your code will be:

```
$node = menu_get_object();
    if ($node->type == 'trailer_videos'){
           $wrapper = entity_matadata_wrapper('node',$node);
           $mynode = $wrapper->field_trailer_video_of->value();
           return $my_node;
     }

```

If you don't want to use entity module, use `kpr` of devel module to get the right syntax, as Ollie said quotes are needed.

---
Tags: views
---


title: Flexslider broken links

text:
# Question
Title: Flexslider broken links
I have a very weird problem with flexslider.

Everything was working ok, but suddenly flexslider stopped to show the images im adding.

My observations are:

* Flexslider rewrites urls to the path, where there is NO images
* there is a access denied warning in drupal logs but my permissions are set to 775/755

Whole flexslider mechanism is working correct, its cycling and stuff, but there is no content inside.

I will appreciate any help, and thanks a lot in advance.

# Answer
This feels like an issue with your files directory permissions. Specifically, the permissions on the directory that contains the image style derivatives for the flexslider. My guess is that they are not being created properly.
> 0 votes

---
Tags: navigation, javascript
---


# Question
Title: Sticky at top of lists node at certain time
I would like to sticky node at certain time and update time of publishing. I tried with module Scheduler but it unpublishes content I need published content it is more like republishing and put that content at the top.

I tried some with Rules module but no success. Is it possible to that somehow?

# Answer
Looks like Rules Scheduler (part of the Rules module) is what you're looking for. "Publish content exactly 24 hours after it was created" contains step by step instructions about how to do so (using the Rules Scheduler).

Here are some video tutorials about a few variations of your question (some are pretty close to your question), which are all resolved with Rules Scheduler:

Ps: There is also the tag, specific to the Rules Scheduler.
> 1 votes

---
Tags: nodes, cron
---


# Question
Title: Is it possible to append Media's file browser to a certain node type?
I have a certain node type with a canvas on it, allowing users to draw on the node. Basic functionality such as lines are working, but I'd like to allow people to upload images to it as well. Since the rest of the site is using the Media module (V2 dev), allowing users to browse the library and their personal uploads... I was hoping to be able to use it here as well.

The same question was posted as a support request in Media issue queue as well but so far there is no reponse: https://www.drupal.org/node/2423415

What I am looking for is a way to embed the media browser on the node and catch the path of the returned file so the JavaScript and the canvas can read it.

So far I've managed to add the media widget to the node with:

```
function mymodule_node_view($node, $view_mode, $langcode) {
  if($node->type == 'mytype') {
    $form = drupal_get_form('mymodule_media_form');

    // append a new field to the content
    $node->content['imageupload'] = array(
      '#markup' => drupal_render($form), // and render the form there
      '#weight' => 10,
    );
  }
}

function mymodule_media_form($form, &$form_state) {
  $form['file'] = array(
    '#type' => 'media-widget',
    '#title' => t('Image'),
    '#description' => t('Upload a file'),
  );
  return $form;
}

```

It shows the Media file upload button, but the dialog does not popup (due to missing JavaScripts I suppose). Is there a better way to load this field with all required JS etc? I do suppose I need to at least use hook\_form() assuming I can't display a form field outside form context.

# Answer
> 0 votes
It appeared I had been using the wrong form element. My custom form was created as below:

```
function mymodule_file_upload_form($form, &$form_state) {
  $form['file'] = array(
    '#type' => 'media',
    '#title' => t('Choose an image'),
    '#description' => t('Choose an image'),
    '#tree' => TRUE,
    '#input' => TRUE,
    '#media_options' => array(
      'global' => array(
        'file_extensions' => 'gif jpg jpeg png',
        'file_directory' => 'conferences',
        'types' => array(
          'image',
        ),
        'schemes' => array(
          'private' => 'private',
        ),
        'enabledPlugins' => array(
          'upload',
          'media_default--media_browser_my_files',
        ),
      ),
    ),
  );

  return $form;
}

```

And then with some javascript I manged to get the fid of the file

```
$("form").on("change", "input.upload", function() {
  var val = $(this).val();
  $.ajax({
    url: Drupal.settings.basePath + 'draw/file/' + val,
    success: function(data) {
      src = data
    }
  });
});

```

That path was registered in hook\_menu() to return the path of the private file as per:

```
function mymodule_menu() {
  $items['draw/file/%file'] = array(
    'page callback' => 'mymodule_page_file',
    'page arguments' => array(2),
    'access arguments' => 'view own private files',
  );
  return $items;
}

function mymodule_page_file($file) {
  global $user;
  if($user->uid == $file->uid) {
    echo file_create_url($file->uri); // Use echo to prevent theme to appear.
  }
}

```

---
Tags: 7, forms, javascript, media, files
---


# Question
Title: Prepare Drupal to be multilingual in the future
I am building a Drupal website with only one language (Italian first) but there might be more languages in the future. This website will use also DrupalGap to create an app. Editors don't need backend Italian interface.

So these are the scenarios I thought about:

**Case one:**

* Install Drupal with English as default.
* I will NOT enable Locale module.
* All machine names (Content types, vocabularies, views etc..) will be in English.
* Labels will in Italian.
* Content and term will be created in Italian.
* Views page title and views block title will be in Italian.

After few months the website may be translated in English so, the steps will be:

* Enable locale.
* Install Italian language.
* Install Entity translation i18n etc...
* Make entities translatable.
* Bulk update all nodes and terms to be Italian as original language.
* Revert all Italian labels into English and use string translation to translate it in Italian.

**Case two:**

* Install Drupal with Italian as default
* All machine names (Content types, vocabularies, views etc..) will be in English.
* Labels will in Italian.
* Content and term will be created in Italian.
* Views page title and views block title will be in Italian.

After few months the website may be translated in English so, the steps will be:

* Install Entity translation i18n etc...
* Make entities translatable.
* Bulk update all nodes and terms to be Italian as original language.
* Translate strings from Italian to English.

In terms of extendability and usability, which approach should I use at the beginning?

Let me know if you have any question.

Thanks in advance.

# Answer
I think the best approach is something similar to your first one.

* Install Drupal in English as defaults
* Configure your environment for multilingual at the beginning.
* Enable Italian Language
* Set Italian to default language
* When you create entities(Users, Content types, Etc..), configure everything at the beginning. Otherwise you might forget things later.
* Enable multilingual support only for other pages excepting admin pages @ admin/config/regional/i18n/select (Under "ENABLE FOR SPECIFIC PAGES" set all pages except "admin/\*")
* Then do everything in Italian for Italian until you need English language stuffs.

Good luck.
> 0 votes

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


# Question
Title: Error when uploading file through Drush on S3 volume
I am using Amazon S3 volume to store the node's attachment. I keep having the following message:

```
file_put_contents(public:///.htaccess): failed to open stream: "DrupalPublicStreamWrapper::stream_open" call failed file.inc:494                                                                                [warning]
WD security: Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your public:// directory which contains the following lines: # Turn off all options we don't need.                                 [error]
Options None
Options +FollowSymLinks.....

```

I tried chmod 777 on private (sites/default/files/private) public (sites/default/files) folders without any success.

Is it because amazon S3 and AWS/SDK are installed. It works weel anyway : my files are created on S3 volumes. But the message is annoying.

Any ideas ?

Thanks

# Answer
It's all there really, it's a security warning and you can fix it by creating a .htaccess file at the root of sites/default/files. The actual content should be:

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

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

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

```

Additionally, the .htaccess of the temporary files directory and private files directory (if used) should include this command:

```
Deny from all

```

Read more in this security advisory.
> 0 votes

---
Tags: files, drush
---


# Question
Title: Ajax Callback Function in Submit Button Doesnt Work
I have a submit button in my form and I want to implement it using ajax:

```
function myid_user_page_form(){

   drupal_add_library('system', 'drupal.ajax');

   $form = array();

   $form['id'] = array(
       '#type' => 'fieldset',
       '#title' => t('ID Information'),
       '#prefix' => '<div id="myid_search_id_number_wrapper">',
       '#suffix' => '</div>'
   );

   $form['submit'] = array(
      '#type' => 'button',
      '#value' => 'Save',
      '#ajax' => array(
         'event' => 'click',
         'callback' => 'myid_user_page_form_ajax_submit',
         'wrapper' => 'myid_search_id_number_wrapper'
      ),
      '#attributes' => array(
        'id' => 'myid_save',
    ),
);

function myid_user_page_form_ajax_submit($form, &$form_state) {
    watchdog('Wow','Wow');
}

```

After executing the code above, the page still has it's `refresh after it's click`functionality. The ajax doesnt work and no `Wow` message log in my watchdog table from my database, which means the ajax callback function isn't called. Where am I missing?

# Answer
> 2 votes
It is because you are changing the id attribute of the button.
The ajax in Drupal automatically attaches the javascript event listener to the submit, but it expects the button the have the automatically generated id.
Adding or changing the class attribute should not affect it though.

All the suggestions TerryCB made in the comments are also valid.

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


# Question
Title: What is rss category format in manage dislay?
Anybody please explain what is the rss-category format, in the manage display settings of term referense field.

When I check this format, nothing is displayed on the node page.

Thanks.

# Answer
This display setting hides taxonomy links on the node page and adds `category` elements into Drupal's RSS feed (http://example.com/rss.xml). Go to your site's RSS feed and you can see it in action.
> 0 votes

---
Tags: feeds
---


# Question
Title: Using PHP 5.2.17 in Acquia Dev Desktop 2
I'm using Acquia Dev Desktop 2 with Drupal 7. On PHP version selection menu, I only see "5.3.29", "5.4.33", "5.5.17".

Is it possible to switch PHP version to PHP 5.2.17 since most of my hosting provider based on PHP 5.2.17.

Or would you recommend anything other than Acquia Dev Desktop 2?

Thank you.

# Answer
They dropped PHP 5.2 support with DevDesktop 2. It has hit EOL so you really shouldn't be developing against it.

That said, if you really want to do this, you can find old versions of DevDesktop that used PHP 5.2. I would guess you might hit problems if your end goal is to deploy to AcquiaCloud.
> 3 votes

---
Tags: acquia-dev-desktop
---


# Question
Title: How to embed plugin configuration form elements into another form?
I have a form that lists entities and each of the entities has a checkbox. The form also contains a list of actions(Action plugin) that can be performed on selected entities as a select list.

I would like to be able to configure actions that extend the \Drupal\Core\Action\ConfigurableActionBase class, which means they are configurable, right in my form since some actions can have very different settings and creating action entity for each variation of those setting is just impossible. I would create a new action entity from those settings, without saving it, and use it to perform the action(although I could do it just with the plugin, but that's not important right now).

I am able to retrieve the form elements for those configurable actions and display them in my form. The issue I have is that incorporating those elements into form is tricky on its own, but validating and submitting them is on another level since I cannot just encapsulate those form elements under some specific form array/key because the validation and submit handler for those plugins will not work with that.

The \Drupal\Core\Plugin\PluginFormInterface::buildConfigurationForm() is not a proper D8 form but it just holds the form elements so it's not like I am trying to embed a form within another form, but it is stillquite impossible as I am seeing it right now.

So how can I do this? Or can you recommend a different approach?

This is the initial design: http://pastebin.com/b8SCFvUQ

# Answer
> 1 votes
I have solved this by making sure my forn had a unique element names to avoid collision with the Action's configuration. I have added a 'x\_' prefix to names of all my elements. Since my form did not use #tree globally I have put the Action's configuration under a 'configruation' key and in form validation and submit callbacks I have provided this array as $form\['configuration'\] to the validation and submit handlers of the Action plugin instead of the whole $form array. So far it works withotu any issues.

---
Tags: forms, 8, actions, plugins
---


# Question
Title: How to set up menu with links to pages in different languages on multilingual sites?
I have a multilingual site determining the language from the URL Path (www.sample.com/lang/page). I need a menu to have a mix of links to pages in both English and French. 99% of these are node pages, one or two are taxonomies. We do not have any translated content only localized. It doesn't seem to make a difference what Translation mode my menu is in (I've tried all three) the system always adds "fr/" in-front of every URL when I put the menu on french pages, even if that node id doesn't exist in french. I'm sure there must be a way to do this, but I can't figure out how... Here's a sample of what i am looking for in one menu:

* About Us - www.sample.com/about-us (not translating to french, but want to link to it from french pages)
* Contactez-nous - www.sample.com/fr/contactez-nous ( node in french, not a translation of another page)
* US Locations- www.sample.com/locations (not translating to french, but want to link to it from french pages)

I'm sure this must be possible, but I have no idea how to get there.

# Answer
How about using "language neutral", or "Indépendant de langue" in French? That's an option you should have on the node "edit" form ("modifier" in French) for each of those 3 pages. And then combine this with creating a (single) menu link, in the appropriate menu of course.

That should make such link show up for both languages. That's how I always implement such pages, typically for pages similar to the ones you mentioned. Or sometimes in cases where some translation is still missing, and at least such page should be shown already in another language for which its content is available already.

FYI: I'm also using "determine language from the URL path").
> 1 votes

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


# Question
Title: How to delete a node with same specific field content and by same user when a more recent one is created in drupal 7?
I have created a review system allowing users to make a review of a place. One of the fields for each review is the actual location which needs to be filled. If a user decides to create a review of **'the Red Lion'** and it happens that she has already written one on that place, I want the old review to be deleted, and only the latest one kept.

I have tried to use Rules with the 'fetch entity by property' and a double loop, but it does not seem to do the trick. Here is the export of a test rule where I just flag the 'former review'. The current result is that it flags all reviews of the **'Red Lion'** made prior to the current one being saved. Any suggestions?

```
{ "rules_delete_old_reviews" : {
"LABEL" : "Delete old reviews",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "flag" ],
"ON" : { "node_presave--review" : { "bundle" : "review" } },
"DO" : [
  { "entity_query" : {
      "USING" : {
        "type" : "node",
        "property" : "author",
        "value" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched_author" : "Fetched node by author" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "entity-fetched-author" ] },
      "ITEM" : { "list_item_nodeauthor" : "Current list item" },
      "DO" : [
        { "entity_query" : {
            "USING" : {
              "type" : "node",
              "property" : "field_revlocation",
              "value" : [ "node:field-revlocation" ]
            },
            "PROVIDE" : { "entity_fetched" : { "old_review_item" : "old_review" } }
          }
        },
        { "LOOP" : {
            "USING" : { "list" : [ "old-review-item" ] },
            "ITEM" : { "list_item" : "Current list item" },
            "DO" : [
              { "drupal_message" : { "message" : "This node \u0022[list-item:title]\u0022 is now flagged." } },
              { "flag_flagnode" : {
                  "flag" : "tagged_review",
                  "node" : [ "old-review-item:0" ],
                  "flagging_user" : [ "site:current-user" ],
                  "permission_check" : "1"
                }
              }
            ]
          }
        }
      ]
    }
  }
]
  }
}

```

# Answer
> 0 votes
Here is how I achieved it in the end:

First, create a component rule 'Listreviews'. This component rule will filter nodes created by the current user and then

1. Component plug-in is set to 'rule'.
2. The variable is of type 'node' of type 'parameter'. Give it a machine name 'nodefromlist' and save.
3. Add a condition: data comparison. This comparison will be have the data selector nodefromlist:author:uid, and it needs to equal site:current-user:uid.
4. Add an action: 'delete entity', which will have the data selector value of 'nodefromlist'.
5. Save!

Then, create a rule 'Delete duplicate review'.

6. the event chosen is 'before saving content type review'
7. no conditions
8. Actions: 'fetch entity by property'
* entity type 'node'
    * property: the field 'location' (in my example)
    * data selector: go down the arborescence up to: node:field-location
    * I put a limit of 10, but may need to be adjusted based on previous content available.
    * Add a label to the provided variables section
    * Add a variable name like: item\_same\_location

Then

9. Create a loop below the action above with the parameter item\_same\_location

* call the current list item: list\_item.
10. In that loop, create an action 'component' with the name of the rule component created above.

* the data selector will be: list\_item.
11. Save your rule!

This should now work. As a bonus, I added a 'display message' action in the component rule in order to let the user know that their previous review was deleted. I hope this helps someone in the future!

---
Tags: 7, nodes, rules
---


# Question
Title: How set div in a specific position inside .tpl.php file
I use views module in my website (built in drupal-7). I have a custom theme. I have set a views-view-fields--**XX**.tpl.php like follows.

```
    <?php /**`
 * Default simple view template to all the fields as a row.
 *
 * - $view: The view in use.
 * - $fields: an array of $field objects. Each one contains:
 *   - $field->content: The output of the field.
 *   - $field->raw: The raw data for the field, if it exists. This is NOT output safe.
 *   - $field->class: The safe class id to use.
 *   - $field->handler: The Views field handler object controlling this field. Do not use
 *     var_export to dump this object, as it can't handle the recursion.
 *   - $field->inline: Whether or not the field should be inline.
 *   - $field->inline_html: either div or span based on the above flag.
 *   - $field->wrapper_prefix: A complete wrapper containing the inline_html to use.
 *   - $field->wrapper_suffix: The closing tag for the wrapper.
 *   - $field->separator: an optional separator that may appear before a field.
 *   - $field->label: The wrap label text to use.
 *   - $field->label_html: The full HTML of the label to use including
 *     configured element type.
 * - $row: The raw result object from the query, with all data it fetched.
 *
 * @ingroup views_templates
 */
?>

<?php foreach ($fields as $id => $field): ?>

<?php if ($id == 'field_voti'):?>
<div class="uniscicampischeda">
<?php endif; ?>
    <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
    <?php endif; ?>
    <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php print $field->content; ?>
    <?php print $field->wrapper_suffix; ?>
    <?php if ($id == 'distance'): ?>
</div>
<?php endif; ?>
<?php endforeach; ?>`
"

```

**in order to** insert some fields into a **new div** with **a specific class**.

With firebug I see the following:

```
<td class="col-1 col-first vistacomplessiva">
    <div class="views-field views-field-title nomeattivita">..</div>
    <span class="views-field views-field-name">..</span>
    <span class="views-field views-field-last-updated">..</span>
    <div class="views-field views-field-field-foto">..</div>
    <div class="views-field views-field-body descrizione">..</div>
    <div class="uniscicampischeda">..</div>
</td>

```

All that I want to do now is to have the div with class="uniscicampischeda" before the div with class="views-field views-field-field-foto", so that with css I will give the right attributes (I want class "uniscicampischeda" with float=right attribute) HOw can I do that? do I have to write some code into views-view-fields--**XX**.tpl.php file? How? Can anybody help me? Thanks.

# Answer
> 1 votes
Well, there are three solutions for your problem,

1. Forget about the div with class `uniscicampischeda` and try to work with the existing classes in order to align them to right.
2. If you want to insert the `div.uniscicampischeda`, try to find out which one of the PHP lines generates the `<div class="views-field views-field-field-foto">..</div>`, then edit the .tpl file and put the DIV before that PHP line.
3. As the last solution and also the most complicated one, in your `template.php` create function `hook_preprocess_views_view_fields(&$var)`, in this function get the Views fields value and insert them in to the `$var` array, then in the .tpl file use those keys of the `$var` array as the variable that generates the corresponding value. Using this solution you will have much more freedom to theme your view output.

If you need help about any of these solutions just let me on it.

# Answer
> 0 votes
I think what you want to do is make a separate views-view-field--FIELDNAME.tpl.php to theme your individual field with that div class. Then in the template you have for the fields, you can iterate through the fields. Is there any reason not to re-order your fields in the view itself?

# Answer
> 0 votes
You can do it easily from back end. There is no need to add it in the .tpl files

Just add a new field in view and filter from above dropdown. Now choose 'Global Custom text' mentioned in the image. Now put your divs in the mentioned textarea.

Hope it will help!

# Answer
> -1 votes
try edit your views-view-field--XX.tpl.php not FIELDS, also double check your iteration end starting and closing tags for the div.

Also take note that firebug will auTO-CLOSE an unclosed HTML tag so check the :view-source in order to be sure whats rendered in HTML...

---
Tags: 7, views, theming
---


title: Static Html elements on different pages

text:
# Question
Title: Static Html elements on different pages
So, I have a frontpage where I simply have a big image and a button that leads to a second page. On that page I want this:

Which are two `sections`. However, when I'm on the `contact page` I don't want the `section Questions?`

I want to write this in `Html` as I don't see how I would create these sections in `Drupal`. So my question is how can I make sure it's not visible on the `contact page` ?

# Answer
There are lots of ways you could do it - blocks, panels, template overrides. The easiest way for you would probably to create a custom block and put the html in that. Then you'd be able to set the block visibility to exclude the `/contact` page.
> 1 votes

---
Tags: theming
---


# Question
Title: Webform select option list from another submission data
I have a webform (webform 1) to record data. In another webform (webform 2) I would like to use the submitted data from webform 1 in select options (Load a pre-built option list). How can I do this? Is there any module that already available to do this?

# Answer
You could try the sandbox project Webform Views Select.
> 1 votes

# Answer
The Webform Autocomplete can do something *similar* to your requirement: it can allow users to autocomplete answers that were already given for that field on the webform. So if one user types "Manhattan" into a field and submits the form, the next person who uses that webform can start typing "ma", and "Manhattan" (and all other previous answers starting with "ma") will be selectable.
> 0 votes

---
Tags: webforms
---


# Question
Title: Creating a form thats gives user chance to filter nodes
Im quet new to Drupal and i dont know how to search for the module i need.

So the idea is... I made a content type with the following fields: Name, Description, Country, Category. The Country field is a list item and the Category is a checkbox item.

So the idea is that the users can submit they nodes. I undestand that part.

The problem is i want to display the nodes based on the Category and Country items.

When the user comes to the home page, they should first see a form in witch they chose the Category and Country, so the nodes get displayed based on that pick.

It should be a filter sistem where they can pick one country, and multiple categorys to display the Name and Description fields.

Can anyone give me a idea how to make that form?

# Answer
In Views:

* create a new view, page or block limited to that content type, as the display format you want (table, teaser, etc)
* create a filter field, choose the Country
* click on 'Expose this filter to visitors, to allow them to change it'
* Filter: operator - is equal to (you can expose this operator if desired, allowing the user to choose is equal to, is not equal to, contains, etc)
* if you want the View empty to start, click on 'required' in the filter field set up
* create a new filter field for Category and repeat the same steps

You will want to play around with the settings to get it exactly how you want, but this should get you going in the right direction.
> 1 votes

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


title: Node Type in Views Template

text:
# Question
Title: Node Type in Views Template
I made a custom template for my view to print fields into a custom html syntax. The problem I have is that in the view I am calling all content types. Now, in my template file I want to display certain information depending on what content type the content is coming from.

For instance, I want something like this:

```
If (node->type['animals']{
    print 'this is the animal node';
}
else{
    print 'this is not the animal node';
}

```

My fields inside the view are printed as follows, but this works:

```
<?php print $fields['title']->content; ?>

```

The only problem I am having is calling the node type.

I tried adding content type to my views in drupal, then tried it that way:

```
<?php if ($fields['type']->content = 'animals'){} ?>

```

but the view looks through the document and see that there is a content type with that name, and prints the data anyway.

# Answer
I believe you are using the wrong template in order to access the relevant information. As your comment states your view template is for the entire View, and as you say it looks through the entire document and will always find the content type if any content of that type is present.

Since you are trying to affect a single field, you should look at other template suggestions for fields only in order to process the fields individually instead of trying to do it at the whole View stage.
> 0 votes

---
Tags: views, theming
---


# Question
Title: Get value for drupal date pager next or prev or current
I am looking around a way to get the date pager next/prev/current value inside the current view.I am listing events in a month and have used date pager.Display is of month type so in header it shows the month value.and in the next and prev it shows the next month. I need to know the value for the pager navigation. Thanks in advance. Arpit

# Answer
I found a work around, keeping in mind that the pager works for calendar view by changing date in the URL.

I created a custom form with fields as day, month, year whose field type is select (dropdown).

This is the code for the form and the submission handler.

```
function mymodule_get_event_view_date_filter($form, &$form_state) {
  $form = array();
  $year = date('Y');
  $year_options = array(
    $year - 4 => t($year - 4),
    $year - 3 => t($year - 3),
    $year - 2 => t($year - 2),
    $year - 1 => t($year - 1),
    $year => t($year),
    $year + 1 => t($year + 1),
    $year + 2 => t($year + 2),
    $year + 3 => t($year + 3),
    $year + 4 => t($year + 4),
  );
  $month = date('m');
  $month_options = array(
    '1' => 'Jan',
    '2' => 'Feb',
    '3' => 'March',
    '4' => 'April',
    '5' => 'May',
    '6' => 'June',
    '7' => 'July',
    '8' => 'Aug',
    '9' => 'Sep',
    '10' => 'Oct',
    '11' => 'Nov',
    '12' => 'Dec',
  );
  $form['event-date-container'] = array(
    '#type' => 'container',
    '#prefix' => '<div id="event-date-container">',
    '#suffix' => '</div>',
  );
  $form['event-date-container']['year'] = array(
    '#type' => 'select',
    '#options' => $year_options,
    '#prefix' => '<div id="event-year">',
    '#default_value' => isset($_SESSION['event']['year']) ? $_SESSION['event']['year'] : $year,
    '#suffix' => '</div>',
  );
  $form['event-date-container']['month'] = array(
    '#type' => 'select',
    '#options' => $month_options,
    '#prefix' => '<div id="event-month">',
    '#default_value' => isset($_SESSION['event']['month']) ? $_SESSION['event']['month'] : $month,
    '#suffix' => '</div>',
  );
  $form['event-date-container']['submit_form'] = array(
    '#type' => 'submit',
    '#value' => t('Apply'),
    '#submit' => array('_mymodule_event_view_date_submit'),
  );
  unset($_SESSION['event']);
  return $form;
}

function _mymodule_event_view_date_submit($form, $form_state) {
  global $base_url;
  $_SESSION['event']['year'] = $form_state['values']['year'];
  $_SESSION['event']['month'] = $form_state['values']['month'];
  drupal_goto('calendar-node-field-event-date/month/' . $form_state['values']['year'] . '-' . $form_state['values']['month']);
}

```

Now call this form in your calendar view in view header print.

```
drupal_render(drupal_get_form(mymodule_get_event_view_date_filter));

```
> 2 votes

# Answer
I tried the above solution and could not get it working. After investigating, I managed to get it working by putting echo in the call in the header php:

```
<?php echo drupal_render(drupal_get_form('mymodule_get_event_view_date_filter')); ?>

```

Like this:
> 0 votes

---
Tags: views, paging
---


# Question
Title: change an exposed filter from a select box to a text field search
I have a view that utilizes a node-reference field. I want users to be able to filter by this field using a search-box (or an autocomplete field), but when I set the exposed filter to the node-reference field, all I get is a drop-down. How can I force this to be either a text field or autocomplete?

Thanks!

views 3 drupal 7

# Answer
> 1 votes
This might help you,

http://drupal.org/node/506654#comment-6412784

Views autocomplete filters

# Answer
> 0 votes
You can also use entity reference instead of node reference. That module offers an autocomplete filter.

---
Tags: views
---


# Question
Title: Results table with form select for filtering
I have a page set up via a custom module, which contains some data rendered in a table, not using views. I didn't use views because it requires some various calculations that views calc couldn't do.

The table works fine, however, I would like to add a dropdown above the table, so that is has the equivalent of exposed filters like you would see in views.

The trouble is, i haven't had any luck in rendering a form (for the filter widget) in the same page callback as the table.

Below is the code i have up to this point. I figured this would be a common use case and this information must exist somewhere, but i haven't had any luck in finding an answer to this.

```
<?php
function mymodule_reports_menu() {
  $items = array();
  $items['people'] = array(
    'title' => 'Members',
    'page callback' => 'mymodule_reports_page',
    'access arguments' => array('access content'),
    'weight' => 1,
  );
  $items['people/fees-by-month-paid'] = array(
    'title' => 'Members by Card Number',
    'page callback' => 'mymodule_fees_by_month_paid',
    'access arguments' => array('access statistics'),
    'weight' => 1,
  );
  $items['people/fees-by-card-number'] = array(
    'title' => 'Members by Card Number',
    'page callback' => 'mymodule_fees_by_card_number',
    'access arguments' => array('access statistics'),
    'weight' => 1,
  );
  return $items;
}

function mymodule_fees_by_card_number_form($form_state) {

  $form = array();

  $form['year'] = array(
    '#type' => 'select',
    '#title' => t('Year'),
    '#description' => t('Toggle the Year'),
    '#options' => array(
      '2015' => t('2015'),
      '2014' => t('2014'),
    ),
    '#required' => TRUE,
  );

  $form['buttons']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#submit' => array('mymodule_fees_by_card_number'),
    '#validate' => array(),
  );
  return $form;
}

function mymodule_fees_by_card_number($form_state) {

  // parameter that i will be setting up as the widget
  $year = '2015';

  $output = drupal_get_form('mymodule_fees_by_card_number_form');

  $members = array();

  $members = mymodule_get_membership_by_year($year);

  foreach($members as $key => $row) {
    $card_number[$key] = $row['card_number'];
    $name[$key] = $row['name'];
  }

  array_multisort($card_number, SORT_ASC, $name, SORT_ASC, $members);

  $yearly_sum = 0;

  $header = array('Card Number', 'Name', 'Paid');
  $rows = array();

  foreach($members as $member) {
    $rows[] = array($member['card_number'], $member['name'], $member['paid']);

    $yearly_sum += $member['paid'];

  }
  $rows[] = array('', '', 'Total:  $' . $yearly_sum);
  $output .= theme('table', array('header' => $header, 'rows' => $rows));

  return $output;
}

```

# Answer
> 0 votes
drupal\_get\_form() returns a render array and theme('table') returns a string so you need to change one of them so they match.

You can either render the form array to a string or pass all the table data through as render array elements and then write a theme function for your form to theme them out into a table later.

The shortest path for you from what you have now would be the former.

To do that you could use this code:

```
$form = drupal_get_form('mymodule_fees_by_card_number_form');
$output = render($form);

```

# Answer
> 0 votes
I don't see a render function anywhere after you create the form. If you didn't exclude it on purpose, after creating the form, it has to be rendered and printed.

in your function you call drupal\_get\_form()

> Return value
>
> The form array.

and later on you add to that with theme()

> Return value
>
> An HTML string representing the themed output.

it looks like you're trying to put together an array and string in the same variable. You need to either render the form first into a string and then add them together, or include the theme data into the form array and render it later on.

---
Tags: forms, theming
---


title: Show blog author info (related content)

text:
# Question
Title: Show blog author info (related content)
I have two content types. Blog and Author. On Blog content type I have entity reference field (blog\_author) where admin can find author of the blog (Author content type).

Now I have a view that is supposed to show Author image and name (fields on Author content type) on the sidebar of blog post. The settings I have on my view:

Filters (published) Relationships (referencing field blog\_author), require this relationship.

But when I go see blog page it always show same author on each blog post (newest Author). Is my relationship somehow wrong? Should it be "referenced field blog\_author" as there is two different entity reference for this field. EDIT: Though I did try this but with same result. So this is why I'm bit baffled now that how to do it. I thought relatioship would be enough but do I need to use contextual filters with this too?

Views settings:

Relationship:

# Answer
> 0 votes
Got it working.

Contextual Filter: Content: Nid (set to "do not use a relationship"; default value of "content ID from URL") Relationship: Entity reference: Referenced entity with "require this relationship"

And then most important thing was that I removed all the fields that I had selected before and reselected and added require above relationship. First time around I didn't remove fields but I just tried to add the relationship but it just didn't show any content. Removing the fields and reassigning them did the trick.

# Answer
> 0 votes
Assuming the author of the blog is the same as the field and content type 'author' when a blog is created, I would suggest using core profile information for the author and use the Author Pane Module:

> 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: 7, views
---


# Question
Title: Showing latest news article from taxonomy
I have News content type on my Drupal 7. With views I want to show latest news within specific taxonomy. So each News content type has taxonomy field where I can set news for example into "Cars" category.

Now I have News Lift content type where I have entity reference field called news\_type that is linked to same taxonomy as is my News content type. When I make a new news lift and I set I want to show post from "Cars" category. On this just created page I want to now show that latest post in that category using views. In Views my current set up is this:

Filters (published & News -content type) Relationships (Entitry referecing news\_type field).

But at the moment it just shows the latest post. It ignores the relationship about the category. What's wrong. Do I need contextual filter too?

# Answer
Download the Views PHP module:

> This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.

In Views:

* create a View of News Content Type, as a block and set it up to show all entries for now in the format and layout you desire
* add a contextual filter for the Category field
* Provide a default value, PHP code:

```
$node = menu_get_object();
return $node->field_category['und'][0]['tid'];

```

The first line retrieves the page object (which should only ever be a News Lift node if the block is set up properly), then returns the term ID associated to the current node as a contextual filter to the view. This assumes a single language site.

* Under `/admin/structure/block` set the view-block to show where you want on the page, limit it to show only on the content type News Lift
> 0 votes

---
Tags: 7, views
---


# Question
Title: General error: 2006 MySQL server has gone away
This is the error I am suddenly getting.

```
Additional uncaught exception thrown while handling exception.

Original
PDOException: SQLSTATE[70100]: Unknown error: 1317 Query execution was interrupted...my query

Additional
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away...my query

```

After doing some research it sounds like a custom module, which I have made, is attempting a query which is too big. A solution that seems to work for a lot of people is this:

1. Open my.ini
2. Change "max\_allowed\_packet" from "1m" to "16m" (or larger)
3. Save my.ini and restart MySQL

However, I am on a shared server, so I cannot edit my.ini, and although my provider has confirmed to me that the value is set to 1M, they won't increase it.

I also tried adding this: `ini_set('mysqli.reconnect', 'on');` to `settings.php`. It didn't solve the problem.

Does anyone know of a another solution, or work around?

Thanks.

# Answer
Shared hosting companies do not give away the **SUPER** privilege. If you have it, you can easily set **max\_allowed\_packet** to 512M by just running this :

```
mysql> SET GLOBAL max_allowed_packet = 1024 * 1024 * 512;

```

No restart is required. Then, all incoming connections thereafter can have a 512M **packet**.

You cannot do this:

```
mysql> SET max_allowed_packet = 1024 * 1024 * 512;

```

because you get

```
ERROR 1621 (HY000): SESSION variable 'max_allowed_packet' is read-only. Use SET GLOBAL to assign the value

```

The only alternative I can think of is to switch to Amazon EC2 and install MySQL there. That way, you can have free rein to edit my.cnf/my.ini and have the **SUPER** privilege.
> 8 votes

# Answer
I asked my provider to increase the value, but they would not. I can understand why, they are a business and they want me to pay 29.99 a month for a dedicated server, rather than 4.99 for a shared server.

However, there is a **solution:** identify the query which is too big and break it up into two or more parts. I split my problem query in half: problem solved. Inefficient - yes - but it's better than my site not working at all or having to pay the extra.
> 0 votes

# Answer
Problem is because `max_allowed_packet`, you set it with bigger value.

**How to fix this problem**(if you are in windows and using xamp else find my.ini file)
Go to xampp\mysql\bin
Open my.ini
Change "max\_allowed\_packet" from "1m" to "16m"
Save my.ini
Now restart MySql through the XAMPP control panel.

Found this solution here. http://minorpoint.blogspot.com/2007/09/mysql-server-has-gone-away.html
> 0 votes

---
Tags: database
---


# Question
Title: How to uninstall one site of a multi-site?
Things are bit messed up in one of my sites, partly because of modules that did not clean up after themselves when I disabled them and partly because I tried to clean up for them, which of course, only partially worked.

So I want to remove this site and start it over again with a fresh install. But I don't see anything on how to uninstall or remove a site.

(This is a development environment, of course!)

Thanks for your help.

# Answer
> 3 votes
Nothing to it as long as they have separate databases:

1. Deactivate the virtualhost pointing at your site and restart apache
2. Backup and delete the database for that site
3. Backup and delete the site folder inside `Drupal_root/sites` where Drupal\_root is your core Drupal repository

Then rebuild however you please.

---
Tags: multi-sites
---


# Question
Title: How to supress the second sidebar in Zen theme?
I have nodes that include blocks in the second sidebar. When all the blocks are removed, every node's content takes up the width of the page (and extends into the sidebar region) which is what I want. When I add any block, even if it isn't displaying on that specific node, the sidebar is no longer suppressed.

I also have to re-save every block I add in the second sidebar region, because if not, it displays the title 2x and it displays on every node, regardless of what it is configured for. So for example, if my block of "related links" displays only on node x, it will show also on node y UNLESS I re-save the block configuration.

I have not found anything in my searches here and on Google (most want to add to a sidebar not remove it), and I just don't know where to even start looking for what could be wrong. Any help would be appreciated.

# Answer
> 1 votes
Go to structure =\> blocks, and move those blocks in another region, voila second sidebar suppressed. You may want to change the regions altogether but that gets into theme templates and such...

---
Tags: 7, nodes, blocks
---


# Question
Title: I want to call a mymodule.functions.inc file
Hi all drupalers i am new in drupal coding i wrote a new drupal module that works perfecr but my boss wanted to put all my functions of my .module file in a new folder called 'includes' and in a files that called mymodule.functions.inc now i got an error in my code that says called of undefined function... How I can call this mymodule.functions.inc file in my mymodule.module file?? I need a real help hear guys plz help me out :)

# Answer
You need to use the module\_load\_include function.

EDIT: As @Darvanen mentions this needs to go in your `.module` file preferably inside a suitable hook. Have you seen the Including code section of the Coding standards page?
> 3 votes

---
Tags: 7, files
---


# Question
Title: Filter date from current date to upcoming 7 days?
I have a week type calendar view. It currently displays form SUN to SAT of the current week.

But I need to display it starting from **current date** to **current date + 7 days**

How can I achieve this?. I am using Calendar Module and created a view using it.

My view is displayed only if I add a contextual filter. With default value as `current date`. This adds a filter criteria from dates starting from the start of the week and end of the week.

# Answer
1. In Views filters find your date field.
2. Now, in filter settings select "is between".
3. Choose "Enter a relative date" and enter "Now" in the first one and "+7 days" in the second field.
> 0 votes

---
Tags: 7, views, datetime
---


# Question
Title: Display different fields depending on field value in node template
I have a field named field\_event\_type. When creating a node, you can select one of two options for this field from a drop-down list:

* birthday party
* Wedding

I want to be able to display different fields in my node depending on which type of event is selected. So in node--events.tpl.php, my node template, I wrote the following:

```
if ($element['#object']->field_event_type['und'][0]['value'] == 'birthday party' )
   {
      print render($content['field_some_field']);
   }

else
   {
      print render($content['field_some_other_field']);
   }

```

However, this does not seem to be working the way I intended it to, not only is it not displaying the additional field content in either event type, but I'm also getting an error in Drupal about an undefined variable. Is my code incorrect?

# Answer
> 1 votes
Given your use of the $element variable in a page.tpl.php file, I would suspect a typo or error in its use.

You could either continue to use the page.tpl.php but use $node instead, or use a field tpl instead and continue to use $element. Which you choose really depends on the complexity of the set up and where you want the modifications to lie

# Answer
> 2 votes
You may find it easier to use the Conditional Fields Module:

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API. You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

---
Tags: 7, nodes, entities, theming, database
---


# Question
Title: Drupal 7 how to programmatically display resent comment from all article with author image and comment content?
I'm just use built in function `comment_get_recent($number);` but its only fetch resent comment's subject and author name, is any built in function available which display resent comment with author image comment subject and comment content?

# Answer
> 1 votes
comment\_load($cid) should load the entire comment object based on the comment id ($cid).

What you do with it then is up to you.

---
Tags: 7, theming, comments
---


title: Limit text field to specific length

text:
# Question
Title: Limit text field to specific length
In my custom content type, I want restricted the length of text entered in a text field. I want to check whether a user entered e.g. thousands of words. For this I tried this one but unable to achieve.

```
$my_field = field_get_items('node',node_load($nid, NULL, TRUE), 'my_field');
$my_field = substr($my_field,0,100).'...';
print $my_field[0]['value'];

```

Is there any way to do this in drupal 7 context?

# Answer
If you're really trying to restrict the character count at the point of entry you need to set the field in your form to have a #maxlength in your form definition.
> 4 votes

# Answer
There is basically two modules that come to my mind regarding this functionality. The second one (Maxlength) is probably a bit more promissing:

* Webform Countdown *"Provides a textarea component for Drupal webforms with a configurable, twitter-style dynamic word or character count."*
* Maxlength *"When the maximum length is enforced for a field, while editing content of that type some Java Script will countdown how many characters are left, also if the Javascript is turned off, it falls back to form API validation."*

\[EDIT\] If you instead want to limit the text length shown in a teaser view, you can do that through the basic display settings of your content type:

`structure > content types > my_content_type > display > teaser`

There you can set the format to "Trimmed" or "Summary or trimmed" and then limit the lenght for example to 600: `"Trim length: 600"`. Afaik this setting can be adjusted in every view.
> 1 votes

---
Tags: 7
---


# Question
Title: Add Google Analytics to track a button press
I have the Google Analytics module installed with Drupal 7. On a page, how would I track the press of a button with id "myButton". There's a great example here:

https://developers.google.com/analytics/devguides/collection/analyticsjs/events

but I'd like to learn how to leverage the GA module in Drupal 7 to do this.

# Answer
> 1 votes
take a look at Google Analytics Event Tracking:

> Event Tracking is a way to track user interaction with out registering a page view. Using Google Maps as an example site, event tracking would allow the user to track Zoom, Drag, and View Change events without contaminating the page view statistic.
>
> This module allows an interface for Google Analytics event tracking capabilities. It provides a hook for other modules or "glue code" and also has some handy drush commands.

---
Tags: 7, google-analytics
---