title: Translate "Order total"

text:
# Question
Title: Translate "Order total"
I have translated my site into Japanese using all the required modules and po files.

But now I'm not able to translate the text "Order total" which appears in Checkout process.

I tried applying patches as suggested here but it didn't help me. Please tell me how to change this text.

# Answer
This post discusses the very same issue. Also, as mentioned in this comment,

> 1) You have to go to this page admin/config/regional/i18n/strings And set the language to english..than the translation strings can be made to your language.
>
> 2) You need to go to admin/config/regional/translate/i18n\_string and enable
>
> Select text groups Fields 3) Then the fields are between the normal translation page to be able to translate: admin/config/regional/translate/translate
>
> 4) After adding translation and nothing showing, back to admin/config/regional/translate/i18n\_string Enable Fields and click REFRESH.

Hope this helps.
> 1 votes

# Answer
```

function template_preprocess_field(&$variables, $hook) {

  if ($variables['field_name_css'] == 'commerce-order-total') {
    $variables['items'][0]['#markup'] = str_replace('Order total', t('Order total'), $variables['items'][0]['#markup']);
  }

}

```
> 0 votes

---
Tags: i18n-l10n, commerce
---


title: How to get previous page title

text:
# Question
Title: How to get previous page title
How can I get the previous viewed page title? For example, I visited node/21 then, I navigate to node/22, then in node/22 I'd like to get the node/21's title. In node/22, there's a text field where the default value is the node/21's title. Is there any function I can use for this? Please help as I badly needed this. Thank you.

# Answer
> 2 votes
You can use `$_SERVER['HTTP_REFERER']` with PHP to get the URL of the last page you were on. This is not a reliable solution because not all user agents support it. plus users can manually intervene with the previous page and mess things up.

If a client side solution is sufficient for you, you can use javascript's document.referrer.

You could use a querystring as well and append that to the URL and read it from the page you're going to.

```
website.com/secondPage?refer=lastPageIWasOn

// then grab the value from the second page
$last_page_value = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';

// or use drupal_get_query_parameters()

// Then do something with it

```

Or you could use cookie/session to do this

```
if (!isset($_SESSION)) {
    session_start();
}
if (!isset($_SESSION['referrer'])) {
    $_SESSION['lastpage'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
}

// second page
$referer = isset($_SESSION['lastpage']) ? $_SESSION['lastpage'] : '';

```

This is a very common use case and StackOverflow has several questions on it with PHP. I suggest googling it. Translating it to drupal will depend on what you're doing with it.

---
Tags: nodes
---


# Question
Title: State of form element based on global config
I have a `form_alter` that adds some settings on a content type. How can I make one of these elements hidden (and cleared?) based on the value of a global config (set with `variable_get`)? I found the states api, but that only manipulates elements based on the values of other elements on the same form. Is there a best practice for what I am trying to do?

# Answer
You can unset a form element using this code :

```
var x = variable_get("VariableName");
if(x confirmed some condition)
{
  unset($form[$ELEMENT_YOU_DESIRE_TO_HIDE]);
}

```
> 0 votes

# Answer
Here is what I did to keep it set but not visible.

```
var x = variable_get("VariableName");
if(x condition){
$form['element'] = array(
    // form api stuff, type is anything, set default value, etc.
  );
}
else {
  $form['element'] = array(
    '#type' => 'hidden',
    // set default value, etc
  );
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Google Analytics Events Tracking Module not working out of the box
I was super excited to learn about the google\_analytics\_et module. I downloaded it and then uploaded to my staging site and enabled the modules like that mentioned. I then clicked around and notice that nothing happens like the documentation states. So I went to the internet to search for some answers. Nothing that helps me.

I am hoping that someone has some information. I wanted to add event tracking and the module seems to have promise. Is there a trick to getting it to work. Do I need to add javascript to the site, example module to make it work?

Is there a better way? Not being a developer is making it harder to figure out.

Thank you in advance.

# Answer
No JS additions are needed; that's taken care of for you. The GA Events Tracking module doesn't work by itself however, it requires 2 things:

* The GA module.
* A module implementing `hook_google_analytics_et_api()`.

The module includes an example module which you can either alter directly (not recommended) or just create a renamed copy of it (renaming files & functions from `google_analytics_et_example` to `mymodule`). More information can be found on the project page on what you need to do. It does require you to know a little something about:
> 1 votes

---
Tags: google-analytics
---


# Question
Title: Simplenews is not Activated Automatically for Users
I'm using Simplenews module for newsletters. My newsletter is set to subscribe users automatically on account creation. However the status remains inactivated after creation.

How can subscriptions be automatically activated?

# Answer
> 1 votes
If you're using the ***silent*** option for new accounts, this only automatically activates if you've disabled email verification for new account registration or an admin activates the account (if requiring administrative approval).

---
Tags: emails
---


# Question
Title: Commerce Kickstart change full text search product display to https
I am currently developing a drupal commerce site with commerce kickstart. I've set the site up so that it's mixed mode SSL using securepages, all seems to be working fine. However, I've found a bug with the full text search (used in the main products display view) which could potentially put customers off as they may think the site is unsecure. Plus the certificate does not show the EV SSL Green bar / padlock, it display's with a yellow warning.

All browsers apart from chrome work ok and from doing my research it looks like it's only the full text search which is causing the issue (when testing using chrome by pressing ctrl + shift + j it shows the error code) on line 223:

Mixed Content: The page at 'https://www.whiterabbitengland.us/contact-us' was loaded over a secure connection, but contains a form which targets an insecure endpoint 'http://www.whiterabbitengland.us/products'. This endpoint should be made available over a secure connection.

Has anyone else encountered this issue and found a way to set the full text search over https?

Thanks Max

# Answer
> 0 votes
Maintainer of Commerce Kickstart.

I just checked out the site, and it's using a relative path like Drupal forms are expected to do. From your source:

```
<form action="/products" method="get" id="views-exposed-form-display-products-page" accept-charset="UTF-8">

```

The search form is a Views exposed filter exposed as a block. There isn't much trickery going on with the form beyond typical site building.

Also, I did not get mixed content warnings.

---
Tags: commerce, views
---


title: Get delta value of Multifield

text:
# Question
Title: Get delta value of Multifield
How do I get the delta value of a multifield in a View template? I need to get the delta value in the Row output View template.

# Answer
```
<?php foreach ($row->field_my_field as $data): ?>

  <?php if ($data['raw']['value'] == 'o'): ?>
    // Output nothing, or placeholder, whatever
  <?php else: ?>
    <?php print $data['rendered']['#markup']; ?>
  <?php endif; ?>

<?php endforeach; ?>

```
> 0 votes

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


# Question
Title: Unexpected Entity Reference Autocomplete behaviour
I'm using Entity API, Form API and Entity Reference Autocomplete in Drupal. I have a relationship between two types, clubs and courses, each `club` can have many `courses` so basically the table `course` contains a column called `goclid` which references the `club` id number like so:

```
// hook_schema()

$schema['course'] = array(
    // other fields...
'goclid' => array(
    'description' => 'Reference to the club',
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
  ),

// ... a few lines later...
'foreign key' => array(
  'related_club' => array( // join alias
    'table' => 'club',
    'columns' => array('goclid' => 'id'),
  ),
),
// etc.
);

```

Then I include a field like so in the `course` form:

```
$form['goclid'] = array(
    '#title' => t('Reference to the club'),
    '#type' => 'entityreference',
    '#era_entity_type' => 'club',
    '#default_value' => isset($course->goclid) ? $course->goclid : '',
    '#required' => FALSE,
);

```

Now, the autocomplete gives suggestions only when I type an id number, and then populates the field value with the label (name of the golf club). What I want is exactly the opposite: I want to get suggestions by typing the name of the club, and then when I choose one, the form field should be populated with the id number of that object.

Why is Entity Reference Autocomplete behaving in an unexpected way? What can I do to obtain the desired behaviour?

EDIT: to understand the solution look not only at the answer but **also at the comments that I left below the answer**; the answer itself only explains how to get the suggestions working but does not explain how to build and save the entity object in your submit function.

# Answer
> 1 votes
I think you might have not specified the "label" column in the entity definition. That goes within the 'entity keys' array, like the 'id' key.

```
$entity_info = array(
   .....
  'entity keys' array(
    'id' => 'primary key column...',
    'label' =>  'column holding the label'
  ),
)

```

Otherwise entityreference will not know which column to use for searching in the DB. That still makes it possible to show the label (as you're experiencing) after you reference the entity, because 'label' key is not mandatory, and you may have specified a "label callback" instead, which the Entity API will use when entity\_label() is called to get the label of a specific entity.

If adding the 'label' column and flushing all caches doesn't solve your problem, I think I'd need the entity definition to be able to help!

---
Tags: forms, entities, ajax
---


# Question
Title: Get file ID and path to use in a template file
I am working in my **Row style template** (`views-view-fields--MYVIEW--block-1.tpl.php`). I need to get the file ID and path of an image. The image field is a multi field, so I need to get all of the images for each row. How do I do this?

I also will need to get the delta value of each image.

I try using kpr($variables) but I can't click to expand:

# Answer
> 0 votes
The `THEME_preprocess_views_view_fields(&$var)` function in the `template.php` in your theme directory is get called just before loading the Row Views Template file. Every component of the current row is saved inside the `$var` array.

To get what you need, simply just `kpr($var)` and it gives you all of the information about the current row. You can also save these information in the `$var` array as an index and use them later.

---
Tags: 7, views, theming, media, files
---


# Question
Title: Why can I not find the og table after installing Organic Groups?
I am using Organic Groups module.

After installation why do I not find the `og` table?

I only have these five tables:

Here is a screenprint from the Drupal log with messages from around the time the og module was enabled:

**Note**: I installed the og module using a new Drupal site (which doesn't have any other contributed modules enabled yet), and I tried a disable/uninstall of it. Then re-installed the module but it did not fix this problem.

# Answer
> 2 votes
The Drupal 7 version of Organic Groups doesn't have an `og` table. The Drupal 6 version does, but it's removed as part of the upgrade process, and never exists in the newer version.

You can always find out what tables a module is responsible for by checking its implementation of hook\_schema() (in this case `og_schema()`).

# Answer
> 0 votes
# Make sure you use the correct Drupal version

The initial version of your question didn't specify which version of Drupal you're using. Though the names of the tables you mentioned are from D7 (not used in D6).

That table was available in D6, as confirmed in the module's installation process for the 6.x-2.x version of it. But that table is no longer available in D7, as confirmed also in the module's installation process for the 7.x-2.x version of it.

# Re-install the module

Try a disable/uninstall of the og module, then re-install the module.

Sometimes it helps to restore and/or repair these kinds of problems.

# Increase memory limit

Another option might be that you need to increase the memory size of your Drupal site. And then retry uninstall/reinstall one more time. Because each time you install a module, your site will be using more memory. So at some point (if you never increase the memory), you'll hit your available memory limit.

Assuming this is NOT a multi site, consider editing your `/sites/default/settings.php`, and change the line to set the memory limit. If it is a multi site, then edit the `settings.php` file related to the site where you are experiencing the problem.

That line in settings.php should look similar to this:

```
`ini_set('memory_limit', '128M');`

```

The '128M' in it might be some other number. Whatever the number is, try to increase it with like 50%, or maybe even double it to see what happens after you do so (of course do not forget to save the file after increasing that number).

Be aware also that the amount of memory you'll actually need, somehow depends on the number of enabled modules (the more modules you (try to) enable, the more memory you'll need.

If needed, refer to https://www.drupal.org/node/207036 for more details, eg if such 'ini\_set' is not yet included in your `settings.php` file. As mentioned in that link: "*Locate the PHP settings section and add that line at the end of that section*".

# Check logfiles

If none of the above helps, then check your log files (both Drupla logs and/or server logs) to find some kind of indication of possible errors.

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


# Question
Title: How to run `drush make` on the existing Drupal installation?
Whenever I try to run this command for a second time I get an error.

```
drush -v make /home/testdev/xipdrupalbasic.make /home/testdev/drupal

```

> ```
> Loading release_info engine.                                            [notice]
> Base path /home/testdev/drupal already exists                           [error]
> Command dispatch complete
>
> ```

I get why it gives me this error, but I would like a way of giving a force or overwrite command with it so it still runs. I get the error because it tries to make a directory that already exist.

I already tried the adding `-r` to it but it will then just install it in the directory you execute the command.

When i just do:

```
drush -v make /home/testdev/xipdrupalbasic.make

```

in the directory where I want it, it will work without a problem.

# Answer
> 3 votes
You can run `drush make` again on the existing Drupal installation, but you've to specify `--no-core` parameter.

> `drush make --no-core` Build an installation profile within an existing Drupal site

---
Tags: drush
---


# Question
Title: Combine recent and popular items in Views
I need to show 2 popular and then 2 most recent items, and again next 2 popular and next 2 recent items in Views.

Any idea how to do this?

# Answer
You can create two separate views which will display two 2 popular items and 2 most recent items and use script below that will print content from these views on the page.

```
for ($i = 0; $i <= $n; $i = $i + 2) {
  $popular = views_get_view('popular');
  $popular->set_display('block');
  $popular->set_offset($i);
  $popular_content = $popular->preview();
  print $popular_content;

  $recent = views_get_view('recent');
  $recent->set_display('block');
  $recent->set_offset($i);
  $recent_content = $recent->preview();
  print $recent_content;
}

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: Displaying all fields of a custom content
I have a `page.tpl.php` ; where I want to display inside a `<div>` in it the fields of a custom content I've created before :

1)The custom content is called "**Slider**"

2)It have a field I've added called image (Machine name :"`field_image_slider`")

I've tried this code but it didn't works :

```
    <?php
        if (!empty($node)) :
           $fieldImage = field_get_items('node', $node, 'field_image_slider');
           print var_dump($node); //to check the fields
           foreach ($node->field_image_slider['und'] as $item) {
              $val=$item['uri'];
              print '<div class="item"><figure><img src="' .file_create_url($val). '" /></figure><h3 class="orange">Hi</h3></div>';
           }
        endif;
    ?>

```

I've spent 3 days figuring how to solve this problem , any help would be extremely appreciated .

# Answer
I think you use wrong theme template. This way you need use node.tpl.php and exactly is node--slider.tpl.php. You can see template suggestions. Or you don't want use node template i think better you can use hook\_preprocess\_page()

```
function YOURTHEME_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    $node = $vars['node'];
    $field_images = field_get_items('node', $node, 'field_image_slider');
    //dpm($field_images);
    if (!empty($field_images)) {
      $output = '';
      foreach ($field_images as $key => $images) {
        $output .= '<div class="item"><figure><img src="' .file_create_url($images['uri']). '" /></figure><h3 class="orange">Hi</h3></div>';
      }
      $vars['slider'] = $output;
    }
  }
}

```

and in page.tpl.php

```
<?php if(isset($slider)): ?>
  <?php print $slider; ?>
<?php endif; ?>

```
> 0 votes

---
Tags: nodes
---


# Question
Title: Displaying image from referenced entity in a view
I am trying to create an image albums with the biblio content. These are the steps I have taken:

1. On the Biblio content type, I added a new field called Image of type Image
2. Created a new content called Album. Added one field of type Entity reference; and referenced, to the Biblio content, with multiple selection
3. This is where I'm stuck, creating a view for the albums. I'm not able to display the image content of the biblio entity reference. I have added a relationship to the entity reference: referencing the biblio entity. And added the field Content:Image with a relationship to the biblio entity.

I'm at loss, I know I have a big mistake in the view, but I'm not getting the big picture on how to relate.

# Answer
I think you're reference relationship is in the wrong direction. Using `Entity Reference: Referenced Entity` as the relationship will provide all fields of the entity (i.e., Biblio content type) that is referenced by your entity reference field (on your Album content type).
> 0 votes

# Answer
I think you want to display the content of "Album" with the contents reference to "Biblio", first in views follow these steps:

1. Select the content type of "Album"
2. Create a relation ship with reference to "Biblio"
3. Then again select an image in fields and enable the relationship with the same (which you have selected in relationship).
> 1 votes

---
Tags: views, entities
---


# Question
Title: page--front.tpl.php being ignore in favour of page--node--page.tpl.php
I've got an issue which I'm not sure how to address. I've got a specific page that I've set as front page. I've created a custom template for it and named it `page--front.tpl.php` and it was as expected until I've added `page--node--page.tpl.php` which seems to be overriding `page--front.tpl.php`.

Is this the correct and expected behaviour? How can I force it the `page--front.tpl.php` to be used?

I'm using Drupal 7 with and a child of the Bootstrap's theme.

# Answer
If you need to have a custom theme for nodes, try to do this using `THEME_preprocess_node` as follow

```
function THEME_preprocess_node(&$variables){
     $node = $variables['node'];
     if($node->type == "SOME_CONTENT_TYPE")
          $variables['theme_hook_suggestions'][]='page__node__SOMETHING';
}

```

Then create `page--node--SOMETHING.tpl.php` in your theme folder. To get the values of the fields you can use the entity module and do something like the following code (I supposed `field_something` is machine name of one of your fields):

```
function THEME_preprocess_node(&$variables){
     $node = $variables['node'];
     if($node->type == "ANY_CONTENT_TYPE"){
        $variables['theme_hook_suggestions'][]='page__node__SOMETHING';
        $wrapper = entity_metadata_wrapper('node',$variables['node']);
        $variables['title'] = $wrapper->title->value();
        $variables['something'] = $wrapper->field_something->value();
     }
}

```

By this code `$title` and `$something` variables are available in `page--node--SOMETHING.tpl.php` file.
> 1 votes

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


# Question
Title: Is there any alternative of node_save to update database fields in iteration?
In Drupal 7, we have big product catalog where we need to update price and stock frequently via Cronjobs.

If we update only 5000 prices then also it takes around 20 min. In each iteration we use `node_load()` and `node_save()` functions to update for each product in database.

It seems that these functions are consuming more memory and taking more execution time to just update 1/2 fields in database. It's drupal's API, so it would be integrated to some other stuff (like node revision) so I doubt that we can simply replace node functions with direct queries.

But I think, this scenario would be common when we manage large product catalog in drupal.

Can anyone suggest better/optimized approach for this scenario where it doesn't break the integrity with drupal platform?

# Answer
you can use entity module. This module proves entity\_matadata\_wrapper API which allows you to load and save fields of nodes. The following code is an example of altering a node's title.

```
$nodeWrapper = entity_metadata_wrapper('node', node_load($node->nid));
$nodeWrapper->title->set(t("Saved by Entity Save"));
$nodeWrapper->save();

```

`entity_matadata_wrapper` is not limited to nodes. As you can see in it's signature you must specify the element which in your case it is node.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to detect modules enabled incorrectly?
If some errors occurs in the process of enabling modules (WSOD due to OOM and others), it happens that the modules are shown as enabled. But in such cases the features of those modules are broken since the enabling/installing of the modules were not completely run.

How do I detect such modules state without re-enabling every single module?

Update: Obviously logs can be disabled/cleared/lost, don't mention them please.

# Answer
The problem is that it depends on each module. When enabled, a module sets up its environment (create tables, variables, declare URL, etc) but this environment is not declared explicitly so you can't automatically check that the module has been installed correctly.

You may check the install file for the modules's scheme (tables defined by the module) and the hook\_enable to see what tasks needs the module when is enabled.

I think best way is to uninstall modules and try to install them again, so all modules's environent are cleared when unisntalling and set up again when enabled again.

Using drush this tasks is very easy and handy.

Ah, and try to clear caches to see if modules works, but you won't be sure modules installed correctly...
> 2 votes

# Answer
You should check the dblog at /admin/reports/dblog after such situation. You can also see error\_log file in the Drupal root installation folder.
> 0 votes

# Answer
Using `drush`, you can check if module is enabled by:

```
drush pm-list | grep foo

```

If the installation process stops, try:

1. Refreshing the page again (with POST-ing the data again)
2. Enable module one of each time.
3. Clear caches (`drush -y cc all`).
4. Check the `.install` file from the module directory to see what tables it should create and other data during the installation. If the installation is broken, re-install it (`drush -y dre` when using Devel).
> 0 votes

---
Tags: 7
---


title: Fixing a failed module install

text:
# Question
Title: Fixing a failed module install
I am on Drupal 7. I was on a hosting company that would give me only 64MB of PHP Memory. That led to several issues when installing new modules. My website would run short of memory and would brake right after installing the module. But when reloading the modules page, the module would prove to be installed and working. I confess I kept on playing with fire until I finally broke the installation of one of my modules. It was Menu Blocks. The module would appear as installed, but clicking on the Configuration link on the Modules page would lead me to the wrong page. I couldn't reach the module configuration page. To make a long story short: the installation failed.

I swiched to a new host with more memory and now I am OK. But I still can't install Menu Blocks. I have tried disabling it and reenabling... Nothing. Still not working. Then I disabled AND uninstalled it. Then reinstalled. Nothing happens, still the wrong behavior for the module configuration page. What do I need to do to really and completely uninstall any problematic traces it could have left on my Drupal install? Completely delete Menu Block's tables on the database in case they still exist in there? If I completely remove those tables, do I risk breaking up my website? Completely deleting the Menu Block package, then restarting? I thought this wouldn't solve the problem... Any help appreciated, thank you!

# Answer
Menu blocks doesn't alter the DB at all during the installation. It uses the 'block' and 'block\_role' tables from drupal core and creates several entries in the 'variable' table to store some config.

So here's what I would do:

* Check admin/reports/dblog
* Install the website locally with wamp or Acquia DEV Desktop (using the import tab and backup migrate module) if you're on windows to do some debugging.
* Check the 'menu\_block\_admin\_settings\_form' function in menu\_block.admin.inc which is called when going to admin/config/user-interface/menu-block
> 1 votes

# Answer
Follow below steps to cleanup menu blocks installation.

1. Disable the module.
2. Uninstall the module.
3. Clear All Drupal Cache Tables.
4. Install the module.
5. Again clear all drupal cache tables.
6. Try the link "admin/structure/block/add-menu-block"

Still if it doesn't work then you need to debug the module is correctly un-installed or not by checking following uninstall conditions are met or not by inspecting database.

```
  // Delete menu block variables.
  foreach (variable_get('menu_block_ids', array()) AS $delta) {
    variable_del("menu_block_{$delta}_title_link");
    variable_del("menu_block_{$delta}_admin_title");
    variable_del("menu_block_{$delta}_parent");
    variable_del("menu_block_{$delta}_level");
    variable_del("menu_block_{$delta}_follow");
    variable_del("menu_block_{$delta}_depth");
    variable_del("menu_block_{$delta}_expanded");
    variable_del("menu_block_{$delta}_sort");
  }
  variable_del('menu_block_ids');
  variable_del('menu_block_suppress_core');
  variable_del('menu_block_menu_order');
  // Remove block configurations.
  db_delete('block')
    ->condition('module', 'menu_block')
    ->execute();
  db_delete('block_role')
    ->condition('module', 'menu_block')
    ->execute();
  cache_clear_all();

```
> 0 votes

# Answer
You can try using `drush`, which is much easier to re-install failed module.

For instance using Devel module:

```
drush -y dre foo

```

> Disable, Uninstall, and Install a list of projects.

---

or using the standard way:

```
drush -y dis foo && drush -y pm-uninstall foo && drush -y en foo

```

Then clear you caches (`drush -y cc all`).

See also: How to detect modules enabled incorrectly?

---

Alternatively you may try to force the installation process again, for instance:

1. Edit `foo.install` and add `foo_install();` at the end to run the function manually.
2. Run the file in drush via: `drush scr foo.install` as standalone file.
3. If installation is completed, remove added `foo_install();`.
> 0 votes

---
Tags: installation, blocks
---


# Question
Title: How to get hook_install() to run all hook_update_N()?
How can i get hook\_install() to run all updates that I have for my module? I have in it mymod.install file.

I have tried

```
function mymod_install() {
  mymod_update_6001();
}

```

but it does not seem to do anything. If I have an mymod\_update\_6002() would I still call 6001(), just call 6002() or call both in the order 6001(), 6002().

I thought it would be common sense to run all the updates when you installed a module by default.

# Answer
You shouldn't get your install hook to run updates. When a module is installed for the first time no updates should be necessary.

Updates are used when the module already is installed (the database or variables have been created). In that case, you don't want to reinstall the module as it will wipe all data, instead you create update\_N hooks. Drupal will detect which updates are needed and those will be run going to `update.php`. In Drupal 6 it will auto select which updates to do, but you can change it, while this is not possible in Drupal 7.

Drupal detects which updates are needed by saving the number of the last run update. This can be changes in the database, which will allow to rerun updates in Drupal 7. Rerunning updates is usually a bad idea and will most often cause errors and can in some cases mess up your data.

Always remember to backup your database before running updates.
> 19 votes

# Answer
The purpose of the hooks is different.

* hook\_install() is invoked when a module is installed; it means the module was not previously installed, and therefore, it doesn't need to be updated.
* hook\_update\_N() is invoked when a module is already installed, and it needs to be updated.

If there are some tasks that needs to be done both when the module is installed, and when the module is updated, then the code should be present in both the hooks. There are no module that invokes all the update hooks during the installation, and that would be especially wrong when the update functions update the schema of the database tables used from the module; hook\_schema() should always return the updated schema, and updating the schema also with the update functions would be wrong.

The code you wrote doesn't work because calling one of the update functions doesn't automatically execute all the other update functions.
Calling the update functions from the implementation of `hook_install()`is wrong, as it wrong to call an update function from another one; if there is some code that needs to be executed from two or more update functions, then that code should be placed in a function that is called from the update functions, and from `hook_install()`, if necessary.
> 15 votes

# Answer
The install hook is only called when the module is freshly installed, so there is no need for any updates. The updates are executed only when the module is already installed, so it can apply additional changes.

To force the update functions to run on install, you've to change your schema version, for instance:

```
function mymod_install() {
  // Reset the schema version, so our update hooks can be processed during the installation.
  drupal_set_installed_schema_version('mymod', '7000');
  // Then run the updates as usual.
  mymod_update_7001();
}

```

Or run it from drush: `drush -y updb`.

See also: Is it possible to force your module's update hook to run?
> 5 votes

# Answer
hook\_install would not work with in `mymod.module` file.

You have to place `hook_install` and `hook_uninstall` in a separate file `mymod.install`

I guess that `hook_update_N()` should also be placed in `mymod.install`

---

Answer after the question updated:

Quoting from a link, Please check your version number in info file.

> Since I am developing privately and not for contribution, my 'VERSION' field in my module's .info file is either blank or unchanged when I update a module. I am actually using Subversive for eclipse PDT and therefore my info files version numbers never get updated. Thus, my hook\_update\_6001 was NOT being called by update.php.
> 1 votes

---
Tags: 6, hooks, installation
---


# Question
Title: Which is the best approach to access post save and post update event of a node ..?
My requirement is to automatically create a PDF after **creating a new node** with its contents and replace the PDF with a new one while **updating the node**. Is there any way to access the event **post save**. My PDF creation code is ready but i dont know which **hook** to use. I need the **nid** too.

**Which hook sholud be used for post save and post update event..??**

Any help appreciated..

# Answer
> 1 votes
You can use hook\_node\_insert() and hook\_node\_update() like in the following eample:

```
/**
 * Implements hook_node_insert().
 */
function MYMODULE_node_insert($node) {
  create_pdf($node->nid);
}

```

# Answer
> 0 votes
You can achieve this through rules section of drupal.

Add the event - After saving a new content

Condition - Particular content type which you want your pdf to be created.

Action - Execute the custom php code.

As you have already finished the pdf creation code, this section will be easy. Try it. May be this will help you.

---
Tags: 7, nodes
---


title: Why wouldn't a .install file be loaded?

text:
# Question
Title: Why wouldn't a .install file be loaded?
My latest module does not seem to be loading .install when enabled. Here's the rundown:

I have a .module file implementing `hook_menu()` and `hook_views_data()`.

Both appear to work fine, after enabling the module: navigating to the menu path works as expected and my new views base type is present.

I have a .install file implementing `hook_install()` `hook_uninstall()` and `hook_schema()`

None of the functions in the install file appear to run. The new tables are not present after enabling and there are no errors logged.

If I manually call the functions in the .install file with devel THEN I get an undefined error. I can only assume that the install file is not being loaded.

Running the .install file through the command line PHP interpreter doesn't bring up any syntactic errors.

I'm at a loss to explain why the file is not loaded into scope when the module is enabled.

I'd appreciate any assistance.

# Answer
> 2 votes
Turns out it was an error in `hook schema()` unfortunately the function failed more or less silently. For example :

```
'description' => array(
                'type' => 'varchar',
                'size' => 'normal',
                'not null' => TRUE,
                'description' => 'Description of vaule type.',
        ),

```

Failed.

```
'description' => array(
                'type' => 'varchar',
                'size' => 'normal',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
                'description' => 'Description of vaule type.',
        ),

```

Worked.

The problem was exacerbated by my mistakenly assumed notion that disabling and re-enabling a module would trigger the install, rather then the removal of the module from the system table.

Thanks again to everyone who provided feedback.

# Answer
> 0 votes
If you added the install file after you enabled the module: disable the module, uninstall the module, then enable the module.

`hook_install()` is only executed the first time a module is enabled and if it is enabled after being uninstalled.

# Answer
> 0 votes
Just want to add this answer for future reference as my .install file wasn't loading and it took me a while to figure out what was wrong, so hopefully this can save someone some pain!

I had defined some update functions, e.g. hook\_update\_7101 but when I navigated to update.php it was saying 'no pending updates'. I added some debug statements and discovered that my functions weren't showing up when the call to get\_defined\_functions() was made (this is a php function). It was like PHP wasn't aware of the update functions.

It turns out that there were two versions of my module in Drupal. One at /sites/all/modules and another at /sites/sitename/modules. So the older version of the module at sites/sitename was overriding my newer version at sites/all.

So bottom line:

```
Check whether there are 2 versions of your module - one at sites/all/modules and another at sites/sitename/modules

```

I removed the older version of the module form /sites/sitename and the updates appeared as expected!

# Answer
> 0 votes
The installation file is only loaded during the installation, update process or to check the module requirements. Loading files on demand (when they're needed) saves the time for execution, memory and overall performance.

To include the install file of your module, you've to include it first, for example:

```
module_load_include('install', 'my_module');

```

---
Tags: 6, hooks, installation
---


# Question
Title: How to set a mini panel to display node fields?
I want to load node fields into a mini panel, but when I do what I think that I need to do, the mini panel (= MP) is invisible (because the fields aren't displayed, I guess).

So far I have:

* Added a Content Type
* Added fields to that Content Type
* Created a Minipanel with Required Context = Node
* Added my various Node Fields to that MP: Add Content \> Node \> Field: \___
* Moved the MP into my Content range in the Blocks Editor

I don't see my MP anywhere. This user seems to have a similar issue, and solved it with the Context settings but doesn't answer the question at all, just closed it. Other people seem to have this issue as well:

Can anyone clarify for me how to make my MPs show up with information populated from the node?

# Answer
As per Beebee comment, you should first try removing the "Node" required context and see if that renders the block. Make it work at the most basic level possible and then add various customisations and contexts.
> 0 votes

# Answer
As per Letharion comment, the easiest way of trying to debug this, is to add a custom text-field to the MP (mini panel), and enter panels specific tokens into it, such as `%node:nid`, and see if they get replaced. If not, you have a context problem. Otherwise, it's likely a formatter/rendering problem.
> 0 votes

# Answer
While you can have nodes in block, you can put it in your panel.
> -5 votes

---
Tags: 7, nodes, panels
---


# Question
Title: Dealing with errors 403, 404 in Google Webmaster Tools
I know it may not be strictly drupal releated question, but I'm curious what would be the best approach to solve it with Drupal.

1. 403 errors to: `taxonomy/term/%/feed`

I have around 900 errors with 403 most of them look like this `taxonomy/term/26/all/feed` so they seem to be caused by `taxonomy/term/%/feed` and my question is how could I best fix this issue ?

So that Google would not penalize me with 404's after ? should I somehow change the view.. or ? not sure how to approach this maybe you have experienced similiar issue also when I try to accesss "`name_of_term/feed`" it doesnt seem to work

2. 404 errors exposed fields with `?field_name=value`

I have have around 200 errors of 404 type most of them look like this: `NAME_OF_TERM?field_brand_tid=All&field_color_tid=192&field_size_tid=253`

From what I understand it is showing options in exposed filters for items that doesn't have any nodes assigned to them.

# Answer
For Taxonomy terms you can use Disable Term Node Listings module (https://www.drupal.org/project/disable\_term\_node\_listings)

There is also a great write up on drupal.org about similar issues: https://www.drupal.org/node/345620

In short use robots.txt to disallow paths like ones you specified above. This will prevent google from indexing those pages in first place.
> 1 votes

---
Tags: taxonomy-terms, xml-sitemap
---


# Question
Title: How can I replace the date picker with a text field that shows a date picker when it has the focus?
I installed the *Date Picker* module, which works fine. This is what appears when I add the *datepicker* element to the form.

>

This is the code I use to add the *datepicker* element.

```
$form['date'] = array(
  '#title' => t('Select your birthdate'),
  '#type' => 'datepicker',
  '#date_format' => 'd/m/Y',
  '#date_year_range' => '-100:+0',
  '#default_value' => date("Y-m-d H:i:s", time()),
);

```

I want to display a text field; when it has the focus, the calendar should be shown.

How should I change the code to make it possible?

# Answer
> 0 votes
Have you tried using **DatePicker inline** module?

From module page:

> This module permits inline rendering of date's popup widget. That is, it display the datepicker embedded in the page instead of in an overlay.
>
> It integrates with **field API**, **form API** and **views exposed filters** (via date\_views).

---
Tags: 7, forms, datetime
---


title: Slow AjaxResponse for node content

text:
# Question
Title: Slow AjaxResponse for node content
I am using Drupal 8 so there is very little documentation or benchmarks, but I believe a route I have set up for ajax responses is not as performant as it could be. This is the route:

```
next_node.ajax:
  path: '/node/{node}'
  defaults:
    _controller: '\Drupal\next_node\Controller\DefaultController::view'
  requirements:
    _permission: 'access content'
    _format: 'json'
    _access: 'TRUE'

```

And this is the controller:

```
class DefaultController extends EntityViewController {
  /**
   * {@inheritdoc}
   */
  public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
    $build = parent::view($node);

    return new AjaxResponse(\Drupal::service('renderer')->renderPlain($build));
  }
}

```

I request the content through this function:

```
jQuery.get( "/node/2?_format=json", function( data ) { /* Do stuff */ });

```

Is it normal that it takes about a second on average to get a response? Where to optimize the code?

# Answer
> 0 votes
There are some different things which could be improved in your code, like using dependency injection, better naming etc, but none of these effect performance.

There are some different things which makes it quite trigger to give a good answer to this. Drupal 8 is still in beta and many performance optimizations are being made. The render cache and page cache should be usable in your case making subsequent requests cached and this a lot faster than the initial request. Being logged in / logged out make a big impact as Drupal has a hard time caching for logged in users, but this is nothing new.

That said, it still sounds a bit slow, but hardware, setup etc also have a lot to say.

So long story short, you can't really performance improve your code.

---
Tags: nodes, ajax, entities, 8, routes
---


title: Update database after feeds' import

text:
# Question
Title: Update database after feeds' import
Hello Drupal community,

I'm trying to develop a customized module that updates the database with some operations on some fields (geocoding an adress field) after an import using feeds. Any idea which hook I should use?

Thanks

# Answer
I found another way to alter the feed import. while importing, feeds uses to node functions : hook\_node\_save() and hook\_node\_presave(). Instead of using feeds' hook i used hook\_node\_presave() which alter the query before it is executed.

Works good for me !
> 0 votes

# Answer
There is a hook\_feeds\_after\_import for this
> 0 votes

---
Tags: database, feeds, location
---


title: Detect device using Varnish

text:
# Question
Title: Detect device using Varnish
I have some difficulties finding a correct code (VCL) to configure varnish to detect if the device is a tablet or a mobile or a desktop.

Here is the best module version found today, but still not detecting tablet if not an iPad.

# Answer
This is very tricky but see this helpful link.

Varnish device detection and redirect to mobile site
> 0 votes

---
Tags: caching, theming, proxies
---


# Question
Title: Is it acceptable solution to set session.gc_maxlifetime in hook_init()?
We need to set session.gc\_maxlifetime separately on the site and mobile (app). Is any best practices here?

UPD. My final solution looks as follows:

```
$args = arg();
$is_mob_rest_api = FALSE;
if (!empty($args)) {
  $is_mob_rest_api = $args[0] == 'api' && $args[1] == 'v1';
}
$session__gc_maxlifetime = $is_mob_rest_api ? 31536000 : 1440;
ini_set('session.gc_maxlifetime', $session__gc_maxlifetime);

```

# Answer
> 1 votes
if you set it always and for all, you should do it in *settings.php*

```
ini_set('session.gc_maxlifetime',  36000);

```

---
Tags: sessions
---


# Question
Title: How to add link internal or external to an image in a view for a slideshow?
I need a slideshow and sometime the images need to have a link. This link might be external or internal and it is posted by users. I use rewrite results in my view. However, sometimes the picture does not have a link. So this does not work for me.

I am using Drupal 7, Views, link and slideshow, picture module. My content type has the following fields:

* field\_slideshow\_image
* field\_link\_in\_picture
* text\_slideshow

I try used another modules but I need to use the picture module to make my pictures responsiveness. Other modules require that use the Formatter in views and picture module uses its own format.

# Answer
> 1 votes
I solved using theming in the view. I use the template in the image field. I ended up with a template like views-view-field--field-slideshow-image.tpl.php.

```
  <?php
//dpm($row); only work if devel module enabled

$url='';

if (!empty($row->field_field_link_in_picture_)){

    $url=($row->field_field_link_in_picture_[0]['raw']['url']);

}

if (!empty($url)) {
     echo "<a href='$url'>" .$output ."</a>"; //print image with link
}
else {
    print $output; //print image
}

?>

```

If someone knows a better way to do this please feel post it here. If I am not doing something in the Drupal way please let me know or you have another way to accomplish this. I would love to hear it :)

If you know little about theming views you can check this video to understand better Theming Views

# Answer
> -1 votes
I would also use

```
//dpm($row); only work if devel module enabled
$url='';
if (!empty($row->field_field_link_in_picture_)){
  $url=($row->field_field_link_in_picture_[0]['raw']['url']);
}
if (!empty($url)) {
  echo "<a href='$url'>" .$output ."</a>"; //print image with link
}
else {
  print $output; //print image
}

```

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


# Question
Title: Where does the mysterious blue bar and question mark come from (when logged in as admin)?
When I'm logged in as an admin, I see a blue bar at the top of the page, with a question mark in a circle, but no text. This is how it looks like:

And the markup is:

```
<div class="region region-help alert alert-info">

```

I guess it's some kind of alert, but obviously there's no text, and nothing I can see in any of the logs that might be related either.

Anyone knows what this might be and how to fix it?

# Answer
I think You should try to:

* search Your modules or themes directory for usage of **drupal\_set\_message** function or **dsm** if You are using devel module.
* check trigger module settings for User under admin/structure/trigger/user
* check theme template for empty container with alert-info class
> 0 votes

---
Tags: views, theming
---


# Question
Title: Is there some module which detects untranslated strings?
I am using the Admin **en/admin/config/regional/translate/translate** tab to translate strings of a multilanguage site.

As I have quite a few languages (9), and collaborators send the translated texts in Excel, and I enter manually the strings, I was wondering if there is some way (via options, contributed modules, etc.) of detecting **untranslated strings**, so I could avoid reviewing different Excels sent, and could collect in a fast and easy way those original strings (English) which do not have a translation in a given language.

I understand that Drupal should go through all the files in which a `t()` appears, but maybe some module does do exactly that?

# Answer
To my knowledge, the answer to your question is = **No there is no such module**. Checkout the article Drupal's multilingual problem - why t() is the wrong answer to beter understand the various challenges to be addressed with anything related to the `t()` function ...

Drupal's translation system consists of 2 basic components: the translation of the **interface** and the translation of the **content** of a site.

The **translation of the interface** is about the translation of various text strings used throughout the site, like labels used on buttons such as submit, or on tabs such as view or edit. They are the same on all sites (no matter what actual content is contained in a site). This is also what the `t()` function is related to.

The **translation of the content** is about the translation of nodes and entities. It requires a place to actually store the translated versions of the content (in multiple languages) and a system to choose which content is to be displayed where. The systems available for translation of content are:

* **Content translation** (used in earlier versions of Drupal, and still available in D7), which translates entire nodes in multiple languages.
* **Entity translation** (its API was first introduced in Drupal version 7, though there is no UI for it yet), which translates fields attached to the same entity.

Typical (often used) modules (in D7) related to **translation of the interface** (apart from the i18n module of course):

For D7 there are basically 2 alternatives available to facilitate the "management" of **translation of content**:

* Translation Overview, mentioned as a recommended add-on on the i18n project page also. From its project page:

> ... provides a table listing the site's nodes and showing what's been translated into each language. It also lets you assign priorities for translating nodes into the various languages.
* Translation Management Tool, considered as the successor of the previous module, and "the" module to move forward with in D8 also. From its project page:

> ... provides a tool set for translating content from different sources. The translation can be done by people or translation services of all kinds. It builds on and uses existing language tools and data structures in Drupal and can be used in automated workflow scenarios.
>
> This module does not make i18n or any other language module for Drupal obsolete. It does only facilitate the translation process.

PS: Obviously, translation of content is NOT what this question is about (at least not yet ...), but pretty sure a related challenge you 'will be' (or 'are already'?) facing in this multi-lingual site ... and which cannot be handled with the `t()` function. Though for the sake of completeness, I hope it's OK to add that part of my answer also ....
> 1 votes

# Answer
If you are using i18n, you can find untranslated strings here..

**Administration » Configuration » Regional and language » Translate interface**
> 0 votes

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


# Question
Title: Drupal 7 CKEditor and KCFinder, how to upload to private files directory
I'm trying to configure KCFinder to upload to the private\_files directory that I created outside of the web root. However, it seems like this may not be possible without hacking some library or module files as the KCFinder upload path requires the absolute URL of the website file upload path. I'd rather set this to my private file upload path "/var/www/private\_files" My best guess is that I can hardcode this in /var/www/my\_site/sites/all/libraries/kcfinder/core/class/uploader.php but I don't know exactly what to change in this section, or if that will work at all:

```
// FULL URL
    if (preg_match('/^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)\/?$/',
            $this->config['uploadURL'], $patt)
    ) {
        list($unused, $protocol, $domain, $unused, $port, $path) = $patt;
        $path = path::normalize($path);
        $this->config['uploadURL'] = "$protocol://$domain" . (strlen($port) ? ":$port" : "") . "/$path";
        $this->config['uploadDir'] = strlen($this->config['uploadDir'])
            ? path::normalize($this->config['uploadDir'])
            : path::url2fullPath("/$path");
        $this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
        $this->typeURL = "{$this->config['uploadURL']}/{$this->type}";

    // SITE ROOT
    } elseif ($this->config['uploadURL'] == "/") {
        $this->config['uploadDir'] = strlen($this->config['uploadDir'])
            ? path::normalize($this->config['uploadDir'])
            : path::normalize($_SERVER['DOCUMENT_ROOT']);
        $this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
        $this->typeURL = "/{$this->type}";

    // ABSOLUTE & RELATIVE
    } else {
        $this->config['uploadURL'] = (substr($this->config['uploadURL'], 0, 1) === "/")
            ? path::normalize($this->config['uploadURL'])
            : path::rel2abs_url($this->config['uploadURL']);
        $this->config['uploadDir'] = strlen($this->config['uploadDir'])
            ? path::normalize($this->config['uploadDir'])
            : path::url2fullPath($this->config['uploadURL']);
        $this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
        $this->typeURL = "{$this->config['uploadURL']}/{$this->type}";
    }

```

# Answer
> 1 votes
I found a solution that works at least in my case. I was on the right path... If you simply want to hardcode an upload path, you just need to configure two things in the uploader.php, the uploadDir where the files will be stored, and the Drupal URL where Drupal can find the private files, in my case:

```
// UPLOAD FOLDER INIT

    // hardcode private file upload path outside of web root, can't be configured through the UI that I could find
    $this->config['uploadDir'] = '/var/www/private_files';
    // hardcode the private file url that Drupal needs to be able to access private files internally
    $this->config['uploadURL'] = '/system/files';

```

I know uploadDir already because that's where I've already configured private files to be stored. To find uploadDir, I linked to a private file already located in /var/www/private\_files, then double clicked to see the first part of the URL on the dialog that points to where the root of /var/www/private\_files is located.

The next thing I had to do was disable htaccess checking in the KCEditor config file (/sites/all/libraries/kceditor/conf/config.php) by setting `'_check4htaccess' => false`

---
Tags: wysiwyg, files
---


# Question
Title: Is there a way to check user permissions in javascript?
Is there a way to check user permissions in javascript? I have a segment of code that I only want visible if the user has the proper permissions, and I think it would be easiest way to check the permissions, and then just set the segment to display: none; if the user doesn't have the right permissions.

# Answer
> 2 votes
It is not secure to only rely on Javacript. It is better to separate that `.js` function which needs permission to execute from other codes then put in a file and load that `.js` file from your `hook_preprocess_page` if the user has permission (or some role). I implement this idea with user roles, you may use another strategy for checking the permission.

```
function THEME_preprocess_page(&$var){
      global $user;
      if(in_array("SOME_ROLE_NAME_WITH_ACCESS_TO_JS_FUNCTION",$user->roles))
            drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/Your_js.js');

}

```

in your theme directory, I supposed you placed your `.js` files in `/js` directory. So you should create `Your_js.js` file in that directory and put that function inside it. If the user has appropriate role, that file with that function in it will be loaded and you can use it later, otherwise it won't.

---
Tags: users, javascript
---


title: Workbench moderation and Views

text:
# Question
Title: Workbench moderation and Views
I have a content type which is being managed by Workbench Moderation. This content type has entity reference field. The full page override has been Panelized and has a view pane which displays fields from the referenced entity.

When viewing the published content this all works fine, however, when viewing the 'draft' version of the content using Workbench Moderation the View Pane is obviously only using references from the published revision with the consequence that editors cannot see the affects of their changes, ie adding additional references.

How can I configure the View pane so that it will always list the the referenced entities from the currently viewed revision?

# Answer
It looks like there are possibily nightmares trying to get Panelizer or IPE and Workbench Moderation to play nice together. I've used both seperately, but not together on 1 site when using Moderation.

See this issue thread for Panelizer and Moderation for possible solutions:

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

---
Tags: panels, workbench
---


# Question
Title: How to force initial imported node to not have draft status using feeds?
I'm using the Feeds (7.x-2.0-alpha9) and the Workflow modules. My imported nodes are automatically going to **draft** state and only go to done state when there is a **second** import of this node and the data is updated.

How can I automatically make the state on imported nodes be "**saved**" not "**draft**"?

I tried adding a rule upon feeds presave, but it never gets to the save since it is a draft.

# Answer
> 0 votes
Here is the answer, thanks to another stackexchanger

```
function mymodule_feeds_after_save(FeedsSource $source, $entity, $item, $entity_id) {
    global $user;
    foreach ($entity->workflow_transitions as $key => $value) {
      $field_name = $key;
      $workflow = $value;
      break; // There should only be one workflow at this point
    }
   //$this_sid = $workflow->new_sid;
  $transition = new WorkflowTransition();
  $entity_type = 'node';

  $old_sid = 2; // sid of Draft status
  $new_sid = 3; // sid of Saved status
  $uid = $user->uid; // You can change with uid of author.
  $stamp = REQUEST_TIME;
  $comment = 'Created by upload';
  $transition->setValues($entity_type, $entity, $field_name, $old_sid, $new_sid, $uid, $stamp, $comment);
  workflow_execute_transition($entity_type, $entity, $field_name, $transition, $force = TRUE);
}

```

# Answer
> 0 votes
Even though this question is related to the Workflow module, the solution you're looking for should come from the Feeds and/or Rules module, as further explained in my answer below.

# 1st attempt: Feeds Rules module

The Feeds Rules module might be what you are looking for. Excerpt from its project page:

> ... provides some Rules integration for the Feeds module.
>
> It provides:
>
> * **Feeds processor**: a processor for Feeds to create content via Rules. (Currently only simple data types like text and integer are supported).
> * **Rules Event**: Feeds After Import
> * **Rules Data**: Feeds Source (properties: ID, imported)

***Recommendation***: this **might** work, however there is only a dev version available for this module ... my advice = no go.

# 2nd attempt: Native Feeds module

The Feeds issue about Rules integration & enable modules to customize imports adds a hook `hook_feeds_before_import()`. Here are some quotes from that issue (bold markup added here):

> ... such that a rules integration could use it to **customize the imported entities before saving** \+ to skip saving.
>
> Based on the hook we could add an event for it + an action for skipping the import. **The entity could be manipulated with the usual rules actions else too**.

Of course, in the question here the goal is to not skip saving. But instead *"customize the imported entities before saving"* and/or *"manipulate the entity with the usual rules actions"*. More specifically: set the value of "state" to "Saved".

***Recommendation***: much better already, but it is not exactly right yet (and requires using a hook, i.e. writing some custom module) ... There has to be a **Rules** based solution ...

# 3rd (and Final) attempt: A rule that should do the job

Inspired (challenged) by the "*I tried adding a rule upon feeds presave, but it never gets to the save since it is a draft*" part of this question, I created a rule. Here is the export that rule, which I believe should be a perfect answer to the question (also because it doesn't require custom PHP code ...):

```
{ "rules_update_entity_after_import_via_feeds" : {
    "LABEL" : "Update field imported via feeds",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "workflow_rules", "feeds" ],
    "ON" : { "feeds_import_node" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_workflow_status" } }
    ],
    "DO" : [
      { "workflowfield_field_set_state" : {
          "node" : [ "node" ],
          "field" : [ "node:field-workflow-status" ],
          "workflow_state" : { "value" : { "3" : "3" } }
        }
      }
    ]
  }
}

```

To get this to work, I enabled the `Workflow API` module (of course ...), and also it's submodules `Workflow UI`, `Workflow Field` and `Workflow Rules`.

My Workflow itself has only status "*Draft*" and "*Done*" (identical to the question here).

The rule above only applies to "node", and only for those "nodes" that have a field defined with machine name "`field_workflow_status`" (if you want to use another field name, change the rule accordingly and it should work also ...). In my case I used "Article" as the content type, though the "`entity_has_field`" prevented that I had to hardcode the content type in my rule ...

Obviously, and to be complete, Feeds and Rules are also part of the solution.

---
Tags: feeds, workflows
---


# Question
Title: Flexslider view preview working but not on actual page
My block is not working for the flexslider: The images are not appearing, but the view preview does work.

I don't know if it is relevant, but a similar problem would happen with just a slideshow view, although one image would appear and it would not cycle.

Could jQuery be a problem?

The following is the actual page with the block that is not showing any images.

>

The following is the view preview, which works.

>

# Answer
> 1 votes
In the config of the 'jquery update' module, select 'Default (Provided by Drupal)' in both of the drop-downs. i.e. 'Default jquery Version' and 'Default jquery Version for administrative pages'

---
Tags: views, javascript
---


title: How to add custom month in Date field?

text:
# Question
Title: How to add custom month in Date field?
In my academic website, I need to add graduation year as a date field but for month field, I want to add only two month (May and December).

Can I do this?

My professor want like this and i don't have any idea to solve my situation.

Can you help me?

# Answer
Use hook\_form\_alter to change the date field on the node form you can only select those two months (and disable the rest).
> 1 votes

---
Tags: datetime
---


# Question
Title: How to automatically generate multiple aliases for one node?
I'm using Drupal 7.22. I'm running four site versions in same Drupal installation.

eg:-

* example.com/site1
* example.com/site1

and its mobile versions:

* example.com/mobilesite1
* example.com/mobilesite2

I'm using URL aliases to meet the conditions. I have created patterns for each content type. Suppose I have content type called `site1_projects` and `site2_projects`, and created aliases for each site content type like `site1/site1_projects` and `site2/site2_projects`.

How can I automatically set an aliasing for these content type for mobile, like `mobilesite1/site1_projects` and `mobilesite2/site2_projects`?

# Answer
> 2 votes
In canse you didnt found it, you need to use the module ***Rules*** and follow these steps:

```
**Delete Node Aliases Ruleset**
- Delete all aliases that point to system path
- Delete all aliases that point to system path
- ... (and so forth)

**Create Node Aliases Ruleset**
- Create alias #1 to point to path A
- Create alias #2 to point to path B
- ... (and so forth)

**Triggered Rules**
- IF new node created (and any other conditions) THEN call Create Node Aliases ruleset.
- IF node deleted (...) THEN call Delete Node Aliases ruleset.
- IF node updated (...) THEN call Delete Node Aliases and then call Create Node Aliases

```

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


title: Custom URL on link to node

text:
# Question
Title: Custom URL on link to node
I've got a field (URL) which contains a custom external URL for each node. My goal is to set this custom url as link on the title which is displayed in a View. This is currently linked to a detail page (mydomain/node/5).

Unfortunately, I can't get it to work. How can I solve this?

# Answer
> 1 votes
You can set the node title as a token on the link-field (in the content type field settings).

You can alternatively output the field in the view as url plain text and rewrite the title to display as a link with the given field link as URL.

---
Tags: views, nodes, uri, redirection
---


# Question
Title: Commerce Kickstart 2 - Disable ajax in seach products backend
How can I disable ajax in admin/commerce/products (Commerce Kickstart 2 menu)? I've searched in Search API settings but found nothing.

Edit: I found that the View Commerce Backoffice: Products (Content) control the search of products in admin/commerce/products. In section Advanced \> OTHER there is field Use AJAX. You can set to `Yes` or `No` this field. But even if you set to `No`, when you search for a product the query is made before you press Enter, what is exactly my client want.

So the question persists, is there a way to change this behavior, to be able to search only when you press Enter?

# Answer
You can install (if it's not installed yet) Better Exposed Filters. If you edit the View in admin/commerce/products/list (or any of them) and you select BEF for displaying your exposed filters (using defaults) then the autosubmit feature will no longer work.

On the other hand, see https://www.drupal.org/node/1735254 for an explanation on how to disable the autosubmit feature. It's just adding a CSS class to your filter. You have to find out how to add classes to exposed filters in Views, though. Some dirty jQuery can help, I guess.
> 1 votes

---
Tags: commerce, search
---


title: Using SQL to output link to a node

text:
# Question
Title: Using SQL to output link to a node
Does anyone know - using SQL only - how to output the link to a drupal node?

If I was using PHP I think it would be something like this:

```
print l($node->title, 'node/' . $node->nid);

```

But I'm not using PHP, I need to use SQL only because the report module I'm using requires it.

# Answer
It's in `url_alias` table, you'll need concatenate it with your domain name.

```
SELECT `alias`  FROM `url_alias` WHERE source = "node/XXX";

```

Note: if you have more than one alias it will return multiple results.
> 1 votes

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


title: How to use Search API with Solr?

text:
# Question
Title: How to use Search API with Solr?
I am new to drupal , I have installed SEARCH API . I have opened an account with open solr and following the process suggested in https://drupal.org/node/2137651
since I am not using apache solr search I am going to search api setting (last para in help ) the setup was succesfful and I was able to connect to solr server and infact was able to delete the index , However I am geeting the error message in config-\>search api-\>server as" You are using an incompatible schema.xml configuration file. Please follow the instructions in the INSTALL.txt file for setting up Solr" I am also not able to index , it gives error 400 I dont know where I went wrong in follwing document of https://drupal.org/node/2137651 .I also copied the schema.xml from (open solr ) to drupal/sites/all/modules/search\_api\_solr/solr-conf/4.x

Any help is highly appreciated Regards Carol

# Answer
> 3 votes
Copy the schema.xml from the Search API Solr module into Open Solr. Also be warned that compatibility with 4.x is not stable, so consider using solr 3.x configuration instead.

# Answer
> 0 votes
> I also copied the schema.xml from (open solr ) to drupal/sites/all/modules/search\_api\_solr/solr-conf/4.x

You have to copy all the configuration files from "drupal/sites/all/modules/search\_api\_solr/solr-conf/4.x" to your conf directory of the solr core (eg. "$SOLR\_HOME/collection1/conf").

# Answer
> 0 votes
I was having the same issue, and receiving the "Please follow the instructions in the INSTALL.txt file for setting up Solr". The solution was to install apache Solr manually, following this tutorial https://www.digitalocean.com/community/tutorials/how-to-install-solr-on-ubuntu-14-04. After that everything went well.

---
Tags: search
---


# Question
Title: How to display the value of a report parameter in a Forena Report and in a CSV export of it?
Using Forena Reports I'm wondering if it's possible to include in a report the **PARAMETERS** passed by the URL?

I'd just like to output those parameters once in the report; probably at the top. Something like this:

You selected **'item a, item b, and item c'**. (where items a,b, and c are the parameters passed).

**Extra question**: When I run the sample report with state=VA and then click 'CSV', the CSV download will not say which parameters were selected. Anyway to have the CSV download also include the parameters (+ their values) that were specified?

# Answer
# Display the value of a report parameter in the report

A sample of showing the values of the specified parameters can be found in `reports/sample.user_distribution_simple`.

If you execute that report with a parm like (eg) `state=VA`, or you just use an URL like `/reports/sample.user_distribution_simple?state=VA`, the report will contain a phrase like "This report lists all users in cities assigned to a state with code = **VA**.".

Line 26 in the .frx source of this sample that creates that phrase looks like *This report lists all users in cities assigned to a state with code = {parm.state}*.

So in this specific case, try something like this:

```
You selected 'item {parm.a}, item {parm.b}, and item {parm.c}'.

```

That is: preceed the parameter(s) with `{parm.` and have them followed by a `}`. Some more details about this:

* The `{` and `}` are an indication you want to include something in your report about the report "context" (= Forena terminology).
* The `parm.` part of it is to indicate "one of the report parameter values".
* The `a` is to actually name the exact parameter (like 'a').

This technique (syntax) is also used to create "linked" reports (drill down reports, etc).

Here is a sample of one of my "custom" reports where I do something similar:

Within the "Report Execution Parameters" (collapsed in the screenprint above), I specify the search criteria of the log messages to be retrieved (the "8" within "... statistics within 8 most recent log messages ..." was the value of one of the parameters).

# Include the value of a report parameter in the exported CSV file

The file saved via the CSV export feature, will actually include all the report data shown in the report as "tabular" format (which is compliant also with the tag description ...). So to get the report parameter (and the specified value) included in the CSV export file, you'd have to somehow include that in the appropriate area of your report.

As a sample, consider the `reports/sample.user_distribution_simple` again. You could enhance (customize) this report (which is specified using xHTML ...), by adding these extra HTML lines before the `</table>` tag:

```
<tfoot>
  <tr>
    <td> </td>
    <td> </td>
  </tr>
  <tr>
    <td><b>Report parameters</b></td>
    <td><b>Parameter values</b></td>
  </tr>
  <tr>
    <td>state</td>
    <td>{parm.state}</td>
  </tr>
</tfoot>

```

In doing so, and by rerunning the report again with report parameter (say) `state = VA`, you should get a CSV export file that looks like so:

```
city,users
Amesbury,"3,991"
Catskill,"3,123"
Ketchikan,"6,107"
Michigan City,"1,741"
Selma,"1,833"
Vineland,"1,825"
 ,
Report parameters,Parameter values
state,VA

```

One could argue about the layout/format of the CSV output file (like the 3rd line from the bottom that only has a ","), but the keypoint is that you can use the full power of xHTML to enhance the layout to fit your needs. E.g. replace the ` ` (twice) with something more appropriate, or move those `tfoot` rows somewhere above the `thead` rows (to have the parms and values shown at the top of the CSV file.
> 2 votes

---
Tags: 7, importing-exporting, forena
---


# Question
Title: view content by two taxonomy terms from two vocabulary
I have a content tagged by two **taxonomy vocabulary** ( **location and category**)

How can I let the user select the `location` then select the `category`, the `view` (or `panel`) will show the contents tagged with both terms

with love

# Answer
> 1 votes
In Views you can do it with Exposed filters.

Just add filtering by your two vocabularies to your view (FILTER CRITERIA) an set each filter "Expose this filter to visitors, to allow them to change it". That will show form to enter taxonomy tags to filter on views page. AND logic "show the contents tagged with both terms" works by default (set each exposed filter to "required" if you dont want to allow "all", that way user must select something).

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


# Question
Title: Empty View does not display "No results behavior" for admin
I have a **View content pane** with a setup to display "`Header`" when there is content and "`No results behavior`" when the view is empty. The view works fine for authenticated and anonymous users, however it always shows the "`Header`" instead "`No results behavior`" for empty view to the admin.

Looking at the html output for the view, I see an empty table with one empty row is being generated for admin, but not for `authenticated or anonymous users.`

In the view table settings, all empty columns are set to hidden. All fields have hide empty checked with no rewrite. The views has a contextual filter to display no results when filter is missing.

Its baffling that the view works for others except admin. Any tips will be appreciated.

# Answer
I had somewhat complex filter criteria that was causing the issue for admin. One would think that this should not cause an issue, but it seems to.
> 1 votes

---
Tags: views
---


title: Multisites with multicron

text:
# Question
Title: Multisites with multicron
Planning is like that:-

> We are going to manage multisites & each site having 3 cron jobs daily basis.

so my question is how can I analyze server performance there for multisites ?

**Current scenario :**

> 10 sites having 3 cron jobs in each 10 minutes & each cron is updating contents in each sites(Number of updating contents maximum 3000 in each site with each cron job) but as I am seeing here cpu utilization & mysql is 100% occupied by first 5 sites.

I don't know resource is enough or not ?

Is this related to resource OR how can I improve performance there with cron jobs?

Right now I am using Elysia cron with each site.

Thanks in advance!

# Answer
To analyze the performance of each multisite you will need to coorelate web server logs with performance logs or use an APM service like Newrelic where you can watch PHP at a very granular level as the cron jobs run.

Unfortunately, there is no easy fix for your problem. Multisites can only be used when the sites are not complex or demand a lot of processing. I believe you have a decision to make.

1. Keep using the multisite function of Drupal and deal with the performance issues you have in complicated and creative ways. Create ways would be using multiple servers and databases to offload the cron jobs to so it does not impact the websites.

OR

2. Break the sites up into different Drupal installations and use a code repository to manage the multiple sites.

You should read the articles written by Pantheon on Multisites. They had the same problem as you and realized the problems (performance) with multisites and devised another way to run complex multisites.
> 0 votes

---
Tags: multi-sites
---


# Question
Title: Adding a link to a node in a Views export
I'm using Views data export to export a view-based search as a CSV file for users. Basically it's working. However I'd like to customize how some of the fields come out in the CSV.

Specifically for this question I'm interested in learning how to export the link to the NODE that is returned. It doesn't have to be an active link per se (although that would be ideal), but just the URL to the node would be great too.

I've tried adding Content: Link to the Fields area but that just exports as 'View' for every single returned node. Not helpful.

I've tried returning my title which is currently set to link to the original content but the export doesn't return it as a link. It just returns the title.

I've tried returning the title and making it return as a link with Content: Link as the URL (absolute path selected). But that doesn't nothing.

Anyone have suggestions?

# Answer
> 2 votes
You need to add a new field "content:path" and check the option in the rewrite results section "Use absolute link (begins with "http://")". This should do what you want.

If you want to output it as a working link, you can check the option " Output this field as a link" and fill the replacement pattern \[path\] into "Link path".

---
Tags: views
---


# Question
Title: Clear views cache after node inserted in Drupal 7
I've views which list the list of node details. I've set views cache for 30 mins.
I want to clear particular views cache when insert a node. I've tried below code to clear cache but there is no difference in my page.

```
function phponwebsites_node_insert($node) {
 if ($node->type == 'tasks') {
   views_invalidate_cache();
 }
}

```

# Answer
The next snippet should work for you

```
cache_clear_all('MY_VIEW_NAME:', 'cache_views_data', TRUE);

```
> 5 votes

# Answer
Try this to clear your view display cache.

```
$view = views_get_view('VIEW-NAME');
$view->set_display('VIEW-DISPLAY');
$cache = $view->display_handler->get_plugin('cache');
$cache->cache_flush();

```
> 1 votes

# Answer
See cache\_clear\_all function. Try this if you need to clear only views cache :

```
cache_clear_all('*', 'cache_views', TRUE);

```

**Edit :** Try Cache Action module. It depends on Rules module.

> Cache actions provides rules actions for clearing drupal caches.
>
> It currently provides actions for:
>
> Clearing Drupal cache bins Clearing CSS/JS cache Clearing The cache of specific views Clearing The cache of specific panel pages Clearing The cache of specific mini panels
> 0 votes

---
Tags: views, caching
---


# Question
Title: Increasing PHP memory limit (Possible Drupal override?)
**Problem**

I've recently come across a problem with my dev version of Drupal where I realised the php memory limit isn't high enough.

I've changed the main `php.ini` files but they seem to be ignored and I can only increase the memory limit by putting the following line into `sites/default/settings.php`:

```
ini_set('memory_limit', '500M');

```

Could there be something Drupal related which is overriding the main settings (that I'm then overriding in `settings.php`) as this is happening in multiple environments?

**Set-Up**

* Windows 7, XAMPP:

Altered php.ini in C:/XAMPP/php/php.ini

```
memory_limit=500M

```
* Ubuntu(10.04), Apache, PHP, MySQL

Altered php.ini in /etc/php5/apache2/php.ini

```
memory_limit=500M

```
* Ubuntu(12.04), nginx, PHP-FastCGI, MySQL

Altered php.ini in /etc/php5/cli/php.ini (checked this was correct ini file using `php --ini`)

```
memory_limit=500M

```

I have a php.ini in my drupal root, but it has

```
memory_limit = -1

```

which I'm pretty sure is no limit.

# Answer
> 1 votes
Ok so a bit of digging and here are the results. The short answer for the first two configs was I couldn't replicate them. Maybe I'd forgotten to restart the server? Not sure.

The two paths I'd listed were the correct paths to change the php memory settings.

However for nginx there is a genuine answer:

1. Although the command `php --ini` says `/etc/php5/cli/php.ini` was loaded the correct file to change is:

`/etc/php5/fpm/php.ini`

You then have to restart the php process manager not the server because nginx doesn't touch the php.

`sudo service php5-fpm restart`

The reason you have to edit `/etc/php5/fpm/php.ini` file is because `/etc/php5/cli/php.ini` is the command line php config file and only decides the config for any command line php functions.

Any php functions called by Drupal are processed by FPM and so use the php-fpm config file.

# Answer
> 3 votes
Drupal does not edit any php config settings. The `memory_limit` and what php.ini it is using depends on how your server is setup, there could be something else that is overriding your php.ini you are trying to set. You should use `phpinfo()` to find out what `php.ini` it is using and make sure the last occurrence of memory\_limit is set to what ever you want.

# Answer
> 2 votes
Changes to `php.ini` require that the server be restarted. Did you restart Apache after making those changes?

Drupal itself doesn't change memory limits; your use of ini\_set in settings.php is the best way to make the change through PHP execution, but many third-party hosts will not allow that setting to be overridden to overridden.

Finally, I'd recommend setting the memory limit to 512M as that reflects how semiconductor memory stores data. There's no real functional advantage of this, though, just OCD :-)

# Answer
> 0 votes
How to deal with PHP memory not being applied.

1. Check if you're editing the right file by going to Drupal page and you can find the right location of your PHP config file in:

> Reports -\> Status report -\> PHP: more information -\> Loaded Configuration File: `/etc/.../.../php.ini`
2. Look for `memory_limit` on the same page.
3. Make sure you placed the right value (e.g. `memory_limit = 512M`).
4. Restart your HTTP server, for instance:

```
 sudo apache2ctl graceful

```

For drush, just run: `drush status` and it would show you the command-line configuration (CLI, which could be different from GUI):

```
$ drush status | grep PHP
 PHP executable                  :  /usr/bin/php
 PHP configuration               :  /etc/php5/cli/php.ini
 PHP OS                          :  Linux

```

---
Tags: 7
---


# Question
Title: How to display only one block in custom page using tpl?
How to show only block and hide all other menus,blocks etc., This is my code

```
function example_menu() {
  $items['appointcal'] = array(
    'page callback' => 'example_show',
    'access callback' => TRUE,
     'type' => MENU_CALLBACK,
   );
     return $items;
}

function example_show() {
  return theme('example_cal');
}

function example_theme() {
  return array(
    'example_cal' => array(
      'render element' => 'elements',
      'template' => 'templates/examplecal'
    )
  );
}

```

My examplecal.tpl.php is

```
<div>
  <?php
    $block = module_invoke('views', 'block_view', 'example-block');
    print render($block['content']);
  ?>
</div>

```

There is need to show only region that is in red color and hide all other regions.

# Answer
Create a Custom tpl for your page by editing **page.tpl.php**. Name should be **page--yourmenuname.tpl.php**. In that page tpl remove all unwanted contents/regions and render your block in required region using **\[block\_load($module, $delta)\]**;

```
$block = block_load('name','delta');
$output = _block_get_renderable_array(_block_render_blocks(array($block)));
print render($output);

```

Hope this will help you..
> 1 votes

# Answer
You can use Context module for this purpose. It provides the same functionality as you require.

**Note**: If you don't want to use any extra module, then it can also be done simply through block configuration setting. There are three options to control the block visibility.
> 2 votes

# Answer
There are two things, depending on your requirements. (People finding this question may have different ideas what they want)

## Programmatically controlling which blocks appear on a page.

Create a custom module with hook\_block\_list\_alter(). There you remove all those blocks that you don't want, depending on the current page.

The advantage of this is that you prevent these blocks from being rendered and processed.

## Showing a page without blocks / "decorations".

If you want a page with only the main content, and no sidebars, blocks and stuff, you can create a page callback which prints the page html directly, and then calls drupal\_exit().

You still want to deliver a complete html page, so you need to make sure that your page callback does something like `theme('html', ..)`. This is "homework" for you to figure out :)
> 1 votes

---
Tags: 7, theming
---


title: Complete backup solution

text:
# Question
Title: Complete backup solution
I'm trying to backup my Drupal website (not only database) as complete as possible, because It's in the desired state. The backup should cover actual versions of all modules, themes, database tables, settings, just everything. Now my method is to `zip` everything under `/var/www/` folder and backup the database with Backup migrate module. The restore process is

1. delete everything in /var/www
2. drop database and create it again and set permissions on it
3. unzip my backup to /var/www
4. restore with `Backup migrate` module

Will this method work? Do you know smarter method to make a complete Drupal web backup?

# Answer
Will this work?

Yes

Is there a smarter method?

### Drush + drush make

Drush is a command line tool that you can use for various things, one of them is to create a site. With a drush make file, you can save all of the modules you use (including version and even patches applied to them if needed). Once create you could recreate all of the modules by doing something like this:

```
drush make --no-core --contrib-destination=[path to the contrib folder like sites/all] [path to the make file]

```

You can read more about drush and drush make which has documentation about usage.

Also backup and migrate will or can add a drop syntax, so that it automatically drops tables when restoring the database. So using it, you wont need to wipe out your database completely. If need be, you can truncate it so you wont have to setup permissions again.
> 9 votes

# Answer
Be careful with Backup and Migrate, because:

1. **Backup and Migrate just handles the Database as expected.** But if you have to restore the complete Website, you probably would like to restore the appropriate backend (php-files, themes, modules, etc.), too
2. **Backup and Migrate can back up the Full site, but you can not restore its own full site Backup!** Backup and Migrate says: *"Files were not restored because the archive did not seem to contain a files directory or was in a format that Backup and Migrate couldn't read"* :-( And: *"Backup and Migrate cannot restore the php code of the site for security reasons. You will have to copy the code to the server by hand if you wish to restore the full site."* :-(

Btw: *"Backup and Migrate cannot restore ... **for security reasons**"*. If a hacker has Access to the Admin-Protal, then it's too late to stop the hacker by modules. Therefore Backup and Migrate does not increase the security, but blocks the usual Administration work.

To answer your question: No, Backup and Migrate is no solution for a complete backup (and restore) which can be handled by normal Website Admins without bash skills.
> 1 votes

---
Tags: 7, backups
---


# Question
Title: Tag users in a content field to create user-specific content listings
I'm newish to drupal and it seems like this should be somewhat straightforward or at least possible with views and/or taxonomy.

I have an embedded video content type. I want to tag multiple users in a hidden field (as if they were taxonomy terms). The desired result is that a user can go to a URL like /videos/my-classes and it will list all the videos they are tagged in.

I've been reading the following thread, but there doesn't appear to be any applicable options when I try adding a views relationship. I'm looking for an option like "Video Embed: User" or something. I tried adding a user entity reference to the content type, but that didn't seem to help.

Thread: Display content with Taxonomy on User and Content matching

What I am trying to avoid is having the user go to /videos/username but instead /video/my-videos which displays different content for each user.

I'm not opposed to writing a code snippet for my theme, but it seems like there's a solution to this given the tools I already have.

# Answer
This task can be done in the next way:

1. Download References module
2. Install User Reference module from this package
3. Add User reference field to your content type
4. It the view, that will display videos add a Contextual filter by created earlier user reference field
5. In the filter settings choose "Provide default value" -\> "User ID from logged in user"
> 0 votes

# Answer
It sounds to me that you might be looking for the Entity Reference module, which provides a field type that can reference arbitrary entities. "Users" could be a sample of such entities. This should work to implement the workflow you described in your question, which is something like "you" want to be abe to "tag" selected users for a given video.

However, as per the "*The desired result is that a user can go to a URL like /videos/my-classes and it will list all the videos they are tagged in.*" in your question, you might also (or as an alternative?) want to consider the option where each user can indicate that they think they should be "tagged" for some video. In Drupal you could do this (easily) using the Flag module ... Think of something like a user who can "bookmark" the videos for which they select to do so.
> 0 votes

---
Tags: views, taxonomy-terms, users, entities
---


# Question
Title: Preview option for entity registration form
Is there a way to display preview before submission using Entity Registration?

Similar functionality as there is with node submit option. So that user can make changes if anything is wrong.

# Answer
I have one another option that i have used:

```
function your_Module_name_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'your_form_id') {
       $form['submit']['#attributes'] => array('class' => array('upersubmit'),'onclick' => 'if(!confirm_vil(this.id)){return false;}');
   }

```

}

/\* Js Function in your js file \*/

```
function confirm_vil(val){
    /* Now here you can add popup code to view all data before submit */
}

```

i hope this is help you..
> 1 votes

# Answer
As i know drupal don't have any module for this, you have to create custom module for this. in which you can view all data into popup before submit..
> 0 votes

---
Tags: entities
---


# Question
Title: 504 Gateway Time-out error in batch process
I have submit the custom form using **batch process** in which process I have upload big xml file(min 200MB) and read xml file and inserted xml data in database

but after 30~35 minits batch process display the

> 504 Gateway Time-out error.

Also I have increased **memory size**, **excution time**, **max upload size** and so on.

Please help me..

# Answer
I have find the answer...

Please increase memory limit, excution time and max input time.

**1. File php.ini**

```
memory_limit = 768M
max_execution_time = 3600
max_input_time = 3600

```

OR

**Define in settings.php**

```
<?php
    ini_set('memory_limit ', '768M');
    ini_set('max_execution_time', 3600);
    ini_set('max_input_time', 3600);
?>

```

My problem is solve. :)
> 1 votes

# Answer
Use **Background Process** Module

> This modules takes over the existing Batch API and runs batch jobs in a background process. This means that if you leave the batch page, the jobs continues, and you can return to the progress indicator later.
>
> Batch jobs are delegated to the service host "background\_batch" if defined
> 0 votes

---
Tags: 6, batch-operations
---


# Question
Title: Drupal 7: Two submit buttons and custom field validation
I have a custom user registration form (D7). I added two custom submit buttons inside THEME\_form\_alter

```
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Sign Up')
  );
  $form['actions']['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Sign Up & Take Survey')
  );

```

These render fine and both handle the registration equally well but when submit2 is clicked I want to redirect to a webform survey.

I added the following:

```
function tweakform_user_register_submit($form, &$form_state) {

  if($form_state['values']['op'] == $form_state['values']['submit2']) {
    echo 'Redirect to survey and populate fields with user details';
    exit;
  }

}

```

I refreshed the cache and this function does not seem to be invoked.

Alex

# Answer
> 3 votes
I'd suggest using the #submit property

For example:

```
$form['actions']['submit'] = array(
 '#type' => 'submit',
 '#value' => t('Sign Up')
);
$form['actions']['submit2'] = array(
  '#type' => 'submit',
  '#value' => t('Sign Up & Take Survey')
  '#submit' => array('custom_submit_for_this_button')
);

```

And then:

```
function your_form_name_submit($form, &$form_state) {
  // your logic for first button here; this is auto-called by Drupal
}
function custom_submit_for_this_button($form, &$form_state) {
  // your logic for second button here
}

```

# Answer
> 0 votes
Inside your form submit for submit2 button you should use `redirect` as follows.

```
function your_form_name_submit($form, &$form_state) {
 $form_state['redirect'] = 'path_to_your_webform_survey';
}

```

# Answer
> -1 votes
```
$form['actions']['submit2'] = array(
  '#type' => 'submit',
  '#value' => t('Sign Up & Take Survey'), //the missing line in above example
  '#submit' => array('custom_submit_for_this_button')
);

```

---
Tags: 7, hooks
---


# Question
Title: Ajax pager failure in view after modifying view on hook_views_query_alter
The requirement is for different pages on the website to show different Twitter feeds according to the current page. There is a context (triggered according to the path) that inserts a view block into the footer. A custom module kicks in when the query for the view block is about to be executed. The module does some simple processing to determine what Twitter feed(s) are required to be displayed on the current page.

So, the custom module contains:

```
/**
 * Implementation of hook_views_query_alter
 */
function twitter_feed_selector_views_query_alter(&$view, &$query) {

  if ($view->name == 'tweets') {

    // Some processing...

    $feed = _twitter_feed_lookup($matching_path);
    $view->query->where[1]['conditions'][0]['value'] = $feed;

  }
}

```

However, the view block has a lite pager and Ajax enabled. And when the user clicks on the pager links to see the next/previous page of tweets, no tweets are coming back from the view.

I can't find how to get around this. If I turn off Ajax on the view, all is well, but the whole page is reloaded each time the pager is clicked -- which is way too clunky.

Can anyone suggest a means to make my amendments to the view query work nicely also with the Ajaxed results from the pager?

# Answer
> 1 votes
When the view query is being called *from inside the pager*, the requesting URL is different. It becomes: '/views/ajax'. This URL does not match any that had been specified in my context, so no results were returned.

I solved the problem by checking if the query view is being called within the pager -- i.e. if $\_SERVER\["REQUEST\_URI"\] == '/views/ajax'. If so, then I extract the correct path instead from $\_SERVER\["HTTP\_REFERER"\]. If not, then it's okay to accept the path from $\_SERVER\["REQUEST\_URI"\].

---
Tags: ajax, paging, views
---


# Question
Title: share users or nodes across multiple sites without sharing database
I have one master drupal site that offers basic functionality for users.(it's a shop); and we have some other sites, for example one news site, one marketplace, one job finding service etc. I want every "spin off" site be a separate site, but users sign up once, then login on each subsite without needing to sign up again. and I want to show nodes of subsites at master site in the user profile. which is the best way of sharing users and contents, since domain access module is not a good option, because we are going to produce lots of data and keeping all data in one database is hard. we want to be able to separate any high traffic spin off in the future, but with domain access, all should be at one database. what options do I have for sharing users and contents without sharing database?

* what I mean is someting like stackexchange that there is no need to sign up anytime. is it possible to do that with OpenID or OAUTH etc?

# Answer
> 1 votes
I tried almost every possible scenarios,

The best thing for me was use of Oauth2 server module for master site to act as authentication server and OpenID Connect module for other sites which use out-of-box authentication.

This solution can be done without needing to merge databases, or host sites on same server, or periodic synchronization. the only challenge I have is that authentication server must use **https**, and I'm going to buy certificate for my host.

# Answer
> 0 votes
Check Single Sign On Multiple Domain

> Single Sign On Multiple Domain module allows login to multiple drupal websites from a single website. If you have multiple drupal website installed at either on same server or other server, then you just need to login to one and it will login you to other websites as configured in the configuration page. For this you have to install this module in all website and do required settings.

# Answer
> 0 votes
Not sure about users, Nikhils answer seems ok.

For nodes, you could provide a rss feed using views from the base site, and the use the feeds module on the other sites to import nodes using the content from those feeds, you can set this to run every 30 minutes if you wish.

---
Tags: 7, nodes, users, domain-access
---