# Question
Title: Routing to production and testing Drupal installations on shared hosting account
I am having issues with routing users to different domains on a shared hosting account. Each of these domains are separate Drupal installations with separate databases. `site` is intended to be the production environment, and `site1-test` is where we do our development and testing of content and modules prior to upload to the main site. Also, if it has any impact on this issue, `clean_urls` are enabled.

Here is my file structure

```
+ public_html
   + site1
   + site1-test

```

`site1` should route to www.site1.com (or site1.com) `site1-test` should route to `www.site1.com/site1-test` (or `site1.com/site1-test`)

To me, this should be *fairly* straightforward updating of the .htaccess files.

Here is what I have done so far:

**public\_html/.htaccess**

```
Options +FollowSymLinks
RewriteEngine on
#========================================================================
# FIRST Handle the http requests first before removing the additional url junk
#========================================================================
#rule for site1.com to link to site1 directory
RewriteCond %{HTTP_HOST} ^(www.)?site1.com$
RewriteCond %{REQUEST_URI} !^/site1/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /site1/$1
#rule for site1.com/site1-test to link to site1-test directory
RewriteCond %{HTTP_HOST} ^(www.)?site1.com/site1-test$
RewriteCond %{REQUEST_URI} !^/site1-test/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ /site1-test/$1
#rule for site1.com to link to site1folder directory

#==========================================================
# SECOND Remove the additional url junk once the new url is loaded
#==========================================================
#rule for site1 url rewrite to remove /site1/index.php from the URL
RewriteCond %{HTTP_HOST} ^(www.)?site1.com$
RewriteRule ^(/)?$ site1/index.php
#rule for site1-test url rewrite to remove /site1-test/index.php from the URL
RewriteCond %{HTTP_HOST} ^(www.)?site1-test$
RewriteRule ^(/)?$ site1-test/index.php

```

**public\_html/site1/.htaccess** and **public\_html/site1-test/.htaccess**

```
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  #RewriteRule ^ index.php [L]
  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

  # no changes within <IfModule mod_headers.c> ...

```

**public\_html/site1/sites/default/settings.php**

```
...
$base_url = 'http://www.site1.com';
...

```

**public\_html/site1-test/sites/default/settings.php**

```
...
$base_url = 'http://www.site1.com/site1-test';
...

```

**public\_html/site1-test/sites/default/settings.php**

So, there are multiple issues that I have. With the code listed above, all themes and login information is completely broken when visiting `www.site1.com`. However, visiting `www.site1.com/site1-test` works fine, although there are some issues with the Testing module (cannot run tests from the web interface, though I think this issue is linked to something being wrong in my htaccess file).

If I comment out the base\_url for site1.com (i.e., `//$base_url = 'http://www.site1.com';`) then site1.com works, however all links show up as `http://www.site1.com/site1`, and all navigation after leaving the front page also shows that subdirectory.

Unfortunately I don't have access to the domain registration, but I do not believe that any redirects currently exist there, simply that the domain points to the site1 subdirectory.

# Answer
Most shared hosting plans have a feature called subdomains or addon domains (these features exists in cpanel plans for sure. I m attaching a screenshot from a godaddy hosting plan). You may use this feature to effectively create a new apache virtual host so you dont have to mess with the .htaccess file to do the routing depending on the domain name

Also note that most shared hosting providers do not support overriding many features using the .htaccess file so many on of the options in your .htaccess file may be ignored depending on the apache configuration file (which you usually do not control)

Also note that .htaccess is an Apache concept. If your hosting provider uses another http server (e.g. nginx or IIS) the .htaccess file will be totaly ignored.

Last if you really want to do this with .htaccess (i dont recomend this) make sure you dont miss the query option in any of your cases. Notice the last part here index.php?q=$1 the `?q=$1` part is very important
> 0 votes

---
Tags: 7, .htaccess, uri
---


# Question
Title: Should dependent libraries list all dependencies?
If I have a library called foo and it depends on jquery I will list is a dependency. But what if I have libraries bar and baz that depend on foo and also jquery. Do I only add foo as a dependency or should I also add jquery as well? What is the concensus on this?

# Answer
> 3 votes
In general, a library (or any entity/resource in programming that depends on other entities/resources) should only include dependencies for things that it actually uses.

Given your example, bar and baz should depend on jQuery if they use jQuery functions directly. If, however, they only use functions that are provided by foo (which, in turn, uses jQuery), then bar and baz should not depend on jQuery.

Here's another way to look at it: in the future, if foo no longer needs jQuery, and you remove jQuery as a dependency from foo, do bar and baz break as a result? If they break, then they should have had a direct dependency on jQuery. If they don't break (because all of the jQuery dependency is encapsulated in foo), then they don't need a dependency.

---
Tags: 8, theming
---


title: Show only latest updated nodes

text:
# Question
Title: Show only latest updated nodes
I'm getting data from a source. In the following example, there is no data in drupal database and there are 4 source "nodes" that I will import. The content type is set to create revisions.

So, **first time** I import data this is what I get:

The update date is `22/11/2015 12:00` for all 4 nodes and views has to show them all.

After half an hour, I make another import from the same source but, data 2 was deleted, so, It will not be imported.

I get this:

At drupal db (green block), you can see that the update date was not changed, only the other 3 nodes were changed.

Is some way (that I don't know how), I need my view to show only nodes 1, 3 and 4, basically, the latest that were updated.

Important to note that, no matter how many nodes I import, the update date will always be the same. Also, I can add fields to my content type and set values when the nodes are first imported or updated and try to use that as filters.

How can I implement this with views? Or, if not possible with views, any other suggestion?

# Answer
> 0 votes
Drupal views support sorting with timestamps by default. You need to install the Date module to add support for date sorting in views. I also recommend that you import the data from your source with the feeds module and use another date field for your date NOT the property "updated" which is a timestamp.

Another solution is to convert the date from your source to timestamp as you import it. The tamper add on module for feeds may help you do this.

---
Tags: views
---


# Question
Title: allow user to sign up for different role
I am new to drupal, so any help would be appreciated in advanced. My requirements are as follow.

1 happened in signed in user environment. 1 :" there must be groups. and they will be assigned under one user (role: manager) only he can manage the user (create,update,read and delete)" - need to be solved

*** There will be a user with (admin permission) will be able to manage groups including manager *** solved\**

in home page : guest environment 2: "User must be able to choose which group they wanna go in: But they might need to be approved by group manager or admin before they can use their account"

for 1: i found some modules like organic group/sub-user

for 2 : i found some modules like multiple registration/ advanced registration (i don't think that gonna make it)

So please, Drupal masters, if you happens to know how to full fill those requirement with drupa stuff like Field, views or whatever. Do let me know. THANKS!!

# Answer
Organic groups can do it however it requires a legthy process form the user. Eg. a manager must create a group (the creator of the group is also the manager of it by default). Then users that wish to join the group must go to the page of the group and request to subscribe. The good thing with og is that it also supports the concept of og content. That is you may create a content type and denote it as og content of a specific group. Then only the members of this group will have permissions to a node of this content type.

Another option is to use a plain old field in the user registration form that will be a list with the desired role. You can do this by going to the user configuration page. Then you can add a rule to automatically grant the requested role to every new user (a simple value comparison in rules) or create a manager view so the manager can see which user wants a role and grant it. The vbo module can help the manager in the later case.
> 0 votes

---
Tags: organic-groups, users
---


# Question
Title: Views: two filters on one term reference (=wrong join)
Strange effect in my view:

I have a list of nodes. On of the fields is a term reference.

* I want the list to only show nodes related to 3 specific terms. that's one filter.
* I want the user to optionally select one of these 3 terms. that's another (exposed) filter.

It almost seems to work. But if the user selects that term from filter 2, in the sql, the first filter is rewritten to explicitly deny that term. zero results. In an almost duplicate display of that view, the same happens, but with one other term (of the same three).

So without selecting anything in filter 2, the sql is:

```
SELECT DISTINCT bla
FROM
{node} node
...
INNER JOIN {field_data_field_publication_cat} field_data_field_publication_cat ON node.nid = field_data_field_publication_cat.entity_id AND (field_data_field_publication_cat.entity_type = 'node' AND field_data_field_publication_cat.deleted = '0')
...
WHERE (( (node.status = '1') AND (node.type IN  ('publication')) AND (field_data_field_publication_cat.field_publication_cat_tid IN  ('48', '50', '49')) ))
ORDER BY ... LIMIT .. OFFSET ..

```

and as soon as I select one of the terms in filter two, it reads

```
SELECT DISTINCT bla
FROM
{node} node
...
INNER JOIN {field_data_field_publication_cat} field_data_field_publication_cat ON node.nid = field_data_field_publication_cat.entity_id AND (field_data_field_publication_cat.entity_type = 'node' AND field_data_field_publication_cat.deleted = '0')
LEFT JOIN {field_data_field_publication_cat} field_data_field_publication_cat2 ON node.nid = field_data_field_publication_cat2.entity_id AND field_data_field_publication_cat2.field_publication_cat_tid != '48'
...
WHERE (( (node.status = '1') AND (node.type IN  ('publication')) AND (field_data_field_publication_cat.field_publication_cat_tid = '48') AND (field_data_field_publication_cat2.field_publication_cat_tid IN  ('48', '50', '49')) ))
ORDER BY ... LIMIT .. OFFSET ..

```

The number 48 in the second query, second join seems fairly random. If I remove and reattach the filter it seems to change.

cat2 is only a left join, but in the where clause, the number 48 is required again. Thats why I get zero results.

What's going on ?

# Answer
Notice that filters are by default added in AND logic. You probably want OR logic so the one filter does not affect the other.

Of course if the two fields are not relevant at all you should have used different vocabularies (e.g. terms and someothercategory)and not only terms
> 0 votes

---
Tags: views
---


# Question
Title: SVG icons do not show up when remotely connected
I have installed Drupal 8 in my linux machine for testing. Everything seems fine initially when I'm accessing D8 from my local machine.

However when I tried to access it via another machine on the same network, the svg icons do not show up. After further investigation using firefox element inspect, I realized some of the request urls are from 192.168.1.18, which is my linux machine IP, while the rest are either from localhost or 127.0.0.1.

Am I missing any configuration here?

Thanks

# Answer
> 0 votes
> I realized some of the request urls are from 192.168.1.18, which is my linux machine IP, while the rest are either from localhost or 127.0.0.1.

I assume you mean "request URLs are **to** 192.168.1.18". This is normal Drupal behavior because some file asset URLs are cached in the HTML output.

Clear the site caches.

Notice you can set $settings\['file\_public\_base\_url'\] in settings.php which will make the asset URLs consistent.

# Answer
> 0 votes
Make sure that in your code you dont reference the icon like http://127.0.0.1/sites/default/somepath/youricon.svg but you re using a relative path instead like sites/default/somepath/youricon.svg.

---
Tags: 8
---


title: User Files Download w/o Upload

text:
# Question
Title: User Files Download w/o Upload
I am trying to figure out a clean way to do this in drupal 7 but can't find a clean way.

Problem: A user needs to be able to download files without the need to upload any files. Files are placed in private dir or uploaded by admin.

Scenario: A file will be placed in /private/userx directory by non-drupal way (cp file), a user needs access to download the files in own dir?

Requirements: 1. A user doesn't upload files. 2. A user can download his subdir files only. 3. A user can't download other users files.

I searched for solution but none found. I tried EntityForm file but that requires user upload and admin can't upload for a user as per other discussions.

One option is to place the file in a private dir and insert file object in the database with userid, but couldn't find example how to do that.

Any insight will be great help.

# Answer
I would use the organic groups module. The idea is to create a content type lets say "userprivatedir" make this a og group and a allow users to create one or more nodes of this type. By default the creator of a og group is the owner of this group. Then i would create another content type lets say "userfile" and make this a og content. Then you may configure og so only the members of the group (i.e. the user that created it has access into it). The "userfile" content type should have a file field that stores files in the drupal private filesystem (so files are not accessible just by hotlinking but only through their node page.

Also if you dont want user to be able to upload at his own "userprivatedir" (i.e. og group node) then create the group node by another manager user and then add only this user (or maybe some more that should see this directory's files) to this node group so they have access.
> 0 votes

---
Tags: files
---


# Question
Title: How to get the nodeid in node_grants so that it works in a view?
I am exploring the node\_grants and node\_access\_records with the following objective:

I want to be able to hide nodes where the current logged-in user is not 'friends' with the node author. The node author selects if they want to limit it to friends or not with a boolean field. Here, the subtlety is that there are a few views which list nodes on my site, so I want it to work for views too.

I am using drupal 7, user relationships for the 'friends' relationship and here is my node\_grants code. How do I get the node id, especially in the context of views?

```
function mymod_access_node_grants($account, $op) {
// Grants all rights if the author
$grants['mymod_access_author'] = array($account->uid);

    $value_friends = field_get_items('node', $node, 'field_friends_only');
    $value_friends = $value_friends[0]["value"];
    $value_friends = 1;

    if ( $value_friends == NULL) {
        $value_friends = 0;
    }
    if ($value_friends == 0) {
        $grants['mymod_access_public'] = array(1);
        $grants['mymod_access_friends'] = array(1);
        $grants['mymod_access_notfriends'] = array(1);

    } else if ($value_friends == 1)  {
        //if node is for friends only, then check if relationship exists...
        $current_user_uid = $account->uid;
        $node_author_uid = $node->uid;

        // Set up the parameters
        $params = array('between' => array($current_user_uid, $node_author_uid));

        // Get the relationships
        $relationships = user_relationships_load($params);

        if ($relationships) {
            $grants['mymod_access_public'] = array(2);
            $grants['mymod_access_friends'] = array(2);
            $grants['mymod_access_notfriends'] = array(2);
        } else {
            $grants['mymod_access_public'] = array(3);
            $grants['mymod_access_friends'] = array(3);
            $grants['mymod_access_notfriends'] = array(3);
        }
    } else {
    }
}

return $grants;
}

```
* PS: although I have $node in my code, it is empty at the moment!

# Answer
You actually need to implement two hooks:

It's the second hook that gets a node object, not the first. Keep in mind that you need to implement both the hooks.

As for `hook_node_access()`, this hook is called when a node is fully loaded, and it not called for node listings, as reported in the documentation.

> Also note that this function isn't called for node listings (e.g., RSS feeds, the default home page at path 'node', a recent content block, etc.) See Node access rights for a full explanation.

As for views, a view doesn't full load a node, but executes a SQL query to get node data. merlinofchaos clearly states it in Views does not respect hook\_node\_access.

> `hook_node_access()` is something that is run after a node is fully loaded. Since Views is loading nodes via query, you can't get the query to respect it unless you also use `hook_db_rewrite_sql()` which is what Views hooks into.
>
> This is not true of just Views, but *any* query that loads nodes. For example, the default Drupal front page will not respect `hook_node_access()` that isn't paired with `hook_db_rewrite_sql()` any better.
>
> `hook_node_grants()` and `hook_node_access_records()` will be used, however, if you set "Disable SQL rewriting" then you are specifically skipping that stuff.

Notice that `hook_db_rewrite_sql()` is not used from Drupal 7 and higher, though. The equivalent for Drupal 7 and higher is `hook_query_alter()`.
> 1 votes

# Answer
I think that the hook you must use in your case is hook\_node\_access https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_access/7 which is fired every time a node is requested and thus the $node variable is not provided by the system and is not empty
> 0 votes

---
Tags: views
---


# Question
Title: Pre-process to change the name of a file field in node
I have a file field in a node and I would like all instances of this field to have a different display name.

I use the file field to upload images that users can download - e.g. flower.jpg, horse.jpg.

Instead of the field displaying " flower.jpg",I want it do display the text "download".

The machine name of my field is "field\_source" and the name of my theme is " kickstart". The content type is " resource".

What would a pre-process function in my template.php look like to do this?

This is as far as i get:

```
function kickstart_preprocess_node(&$vars){
  if($vars['type'] == 'resources'){
    $vars['content']['field-source']['#title'] = 'download';
  }
}

```

Thanks!

# Answer
if you only want to change the label maybe the module string overrides is your best option https://www.drupal.org/project/stringoverrides

you can also edit your settings.php file to change the label https://www.drupal.org/node/522036
> 0 votes

# Answer
The easiest programmatic way to do this is to override the field template file for your specific field.

1. Create a file named `field--field-source.tpl.php` (assuming that the machine name of your field is field\_source).
2. Copy and paste the code for the default Drupal field template file (which is called `field.tpl.php`, and is very well documented in terms of the variables it receives). Customize it to your needs.

Use the `dpm()` function (enable `Devel`) to troubleshoot the variables that the new template file receives.

Information about Drupal's template files.
> 0 votes

---
Tags: nodes, theming
---


# Question
Title: How to hide node webform programatically?
I want to make hide WEBFORM particular content type programmatically in default / custom mode. Any help will be appreciable.

# Answer
> 0 votes
Got it after checking field module in core.

```
$bundle_settings = field_bundle_settings('node', $bundle);
  $viewmode = 'custom';
  $name = 'webform';
  $bundle_settings['extra_fields']['display']['webform']['custom'] = array(
    'weight' => 1,
    'visible' => TRUE / FALSE,
  );
  field_bundle_settings('node', $bundle, $bundle_settings);

```

This will enable/disable field in specified view mode

# Answer
> 1 votes
Try implementing hook\_node\_view.Then you can put your condition on `$node->type`, access the webform with `$node->webform` and use `$view_mode` to load the current view mode.

# Answer
> 1 votes
In your custom module disable it with :

```
function yourmodule_node_view($node, $view_mode){
    // if you want exclude you content type
    if($node->type =='yourcontenttype' && $view_mode=='yourdesireviewmode'){
    $node->content['webform']['enabled'] = FALSE;
  }
}

```

for more details take look at hook\_node\_view and webform\_node\_view.

# Answer
> 0 votes
This handy module will do it as well and will give you some nice config options: https://www.drupal.org/project/rabbit\_hole

From the project page: This works by providing multiple options to control what should happen when the entity is being viewed at its own page. You have the ability to

Deliver an access denied page. Deliver a page not found page. Issue a page redirect to any path or external url. Or simply display the entity (regular behavior).

---
Tags: 7, webforms, nodes
---


# Question
Title: Find the total amount of multiple products of the same type - Commerce
I've created a rule that sends a thank you email to anyone who donates less-than-or-equal-to a certain amount (which works perfectly), but I cannot figure out how to pull out the total $ amount of all donations on the order and include it in the email.

If it were guaranteed there would only ever be a single donation line item the issue would be simple. However, there is no guarantee there won't be more than one on a single order, and there will usually be at least one other line item of a different product type included in the order. I've searched, but cannot figure out how to, for example, calculate the total donation amount for an order that has 2 donation line items of $10 & $20, plus one or more other line items of a different product type, then put the donation total into the thank you email that gets sent out.

Any / all help will be much appreciated!

# Answer
Use commerce\_donate module to get donation then this field use in your rules

1. Create a rule add events in Rule
2. Add condition entity has a field (your donation field)
3. Add variables in this you can use php field to get total amount of donation.
4. Add action in email section use token of variables

I am not already try this but hopefully this may work.
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: URL & Geomap Lat/Lon fields are not showing in Target List during mapping in Feed?
I am using the Feeds module. All the fields from node are showing in target list except URL field Type and Geomap Latitude and Longitude Fields. I can't figure out how to map values from CSV to them.

Any suggestions?

# Answer
Finally I was able to import the data for lat/lon values from CSV file to geoField field lat/lon.

I required to use a patch in "geofield.feeds.inc" file in GeoField module which solves this issue.

You can get this patch from under mentioned URL:

GeoFiled Feed Patch File

Hope this patch will help more developers as it does for me too.
> 0 votes

---
Tags: feeds
---


title: Form_set_error for array of fields

text:
# Question
Title: Form_set_error for array of fields
I got below code in form\_validation

```
$form_state['values']['field_address'][LANGUAGE_NONE][0][postal_code];

```

I've tried below tricks but it didn't make red color in textbox.

```
form_set_error('field_address][postal_code', 'error');
form_set_error('field_address[und][0][postal_code', 'error');
form_set_error("field_address[und][0]['postal_code']", 'error');
form_set_error('field_address[LANGUAGE_NONE][0][postal_code', 'error');

```

# Answer
> 0 votes
Your `form_set_error` like that

```
form_set_error('field_address][postal_code', t('enter postal code'.));

```

---
Tags: forms
---


# Question
Title: db_select with mysql reserved word in the statement
This seems to be fairly easy question, but I could not find simple answer to it.

Using `db_select` when database column happens to be a reserved mysql word (`when` in this case) results in an error.

Table:

```
+-----------------------------------+------------+--------+
|               sort_id             |    when    |  user  |
+-----------------------------------+------------+--------+
| 1                                 | 1448270950 |    123 |
| 3                                 | 1448270955 |     12 |
| 50                                | 1448270959 |     45 |
+-----------------------------------+------------+--------+

```

Standard drupal7 select using `db_select`:

```
$query = db_select('my_table', 'd')
    ->fields('d', array('sort_id', 'when', 'user'))
    ->condition('user', $uid)
    ->execute();

```

BUT column named `when` is the problem here.

I know I can write the query using plain SQL:

```
db_query("SELECT sort_id, user, `when` FROM {naughty_table} WHERE user = :user", array(":user" => $user_id));

```

But there **should** be a way to solve this using regular db\_select?

**IMPORTANT:**

I have tried to use backticks like this:

```
$query = db_select('my_table', 'd')
    ->fields('d', array('sort_id', '`when`', 'user'))
    ->condition('user', '123')
    ->condition('`when`', '1448270950')
    ->execute();

```

But backticking like this does not seem to work whatsoever.

# Answer
You can use `where()` instead:

```
$query = db_select('my_table', 'd')
  ->fields('d', array('sort_id', '`when`', 'user'))
  ->condition('user', '123')
  ->where('`when` = :timestamp', array(':timestamp' => 1448160590))
  ->execute();

```

Produces:

```
SELECT d.sort_id AS sort_id, d.when AS when, d.user AS user
FROM
{my_table} d
WHERE  (user = :db_condition_placeholder_0) AND (`when` = :timestamp)

```
> 4 votes

---
Tags: 7, database
---


# Question
Title: address field hides if country is changed
I have used Address field module for storing user address. Also I have used Customer Profile Type UI for adding customer profile. I have added customer profile field in the user page by adding customer profile field in account settings. In the customer profile type I have added address field, name field and etc..

In my case Check box will be available on clicking checkbox an ajax callback happens which renders the customer profile form which has address field and name, for now no problem occurs. In address field all country are available and showing site default county as default one. **If user change the country ajax call happens and address field hides**. Please help me.

# Answer
> 2 votes
It works as designed. For some countries there is no need to enter ZIP code.

You can change this behavior by implementing this alter in your custom module:

```
/**
 * Allows modules to alter the predefined address formats.
 *
 * @param $address_formats
 *   The array of all predefined address formats.
 *
 * @see addressfield_get_address_format()
 */
function hook_addressfield_address_formats_alter(&$address_formats) {
  $address_formats['AF']['required_fields'] = array('postal_code');
  $address_formats['AF']['used_fields'] = array('administrative_area', 'postal_code');
}

```

Change required\_fields and used\_fields as desired. More code you can find in this file:

```
addressfield/addressfield.address_formats.inc

```

# Answer
> 0 votes
It is possible by using these modules :

Conditional Fields

> Define dependencies between fields based on their states and values.
>
> Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content

Field Conditional States

> With the Field Conditional State module you can change the state of any supported fields form element depending on the content of other fields. This is done by providing an UI for Drupal's States API. All the changes made to a form by FCS (Field Conditional States) utilize only the States API and therefore are clientside only

# Answer
> 0 votes
Finding the main reason of this issue need some debuging but I as you wanted I suggest you a solution that bypass this issue:
In your Custom JS file handle it by custom JS,provide a change handler and on change if country JQUERY event, show Zip Code field. something like

First Try it Firebug Console and when worked put it JS file
**\< Change The page class and element ID according your HTML elemets \>**

```
(function($){
$('.page-review #edit-customer-profile-shipping-commerce-customer-address-und-0-country').on('change',function(){
     $('.page-review #edit-customer-profile-shipping-commerce-customer-address-und-0-postal-code--2').show();
});
})(jQuery);

```

---
Tags: 7, ajax, users, entities
---


# Question
Title: Inline Entity Form - How to change label for the EDIT button and REMOVE button
I try to modify the 'Edit' and 'Remove' label on the buttons displayed in the IEF table. I can modify the 'Add new node' buttons with the code bellow

```
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'CONTENTTYPE_node_form') {
    /*
    * Modify the Add node button when it's the first one
    */
    $form['MY_FIELD']['und']['form']['actions']['ief_add_save']['#value'] = t('CUSTOM TEXT');
    /*
    * Modify the Add node button when there is at least one node
    */
    $form['MY_FIELD']['und']['actions']['ief_add']['#value'] = t('CUSTOM TEXT');
  }
}

```

But I can't make it work for the Edit or Remove buttons

For the Edit button, I tried to add in this function:

```
$form['MY_FIELD']['und']['form']['actions']['ief_entity_edit']['#value'] = t('CUSTOM TEXT');

```

Doesn't work

```
$form['MY_FIELD']['und']['actions']['ief_entity_edit']['#value'] = t('CUSTOM TEXT');

```

Doesn't work either

Any idea ?

# Answer
Try form after build. it may give you solution.

```
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'CONTENTTYPE_node_form') {
    /*
    * Modify the Add node button when it's the first one
    */
    $form['MY_FIELD']['und']['form']['actions']['ief_add_save']['#value'] = t('CUSTOM TEXT');
    /*
    * Modify the Add node button when there is at least one node
    */
    $form['MY_FIELD']['und']['actions']['ief_add']['#value'] = t('CUSTOM TEXT');
    $form['#after_build'][] = 'yourmodulename_after_build'; //Calls function
  }
}

```

Use dpm($form) or print\_r($form) to find the edit button id
> 1 votes

---
Tags: entities
---


title: Drupal views_get_view in custom service

text:
# Question
Title: Drupal views_get_view in custom service
I created a custom service with mymodule\_services\_resources and I'm calling a function to return some items. This function inside is calling a view with views\_get\_view. The problem is always return an empty array.

If tested the same code somewhere else it shows the right results, but it does not work with services. I have something like this:

```
$view = views_get_view('the_view');
$view->set_display('default');
$args = array("my_param");
$view->set_arguments($args);
$view->pre_execute();
$view->execute();
$view->result; //empty array in the WS

```

I tried loading the admin user ($user = user\_load(1); ) before calling the view but I had the same results.

Is there something I should add, change or remove in order I can get the results of a view calling service endpoint?

Thanks!

# Answer
the module services\_views will help you expose the view as a resource in two different ways

It has currently two features:

* Create view based resource creating Services display in a view
* Execute any view of the system via views resource call
> 0 votes

---
Tags: views, services
---


title: URL for Created Services View?

text:
# Question
Title: URL for Created Services View?
Apologies for the newb question, but: Is there a way to see the entire URL of a Services View I've created? I know it lets me name the path, however when I navigate to the URL, I get "View not found" (though the Views preview shows perfectly). I keep thinking maybe I'm just typing it in wrong? Right now, I'm navigating to:

http://domainnamehere.com/endpointname/views/viewname

Thanks all.

# Answer
the right url will like domain/endpoint/services\_url If you need to get any view the url will be like

domain/endpoint/viewname?display\_id=block\_id

More details found here
> 1 votes

---
Tags: 7, views, services
---


# Question
Title: "An AJAX HTTP error occurred.HTTP Result Code: 200"
I'm new to Drupal, and I'm working with a Drupal site that someone else wrote. From the admin menu, when I go to Structure -\> Pages -\> Edit Content -\> Gear Menu -\> Edit (or Settings), Drupal throws up this error:

> "An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /panels/ajax/editor/edit-pane/panel\_context%3Apage-join\_step\_two%3Apage\_join\_step\_two\_panel\_context/4 \[...\] RESPONSE = nullnullnullnullnullnullnullnullfalseCancelled: Error bad character content for element 'data\_key'***_*\__*_*\__*_***\_nullnullnullfalsenullnull"

The code is also inserting the line

> "RESPONSE = nullnullnullnullnullnullnullnullfalseCancelled: Error bad character content for element 'data\_key' ***_*\__*_*\__*_*_** nullnullnullfalsenullnull"

at the bottom of every page.

I know that Firebug can cause the Ajax HTTP 200 error, but I don't have it installed. I've spent hours looking through help pages for this error, and nothing has worked. Can you help? Thanks!

# Answer
> 0 votes
we need to uncomment .htaccess file in php\_value auto\_append\_file none may be it work. in ajax return value must be defined.if not exist show this kind of error.clear cache. one other solution if you working on the local you need to disable newest module than check it\[first you need to take DB backup\].

# Answer
> 0 votes
Ajax HTTP 200 error is generic error and there is not enough info to properly solve it.

You'll need to:

```
grep -r "find in files" .

```

in the code base the string `data_key` (or whatever is printed) and can then debug from there.

# Answer
> 0 votes
* Just disable recently enabled module. or
* May be this error comes to the jQuery module 1.8, not come in 1.7 so check it updated or not.
* Every module start with `<?php`. just check this line.

This seems to have occurred because of a `Javascript` conflict with some other module or theme.

Many users solved the issue by doing the following;

* Removing the Drupal for Firebug addon (This did the trick for a majority of the users who reported the issue).
* Disabling Firebug.
* Flushing the theme's cache.
* Uninstalling Jquery UI and Jquery Update modules.
* Removing the Twitter Profile module solved the issue for a small number of users.
* Disabling the Theme Developer module solved the issues for a user.

# Answer
> 0 votes
> Error bad character content for element

means there is a validation error in your XML while parsing the file or response.

This could be related to some external service or custom module breaking Drupal instance.

The problem can be tracked by looking for some specifics in the database, e.g.:

```
drush sql-dump --ordered-dump | grep data_key

```

---
Tags: ajax, http-request
---


# Question
Title: Drupal admin links broken for site when using WAMP (e.g. localhost/test2/admin/content)
I decided to try out the newly launched Drupal 8. After resolving some issues I finally got the installer up and running (using WAMP), and arrived onto clean homepage of my test site.

the problem here is that clicking on any Admin menu links at the top of the page takes me to a Page Not Found... Anyone know if this has been reported among other users and if there is a fix for this?

# Answer
> 0 votes
Thank you to @kenorb for supplying the answer that resolved the issue involving WAMP, Drupal 8.0.0 and having the admin menu links break when clicking on them.

The solution is to uncomment `RewriteBase` line in `.htaccess` file and setting it to `/test2` which is used as my base URL.

---
Tags: 8, uri
---


# Question
Title: Hosting Multiple Domains seamlessly with same site code, theme, modules, data etc. not a multisites situation!
I would like to use D7 to support two domains with same code, themes, modules and even database and content, completely transparent to the end-user.

So, user of oxustech.com would see only oxustech.com and user of oxustechnolgies.com would see only oxustechecholgies.com (not be redirected to oxustech.com).

We don't want to use forwarding/frame forwarding. because frame forwarding will hide the full url and will show every url as oxustechnologies.com only.

The site is under shared hosting and we don't have enough permission to change the Apache setting.

Pointing oxustechnologies.com to same htdocs didn't work.

# Answer
> 0 votes
This has worked for me in the past. Given the following assumptions:

* I assume the server is already configured to direct requests for the domain oxustech.com to the correct site (meaning that this is already working for you)
* I assume Drupal is finding for your site's `settings.php` file in the directory `/sites/oxustech.com/settings.php`
* I assume you want to make requests for the domain oxustechnologies.com to show the SAME site (same database) as oxustech.com, but displaying the domain oxustechnologies.com as the base URL for all pages accessed through this requests.

IF this is the case, this has worked for me. Try this:

1. In the `/sites` directory, rename the file `example.sites.php` to `sites.php`
2. Add the following line at the end: `$sites['oxustechnologies.com'] = 'oxustech.com';`

This will effectively tell Drupal that oxustechnologies.com is an "alias" of oxustech.com, will use all settings (including the database) for oxustech.com. It will also always display oxsutechnologies.com as the base URL when you navigate inside the site. But people who access the site through the name oxustech.com will continue to see that as the base URL.

---
Tags: 7, multi-sites, domain-access, configuration
---


# Question
Title: Not able to import images using feed image grabber module in content image field
I am using Feed and Feed Image grabber module for importing data form non Drupal site to my Drupal Site. All fields are successfully imported except image field, I have checked all the steps to FIG module configuration but with no success.

I have also tried for new content type but again no success. My CSV file have following data Title,Description,image Test1, testdescription,https://s3.amazonaws.com/brewerydbapi/brewery/snQlvg/upload\_qMSc0A-medium.png

When file imports, only first two columns data saved not image and also no error shows in logs also.

Please confirm whether we can use external links or not?

Any suggestions?

# Answer
Finally with a struggle for more than a day, I finally get succeeded in importing images in Drupal Content type.

I used Feed Image Grabber Module with feed but not works for me might be my image path is from external server.

Then I used Media, File Entity and Media Feeds module which gives me ability to import images from external URL too.

1. After all the above modules get enabled.
2. I have added one more mapping "source-\>target" in my Feeds Importer under Mappings and Select "Target Field" appended with "(media\_internet)(field\_image)" and then save.
3. Then upload CSV file and finally my images start getting saved in image field.

Hope this will help someone.
> 2 votes

---
Tags: media, feeds
---


# Question
Title: How do I change the base URL to use a more user-friendly domain?
I want to change my domain name from reallylongandnotuserfriendly.example.com to you.example.com.

Is there a setting that could expose these change to the public, without actually changing the real domain name?

# Answer
> 2 votes
You could create a Drupal alias as follows:

1. In the *sites* directory, find and rename the example.sites.php file to sites.php
2. Add the following line

```
$sites['you.example.com'] = 'name_of_the_directory_where_your_settings.php_is';

```

In your case, the settings.php file is likely to be inside *sites* in a directory called *reallylongandnotuserfriendly.example.com*, which means the line would be:

```
$site['you.example.com'] = 'reallylongandnotuserfriendly.example.com';

```

Just be sure that you configure your server to point you.example.com to your base Drupal installation.

# Answer
> 0 votes
1. Open the setting.php file
2. Find `$base_url` in that file
3. Change the value of `$base_url`

change the file permissions for that file, since by default it is a read-only file.

---
Tags: uri
---


title: Field Info API as REST

text:
# Question
Title: Field Info API as REST
We would like to get label for the field.

As per previous question: How do I get a field label by the field name?

But I need to get this through the REST API of Drupal.

Could anyone please suggest what should be the approach to use the Field API from as REST service.

# Answer
> 0 votes
Simply you need to create a custom resource as described here.

In the call back put the piece of code answered here

taking args int he resource, But I suggest using field\_info\_field as it only takes the field name and returns all details as an array that you could choose what you need to return

---
Tags: entities, 8
---


# Question
Title: Custom line item types without a product reference field
Let me start by saying I am aware of this module: https://www.drupal.org/project/commerce\_custom\_product

This module works great for custom line item types that need to reference a product, however (correct me if I am wrong) this module can't be used to create custom line item types that do NOT reference a product.

I need a custom line item type, that doesn't reference a product. Which lead to the discovery of this:

http://cgit.drupalcode.org/commerce\_examples/tree/line\_item\_example/line\_item\_example.module

Utilizing `hook_commerce_line_item_type_info()` I am able to successfully create a custom line item type, and have it automatically come with the Unit and Total price fields automatically.

All is well so far...

Now if I use the Drupal UI to add a custom field (e.g. an entity reference field, not a product reference field) to this custom line item type, I am able to do this without issue. I can add as many fields as I want.

Now for the problem...

However, when I use the admin order form and try to manually add this custom line item type to an order, the custom field(s) don't show up in the form.

I see from the documentation that I could implement the `configuration`, `add_form` and `add_form_submit` callbacks. But I figured any fields added through the UI would automatically show up on the form(s).

What is going on here? Must I implement the form code-side for all fields on the custom entity type?

# Answer
A line item **must** have a product associated with it. Rules, Commerce Cart, and Commerce Shipping all depend on having the `commerce_product` field on a line item object.
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: Custom Profile Type and UPS Shipping Service
I have an issue that I have been wrestling with for a few months now. I have a B2B site that needs a separate "Drop-shipping" shipping address field from the default shipping address that comes with commerce shipping. The fields need to be different because the client wants the default shipping address field to be constrained to only items in the users address book (controlled by the client, not the customer and created by the site admin when adding new registered users) but allow the second "Drop-shipping" added field to be an editable address form for drop-shipped addresses.

So, using the module "Customer Profile Type UI" I created the "Drop-shipping Information" profile type. Using "Checkout Pages" module I created a new page named "Drop-shipping Information" positioned before the checkout page, with a drop-shipping check-box. It is obviously the first page the customer will see when entering the check-out process, and before the checkout page, so that I can capture a Boolean value that will drive which check-out pane ("Drop-shipping Information" or just "Shipping Information" address fields) are shown on the checkout page.Then I use rules and "Change pane properties" to disable the "Shipping Information" pane if the user has selected "Drop-shipping" on the first page, and vice-verse if not. All of that works properly.

The problem is, when "drop-shipping is selected and a valid address provided, when moving from the checkout page to the shipping services page (with UPS enabled and tested to return rates), it returns the rates for the "Shipping Information" address, and not the "Drop-shipping Information" address.

I realize that rules may only be hiding the default "Shipping Information address form (which is including a default shipping address from the customers account profile) ... but how do it make it use the address in the "Drop-shipping Information" address form instead?

Not sure what I am doing wrong, and I see no configuration options to change the behavior. Can someone tell me what I might be missing or perhaps provide an alternate method (that doesn't require custom coding) after reading the details of my requirements above? Either way, you should know that I am not a developer, and could use at least some mid-level instruction on what I have missed or need to do.

Thanks in advance for any serious help. :)

# Answer
Commerce UPS calls `commerce_physical_order_shipping_field_name($order)` to determine what field holds the shipping profile for a given order. That means you can then use Commerce Physical's `hook_commerce_physical_order_shipping_field_name_alter()` to specify a per-order shipping profile field.
> 1 votes

---
Tags: commerce
---


# Question
Title: Forcing together line items of the same unit type in Rooms and Commerce
I am using Rooms and Commerce together as a booking system. One thing that bothers me is that it's possible for a customer to book let's say 50 pairs of roller skates, but Commerce will render each pair of roller skates as its own line item, which becomes insane as you have a long list of roller skate bookings when it could just print 50 x Roller Skates instead. Is there a way to force Rooms to recognize that items of the same unit type should be counted as several instances of one booking instead of several separate bookings?

Alternatively, does someone have a better idea of creating an equipment booking system that has checkout and payment integration? I also need the possibility to give discounts for multi-day bookings.

# Answer
When editing the field display formatter for the product reference, there is an option you can select to combine like products in the cart:

If that's selected, then you can dig a bit deeper by looking at `commerce_cart_product_add()`. The logic to reckon a combination starts about a third of the function down. The biggest thing here is the comparison properties. Commerce uses at least two fields initially to determine if a product is a "like product": `type` and `commerce_product`. Then, it will add any fields that are exposed to the add to cart form, and finally you can then view or alter these fields by using `hook_commerce_cart_product_comparison_properties_alter()`.

Effectively, it won't allow any products to be combined that do not sure the same SKU or unique properties that identify it.
> 0 votes

---
Tags: 7, commerce, bookings
---


# Question
Title: How do I get the MIME type of a file basing on its content and not its extension?
I want to get the exact MIME type basing on the file content, not its extension. I have used PHP methods and the API exposed by a module, but they return the MIME type basing on the file extension.

How do I get the MIME type from the file content?

# Answer
Suppose you have the file binary source sent in a post request **JSON** encoded or any encoding method you could get the MIME type like in the following piece of code

```
$data = base64_decode(trim($_REQUEST['file']));
$finfo = finfo_open();
$mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
finfo_close($finfo);
// get file type png. jpg
$ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';

```

**Hint**:Its better to send the file mime type in the request as encoding and decoding may cause not get the MIME type.

Using **file\_get\_contents**

```
$buffer = file_get_contents($url);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$ext = $finfo->buffer($buffer);

```

More information found here

**Save** the file using file\_save\_data to be a managed file and you could then use it as a field in any entity
> 3 votes

# Answer
You can easily get the MIME type of a file using mime\_content\_type() function.

```
$mime_type = mime_content_type($path_to_the_file);

```

I've just tested it on my local machine; placed a `test.pdf` file in my home folder and renamed it giving it no and an incorrect extension. In both cases I got the right MIME type:

> ```
> $ ls
> test.pdf
>
> $ drush eval 'var_dump(mime_content_type("/home/elin/test.pdf"))'
> string(15) "application/pdf"
>
> $ mv test.pdf test
> $ drush eval 'var_dump(mime_content_type("/home/elin/test"))'
> string(15) "application/pdf"
>
> $ mv test test.jpg
> $ drush eval 'var_dump(mime_content_type("/home/elin/test.jpg"))'
> string(15) "application/pdf"
>
> $ mv test.jpg test.png
> $ drush eval 'var_dump(mime_content_type("/home/elin/test.png"))'
> string(15) "application/pdf"
>
> ```
> 3 votes

---
Tags: files
---


title: Content Type Layout for Users

text:
# Question
Title: Content Type Layout for Users
I have a content type with fields that I want to customize for my clients to look more professional that it does in the current layout. Is this possible?

# Answer
> 2 votes
You could use Display Suite to create custom layouts of your forms and content displays.

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

A combination of Display Suite and css will allow you to really tweak the standard layout of your theme.

Otherwise Panels is another module that allows you to customize the layout, among many other features.

---
Tags: entities, nodes
---


title: Ajax Attached Form

text:
# Question
Title: Ajax Attached Form
I have an ajax dropdown that loads another form based on the selection. When a staff member is selected, it loads the follow up form fine. However, when the follow up form's ajax is fired, it returns an ajax error containing the whole page.

When the second ajax form is used manually (not from being loaded by ajax) it functions perfectly.

My Initial Ajax Form:

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['form']['staff'] = [
      '#type' => 'select',
      '#options' => ['Select'] + $this->dbService->getStaffList(),
      '#ajax' => [
        'callback'  => [$this, 'loadStaffAjax'],
        'progress'  => [
          'type'    => 'throbber',
          'message' => null,
        ],
      ],
    ];

    return $form;
  }

```

loadStaffAjax method:

```
  public function loadStaffAjax(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    $forms = [
      '#weekPopup_wrapper'    => 'Drupal\MODULE_NAME_REDACTED\Form\WeekPopupForm',
    ];

    $staff = $form_state->getValue('staff', null);

    if (!is_null($staff) && $staff > 0) {
      //Load each form.
      foreach ($forms as $form_id => $form_path) {
        $form = \Drupal::formBuilder()->getForm(
          $form_path,
          $staff
        );

        $response->addCommand(new HtmlCommand($form_id, $form));
      }
    } else {
      //Clear each form.
      foreach ($forms as $form_id => $form_path) {
        $response->addCommand(new HtmlCommand($form_id, ''));
      }
    }

    $status_messages = ['#type' => 'status_messages'];
    $response->addCommand(new HtmlCommand('.highlighted aside .region', $status_messages));

    return $response;
  }

```

Answer: The answer provided by Berdir resolved my issue. I was thinking about the process in the wrong way, instead of breaking each section up into different forms I modified the code to be one single form.

Example:

```
  public function buildForm(array $form, FormStateInterface $form_state, $admin = FALSE) {
    $form['form']['admin'] = [
      '#type'  => 'hidden',
      '#value' => $admin? '1' : '0',
    ];

    $form['form']['staff'] = [
      '#type' => 'select',
      '#options' => ['Select'] + $this->dbService->getStaffList(),
      '#ajax' => [
        'callback'  => [$this, 'loadStaffAjax'],
        'progress'  => [
          'type'    => 'throbber',
          'message' => null,
        ],
      ],
    ];

    if ($form_state->getValue('staff', 0) > 0) {
      $selectedDay = '';

      $form['form']['weekOf'] = [
        '#type'                 => 'textfield',
        '#title'                => $this->t('The week of'),
        '#size'                 => 20,
        '#default_value'        => $selectedDay,
        '#ajax'                 => [
          'callback'  => [$this, 'weekSelectedAjax'],
          'event'     => 'change',
          'progress'  => [
            'type'    => 'throbber',
            'message' => null,
          ],
        ],
      ];
    }

    return $form;
  }

  public function loadStaffAjax(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#staffDropdownForm', $form));

    return $response;
  }

```

# Answer
I don't think you want to display another form, why not just update the form that you have with additional fields?

The (or at least my) golden rule for ajax in forms is that the ajax callback must not contain any form logic. An ajax callback should trigger a submit callback that rebuilds the form, there you re-generate the form based on the submitted values and then the ajax callback does nothing but update the part of the form that was changed (or multiple parts, but in most cases, one is enough. You can even replace the whole form).
> 1 votes

---
Tags: forms, ajax, 8
---


# Question
Title: disappeared comment fields in content type, how to put them back
I'm working on a drupal page and recently encountered a problem when I couldn't enable comments on a certain content type. Looking for the problem I found that there were no fields for the comments in that content type.

I checked the other content types where comments were enabled without problems and checked which fields were enabled for the comments. I tried to enable the comments in the first content type by adding an existing field for comments, but the comment fields were not available to choose.

Here i attach an image of what it looks like on the drupal (It's in spanish but I hope you can get the context)

This is how it should look like with the comment fields:

Is there a way to retrieve this fields so comments can be enabled for this content type?

# Answer
> 0 votes
Basing on the code for `comment_field_extra_fields()`, I think that what you are noting can be explained with the `comment_subject_field_$type` persistent variable being set to a value different from 1. (`$type` is the machine name of the content type.)

```
function comment_field_extra_fields() {
  $return = array();

  foreach (node_type_get_types() as $type) {
    if (variable_get('comment_subject_field_' . $type->type, 1) == 1) {
      $return['comment']['comment_node_' . $type->type] = array(
        'form' => array(
          'author' => array(
            'label' => t('Author'),
            'description' => t('Author textfield'),
            'weight' => -2,
          ),
          'subject' => array(
            'label' => t('Subject'),
            'description' => t('Subject textfield'),
            'weight' => -1,
          ),
        ),
      );
    }
  }

  return $return;
}

```

`comment_form()` contains the following code.

```
  $form['subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#maxlength' => 64,
    '#default_value' => $comment->subject,
    '#access' => variable_get('comment_subject_field_' . $node->type, 1) == 1,
    '#weight' => -1,
  );

```

Only when the `'comment_subject_field_' . $node->type` persistent variable is set to 1 the users have access to that form field.

Changing the value of that persistent variable to 1 should restore those form fields you are expecting to see.

---
Tags: entities, comments
---


# Question
Title: How does drupal 7 know its version? which file does it check?
Hi Im just curious to know where is the metadata of the version info, where does drupal have defined its version in the files...

# Answer
The `VERSION` constant is defined on line 11 of `bootstrap.inc`:

```
/**
 * The current system version.
 */
define('VERSION', '7.41');

```
> 7 votes

---
Tags: 7, version-control
---


title: URL-Alias redirect

text:
# Question
Title: URL-Alias redirect
A few days ago I made a mistake and I lost all my rankings during the weekend.(Google Sandboxed - duplicate pages ) Google indexed my website with eg."node/123" instead with the "URL-Alias". I changed everything and my site is working like it was before.

But how can I reindex my website with my old URL-Alias or to remove the e.g "node/123"

Do I have to set an 301 redirect from "node/..." -\> URL-Alias? Or is the URL -Alias already a 301 redirect and it will be done automatically?

Thanks for your help.

# Answer
It depends what module you are using, if you are using Pathauto, then no, you don't need to worry about reindexing your site.

To double check if your site is already using a 301 on it's redirect, you can open the page your looking for in chrome with the inspector window open. Click on the network tab and then go to your redirected page (node/123). If node/123 shows up with a status of 301, your good. Google will follow that and update it's page rankings accordingly (see picture for what your looking for).
> 0 votes

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


title: Multisite subdirectory not working

text:
# Question
Title: Multisite subdirectory not working
Reading the guide, this seemed like it would be a walk in the park but I can't get to an install screen for my subdirectories.

I have created my database and users without any issue, I've got my httpd setup and ready for when I get Drupal to pick this up.

I followed the guide https://www.drupal.org/documentation/install/multi-site and followed steps through to 6 except I do not get a install page I simply get the root site that is installed already.

My current url is dev.sitename.com and I am trying to get it to work with dev.sitename.com/fr and dev.sitename.com/de

All permissions are correct so I believe my issue is how I have done the /sites/ step? In this folder I have "all", "default", "sitename.fr" and "sitename.de". The codebase I want to use is "default" and within the "sitename.fr/.de" directories I have the settings.php file setup which looks to be correct. I got my 2 symbolic links by running the command "ln -s . de" and "ln -s . fr".

If I can get to the install page my problems will be sorted. Any help would be appreciated.

# Answer
The directory should be named `dev.sitename.com.fr` not sitename.fr. Also, you may find it easier to create a `sites.php` file from `example.sites.php`. I recommend that over directory naming.
> 0 votes

# Answer
You need to have the .com in your directory names. So your two sub-directories should be named sitename.com.fr and sitename.com.de. Also make sure you declare these sites in your sites.php file to link the symbolic links to the folders, at the end of it add:

```
$sites = array("sitename.com.fr" => "fr", "sitename.com.de" => "de");

```
> 0 votes

---
Tags: 7, multi-sites
---


# Question
Title: I need to add title of specific nodes in a select box
I would like to have the title field of specific Nodes from a Content Type show up in a Select Box on a Webform. Technically, it should not grab all of the nodes titles of that content type, it should only grab specific ones (that I'll need to mark somehow), so am thinking I'll need to create a vocabulary and assign this to the nodes somehow, but than I'd like to be able to use this taxonomy term to grab the titles of these nodes only. Is this even possible? Is there a module that ties into the webform that can do something like this? Or perhaps a better way to go about doing this?

# Answer
Depending on your requirements could try drupalising your webforms a little so that you could use all the lovely field based modules.

If you elected to use entity form, instead of webform, then you should be able to use a normal entity reference field or a views derived field (eg entity reference view widget) on your form.
> 0 votes

# Answer
Webform Views Select is what you are looking for. Set up a view to show the titles you want, and then configure a Webform select list to pull in that view.

This project is just now transitioning from a sandbox project, but I found it works great for this use case!
> 0 votes

# Answer
## OPTION 1

You could also use the Webform References module. It can provide you with a select box where you can list nodes, terms or users.

## OPTION 2

As autopoietic suggested, if you haven't established your site's structure to use Webforms then maybe you can use the Entityform module which is also geared for Drupal 8 and may be easier to maintain and future proof.

## OPTION 3

If you don't mind altering things, you only need the title, and creating custom modules you can:

1. Add a field into your content type maybe a checkbox or whatever you're preferred structure is.
2. Use hook\_form\_alter to add a field into your webform and create a custom query that lists the nodes you want to display on the select box using the content type's field you added.
3. Create a text field on your webform that is hidden
4. Add a custom submit callback to webform that gets the title/data from the field you added in hook\_form\_alter() and set your webform's title field value with the selected node title.

Here you could also store the node's ID just to reference it in Views or something.
> 0 votes

---
Tags: webforms, taxonomy-terms
---


# Question
Title: adding a contrib dependency to simpletest
Is it possible? I am trying to contribute to a drupal module (first time) and I have uploaded a patch.

But the test keeps failing because of an unmet dependency on the libraries API. I have added the dependency to the $modules static in the simpletest but now I get an error:

fail: \[Other\] Line 33 of modules/swiftmailer/src/Tests/SwiftMailerSettingsTest.php: Unable to install modules libraries, swiftmailer, block due to missing modules libraries.

I'm getting really frustrated because I can't figure out how to fix it. D8 documentation is just not sufficient...

I would greatly appreciate it if somebody could help me out because I'm about ready to give up.

The issue page I created is here https://www.drupal.org/node/2620822 And this is the test code:

```
<?php
/**
 * @file
 * Contains \Drupal\swiftmailer\Tests\SwiftMailerSettingsTest.
 */

 namespace Drupal\swiftmailer\Tests;

 use Drupal\simpletest\WebTestBase;

/**
 * Tests the Transport and Message Settings UI.
 *
 * @group swiftmailer
 */
class SwiftMailerSettingsTest extends WebTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = [
    'libraries',
    'swiftmailer',
    'block',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
  parent::setUp();
  $this->drupalPlaceBlock('local_tasks_block');
    $this->drupalPlaceBlock('local_actions_block');
  }

  /**
   * Tests the Transport Settings.
   */
  public function testTransportSettings() {
// Unauthorized user should not have access.
$this->drupalGet('admin/config/swiftmailer/transport');
$this->assertResponse(403);

// Login..
$user = $this->createUser(['administer swiftmailer']);
$this->drupalLogin($user);
$this->drupalGet(t('admin/config/swiftmailer/transport'));
$this->assertText(t('Transport types'));

//Select Smtp tranport option.
$this->drupalPostAjaxForm(NULL, [ 'transport[type]' => 'smtp' ], ['transport[type]' => 'smtp']);
$this->drupalPostForm(NULL, [
  'transport[type]' => 'smtp',
  'transport[configuration][smtp][username]' => 'example',
  'transport[configuration][smtp][password]' => 'pass'
], t('Save configuration'));
$this->assertText('using the SMTP transport type.');

//Loading configuration to check if is set up correctly.
$config = $this->config('swiftmailer.transport');
$transport = $config->get('transport');
$user= $config->get('smtp_username');
$password= $config->get('smtp_password');
$this->assertEqual($transport, 'smtp');
$this->assertEqual($user, 'example');
$this->assertEqual($password, 'pass');

//Select Sppol tranport option.
$this->drupalPostAjaxForm(NULL, [ 'transport[type]' => 'spool' ], ['transport[type]' => 'spool']);
$this->drupalPostForm(NULL, [
  'transport[type]' => 'spool',
  'transport[configuration][spool][directory]' => 'aaaaa'
], t('Save configuration'));
$this->assertText('using the Spool transport type.');

//Loading configuration to check if is set up correctly.
$config = $this->config('swiftmailer.transport');
$transport = $config->get('transport');
$directory = $config->get('spool_directory');
$this->assertEqual($transport, 'spool');
$this->assertEqual($directory, 'aaaaa');

//Select Sendmail tranport option.
$this->drupalPostAjaxForm(NULL, [ 'transport[type]' => 'sendmail' ], ['transport[type]' => 'sendmail']);
$this->drupalPostForm(NULL, [
  'transport[type]' => 'sendmail',
  'transport[configuration][sendmail][path]' => 'bbbbb'
    ], t('Save configuration'));
    $this->assertText('using the Sendmail transport type.');

    //Loading configuration to check if is set up correctly.
    $config = $this->config('swiftmailer.transport');
    $transport = $config->get('transport');
    $path = $config->get('sendmail_path');
    $this->assertEqual($transport, 'sendmail');
    $this->assertEqual($path, 'bbbbb');
  }

  public function testMessageSettings() {
    $this->drupalGet('admin/config/swiftmailer/transport');
    $this->assertResponse(403);

    // Login..
    $user = $this->createUser(['administer swiftmailer']);
    $this->drupalLogin($user);
    $this->drupalGet(t('admin/config/swiftmailer/transport'));
    $this->assertText(t('Transport types'));

    $this->clickLink('Messages');
    $this->assertText(t('Message format'));

    $this->drupalPostForm(NULL, [
      'format[type]' => 'text/html',
      'convert[mode]' => 'TRUE',
      'character_set[type]' => 'EUC-CN'
    ], t('Save configuration'));
    $this->assertText('The configuration options have been saved.');

    $config = $this->config('swiftmailer.message');
    $format = $config->get('format');
    $mode = $config->get('convert_mode');
    $character = $config->get('character_set');
    $this->assertEqual($format, 'text/html');
    $this->assertEqual($mode, 'TRUE');
    $this->assertEqual($character, 'EUC-CN');
  }
}`

```

So things seem to be going wrong during the setup process: i want to enable the contrib module libraries becaues the module depends on that. But that doesn't work.

# Answer
I don't understand why you need libraries module for swiftmailer?

Swiftmailer dependencies in 8.x-1.x are installed using composer (manager). Which is something that the testbot currently simply does not support.

That said, the generic answer:

Adding the dependency to the test is not enough, it also needs to be specified in the info.yml file as test\_dependencies entry. That however only works when already committed. So if you try to do that, you need two patches/issues. First add the dependencies, wait a while until dependencies are rebuilt and then provide the rest of the patch.
> 1 votes

---
Tags: 8, testing
---


title: Removing "Home" from the title

text:
# Question
Title: Removing "Home" from the title
How do I remove *Home* from the page title?

I added in page.twig.html this part of code.

```
{% if not is_front %}

      {{ page.content }}

      {% endif %}

```

The title appears as follows.

>

I just want it to be *Nekretnina.ba*, without *Home |*.

# Answer
Override `html.twig.php` in your template, not `page.twig.html`. May I also suggest metatag for better control over page titles?
> 2 votes

---
Tags: theming, 8
---


# Question
Title: Boost - Ignore url variables but still cache the page
It seems like I'm not the only one with this problem but none of the other issues presented a clear solution.

I have a url variable called "?slide=X" which is only controlling which slide opens on the javascript slideshow when the page loads. Obviously I don't need 10 different Boost caches for each of the slides since they're all loading the same html.

All the .htaccess rules above don't really do it for me. Anybody had any luck on this?

examples.com/node/10?slide=3 needs to call the cache/normal/examplecom/node/10\_.html file instead the cache/normal/examplecom/node/10\_slide=3.html

Is this at all possible?

It would be great to have a general option on the settings page to ignore all url parameters or maybe ignore specific ones but still cache the pages. I think boos for D6 had this.

Thanks in advance

# Answer
i just saw you in this issue :D

have you tried:

2 options to solve this. Create a rewrite rule at the server level to strip userID=1234 or in setting.php strip it out & use hook\_boot to add it back in.

> A more interesting solution proposed in this thread by mikeytown (maintainer of several high performance Drupal modules like Boost and Advagg), is to remove specific query parameter at the server level or in settings.php, thereby tricking Drupal into getting and setting the page cache using a cleaner URL string. This will almost certainly have unintended consequences, however, and should be implemented with extreme caution.

Found here: http://www.asmallwebfirm.net/blogs/2012/07/page-cache-vs-landing-page-performance
> 1 votes

# Answer
As per Caching pages with boost based on a cookie value resolved this by adding this to the end of my setting.php page:

```
//check if url has parameters
if(strpos($_SERVER['REQUEST_URI'],'?') == true) {
    //clean all parameters
    $_SERVER['REQUEST_URI'] = strtok($_SERVER['REQUEST_URI'], '?');
}

```

Adding more php logic to ignore specific parameters should not be hard but since my website uses only one I choose to remove it all.
> 0 votes

# Answer
What if the parameter is required for rendering the page, but not for caching? What about removing it from the cache key?
> 0 votes

---
Tags: uri, caching
---


# Question
Title: How to show the author as entity reference of a file used in a node?
I have a content type where images are uploaded / managed with media module. Images have a mandatory entity reference field for the author. Now i want to show the author always next to the images. I can't get it to work. Last thing i tried was an entity view attachment, which works great if attached to the file itself, but not if attached to the node. I think the problem is the contextual filter. If i use the file-id the view takes the node id and shows the wrong author. If i try the node-id as contextual filter, it doesn't show anything (because the nodes have no author). How do i setup this configuration right?

Any help appreciated! Thanks!

# Answer
Yes, ultimately a query needs the file ID. There are a few ways you can get the file ID considered. You should pick the mode most consistent with the rest of your site build:

1. If you are using the Panels suite you then have a ton of options both within the "Views content panes" module (that comes as a part of CTools) and within Panels itself for setting up the passing of arguments. My main recommendation under this approach would be to use the "context" concept within panels to go from the node object to the file object that can then be passed to a contextual filter.
2. You've tried Entity Views Attach. This works well if it is appropriate to show the author of the file within the View Mode of the file.
3. You've also tried the "Provide default value" option under contextual filter handing but there isn't a suboption for "value from field X on current node". These are "default argument handlers" and here is the code for the one you are using: http://cgit.drupalcode.org/views/tree/modules/node/views\_handler\_argument\_node\_nid.inc and the generic API page for them: https://api.drupal.org/api/views/plugins!views\_plugin\_argument\_default.inc/group/views\_argument\_default\_plugins/7 If you are comfortable with PHP you can write one custom to your use case.
4. Views Field View (https://www.drupal.org/project/views\_field\_view) is maybe the ugliest (but perhaps the easiest) option. It would allow you to construct a View that takes the argument of the NID (which you already have working) and using that to get the FID as field which would then be passed to another View. A View inside a View.
> 1 votes

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


title: Multiple terms in one filter

text:
# Question
Title: Multiple terms in one filter
I am passing multiple tags into an exposed field separated by a comma. If a single tag doesn't have a result, it ruins the entire view.

Is there a way to treat the extra tags as optional?

# Answer
Use '+' to separate the tags instead of ','. The '+' is used for "OR" while the ',' is used for "AND".

Here is a screenshot from the Views administrative interface:
> 3 votes

---
Tags: views
---


# Question
Title: Getting node user view permissions (Nodeaccess)
Is it possible to get node permissions through PHP. Like I load node id by ID and test it thru user ID. Is this user has permission to view this node or not.

I'm using nodeaccess module and I want to archive this through grants (assigning some users have rights to see and some not depending content). Calling something like if node page is ID = 12 (to get all project certain page). Then if it is I load some project nodes there (created new content type). I have to be sure, that viewer (account) has permission to see this data.

# Answer
I am not sure if I fully understand your question but this is what I make out of it: you want to check if a certain user has access to a certain node, am I right?

If this is the case, this can easily be achieved with the following code:

```
// Use this if you want to load the current user.
global $user;
// Use this if you want to load a user by UID.
$user = user_load($uid);
// Load the node object.
$node = node_load($nid);
// Perform the access check.
if (node_access('view', $node, $user)) {
  // The user has permission.
}

```

You can read more about node\_access in the Drupal docs.
> 0 votes

# Answer
I found out real problem. Patrick Scheffer answer is correct but if content is created before installing nodeaccess it does not work. All new content works like expected.
> 0 votes

---
Tags: users
---


# Question
Title: How do I override the "This image has been removed" message?
I'm using Drupal 8.0.0-beta10. I just tried to add a new basic page node that contains an image hosted in an external website: While it's showing up in the preview, the image isn't showing up once the node is published; when I hover over the broken image, it shows the following message.

> This image has been removed. For security reasons, only images from the local domain are allowed.

How do I override this?

# Answer
First, you need to know which input text filter you have enabled where the images are not showing. For the sake of this answer, let's say it's the **"Basic HTML"** input filter.

Go to the configuration for this input filter, such as `/admin/config/content/formats/manage/basic_html`

Scroll down to "Enabled Filters" and look for:

**"Restrict images to this site"**
Disallows usage of tag sources that are not hosted on this site by replacing them with a placeholder image.

If you can not view externally-hosted images, it is likely this filter is enabled. Simply disable this filter.
> 18 votes

---
Tags: 8, media
---


# Question
Title: View Slideshow with different effects on the same view
I want to create a slideshow with caption using Views Slideshow. I've set up a view with `image` | `description` fields, but everything slide at the same time. How can I set different effects for different field? Should I use different views and attach them together?

# Answer
> 1 votes
If you want to implement different effect for each `slide`, then you can use views fractionslider module to implement same.

> jQuery plugin for image/text-sliders. It allows you to animate multiple elements per slide. Set different animation methods like fade or (from) left, delays and easing for each element, or simple set some defaults in the plugin options. You also have full layout/design control through html and css (every html-element can be animated). Its also fully responsive.

# Answer
> 1 votes
It may cost you some money but this seems to be a very nice Drupal module http://codecanyon.net/item/mega-slider/4313171?WT.ac=category\_thumb&WT.seg\_1=category\_thumb&WT.z\_author=megadrupal

# Answer
> 0 votes
Making a view attachment works, except the controls aren't linked and they can get out of sync with each other.

I've been trying to accomplish something similar. I'd like one field to fade and another to slide. The method I'm trying to duplicate is on www.bluecadet.com, but I'm guessing they're using a custom slider they made in-house.

I'm exploring overriding the views slideshow tpl files, but I'm quickly getting lost.

# Answer
> 0 votes
If you're using the jquery cycle plugin you can use the advanced options to apply some jquery to the elements within each individual slide. I found it easiest to do this inside of a custom js file, rather than doing it from the views configuration page.

the `before` and `after` settings are what you'll need to use. So your custom js file could have some code similar to this:

```
$('YOUR_SLIDESHOW_WRAPPER_DIV_NAME_HERE').cycle({
     fx: 'fade',
     speed: 'slow',
     timeout: 0,
     before: onBefore,
     after: onAfter,

    });

 function onBefore(curr, next, opts){
    // Code to do stuff before the slide changes
       $('.slide_description_wrapper').slideUp();
    }

 function onAfter(curr, next, opts){
   // Code to do stuff after the slide changes
    $('.slide_description_wrapper').slideDown();
}

```

You can see an example of this here... it's a bit more complex than what's in the code above, but it gives you a good idea of how you can trigger custom jquery events on elements within each slide.

# Answer
> 0 votes
In your view slideshow format setting under the avanced jquery option select the fx option under advanced option value you can enter the various effect seprate by comma.this operation require the json2.js.you should but this file in sites/all/libraries/json2 for jQuery Cycle Plugin - Option Reference-http://malsup.com/jquery/cycle/options.html

---
Tags: 7, views
---


title: Drupal multisite manager module

text:
# Question
Title: Drupal multisite manager module
I am currently working on an internal project that would host a Drupal multisite platform.

For this, I am in the process of creating a site\_manager module that will be running in the "main" Drupal instance, within the multisite setup.

Now, I want to be able to run a lot of functions in the context of a specific subsite.

For example: I want to run a cache\_clear\_all() or a module\_enable() in a subsite.

When I call these functions, it will always run the functions in the current site's context (the "main" Drupal instance).

I have tried to use db\_set\_active() to resolve this, but no luck. It will always run it in the current "main" site.

To resolve the problem I started implementing a custom class that holds methods for the actions I want to perform, that fire custom db\_query() implementations...

It works, but that cannot be the cleanest way to do this... Clearing the cache tables manually via db\_query does not seem like the best way to do this, especially when you know that just calling cache\_clear\_all() should do the trick, when ran in the correct context.

Some research brought me here: Programmatically create user in another Drupal site But I don't really see how this would work, because I want the platform to be extendible,so that I can add functions later.

I could try to setup some kind of "client" module that listens for calls from the main site or something like this?

**EDIT**

After doing some additional research, I am looking into the possibilities of XML-RPC or some kind of webservice (json) that might do the trick as well.

It might be good to note that I would like to find a sustainable solution when looking forward to D8...

Anyway, did any of you try something like this?

Thanks in advance!

# Answer
Normally, you would execute these commands on particular sites with Drush and site aliases (`drush sa` lists the aliases). I do it all the time.
> 0 votes

# Answer
I would suggest to use jenkins for this case. With jenkins you can create as many jobs as you want and call over http request those jobs. In this case you will have a freedom in your commands.
> 0 votes

---
Tags: multi-sites, services
---


title: Custom drush command not working

text:
# Question
Title: Custom drush command not working
I have used hook\_drush\_command to create a new drush command. This is my custom code for creating drush command.

```
/**
 * Implementation of hook_drush_command().
 */
function mymodule_drush_command() {
  $items = array();
  // Name of the drush command.
  $items['list-site-users'] = array(
    'description' => 'Print the list of users in the site',
    'callback' => 'drush_get_site_users',
  );
  return $items;
}

function drush_get_site_users() {
  $query = db_select('users', 'u');
  $query->fields('u', array('name'));
  $result = $query->execute();
  while($record = $result->fetchAssoc()) {
       print_r($record['name']);
  }
}

```

After this I have exceuted `drush cc all` and `drush cc drush` for clearing drush. Then I have executed my custom drush command `drush list-site-users` command, but it is throwing the below error.

> The drush command 'list-site-users' could not be found. Run `drush
>  cache-clear drush` to clear the commandfile cache if you have installed new extensions.

My drush version is 5.10.0

# Answer
> 6 votes
Try the following:

```
/**
 * Implements hook_drush_command().
 */
function mymodule_drush_command() {
  $items['list-site-users'] = array(
    'description' => 'Does a database cleanup.',
    'examples' => array(
      'list-site-users' => 'Retrieve list for all users',
    ),
    'aliases' => array('lsu'),
  );
  return $items;
}

function drush_mymodule_list_site_users() {
  $query = db_select('users', 'u');
  $query->fields('u', array('name'));
  $result = $query->execute();
  while($record = $result->fetchAssoc()) {
       print_r($record['name']);
  }
}

```

**NOTE:** Make sure you write the above code in `mymodule.drush.inc` file of any module. Clear the cache and your drush command should work.

# Answer
> 3 votes
I have made a mistake. For creating custom drush command we have to place code inside the `module.drush.inc`. I have placed the code inside my custom module. After placing the code inside `module.drush.inc` it works fine.

---
Tags: 7, drush
---


# Question
Title: How to create and view a clickable list of information on a user profile?
I am basically trying to replicate the attachment in Drupal. Ideally the user will click a user and have a Financial tab which they can add invoices/notes to. This would need to be a collection of fields (field collection?).

# Answer
Seems like you're looking for something like what I'd call some type of "drill down" facilities. Have a look at the Master Summary with drill down example. Click on some of the links in the tabular report (or bars in the chart ...), to get some related report (for the link you followed). Think of "states" as the equivalent of your "invoices" to get the idea.

The above sample is created with the Forena module. After you install it in your own environment, you'll have access to another set (category) of reports, related to "Drupal Administration" (applied to your own site). One of the reports in it is the "Logs for User" report (located at `/reports/drupaladmin.user_logs`). It'll show you a summary of watchdog entries (for the user you selected). And the resulting report includes a link "*Details*" for any of the watchdog records shown, which you cann use (follow) to get way more details about the specific watchdog record. The format of such "detail" is shown in a format that is pretty close to your "Invoice details" screenprint.

Here is a screenprint of another (custom) report that also includes such drill-down facilities (don't look at the actual formatting of it):

The (red) numbers in it are actually hyperlinks which you can use to get the actual Watchdog details (corresponding to the link you selected). The (collapsed) "Report Execution Parameters" can be expanded to "filter" the data to be included in the report. Even though it's a custom report, it is pretty forward to build such kind of reports, e.g. using Forena's WYSIWYG report writer and/or WYSIWYG query builder.

The above is about displaying (reporting) all such data. To also be able to "add" new records (invoices), you could expand the so called "frx" files (which is just plain XHTML), to insert something like an hyperlink to "add a new invoice". Such link would then probably correspond to something like `node/add/invoice` (assuming the machine name of your content type is `invoice`). Optionally you could also use a `destination` parameter in such URL to return to the "report" after the new node (invoice) was added.

Disclosure: I'm a co-maintainer of Forena.
> 0 votes

---
Tags: views, entities, users, log-messages
---


title: Cron runs in all server instances

text:
# Question
Title: Cron runs in all server instances
We are facing really big issue with the cron. Our site is running on 2 ec2 instances under the load balancer. We have lot of cron tasks which are performed every day. But the problem comes when the cron run, during this time all instances start processing the cron jobs, and site will not be accessible for the users. Here all the instances are sharing the same db including the staging instances(another 2 instances). I don't understand that, why all instance's CPU utilization is going high when cron run(all 4 instances).

Because of this behavior, what we are planning now is, to move the cron to a separate server, there it will perform all the jobs. But I'm not sure how I can achieve this.

How can I move the cron job to a separate server?

# Answer
Instead of moving cron, you need to look into what parts of cron are so CPU itensive and why it takes such a long time to complete.

You can start by logging executed tasks, how when they start, finish and a comment about what they do.
> 0 votes

---
Tags: 7, cron
---


# Question
Title: Uploaded images in theme settings is going to be lost
I have a flexslider and I make its images customizable through the theme settings. I added a caption property for the the slide to meet multiple languages websites as follows in theme-settings.php:

```
// setting property to determine the rendered images fields
$form['best_responsive_settings']['imagesCount'] = array(
      '#markup' => t('Enter the total number of images in the slideshow'),
      '#type' => 'select',
      '#options' => associate_array_vals(explode(',',  theme_get_setting('imagesCountOptions'))),
      '#selected' => theme_get_setting('imagesCount'),
      '#default_value' => theme_get_setting('imagesCount'),

  );

  $lang_list = language_list();
// rendering upload image form with caption textfield for every language supported by the website

  for ($i = 0; $i < theme_get_setting('imagesCount'); $i++){
      $form['best_responsive_settings']['slideshowImages'.$i] = array(
        '#type' => 'managed_file',
        '#title' => t('Image').' #'.($i+1),
         '#required' => false,
        '#upload_location' => file_default_scheme() . '://slides',
    '#default_value' => theme_get_setting('slideshowImages'.$i,'best_responsive'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
      'file_validate_image_resolution' => array('960x400','430x400')        ),

      );
      foreach ($lang_list as $lang){
      $form['best_responsive_settings']['slideshowCaption'.$lang->language.$i] = array(
    '#type' => 'textfield',
    '#title' => t('Caption').' #'.($i+1).' -- '.$lang->name,
    '#required' => false,
    '#default_value' => theme_get_setting('slideshowCaption'.$lang->language.$i, 'best_responsive'),
  );
      }
  }

```

In page.tpl.php I use the following to render the images:

```
<?php if (theme_get_setting('slideshow_display','best_responsive')): ?>

    <div id="home-slider">
      <div class="flexslider-container">
        <div id="single-post-slider" class="flexslider">
          <ul class="slides">
            <?php for ($i = 0; $i < theme_get_setting('imagesCount'); $i++): ?>
              <?php  if (theme_get_setting('slideshowImages'.$i) != ''): ?>
 //the following line causes a problem after some time
            <li class="slide"><img src="<?php echo file_create_url(file_load(theme_get_setting('slideshowImages'.$i))->uri);?>" alt="Slide"/><?php if (theme_get_setting('slideshowCaption'.$language->language.$i)): ?><span class="flex-caption"><?php echo theme_get_setting('slideshowCaption'.$language->language.$i) ;?></span><?php endif;?></li>

              <?php endif; ?>
            <?php endfor; ?>
          </ul><!-- /slides -->
        </div><!-- /flexslider -->
      </div>
    </div>
    <?php endif; ?>
    <?php endif; ?>

```

Everything, initially, works fine, the images are uploaded to the theme settings and images are rendered well in the slideshow. However, after some time! I noticed that the images are disappeared from the template settings page and only the caption if supplied is remained. In addition I got the following notice:

```
Notice: Trying to get property of non-object in include() (line 159 of C:\xampp-2\htdocs\4test\drupal-7.28\sites\all\themes\best_responsive\templates\page.tpl.php).

```

Where the line 159 is the line regarded in the comment of the second code snippet above. This notice is repeated twice. What is the problem here? What is making this code initially works then after sometime it fails? What is making the uploaded files disappeared from the settings. **In addition, the destination in-which images should be uploaded /sites/default/files/slides becomes empty. i.e the uploaded images files are deleted!**

# Answer
> 5 votes
My solution is to ensure to make permanent the image when drupal load page theme settings. You don't need to create a custom submit handler because after the new settings are saved the settings page is reloaded, and the fix executed.

Plus, you cannot use "active theme" because sometimes the current active theme is the admin theme, and not the default or maybe the user is changing the settings theme in a theme that it's not set as default.

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

  $default_file_dir = 'public://template/logos';
  $folder = file_prepare_directory($default_file_dir, FILE_CREATE_DIRECTORY);
  $settings_theme = $form_state['build_info']['args'][0];

  if ($folder) {
    $my_logo = theme_get_setting('my_logo');
    // BUG: Force file to be permanent.
    if (!empty($my_logo)) {
      _fix_permanent_image('my_logo', $settings_theme);
    }
    $form['my_logo'] = array(
      '#type'               => 'managed_file',
      '#title'              => l('My logo'),
      '#default_value'      => $my_logo,
      '#progress_message'   => t('Please wait...'),
      '#progress_indicator' => 'bar',
      '#upload_location'    => $default_file_dir,
      '#upload_validators'  => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
        'file_validate_image_resolution' => array('375x50', '30x50'),
      ),
    );
  }

}

function _fix_permanent_image($image, $theme) {
  $fid = theme_get_setting($image, $theme);
  if ($fid > 0) {
    $file = file_load($fid);
    if (is_object($file) && $file->status == 0) {
      $file->status = FILE_STATUS_PERMANENT;
      file_save($file);
      file_usage_add($file, $theme, 'theme', 1);
      drupal_set_message($image . ' saved permanently.', 'status');
    }
  }
}

```

# Answer
> 1 votes
By default, Drupal marks files as "temporary", meaning that they will be deleted after 6 hours.

You will need to change the file status to permanent in order to keep the files. This doesn't seem to be clearly stated in the documentation.

See these question for some example code and explanations: Managed file: the file used in the field may not be referenced

You will need to do the following in a submit validation (or similar):

```
// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;
// Save the file.
file_save($file);
// Record that the module (e.g. user module) is using the file.
file_usage_add($file, 'user', 'user', $user->uid);

```

# Answer
> 1 votes
For a detailed guide on where to implement the custom code to set your files as permanent, you might want to check this: http://ghosty.co.uk/2014/03/managed-file-upload-in-drupal-theme-settings/

Basically, it adds a custom form submit handler for the theme settings form; which is not straightforward in Drupal and a bit hackish.

```
$form['#submit'][] = 'MYTHEME_settings_form_submit';

// Get all themes.
$themes = list_themes();
// Get the current theme
$active_theme = $GLOBALS['theme_key']
$form_state['build_info']['files'][] = str_replace("/$active_theme.info", '', $themes[$active_theme]->filename) . '/theme-settings.php'

```

And then inside your submit handler you can do something like this to set the files as permanent.

```
function MYTHEME_settings_form_submit(&$form, &$form_state) {
$image_fid = $form_state['values']['secondary_logo'];
  $image = file_load($image_fid);
  if (is_object($image)) {
    // Check to make sure that the file is set to be permanent.
    if ($image->status == 0) {
      // Update the status.
      $image->status = FILE_STATUS_PERMANENT;
      // Save the update.
      file_save($image);
      // Add a reference to prevent warnings.
      file_usage_add($image, 'MYTHEME', 'theme', 1);
     }
  }
}

```

Good luck.

---
Tags: 7, files
---


title: Taxonomy templates

text:
# Question
Title: Taxonomy templates
I have a view that lists all the terms in my taxonomy. When you click the link (url structure is (\[tax\_name\]/\[tax\_term\]) it takes you through to a page that has the description of the term and then the outputed content with the content types template, one after the other. Now I want to edit this template but I can't figure it out. I found taxonomy-term.tpl.php within the taxonomy module. But when I put this into my templates folder nothing I do seems to effect it. I have also tried taxonomy-term--\[tax\_name\].tpl but no luck. From what I can see this is all I should have to do? I have of course cleared the cache. What am I missing?

# Answer
Views 3.0 comes with a view that replaces the normal taxonomy page. This view is disabled by default but you may have enabled it. Make sure the view *Taxonomy term* is not enabled; then, you can use your custom template to override the default template.

If this doesn't work, you can try using this code.

```
function template_preprocess_page(&$variables) {
  if (arg(0) == 'taxonomy') {
    $variables['theme_hook_suggestions'][] = 'page__taxonomy';
  }
}

```

You should now be able to create the page--taxonomy.tpl.php file in your theme folder.

Of course you can also enable the *Taxonomy term* view and override that template (*Edit view*, under *Advanced* click *Theme: information*).
> 0 votes

# Answer
In this taxonomy\_template describe how customize template of taxonomy term in drupal

**`taxonomy-term--[vocabulary-machine-name|tid].tpl.php`**

base template: `taxonomy-term.tpl.php`

Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

1. taxonomy-term--tid.tpl.php
2. taxonomy-term--vocabulary-machine-name.tpl.php
3. taxonomy-term.tpl.php

Note that underscores in a vocabulary's machine name are replaced by hyphens.
> 0 votes

---
Tags: taxonomy-terms, theming
---


# Question
Title: How to use tokens as watermark on images
I need to create a watermark on images in my website. The watermark should contain a text which consists of the node ID and its author ID.

So for every image a unique watermark is created. How can I do that?

I tried the following modules so far but I am not sure if they can do what I need:

1. Imagecache Actions
2. ImageMagick
3. textimage
4. IMCE Watermark
5. Media watermark

# Answer
I think Imagecache Actions can do what you want. Text Overlay watermarking comes default in this module. I haven't checked if it supports tokens but you'll notice it immediately if it does. Don't forget to enable the tokens module.
> 1 votes

---
Tags: 7, media
---