# Question
Title: Contextual Filter Problem in Drupal Commerce Using Indexed Textfield
I am trying to filter products by brands, which have been inputed into a text field in Drupal Commerce and indexed.

If I try for instance "Breitling" in the contextual filter it works perfectly and I can see the correct products shown in the Views preview. I am using PHP code for the contextual filter. So as a test I just used the following in the contextual field and it does not work (I have tried both options for using the contextual field)

```
    return "Breitling";

```

What I do get is no results.

# Answer
> 1 votes
I think it's because the value that you put into the Views preview will just be a value to pass to the PHP code. So if you enter `return "Breitling"`, your code is going to try and find a brand named 'return "Breitling"'.

If you just need to return all results from the brand Breitling for testing purposes, in your PHP code in the contextual filter, set the value to look for as "Breitling".

Let me know how you get on.

---
Tags: commerce, views
---


title: Upload directory for a field instance

text:
# Question
Title: Upload directory for a field instance
I've been searching a lot for this, but no luck. I've created a custom file field along with an instance for my custom content type in the .install file.

I've set up everything except that I want that by default this instance of the file file that I created to upload to the 'private' directory and if it's not defined, to define it with this module.

```
  $file_download_link_instance = array(
  'field_name' => 'file_download_link',
  'required' => true,
  'entity_type' => 'node',
  'bundle' => $machine_name,
  'label' => t('Files to upload'),
  'settings' => array(
    'file_extensions' => 'txt doc docx pdf ods odt xls xls png jpg jpeg',
    'description_field' => TRUE,
    ),
  'description' => t('Please upload here the files.'),
  'display' => array(
    'default' => array(
      'type' => 'hidden',
      ),
    'teaser' => array(
      'type' => 'hidden',
      ),
  ),
  'locked' => TRUE,
);

```

I believe that I have to edit the 'settings' array, but I don't know the syntax. Thanks!

# Answer
> 0 votes
You just wanted to add attribute *`file_directory`* inside the *`settings`* array

```
  'settings' => array(
    'file_directory' => 'myModule/images',
    ),

```

Here is other attributes that might be added:

```
  'settings' => array(
    'file_extensions' => 'png jpg jpeg',
    'file_directory' => '',
    'max_filesize' => '20 MB',
    'alt_field' => 1,
    'title_field' => 1,
    'max_resolution' => '300x200',
    'min_resolution' => '200x125',
    'default_image' => 0,
  ),

```

---
Tags: nodes, entities
---


# Question
Title: How do I alter the path of an uploaded image/file such that it includes the path of the node I attach it to via an image field?
I added an Image Field to my Node content type. Now, when I upload an image "image1.jpg" that is attached to a node mysite.com/note/123, I want the uploaded image's path to be mysite.com/node/123/image1.jpg. How do I achieve this? I've tried to change the subfolder of the image with a token. I used the token \[current-page:path\], but that doesn't return the node where I'm attaching to, but the last page that was visited. (Which might be the node edit form or something completely different with ajax, say)

# Answer
Seems you are looking for a File (Field) Paths module:

> The File (Field) Paths module extends the default functionality of Drupal's core Upload module, the FileField module and many other File Upload modules by adding the ability to use node tokens in destination paths and filenames.
>
> In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

Be aware that it's not yet stable. Test intensively before using in production environment. On the other hand, I don't know anything better and I know for a fact it may work all right.
> 4 votes

# Answer
If you wanted a programmatic solution, you could use the setting array when creating image field instance:

```
'settings' => array(
        'file_directory' => 'YOUR_DIRECTORY_HERE',
)

```

For example:

```
 // Create the instance.
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => 'article',
      'label' => 'Article Image',
      'description' => 'An image for the article.',
      'required' => TRUE,
      'settings' => array(
        'file_extensions' => 'png jpg jpeg',
        'file_directory' => 'myModule/news', //your wanted attribute
        'max_filesize' => '20 MB',
        'alt_field' => 1,
        'title_field' => 1,
        'max_resolution' => '300x200',
        'min_resolution' => '200x125',
        'default_image' => 0,
      ),

```
> 0 votes

---
Tags: entities, media, tokens
---


# Question
Title: How do I resize image directly while uploading the image?
How do I resize image directly while uploading the image?

Select image from Computer \> Upload \> Resize directly to dimension that I want.

# Answer
If you are looking for crop image, then use **Imagefield Crop** module you can do that. Use image upload with crop as your widget after installing this module. Some other image crop modules are also available.
> 0 votes

# Answer
Try **Max Image Size** module

On the module page it says:

> This module will resize uploaded images to be below the set dimensions. It is not an image style or other presentation layer module. If you want to maintain the original image you should use Image Resize Filter or an image style. The use case for this module is sites where users may upload very large images, but you do not want/need to keep the original.
> 1 votes

---
Tags: 6, media
---


title: Posting in Ruby leads to a 403 error

text:
# Question
Title: Posting in Ruby leads to a 403 error
I am writing a Ruby script to ingest content into Drupal 7. This is on my local machine. I'm using the Services module and its rest service to GET and POST. I could log in and grab the csrf token and the cookie information but I get a 403 error when I try to post a new node. I checked my local apache access and error logs. There were no errors listed and the access log only reports the status. This is my code so far:

```
require "rest-client"
require "json"

node = create_node(node_hsh)
node_json = JSON.generate(node)
response = RestClient.post('localhost/drupal/restfulapi/node', node_json,
:content_type => :json,
:accept => :json,
:headers => {:cookie => cookie, 'x-csrf-token' => csrf_token}
)

```

I'm not sure where else to look? I would really appreciate any pointers. Thanks.

# Answer
> 1 votes
I figured it out. Posting this for documentation: I had to pass the cookie after the user had logged in to do a GET on the token (localhost/services/session/token) for the Services module. Once I had the token, I could pass the cookie and the token to do a POST of the resources. I also switched the gem from rest-client to Faraday because I could customize my headers better. Also, the logging functionality was more verbose in Faraday which was helpful in debugging.

# Answer
> 0 votes
There are a couple ways to go about POSTing data to a resource. First, there is a handy Firefox plugin called Poster which allows the posting of arbitrary data to specified URLs. Poster can be downloaded from here.

For Google Chrome, you can use the Advanced REST Client extension found here.

It is fairly simple to use and it remembers your last entry so you can easily continue to test even after closing the browser.

The steps below are for Poster plugin for Firefox, but they are similar to Advanced REST Client for Chrome.

Here is a short tutorial on using Poster to POST data to create a new user through the user resource.

> 1. After installing Poster you will need to reboot Firefox. Once you have rebooted you can active Poster from the menu at Tools-\>Poster.
> 2. In the URL field, enter the base URL for your resource.
> 3. Click the Parameters tab. This is where you enter the data to be submitted, which mimics the fields that would be posted from a web form.
>
> Note that for other types of data like nodes, you will need quite a bit more information than this. For more information on what type of data is needed to create a resource, please reference the documentation for that resource's create method.
>
> 4. Now click back to the Content to Send tab and click Parameter Body. This will convert your Parameters to properly encoded data, and change the Content Type to 'application/x-www-form-urlencoded' (you can test with your set Content Type).
> 5. Under Actions you'll see several buttons. Create requests are POSTed to the resource, so click Post. Ideally, if all went well, you will see something positive response.

Please let me know if you have any query/concern regarding this.

---
Tags: 8, services
---


title: Upload Images to specific folders

text:
# Question
Title: Upload Images to specific folders
how do I upload images (Media) to specific folders inside the default directory? I will have thousands of pictures and would like to have an organized structure of folders.

Thanks a lot.

# Answer
You can use File (Field) Paths module. It allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

You can use value of any node field as folder name where files will be uploaded. Or you can create new field for this purpose.
> 2 votes

# Answer
If you wanted a programmatic solution, you could use the setting array when creating field instance:

```
'settings' => array(
        'file_directory' => 'YOUR_DIRECTORY_HERE',
)

```

For example:

```
 // Create the instance.
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => 'article',
      'label' => 'Article Image',
      'description' => 'An image for the article.',
      'required' => TRUE,
      'settings' => array(
        'file_extensions' => 'png jpg jpeg',
        'file_directory' => 'myModule/news', //your wanted attribute
        'max_filesize' => '20 MB',
        'alt_field' => 1,
        'title_field' => 1,
        'max_resolution' => '300x200',
        'min_resolution' => '200x125',
        'default_image' => 0,
      ),

```
> 0 votes

# Answer
If you just want to upload image in sub directory. their is configuration for drupal image field . Path is your\_example\_domain.com/admin/structure/types/manage/your\_content\_type/fields/field\_image. you can set the file directory by using token and like static name "your\_subdir\_name". hope this help!
> 0 votes

---
Tags: files
---


# Question
Title: Show list of taxonomy terms, with node's current terms given a class
My goal is simple: to display a list of taxonomy terms (alphabetically), with the terms on the current node being highlighted by a current css class. I've tried using views of taxonomy term, but I can only get either the full list or the terms on the node to display, and I want something of a mashup.

So for the visual thinkers I want an output of this:

```
< ul >
    < li class="current" >Blue< /li >
    < li >Red< /li >
    < li class="current" >Rouge< /li >
    < li >Yellow< /li >
< /ul >

```

I feel like I'm about to have a very "duh!" moment, so please, enlighten me. Seems like this should be simple to do in Views, yet I can't seem to get it and will resort to doing it in the template.php file if I can't find an answer. Thanks for any help.

# Answer
I think I have found a solution that achieves the desired result in good way (in terms of not writing spaghetti php or hardcoding stuff in the theming layer). Instead of providing the full configuration at once, I will try to guide you step by step.

**1/** Create a new view (mine is called 'test') that only has a Block display, and displays Taxonomy terms for a specific vocabulary (mine is called 'Target Group'). Use 'HTML list' as the selected Format, make sure the 'Taxonomy term: Name' is added in the list of the displayed fields, also use 'Taxonomy term: Name' as a sorting option in ascending order, select 'Display all items' in the pager settings, and make sure query Distinct settings are *DISABLED* (we will achieve that via aggregation later on). Save your view. You can see the view results in the preview section of the view manage page, or place the block in the respective node display if you prefer to view it directly in the front end. At this point, you will be able to see a list of all the terms form the specific vocabulary.

**2/** Add a new relationship to your view (in the Advanced section). The relationship should be the one labeled **'Taxonomy term: Content with term'**. It is highly important (for the rest of the code that will be provided) that you choose this generic relationship option, instead of the more specific one labeled 'Taxonomy term: Content using Target group' (where Target Group is the vocabulary name I used for this example). Provide an identifier for this relationship - I left the default one labeled 'node'. Make sure that 'Require this relationship' is **NOT** checked - this will create a LEFT JOIN between the terms table and the node term data table. Now go to the fields section and add the field 'Content: Nid' and set it to use the relationship with the aforementioned identifier. Any other field settings do not matter for now - we will adjust them later on. Save your view. At this point you will be able to see plenty of duplicates for all terms, each one with a different nid. Good.

**3/** Now go to the contexual filter section and add a new one for 'Content: Nid'. Make sure the 'node' relationship is used. For 'When the filter value is NOT available' choose 'Provide default value' and set 'Type' to 'Content ID from URL'. It is recommended to 'Specify validation criteria' as you see fit. Save your view. The configuration until this step, is actually the one presented in this excellent answer here which has some screenshots too. Up to this point, you will be able to see only the terms with which the current node is tagged. "Duhh, that was the original problem" you'll say, but bear with me as we take it one step further.

You see, when adding a contexual filter, views adds the restriction to the WHERE clause of the generated query (which is good and desired in the majority of cases). The current query generated is the following:

```
SELECT DISTINCT taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_term_data.tid AS tid, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name, node_taxonomy_index.nid AS node_taxonomy_index_nid
    FROM
    taxonomy_term_data taxonomy_term_data
    LEFT JOIN taxonomy_index taxonomy_index ON taxonomy_term_data.tid = taxonomy_index.tid
    LEFT JOIN node node_taxonomy_index ON taxonomy_index.nid = node_taxonomy_index.nid
    LEFT JOIN taxonomy_vocabulary taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
    WHERE (( (node_taxonomy_index.nid = '4072' ) )AND(( (taxonomy_vocabulary.machine_name IN  ('topics')) )))
    ORDER BY taxonomy_term_data_name ASC

```

But what we DO want in our case, is that the nid restriction is applied as an additional restriction to the LEFT JOIN with the node\_taxonomy\_index in order to filter the join and not the whole result set. Unfortunately, views does not support that out of the box but after some digging I found that it is programmatically supported in *views\_join* handler which can be gracefully managed via *hook\_views\_query\_alter*. So, moving on.

**4/** In order to implement a hook, you will require a custom module. If you are not sure how, then read the respective documentation. Here is the implementation that removes the nid restriction from the where clause and adds it to the LEFT JOIN clause

```
function my_custom_module_views_query_alter(&$view, &$query) {
  if ($view->name == "test") {
    // try to resolve the nid from the contexual filter condition
    $contexual_nid = null;
    if (!empty($query->where)) {
      foreach ($query->where as $delta => $where_clause) {
        if (isset($where_clause['conditions']) && count($where_clause['conditions'])) {
          $condition = $where_clause['conditions'][0]; // in the current use case, there will be only one condition
          if (isset($condition['field']) && strpos($condition['field'], "nid") !== FALSE) {
            $contexual_nid = array_shift($condition['value']);
            // remove the nid constraint from the where clause
            unset($query->where[$delta]);
          }
        }
      }
    }
    // add the nid constraint to the relationship
    if ($contexual_nid != null && isset($query->table_queue['node_taxonomy_index']) && isset($query->table_queue['node_taxonomy_index']['join'])) {
      $join = $query->table_queue['node_taxonomy_index']['join'];
      $join->extra = array(
        array(
          "field" => "nid",
          "value" => $contexual_nid
        )
      );
      $query->table_queue['node_taxonomy_index']['join'] = $join;
    }
  }
}

```

So, at this point, you have a list that has tons of duplicates. "Duh, I had achieved that via 'views\_field\_view' and with less duplicates" you'll think. Well, no. First of all, the list is now sorted alphabetically, and second, getting rid of the duplicates, now that we are dealing with a single result set, is a piece of cake via aggregation. Back to the view administration then.

**5/** In the Advanced section, set 'Use aggregation' to Yes. For field 'Content: Nid', click on the 'Aggregation settings' and set 'Aggregation type' to 'Count'. For field 'Taxonomy term: Name' the aggregation type should be the default 'Group results together'. Save your view and say goodbye to the duplicates.

**6/** Last step in order to convert the 'Content: Nid' to useful markup. Click on the field which is now labeled '(node) COUNT(Content: Nid) (Nid)' and apply the following settings:

* Create a label: unckeck
* Exclude from display: check
* REWRITE RESULTS: Rewrite the output of this field: checked
* REWRITE RESULTS: Text: 'current' (the actual literal 'current' without the quotes)
* NO RESULTS BEHAVIOR: Count the number 0 as empty: checked
* NO RESULTS BEHAVIOR: Hide if empty: checked
* NO RESULTS BEHAVIOR: Hide rewriting if empty : checked

And finally click on the Settings link for the HMTL list format and for 'Row class' enter token '\[nid\]'. Save your view. Everything should look as expected.
> 1 votes

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


# Question
Title: Alter entity reference autocomplete field
I have made a module to alter the way entity reference works with autcomplete fields. I have override the entity\_reference\_autcomplete function where i have changed the following line:

```
        $key = "$label ($entity_id)";

```

with

```
        $key = "$label";

```

It seems to work when completing fields in form , but after the form has been submitted the autcomomplete field gets blank and the result is not saved . How can i solve this issue ?

# Answer
> 1 votes
This should be done by writing a custom CTools EntityReference selection plugin. Your new class would just extend EntityReference\_SelectionHandler\_Generic\_node and I think it would only need to override the getLabel() method to make things "just work".

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


# Question
Title: Drupal navigation always returns a 404 error
I have been given a Drupal site which I have to get it running.

I have Apache / Drupal / MySQL up and running, and created a new `.conf` file in Active Sites, and set the document location to /var/www/html/

I have edited my hosts file so that I have an entry for

```
127.0.0.1 samplesite.com

```

If I browse to `samplesite.com/index.php` I see the index of the site. So far so good. It is all styled, and as I see genuine content I must be hitting the database

Now no matter what link I click on on that page, I get a `404 error`. (Looking in the log files its a 404 523 error if that has any bearing on it.)

I then found out the admin userid (using drush), reset the password, and cleared all caches. Still the `404 errors`.

If I go to `samplesite.com/user` or `samplesite.com/admin`, I still get the 404 error, not an admin login page.

As this is an existing site, and works online, I am blaming something in my setup / configuration (being as the url on a failed link is similar to samplesite.com/about, I am assuming it is in the navigation configuration, but now I am stuck).

Is there an apache url rewriting module (or drupal one?) that needs some configuration? Or can anyone suggest something else I may have overlooked in apache / drupal configuration?

I now have the line $base-url = 'samplesite.com'; in my settings.php file, and none of the other urls work. However it accepts that I am logged in as admin as I have an additional admin menu at the top of the page. (none of the links work though) Curiously, if I disable wifi, then the page doesn't load at all (I wouldn't have thought that wifi on or off would affect localhost)

Ok, My fix came when I followed this thread https://www.drupal.org/node/1572984

I needed to add in the following.

```
<Directory /var/www/html>
   RewriteEngine on
   RewriteBase /
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</Directory>

```

However I only got here because of the help I received along the way, I think this was just the missing piece.

# Answer
> 6 votes
# Option 1 - RewriteRule and RewriteBase

Check if you can use an URL containing `?q=user` or `?q=admin`. Refer to my answer to the question "7.26 /admin, /user not found on Localhost" (which is about `RewriteRule`) for more details on that.

In that answer there is a link to the question about "drupal /?q=user is working but /user not working", for which the accepted answer of that question provides more details about tuning `RewriteBase` in your .htaccess.

# Option 2 - Admin option 'Clean URLs'

I you can use the `?q=admin`URL, then try to navigate to `/index.php?q=admin/config/search/clean-urls` to check the current status of **clean urls** (if it is enabled or disabled). Make sure "clean urls" is enabled.

Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.

# Option 3 - base\_url

Make sure the value of "base\_url" is set correctly (in your settings.php).

# Option 4 - .htaccess file

Verify if the .htaccess file is present in the directory where Drupal resides (and/or that it is not incomplete or corrupt). If it is missing, then upload it. If needed copy it again from the "Drupal" archive file (.zip or .tar) from Drupal.org again, and just use that new .htaccess file.

---

**Note** (about your "*The ?q=admin URL didn't ask me to log in*" comment to this answer) Check if you get the same problem using another browser. If with another browser it works, then that part might be a cookie problem (delete the cookie in the browser where you have the problem, and try again).

# Answer
> 1 votes
According to this link and my experiences I Think it is because incorrect RewriteBase in `.htaccess` file, one and simple solution is download raw drupal version from drupal.org (or if you has been downloaded it before) repalce `.htacess` file from it to your current root directory.

---
Tags: navigation
---


title: only selected view modes per node?

text:
# Question
Title: only selected view modes per node?
The view mode per node option in DS Extras is great. But I want to give my editors only the 2 view modes they need, I don't want to burden them with the complete list of some 20 view modes I use all over the site. Is it possible to configure this?

Thanks for any help Kind greetings Frank

# Answer
This functionality appears to already be in the current release of Display Suite. See here for details: https://www.drupal.org/node/1673626
> 0 votes

---
Tags: display-suite
---


title: Problems adding custom field formatter

text:
# Question
Title: Problems adding custom field formatter
I'm having difficulty getting my custom field formatter to activate. My intention is to allow users to request a 'Copy to Clipboard' button to be added to a text field.

I've tried to follow online tutorials and examples:

http://www.metaltoad.com/blog/drupal-7-tutorial-creating-custom-formatters

https://github.com/SpaceBeers/Drupal-YouTube-Formatter/blob/master/youtube\_formatter.module

and I've come up with the following (in a file `clipboard.module`, referenced from `clipboard.info`): the `formatter_view()` function is currently left empty until I figure the other stuff out.

How can I trigger this code? I've tried unloading and reloading the module, clearing the cache, but whenever I add a new text field and then go into the Field Settings for that field, I don't see any form appearing for the custom settings. Should I be setting some other config elsewhere in Drupal in order to enable this?

Thanks in advance for any help.

```
/**
 * Implements hook_field_formatter_info().
 *
 */

function clipboard_field_formatter_info() {
  return array(
      'clipboard_formatter' => array(
      'label' => t('Copy to Clipboard'),
      'field types' => array('text','text_long','text_with_summary'),
      'settings' => array('show_clipboard_copy_button' => FALSE),
      )
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */

function clipboard_field_formatter_settings_form($field, $instance,   $view_mode, $form, &$form_state) {
  //This gets the view_mode where our settings are stored
  $display = $instance['display'][$view_mode];
  //This gets the actual settings
  $settings = $display['settings'];
  // Initialize the element variable
  $element = array();
  $element['show_clipboard_copy_button'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable/Disable Button'),
    '#description' => t('Controls display of Copy to Clipboard Button'),
    '#default_value' => $settings['show_clipboard_copy_button'],
  );

  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */

function clipboard_field_formatter_settings_summary($field, $instance,     $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = t('Enable or Disable a Copy to Clipboard button for text fields', array(
    '@show_clipboard_copy_button'     =>     $settings['show_clipboard_copy_button'],
    )
  );
  return $summary;
}

/**
 * Implements hook_field_formatter_view()
 */

function clipboard_field_formatter_view($entity_type, $entity, $field,     $instance, $langcode, $items, $display) {

  $element = array();
  return $element;

}

```

# Answer
You are not supposed to see the settings form in Manage Fields \> edit (a specific field) \> Field settings as you expect. Formatters are used for managing the display of fields (theming). So, go to 'Manage Display' tab (for your Content Type) and choose the view mode for which you want to manage the button visibility (default, full content, teaser, e.t.c). Find the field(s) you wish this functionality to be applied, and then select as 'Format' option, the label of the formatter you just created, which in this case is 'Copy to Clipboard'. Then if you click on the cogwheel icon on the right, you will see your settings form. Note that this setting will be applicable to all instances of this CT for the specified field for the specified view mode.

If you want other fields of the same CT as well, you need to repeat the process for the other fields as well. If you want this functionality for additional displays of this CT (e.g. teaser view), then you need to repeat the process. And of course, repeat the process for all CTs/view modes/fields as well. This is because Drupal offers much flexibility and variety in displaying content. If you want such a functionality to be applied globally (e.g. for all CTs, for all text fields) then perhaps you should consider another strategy; a new theming function or override of an existing one for example.
> 1 votes

---
Tags: entities
---


# Question
Title: *Some* Users Experiencing Login Failures
A significant minority of our users *repeatedly* experience login failures and have to reset their passwords every time. Can anyone suggest possible solutions please? Details as follows.

Apparently, the behaviour is as follows:

* User opens login page, enters valid username and password.
* Login fails, repeatedly!
* User requests password reset. Then, using link from e-mail able to: reset password, login and access their account
* Next login, user has to repeat process.

Unfortunately, we can't duplicate the issue ourselves. But we have looked through Drupal logs and Apache access logs and observed the following:

* The problem is not confined to a specific browser (seen on IE, Safari, Firefox) nor a specific OS (seen on Windows, Mac, iPad)
* The users do generally have cookies turned on. We have inserted some custom code to warn users with cookies turned off and write "cookies disabled" to Drupal logs.
* Clearing all caches in Drupal doesn't fix issue.
* Clearing cookies in browser doesn't fix issue either, one of our users has tried.

We are running Apache on an Ubuntu server.

In settings.php, $base\_url is commented out; $cookie\_domain is also commented out. It was set, but we decided it was safer to remove it although, I'm not sure that made any difference.

We are using "Profile2" and "Profile2 Registration Path" modules. However, I doubt those modules are the source of our problems as I cannot find any record of anyone else having login problems with those modules.

Do you have any suggestion?

I should have mentioned, the site is running Drupal 7.13.

When the user clicks on the password reset link they are currently prompted to change their password.

We have also asked one user to try another browser but sadly, that didn't fix their problem. Also we have noticed that the problem on IE, Firefox & Safari so, we don't think it's browser specific

# Answer
> 3 votes
Not meaning to dig up an old thread, just trying to help anybody who finds it - we had the exact issue described here, on two occasions, on two sites. We finally figure it was caused by users trying to log in with their email address instead of their username, which is why they are able to reset the password but not log in.

# Answer
> 2 votes
I would ask one of the people who has had this problem to work through it with you. Do a skype screenshare or look over their shoulder while they experience the problem.

In my experience, these people are not clicking "save" after entering a new password so their password isn't actually getting changed.

# Answer
> 0 votes
Perhaps your users are being flood-locked. Too many unsuccessful logins will cause the user to be blocked. A less-well-known feature is that too many unsuccessful logins from a given IP will cause a user to be blocked. This is set to 50 failed attempts per hour by default.

So if you have a lot of users accessing via a single IP (maybe they're on a company network) then a few people forgetting their passwords can inadvertantly lock each other out. The next time you get this problem it would be interesting to take a look at the flood table to see if they're locked.

To test this, you could also increase the flood lock values user\_failed\_login\_ip\_limit and user\_failed\_login\_ip\_window. There's no UI for this in core but the Flood Control module provides one. Or you can easily set the value from drush or in your settings.php file.

---
Tags: users
---


# Question
Title: Is there a way to position my Article title in Drupal 8 teaser?
I have In teasers and other custom display types I would like the image to appear above the title. However, when I try to manage the display fields from the admin menu there is no way to change the title or byline.

In other words the only field I choose to display from that menu is image, but on the page the title, date and author appear.

```
 <title>
 Submitted by <author> on <date>

```

Is there a way outside CSS to move these things around

# Answer
You either need to do it in node templates or you can try out Display Suite, but I'm not sure about the exact state of it in Drupal 8.

Update: Didn't see that you also mean the byline. That one is easy, that's a setting on the node type form whether it should be shown or not.
> 3 votes

---
Tags: views, 8, nodes
---


title: Pathologic breaks my external links

text:
# Question
Title: Pathologic breaks my external links
My basic page is using a wysiwyg editor (ckeditor) which is filtered by pathologic to generate links that uses my pathauto aliases. This is great. My problem is with external links. Somehow, pathologic detect those links as a broken internal link and replaces the external domain with its local domain...

ex: my site is on domain.com and on a page's wysiwyg field I am putting an external link to anotherdomainwehost.com/about/us.

This is changed by pathologic to "domain.com/about/us" which is completely wrong!

How can I fix this? Somehow pathologic thinks that anotherdomainwehost.com is the same web site as domain.com. I don't know why and can't find where are those configured.

I found no where in my installation a way to edit the pathologic settings. I went to the Pathologic page but can't find the provided link. I have no "Pathologic" option in the Content Authoring menu...

I am willing to hack the damn thing, whether it is in the code or in the db if someone tells me where to look!

# Answer
> 3 votes
Pathologic settings are on the text format. So you'd go here: admin/config/content/formats and click "configure" next to the format you want to tweak. If it's a format that has Pathologic selected for it, then you will see a "Correct URLs with Pathologic" vertical tab down near the bottom of the page. The settings are in there.

It sounds like you have anotherdomainwehost.com in the list of "all base paths for this site".

---
Tags: 7, input-formats
---


# Question
Title: Problem installing Drush 7 due to missing ext-pcntl PHP extension - any workarounds?
I attempted to install Drush 7 using the "manual install" instructions, and the "composer install" step failed with the error that the ext-pcntl PHP extension was not found. The hosting company (which I don't have control over choosing) says they are unwilling to install ext-pcntl in a production environment due to security concerns. Are such security concerns justified? Is there any workaround for installing Drush 7 without the ext-pcntl dependency? If not, I might try to install an older Drush version that doesn't have the dependency.

# Answer
# Are such security concerns justified?

Given the description on extension's introduction page, **yes**:

> Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control **should not be enabled within a web server** environment and unexpected results may happen if any Process Control functions are used within a web server environment.

Emphasis mine.

But also **no**, because, as greg\_1\_anderson stated in his answer, it can be enabled (or even compiled) into CLI only.

Then again, it **might be yes**. With functions like `pcntl_fork` it might be possible to make a fork bomb. Other bad things may also be possible. Personally, I wouldn't allow it on shared server.

# Is there any workaround for installing Drush 7 without the ext-pcntl dependency?

**Not really\*, but** if you can mount webserver's filesystem on your local machine and tunnel SQL port, you can install drush locally and still use it on remote website. From Drush's point of view there will be no difference.

---

* Correct me if I'm wrong here.
> 1 votes

# Answer
php-cli has a different php.ini file than the webserver's php environment, so it is entirely possible to enable ext-pcntl for php-cli, but not for the php in the web server environment. Some shared hosting environments only allow one shared php.ini file, though. It is also possible that they may be unwilling to install it simply to prevent their clients from accidentally enabling it for the web server environment.

Drush uses ext-pcntl in backend invoke, so it is unlikely that you'll be able to use Drush successfully without it. The missing dependency might not be enforced in pre-Composer versions of Drush, so it might work to install Drush 6 or earlier, provided you do not call any functions that redispatch back to drush (e.g. use `drush pm-updatecode` followed by `drush updatedb` rather than using `drush pm-update` -- not that you'll be updating your live site on the hosting platform with `pm-update` though, right?)
> 1 votes

---
Tags: drush
---


# Question
Title: How to pass information by reference from a hook to Feeds?
I need to have the ability to tell Feeds to skip a node from `hook_feeds_before_update`. But since there is no variable sent by reference I don't know if it's possible without having to modify the code in Feeds.

Anyone know how to do this?

# Answer
The hook hook\_feeds\_before\_update() doesn't support skip items. You could use the hook hook\_feeds\_presave() instead. Set $entity-\>feeds\_item-\>skip to TRUE if you want to skip saving the entity. See feeds.api.php for an example.

You could also use the hook hook\_feeds\_after\_parse() to remove items from the list to be imported. The items are in $result-\>items. This hook is invoked before processing happens, so at this point it is still unknown to which entities the items will be imported (you have no entity ids). Feeds Tamper uses this hook to modify the data to be imported.
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: Unable to filter Views by a date field in the user profile
I have used the Profile module to create a date field on users profiles.

Now I want a view to list users filtering by that date field, but when I choose "Add filter criteria" in the Views UI, it does not list the date field. Fields of other types show up normally.

Is this a Views bug? How can I filter a view based on a date field from user profiles?

# Answer
To create a view about **Users**, you start from `admin/structure/views/add` (of course).

However, below "Description" you need to select what type of data you want to "Show", and then optionally also select a "Type", etc).

By default (when you start creating a new view) it will suggest "Content" as value for "Show". But in your case you should have selected "Users" instead. If you do select "Users", you won't be able to select a "type" anymore. Because of the "*... Fields of other types show up normally ...*" in your question I assume you used the default (Content) instead of "Users".

That's possibly the reason why you can't select the user related fields either ... To resolve this, just create a new view about "Users".
> 0 votes

# Answer
Since the date is in a profile and not in the user, you view is going to have to use profile as your main content type and then join the content with user on the user ID field.

Be aware that the author of the profile2 module has stated that it might be better to add the fields to user rather than use the profile module. When the profile module was written user objects could not have additional fields added to them. This changed with the introduction of Drupal 7 and entities.

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

---
Tags: 7, views, users
---


# Question
Title: How to solve claimitem() in batch process?
I am doing batch process in D8. here is my code: This code is in **Controller.php**

```
$batch = array(
          'title' => t('Started Importing node Data.'),
          'error_message' => t('Error!'), //Error Message
          'finished' => 'node_data_import_batch_finished',
        );
        $count_nodes = '';
        $j = 0;
        $data_chunk = array_chunk($csv, 100);
        foreach ($data_chunk as $node_created) {
          $count_nodes += count($node_created);
          $batch['operations'][] = array('node_data_import_batch', array($node_created,  $keys));
          $j++;
        }
        batch_set($batch);

```

And callback function is in **.module**

```
function node_data_import_batch($node_created,  $keys){
//Code here
}

function node_data_import_batch_finished($success, $results, $operations){
 if ($success) {
    $message = "Batch Process Successfully executed for Node Data.";
    drupal_set_message($message);
  }
}

```

I am getting error like this. Any help will be appreciable Thanks.

# Answer
> 0 votes
Add the `'file'` key in your batch:

> * file: Path to the file containing the definitions of the 'operations' and 'finished' functions, for instance if they don't reside in the main .module file. The path should be relative to base\_path(), and thus should be built using drupal\_get\_path().

```
$batch = array(
  'title' => t('Started Importing node Data.'),
  'error_message' => t('Error!'), //Error Message
  'finished' => 'node_data_import_batch_finished',
  'file' => drupal_get_path('module', 'YOUR_MODULE_NAME') . '/YOUR_MODULE_NAME.module',
);

```

---
Tags: 8, batch-operations
---


# Question
Title: An AJAX HTTP error occurred. HTTP Result Code: 500
Everytime I try to edit content on one of my panels I get the following error message.

```
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /panels/ajax/editor/edit-pane/panel_context%3Apage-   sign_up_page%3A%3Apage_sign_up_page_panel_context%3A%3A%3A%3A/417
StatusText: Internal Server Error
ResponseText:

```

I am using Panels 7.x-3.5. Anyone have any idea how to go about fixing this?

# Answer
You guys were right and it was a problem with CKEditor and Media not working well together. I fixed it using a patch found here: https://www.drupal.org/node/2455391
> 1 votes

---
Tags: ajax, panels, debugging
---


title: Can't update custom module

text:
# Question
Title: Can't update custom module
I need to add some tables to the database in a new module version. I created a hook\_update function:

```
function bundles_update_7000()
{
    ...
}

```

But for some reason my module is missing in the updates list in the admin interface. When I run:

```
drush pm-update bundles

```

it writes: "No code updates available."

What could be the issue?

# Answer
You need to run drush updb, not drush pm-update. And you don't specify the module name. So just:

```
drush updb

```
> 4 votes

---
Tags: 7, updating
---


# Question
Title: Returning code in views search tpl but ONLY if user clicked 'search' button and results were returned
I have a Views-based search page on my site. I've created a views-view-search--tpl.php file to customize the order of elements on the page. I have a specific block I'd like to return but ONLY if a user has already clicked the search button and results were returned.

Here's the code I'd like to return based on that condition:

```
  <?php if ($feed_icon): ?>
   <div class="feed-icon">
    <?php print $feed_icon; ?>
   </div>
  <?php endif; ?>

```

I guess I probably need an 'if' statement or something before that block but I'm not sure how to reference if results and/or if user clicked the search button...

Anyone know how to do this?

# Answer
> 1 votes
This should probably be done in a pre-processor rather than a template file, but I'll stick to the question as asked, for now:

```
<?php if (!empty($view->exposed_input) && !empty($rows)): ?>
 <?php if ($feed_icon): ?>
  <div class="feed-icon">
   <?php print $feed_icon; ?>
  </div>
 <?php endif; ?>
<?php endif; ?>

```

---
Tags: views, theming, search
---


# Question
Title: How can I use the Private Message module for anonymous users?
I am using the Private Message module as a way of contacting the author of a node.

I have the problem that the button that says "*Send author a message*" only appears on the node when the user is logged in. If the user is not logged in, then the button that appears is the one that says "*Log in or register to be able to post comments*" (or something like that)

What I want to achieve is that the user (not logged in) can see the "*Send author a message*" on the node. And when this user clicks on this button he will be taken to the login form first, and then, after login, the user gets redirected to type the message to the node author.

How can I achieve this?

# Answer
The Privatemsg module CANNOT be used for anonymous users ... Unless you are ready for some "tweaks" ... as detailed below.

I'm assuming your question is about D7, if it is for D6, you might consider using what's described in Issue # 490264. But it's worth reviewing that issue to get "an idea" about a possible work around ...

So how about D7? Issue # 554238 is about D7, and Comment #7 in it refers to the issue I mentioned above (which is for D6). However Comment #8 in that issue might be the solution. It contains this code sample:

```
<?php
$msg = "Hello there";
$source_tag = "from {$_SERVER['REMOTE_ADDR']}";
$result = privatemsg_new_thread( array(user_load(1)), "Browser visit {$source_tag}", $msg, array('author' => user_load(1)) );
// If you wanted to show an error, uncomment the following:
if (!isset( $result['success'] ) || !$result['success'])
{
  printf( "<p>Failed to send: %s</p>\n", $result['error'] );
}
?>

```

Apart from what is above, there is also the (way more) recent issue \# 2231795. Comment #1 in it contains a code sample also. So if the above code doesn't fit (or work), consider this as an alternative.

So by using the Privatemsg module, and some tweaks (see above) you should be able to make it work somehow for anonymous users also
> 1 votes

---
Tags: 7, privatemsg
---


# Question
Title: Why is my MONTH view still showing a DAY as the title?
UPDATE: I see the issue was not fixed in the current release so am especially interested in any suggestions for workarounds. For example, maybe I could hide the default header with CSS and add the correct title in the view.

ORIGINAL QUESTION: I know this was a bug in the 7.x-2.x-dev version of the Date module, but it seems to have been patched. I am running 7.x-2.8 (the latest) in which it should be fixed.

Why am I having this problem, and more importantly how can I work around it? I am working on a site where I only have access to the site administration, and not the server (ie: I can't patch the module myself).

# Answer
> 2 votes
It appears that the fix isn't in the latest release (7.x-2.8) yet and is instead in the current (7.x-2.x-dev) version. According to the comment #70 in that thread you posted, the patch is meant to be applied to the current release and not the latest dev (which is why it failed). If you run the patch in comment 70 against your 7.x-2.8 version it should correct the issue. As you stated that isn't an option, you can try to have the drupal update page grab the latest dev.

You can always check the release date for different branches on the project page. For example, Date currently shows the 7.x-2.8 branch as having been released on July 29th, 2014 while the latest commit, 7.x-2.x-dev, was released on June 16th, 2014. Hope that helps

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


title: 2 different views page per Node

text:
# Question
Title: 2 different views page per Node
I have a content type "X", and would like to have 2 different view mode per node(I guess it should be 2 different url per node: /node/1 & node/1/summary). I'm not sure is it possible, but I want to make a view that list node of content type "X", each node has 2 links(2 fields), they are link to view mode 1(some fields) and view mode 2(full).

I have been searching this for day with no luck, and hope someone have done this before.

**-- update my question for the confusion : Aug 5, 2015 at 5:pm --**
What I really need is to have 2 different views mode pages per node(2 actual page per node), so each node can have their summary page(not a list of teaser mode) and full content page.

# Answer
you Could create your own display mode using see this Then you create a menu route using hook\_menu, similar to this:

```
function yourModule_menu() {
$items = array();

$items['node/%node/viewmode2'] = array(
'title' => 'Test',
'page callback' => 'yourModule_page_callback',
'page arguments' => array('node', 1),
'access arguments' => array(1),
'type' => MENU_CALLBACK,
);

return $items;
}

function yourModule_page_callback($node) {
 // here you render the node with the view mode 2
 $node_view = node_view($node, 'view_mode2_key');
 $rendered_node = drupal_render($node_view);
 return $rendered_node;
}

```

for the other view mode you could use the default display mode on node/node\_id or you could create extra one with same approach
> 2 votes

# Answer
sam2de has a very good answer. You could also do this without any custom code using Panels. You would create a new Panels page, set the path to be node/%node/viewmode2, then embed a pane of type "rendered node" that renders the node using the view mode you desire.
> 0 votes

# Answer
Found View Mode Page module do the trick. This module can create separate pages for different view modes for a given content type.

**How to add a view mode page**

1. Create a content type
2. Configure a view mode. If you are using Display Suite, or another means of adding view modes, you may need to add a new one.
3. Go to the "manage display" tab for your content type.
4. In the "View mode pages" tab, enter your URL pattern for the view mode page.
5. Save the content type. You may also need to clear the Drupal cache, but the page should be available!
> 0 votes

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


# Question
Title: Naming Structure for Create Node Page template?
I need to create a custom template for: /node/add/node

It's currently using: page--node.tpl.php

What's the file naming convention for this?

# Answer
"page--node--add--nodetype.tpl.php" overides it.
> 0 votes

---
Tags: theming, nodes
---


# Question
Title: How to reveal the admin password when logged in with one time login link?
I just started on a project and there is a prod and dev server. I have access to the dev server and I'm able to do a force login via 'drush uli admin' but I do not have access to the prod server to do the same thing. Is there a way to reveal the admin password on the dev drupal when logged in as admin?

# Answer
> 2 votes
The short answer is: no.

A Drupal password is saved to the database after getting hashed, and the hash is not reversible in any sense that you're hoping for.

An alternative solution would be to try to reset the password to something you know. Drupal has a description of an SQL approach if you can't use the "reset password" function.

If you don't have command line access you can try using a PHP method to reset it. However, that is really a last resort kind of situation because of the security implications. **Super last resort.**

# Answer
> 0 votes
You could install the AES module. It might give you that ability.

---
Tags: drush, users
---


# Question
Title: Field collection with condition node tpl
I've been researching this for the last few days and I cant find a clear explanation of this issue im facing. I'm receiving an error when a node has an empty collection with no values.

The collection field: field\_window\_shade
The fields within the collection: field\_question, field\_answer

Here is my code that is only looping thru the collection array *within my node.tpl*:

```
            $wrapper  = entity_metadata_wrapper('node', $node);
            $formtype = field_get_items('node', $node, 'field_window_shade');

            foreach($formtype as $itemid) {
                 $item = field_collection_field_get_entity($itemid);
                 print $item->field_question['und'][0]['value'];
                 print $item->field_answer['und'][0]['value'];
            }

```

I am after something like this:

```
            $wrapper  = entity_metadata_wrapper('node', $node);
            $formtype = field_get_items('node', $node, 'field_window_shade');

            if (isset($wrapper->field_question)) {
              foreach($formtype as $itemid) {
                 $item = field_collection_field_get_entity($itemid);
                 print $item->field_question['und'][0]['value'];
                 print $item->field_answer['und'][0]['value'];
              }
            }

```

I've seen this question asked about 5 different times with 10 different solutions and I can't seem to reach a solution here.

Thank you !

# Answer
> 1 votes
Did you try `field_collection_item` in `entity_metadata_wrapper`? I mean this

```
$wrapper  = entity_metadata_wrapper('node', $node);
$raw_collection = $wrapper->field_window_shade->value();
$fwrapper = entity_metadata_wrapper('field_collection_item', $raw_collection);

```

Now use `$fwrapper` to extract the items (This code is not completely accurate a few modification may be needed)

Visit Extracting a specific data part of a Field Collection Item for more details. Also Programmatically create and update field collection with Entity API and Understanding Field Collection Values can be helpful.

# Answer
> 0 votes
I've solved this by using the correct field format (filter) type.

here: $item-\>field\_answer-\>value-\>raw(); error is now gone

```
     <?php
            $wrapper         = entity_metadata_wrapper('node', $node);
            $raw_collection = $wrapper->field_window_shade->value();

            foreach ($wrapper->field_window_shade as $item):
                print "<div class='faq collection-item'><h3 class='toggle'><p>" . $item->field_question->value() . "</p></h3>";
                print "<div class='faq-content'><div class='faq-content-inner'><p>" . $item->field_answer->value->raw() . "</p></div></div></div>";
            endforeach;
        ?>

```

---
Tags: theming, entities
---


# Question
Title: Table Pager Rendered in an Ajax Callback Shows White Page
I have the callback function below that renders a table with a pager. Every page of the table is 20 rows. Below is the code:

```
function myid_print_all_submitted_id_callback($form, &$form_state){
    $table_html = '';
    $rows = array();

    // Build the sortable table header.
    $header = array(
        'idnumber' => array('data' => t('ID Number'), 'field' => 'idnumber'),
        'student' => array('data' => t('Student'), 'field' => 'student'),
        'status' => array('data' => t('Lacking ID Information | Status'), 'field' => 'status'),
    );

    $query = db_select('student', 't1',array('target' => 'import'));
    $result = $query
        ->fields('t1', array('idnumber','student','status'))
        ->condition('t1.studid', 1 ,'=')
        ->extend('TableSort')->extend('PagerDefault')->limit(20)
        ->execute();

    foreach($result as $record){
        $rows[] = array(
            'idnumber' => $record->idnumber,
            'student' => $record->student,
            'status' => $record->status,
        );
    }

    $table_html = theme('table', array('header' => $header, 'rows' => $rows)) . theme("pager");

    //Build the table
    $form['table'] = array(
        '#type' => 'item',
        '#markup' => $table_html,
        '#empty' => t('Table has no row!'),
        '#prefix' => '<div id="myid_table_wrapper_div">',
        '#suffix' => '</div>',
    );
    return $form['table'];

```

}

It looks like the image below:

When I click the next page it shows a blank page:

Where did I go wrong? It was redirected to `http://19.46.1.13/myid/system/ajax?page=1`, when it must be redirected to `http://19.46.1.13/myid/user/1/myid_print?page=2`.

I was guessing it is because the table pager was not loaded yet because it was rendered by a callback function. Any suggestions/solutions on how to solve it?

# Answer
> 0 votes
This sounds like a known bug in core:

Pager, tablesort links in a form point to system/ajax when reloaded via AJAX https://www.drupal.org/node/1181370

Someone has offered up a "quick fix" in comment #22:

> As a quick fix I overrode theme\_pager\_link() to set the url of my AJAX-loaded pager to the page url instead of $\_GET\['q'\] (which was system/ajax).

\[Edit...\]

I haven't tested this, but give it a try:

1. In your callback function, save the current path in a session variable:

```
$_SESSION['page_path'] = current_path();
```
2. Copy and paste this function into your \*.module file:

```
/**
 * Implements hook_theme_registry_alter().
 */
function YOUR_MODULE_NAME_theme_registry_alter(&$theme_registry) {
  $theme_registry['pager_link']['theme path'] = drupal_get_path('module', 'YOUR_MODULE_NAME');
  $theme_registry['pager_link']['function'] = 'YOUR_MODULE_NAME_pager_link';
}

```
3. Copy the theme\_pager\_link() function into your \*.module file.
4. Rename the function `YOUR_MODULE_NAME_pager_link`.
5. In the function, replace the following line:

```
$attributes['href'] = url($_GET['q'], array('query' => $query));

```

with:

```
if (isset($_SESSION['page_path'])) {
  $attributes['href'] = url($_SESSION['page_path'], array('query' => $query));
}
else {
  $attributes['href'] = url($_GET['q'], array('query' => $query));
}

```
6. Clear the caches.

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


# Question
Title: Does drupal have another module that have the same feature as media watermark?
I am looking a watermark module that have a selection watermark just like in the image.

Unfortunately the media watermark module is support drupal 7.

Does drupal have another module that have the same feature as media watermark?

PS: I am using drupal 6.

# Answer
> 0 votes
Try ImageCache Actions Module. I think this will help you...

---
Tags: media
---


# Question
Title: How to restrict access to a path like user/%/flag?
I have created a views to display flagged content. But the flag page is accessed by all users. I want users to access only their own flagged page.

# Answer
You need to create custom Views access plugin for this. First, you need to create mymodule.info file with next code

```
name = Mymodule
description = Custom code
core = 7.x
package = custom
dependencies[] = views
files[] = mymodule_access_plugin.inc

```

Second, add mymodule\_access\_plugin.inc in the your module folder with next code

```
<?php

/**
 * Access plugin that provides property based access control.
 */
class mymodule_access_plugin extends views_plugin_access {

  function summary_title() {
    return t('Custom access plugin');
  } // summary_title()

  /**
   * Determine if the current user has access or not.
   */
  function access($account) {
    return mymodule_access($account);
  }

  function get_access_callback() {
    return array('mymodule_access', array());
  }

}

```

Third, implement hook\_views\_plugins in your mymodule.module file

```
<?php

/**
 * Implements hook_views_plugins()
 */
function mymodule_views_plugins() {
  $plugins = array(
    'access' => array(
      'test' => array(
        'title' => t('Custom access check'),
        'help' => t('This is a custom access plugin'),
        'handler' => 'mymodule_access_plugin',
        'path' => drupal_get_path('module', 'mymodule'),
      ),
    ),
  );
  return $plugins;
}

function mymodule_access($account = NULL) {
  global $user;
  if (!empty($account->uid) && $account->uid == $user->uid) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

```

Fourth, clear caches and apply your custom access plugin in views
> 2 votes

# Answer
Use the Rules module, and a rule that is a variation of the rule I included (in export format) in my answer to the question about How to restrict access to a node via node/12 and allow access via a path like content/sometitle?

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

* Change `node` to `user` and add `/flag` at the end.
* Add a Rules '*Condition*' like "If the value used for `%` does not match the `uid`".
* Change the "Message" (in the Rules '*Action*'- to something to indicate that the user can only use a value that matches their own `uid`.
* Modify the Rules '*Action*' to fit your own requirements, e.g. to issue a redirect to their own 'flagged page'!

Haven't experimented/tried creating this rule (= variation of the rule in the answer I mentioned above). But pretty sure it'll work. Hopefully you'll be able to complete the rest of the puzzle in my answer on your own.
> 0 votes

---
Tags: 7, views, users, flags
---


title: Server Error 500 on every Ajax Call

text:
# Question
Title: Server Error 500 on every Ajax Call
we have a problem that we get a internal server error on about every ajax call. The example below happens when editing a view clicking "add filter" and directly click on abort. It also happens when making changes to a view. At first glance the change seemed to be ignored but after refreshing the pages the changes will be visible.

When accessing the URL which throws the error we get a valid json string (checked with jsonlint.com).

Our server logs sadly show nothing interesting. I would appreciate any kind of hint where to look for a solution.

**Edit:** The nojs version seems to work fine but that's no solution in the long term :/

# Answer
Look at your PHP error log. It should give you the file and line number it's having an issue with.

If you can, copy and paste the last few lines of the error log on here for us to look at.
> 1 votes

# Answer
When I have something like this it has always to do with the .htaccess file. Or maybe you just haven't enabled clean url's or something like that.

**EDIT** Is there somthing like this in your htaccess file

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

```

Make sure it's uncommented
> -1 votes

# Answer
Create a separate page using `hook_menu` and write the same logic on the page where you are hitting. Also pass the arguments if any, if the newly created page is working fine then just replace that page with this newly created page.
> -1 votes

---
Tags: views, ajax
---


# Question
Title: How to put multiple fields in an index operation on a GET HTTP request with services?
I'm working with the module "services" everything's ok with a get request, note that i've create my own custom resource with CRUD operations, the "retrieve","update" are ok but the problem is with the index operation. With only one field it works and show all records with the default field I declared on resource. Now how to put an array of $fields ?

This is the resource declaration (the "fields" part of the code) :

```
array(
        'name' => 'fields',
        'optional' => TRUE,
        'type' => 'string',
        'description' => 'The fields to get.',
        'default value' => 'field_title_value',
        'source' => array('param' => 'fields'),
      ),

```

now here is the function index (callback) :

```
function _my_module_livre_index($page, $fields, $parameters, $page_size){

$query = db_select('field_data_field_title','t');

services_resource_build_index_query($query, $page, $fields, $parameters, $page_size, 'Livre');
$result = services_resource_execute_index_query($query);

$bien = services_resource_build_index_list($result, 'livre', 'field_title_value');
return array('code'=>'0', 'response'=>$bien);
}

```

The doc of services said that $fields is an array of fields i want to return, when i make : `$fields = array('field 1','field 2','field 3');` It return an error. If I make a "classic" :

```
$query = db_select('my table')
->fields('my table', array('field 1','field 2','field 3')

```

Same error.

Any help please ?

Thank you all.

# Answer
The simple db\_select with fields make it work easy as that :

```
function _my_module_livre_index($page, $fields, $parameters, $page_size){

$query = db_select('field_data_field_title','t')
->fields('t', array('field_title_value','entity_id','delta'));//<+++++ whatever you want

services_resource_build_index_query($query, $page, $fields, $parameters, $page_size, 'Livre');
$result = services_resource_execute_index_query($query);

$bien = services_resource_build_index_list($result, 'livre', 'field_title_value');
return array('code'=>'0', 'response'=>$bien);
}

```
> 1 votes

---
Tags: services, database
---


title: How to change the display of my field?

text:
# Question
Title: How to change the display of my field?
I have a field in one of my content types called lab\_test\_id. When Editors add content of that type they enter all the ids of the lab tests associated with that node. I need to be able to take that id, call that lab test database, and display the lab test fields I get back.

Can I accomplish that by changing the display of the lab\_test\_id field via hook\_field\_display\_alter or should I find another way to accomplish that?

# Answer
I think you can do this using `hook_field_display_alter`, however, I would personally prefer to create a custom formatter for the used field type. With the main advantage that you can save settings for the field formatter.

See the answers of How do I write an additional field formatter for an existing field for basic steps on how to create your own field formatter.
> 1 votes

---
Tags: entities
---


# Question
Title: Copy blocks from one drupal installation to another
With a lot of help from the users of this forum yesterday I managed to get my local installation running.

I have copied across the theme from the site I wish to base mine on (with the permission of the theme owner, so nothing dodgy is going on).

But when I go to Blocks, there are none present. If I look in the admin on the old site, there are a number of blocks that appear in the header (menu, search bar and so on). If I click on create new block on my install I get a blank form. Is there any way to copy existing blocks from the install I am mimicking to mine?

# Answer
Blocks are considered content, like nodes are. So basically you want to migrate content? You could work with Migrate or Block Export Import.
> 0 votes

---
Tags: blocks
---


# Question
Title: How to display block using hook_block on specific pages only
I am creating the block using the following code , but i need to dsiplay this block only in specific pages only . How can i achieve this ?

```
function mailusers_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0] = array(
      'info' => t('User Management block'),
      'weight' => 0,
      'status' => 1,
      'region' => 'left',
    );

    return $blocks;
  }

  else if ($op == 'save' && $delta == 0) {
    variable_set('test_block_items', $edit['items']);
  }
  else if ($op == 'view') {
    switch ($delta) {
      case 0:
        // Your module will need to define this function to render the block.
        $block = array(
          'subject' => t('User Group Management'),
          'content' => mailuser_block_conent(),
        );
        break;
    }
    return $block;
  }
}

function mailuser_block_conent(){
    //create menu links
     $ret = '<a href="'.$base_url.'/mailusers/adduser">Add User </a>';
     return $ret;
}

```

# Answer
You need to add 'visibility' option that is equal to 1 and 'pages' option that should be a string that contains one or more page paths separated by '\n', '\r', or '\r\n' for your block information

```
 $blocks[0] = array(
  'info' => t('User Management block'),
  'weight' => 0,
  'status' => 1,
  'region' => 'left',
  'visibility' => 1,
  'pages' => 'node/1'
);

```
> 0 votes

---
Tags: 6, blocks
---


# Question
Title: How to resolve my error in bootstrap.inc?
I use Drupal 7.38 and I have taken the backup from server side and added in my local server. Then the following error showns up:

> Fatal error: require\_once(): Failed opening required
>
> 'D:\xampp\htdocs\kaya/sites/all/modules/commerce\_invoice\_receipt/commerce\_invoice\_receipt.admin.inc'
>
> (include\_path='../lib;D:\xampp\htdocs\kaya\sites\all\modules\custom\commerce\_citrus\lib;.;D:\xampp\php\PEAR') in D:\xampp\htdocs\kaya\includes\bootstrap.inc on line 3186

How can I resolve this error?

# Answer
The file

> D:\xampp\htdocs\kaya/sites/all/modules/commerce\_invoice\_receipt/commerce\_invoice\_receipt.admin.inc

Is missing; the Commerce Invoice Receipt module is installed on your site, so the file needs to exist.

If you've lost the file(s) somehow, just download the module again and put it back in place.

If you've removed it on purpose, but without uninstalling the module, follow the above first, *then* disable and uninstall it. Then you can remove the files safely.
> 1 votes

---
Tags: 7
---


# Question
Title: Why can not Drupal find my theme for a custom block?
I read this answer, but I can not figure out, why my block is not shown. My block is activated in footer and should appear on `<front>`.

```
/**
 * Implements hook_theme().
 */
function poll_dialog_theme() {
  return array(
    'poll_dialog_output' => array(
      'variables' => array(
        'title' => NULL,
        'content' => NULL,
        'popular_content' => NULL,
      ),
      'template' => 'theme/poll_dialog',
    ),
  );
}

function poll_dialog_block_info() {
  $blocks['poll_dialog'] = array(
    'info' => t('Poll Dialog'),
    'cache' => DRUPAL_NO_CACHE, //there are a number of caching options for this
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function poll_dialog_block_view($delta = '') {
  switch ($delta) {
    case 'poll_dialog':
      $block['subject'] = t('poll_dialog');
      $block['content'] = _poll_dialog_block_content();
      break;
  }
  return $block;
}

/**
 * Callback implemented by hook_block_view().
 */
function _poll_dialog_block_content() {
  $static_title = t('Static Title');
  $static_content = 'static content';

  return theme('poll_dialog', array(
      'title' => $static_title,
      'content' => $static_content,
      'link' => l('Poll', 'some url'), array('attributes' => array('target' => '_blank'))),
    )
  );
}

```

# Answer
You're calling a non-existent theme function. Your code should be:

```
return theme('poll_dialog_output', array(
    'title' => $static_title,
    'content' => $static_content,
    'link' => l('Poll', 'some url'), array('attributes' => array('target' => '_blank'))),
  )
);

```

or, even better:

```
return array(
  '#theme' => 'poll_dialog_output',
  '#title' => $static_title,
  '#content' => $static_content,
  '#link' => l('Poll', 'some url'), array('attributes' => array('target' => '_blank'))),
);

```

The main point is that the name of the theme function you call needs to match what you've used in `hook_theme()`.
> 2 votes

---
Tags: blocks, theming
---


title: How to alter query of services module

text:
# Question
Title: How to alter query of services module
I am using `service module 7.x-3.12`. The index call by node resource provides provides node related data but only from node table. I can't fetch the value from custom fields of a node. So I want to alter the query in index call build by `services_resource_build_index_query()` function. But I can't find any way to alter the query.

# Answer
> 1 votes
You can use rules for this to add custom field or you can use "hook\_services\_request\_postprocess\_alter" to add new array with custom field.

Using rule you can set in **event** "Content is viewed of type .." and in **action** you need to custom php that returns $node-\>custom\_field = val;

# Answer
> 0 votes
You can use `hook_query_alter()` to alter any query that uses Drupal's database API.

Example from the docs:

```
function hook_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('micro_limit')) {
    $query->range(0, 2);
  }
}

```

---
Tags: 7, services, database
---


# Question
Title: Send push notifications by limit per user
I have configured multiple rules to send push notifications to multiple users with no limit (because push notifications does not provide any limit how much notifications system send to user). I would like send push notification to particular user with limit of 4 notification for some extent of time. If user get lot more notification he remove app from mobile or frustrate. Anybody have any idea how this can be achieved.

# Answer
> 0 votes
A simple way to do this is to add a user field. This field will keep track of the number of push notifications sent and will increment every time you send a new push notification to the user.

In your rule, add a condition that checks the value of the field and execute the actions if value \<= 4. Then, in the action part of the rule, increment the value of the field by one.

---
Tags: 7, notifications
---


# Question
Title: Creating a custom field view using theme_field template
Folks - I'm trying to create a custom field view with custom content that utilises the standard `theme_field` template, to display in a node template.

I've tried to call the function programmatically e.g:

```
  $field_vars = array(
    'title_attributes' => 'test123',
    'label' => t('custom field label'),
    'items' => array('<p>This is a test</p>'),
    'classes' => 'test',
    'attributes' => FALSE
  );
  $my_field = theme('field', $field_vars);
  print $my_field;

```

It returns the template, but none of the `$field_vars` are being used. Has anyone done something similar?

# Answer
I'm not really sure what you are trying to do, but if you only like to render a custom array with the field template this should work:

```
$field = array(
  '#theme' => 'field',
  '#field_type' => 'text',
  '#field_name' => 'temp_field',
  '#entity_type' => 'node',
  '#bundle' => null,
  '#items' => array(
     array(
       'value' => '',
     )
   ),
   0 => array(
     '#markup' => '<p>This is a test</p>'
   )
);
print theme_field(array(
  'label_hidden' => false,
  'label' => t('custom field label'),
  'items' => array($field),
  'classes' => 'test',
  'content_attributes' => '',
  'attributes' => '',
  'item_attributes' => ''
));

```

You can load one of your existing field using `field_view_field()` to check what data the renderable array contains. For example to load the `body` field from a node with an `id` equal to 1000 you could do like this:

```
$node = node_load(1000);
$field = field_view_field('node', $node, 'body');
print_r($field);

```
> 1 votes

---
Tags: entities
---


title: Map Views fields from custom query

text:
# Question
Title: Map Views fields from custom query
I have a view and I want to override the query by writing my own using the Database API of Drupal. I already wrote a function that overrides the query and returns the result set I need:

```
function kviews_views_pre_execute(&$view) {

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

    $sql = db_select('node', 'n'); //Initial table select

    $sql->join('field_data_field_metric', 'm', 'n.nid = m.entity_id'); //Join the metrics table
    $sql->join('field_data_field_values', 'v', 'n.nid = v.entity_id'); //Join the values table
    $sql->join('field_data_field_page_connection', 'p', 'n.nid = p.entity_id'); //Join the pages table
    $sql->join('field_data_field_value_date_date', 'd', 'n.nid = d.entity_id'); //Join the dates table

    $sql->fields('n', array('title')) //Add fields - chained
    ->fields('d', array('field_value_date_date_value'))
        ->fields('v', array('field_values_value'))
        ->condition('m.field_metric_value', 'page_fans', 'LIKE')
        ->condition('p.field_page_connection_tid', 69, '=')
        ->condition('d.field_value_date_date_value', strtotime(date('Y-m-d')), '<')
        ->condition('d.field_value_date_date_value', strtotime(date('Y-m-d').' -8 days'), '>')
        ->orderBy('field_value_date_date_value', 'ASC') //Order results - chained
        ->range(0,15); //Limit results - chained

    $view->build_info['query'] = $sql;

}
}

```

The query executes successfully, in PHPMyAdmin it returns the right data and in the preview window of the view it displays the right amount of rows. All I get though is the label of the field I choose in the UI:

How can I map the fields I get from the query to the fields I add to the Views UI? Or maybe I need to add the fields to the view using a hook?

Thanks!

# Answer
One solution I found is to add PHP fields for the data you want to present into the view. The variable `$data` that holds what was retrieved from the database, per row, is printed this way:

```
print $data->[alias];

```

Where \[alias\] is the field alias from the database, without the brackets (ex. in `$sql->addField('n', 'title', 'node_title')` the alias is `node_title`).

This solution is not as clean as I would like so I will wait for more, "cleaner" answers before accepting this one.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Why do all my products (in Ubercart) get taxes applied after upgrading my Rules module?
I am using Drupal 7 and Ubercart (version 3). I try to add TAX to only certain items which has a particular Taxonomy Term Selected.

This functionality worked fine in previous version of Rules 7-2.8 But now for some reason all rules conditions come back as true and VAT is applied on all products.

I have tried downloading the older version same issue.

How to Replicate:

* Configuration \> Tax \> Editing Condition Set VAT
* Entity has field (Parameter `order:product:0:node`) has Field Product\_Type
* Data Comparison (Parameter `order:product:0:node:Product_Type`) one of Books, Hardware

So my real problem is that somehow all the products which do not have these terms selected are getting Taxes.

Any suggestions?

# Answer
Your comment about Rules version 7.x-2.3 rings a bell: I'm about sure that that is actually causing your problem. Refer to these issues for some more details:

I've hit a similar issue some months ago (in an "old D7 site where Rules wasn't upgraded yet from a pre-7.x-2.3 version). After I upgraded to the most recent Rules version (7.x-2.9) my site was broken also. I don't remember what the actual error was, but I narrowed it down to this Rules upgrade issue.

The way I got around it was like so:

* **Uninstall** the 7.x-2.9 version of Rules (that I had ust upgraded to).
* **Re-install** (from scratch) the 7.x-2.9 version of Rules.

That solved "my" issue. And I'm pretty sure it will also solve yours ... wanna try it? Attention: backup any of your custom rules first. E.g via an "export" of those custom rules (before uninstall), and "import" again afterwards (after you upgraded).

PS: just in case anybody else ever looks at this answer before upgrading from a pre-7.x-2.4 version of Rules, you can avoid the above surprises when upgrading Rules to something like 7.x-2.9 by:

* first uninstalling the old version (after export of custom rules),
* and then installing the newest Rules version (and then import of custom rules).
> 0 votes

---
Tags: 7, taxonomy-terms, rules, ubercart
---


# Question
Title: Make private pdf files Non-Downloadable via absolute url links
In a content type I have option for pdf file upload, the uploaded files are stored in private folder.

The uploaded file has absolute url of http://example.com/system/files/abc.pdf

At the moment anyone with the absolute url can download the file (no matter the user roles, access and permissions)

I want to redirect visitors to the front page of the website (instead of downloading) if they use the absolute url of pdf in browser to download it.

So far I tried something with JavaScript something like:

```
$(document).ready(function() {
  if(window.location.href.indexOf(".pdf") > -1) {
    $(location).attr('href', window.location.protocol + "//" + window.location.host); // Redirect to front page
  }
});

```

Usually this would do the trick if it was rendered webpage where javaScript is loaded, but it doesn't work with pdf files (as javaScript is not loaded while clicking the absolute url of the pdf file).

I have already tried private files download permission module, but that doesn't do what I want, as my downloadable links are accessible to Anonymous users as well.

Any hints, suggestions, how to accomplish this?

# Answer
> 0 votes
It should be as easy as adding an implementation of `hook_file_download()` to a custom module:

```
function MYMODULE_file_download($file) {
  // Add whatever other conditions you need to this, e.g. test the
  // file extension for .pdf
  if (user_is_anonymous()) {
    // Deny
    return -1;
  }

  // Allow
  return file_get_content_headers($file);
}

```

---
Tags: 7, files
---


# Question
Title: Are absolute paths allowed in info files?
I'm writing a `.info` file for a module, and I want to include a script which has been installed in `/sites/all/libraries`:

So I have included the line below in my `.info` file:

```
scripts[] = /sites/all/libraries/zeroclipboard-2.2.0/dist/ZeroClipboard.js

```

However, with or without the leading slash on this path, I always get the same result: Drupal treats this as relative to the module directory and tries and fails to load

```
/sites/all/modules/custom/clipboard//sites/all/libraries/zeroclipboard-2.2.0/dist/ZeroClipboard.js?nsnrjh

```

So maybe I've answered my own question, but I can't find any definitive answer to this in the Drupal docs?

Thanks all,

MB

# Answer
`_system_rebuild_module_data` is responsible for that. There is a whole section in code just to make sure:

```
// Prefix stylesheets and scripts with module path.
$path = dirname($module->uri);
if (isset($module->info ['stylesheets'])) {
  $module->info ['stylesheets'] = _system_info_add_path($module->info ['stylesheets'], $path);
}
if (isset($module->info ['scripts'])) {
  $module->info ['scripts'] = _system_info_add_path($module->info ['scripts'], $path);
}

```

My *guess* is that module should never assume that something exists if module itself does not install it. It's a way to introduce errors. Also, allowing modules to reach outside their directory might be a security breach.

If you need a script you can't include in your module, use Libraries API. Of course there are other ways, but most of them is problematic, and fixing all problems would pretty much result in cloning this ready module anyway.
> 2 votes

# Answer
If you are creating custom module then you can use these function to add library or js file from lirary.

```
$info = libraries_load('ui.tabs');
drupal_add_library('system', 'ui.tabs');

```
> 0 votes

---
Tags: javascript, .info
---


title: How to theme the views exposed form?

text:
# Question
Title: How to theme the views exposed form?
I've created a view with a number of exposed filters, but it is pretty ugly looking.

I'd like to improve the theming, including wrapping the whole thing in a fieldset as well as grouping some of the other elements (like pairing the published and updated inputs), but not sure how to go about this.

I tried to var\_dump the form, but it seems to go on forever and my browser locks up, so I can't easily learn anything about the form that way.

I also tried putting the form as a fieldset child in another form, but getting all the form ID information and so on proved problematic (although, I did get the fieldset styling).

Anyone got any pointers?

Update:

I copied over the template from the module to my site's theme directory, and made a start.

```
<fieldset>
    <legend>Filters</legend>

    <div class="views-exposed-form">
        <div class="views-exposed-widgets clear-block">
            <?php foreach($widgets as $id => $widget): ?>
                <div class="views-exposed-widget">
                    <?php if (!empty($widget->label)): ?>
                        <label for="<?php print $widget->id; ?>">
                            <?php print $widget->label; ?>
                        </label>
                    <?php endif; ?>
                    <?php if (!empty($widget->operator)): ?>
                        <div class="views-operator">
                            <?php print $widget->operator; ?>
                        </div>
                    <?php endif; ?>
                    <div class="views-widget">
                        <?php print $widget->widget; ?>
                    </div>
                </div>
            <?php endforeach; ?>
            <div class="views-exposed-widget">
                <?php print $button ?>
            </div>
        </div>
    </div>
</fieldset>

```

I can't seem to figure out how to pair up the date fields - I need to somehow modify the widget properties so I can wrap them in HTML (using hook\_form\_alter doesn't work because the #prefix and #suffix are added to `$widget->widget` so they break the output)

# Answer
Theming Views' exposed form is hard because it doesn't behave like most forms and use its own label mechanism. So, you can't simply use a `form_alter` hook to add `#prefix` and `#suffix` to elements. But using `THEME_preprocess_views_exposed_form`, you can craft your own suffix/prefix mechanism:

```
function THEME_preprocess_views_exposed_form(&$variables) {
  if ($variables['form']['#id'] == 'views-exposed-form-VIEWNAME-DISPLAYID') {
    foreach ($variables['widgets'] as $id => &$widget) {
      switch ($id) {
        case 'first_date_id':
          $widget->prefix = '<div class="date-widgets-wrapper">';
          break;
        case 'last_date_id':
          $widget->suffix = '</div>';
          break;
      }
    }
  }
}

```

and in the template file

```
<fieldset>
    <legend>Filters</legend>

    <div class="views-exposed-form">
        <div class="views-exposed-widgets clear-block">
            <?php foreach($widgets as $id => $widget): ?>
                <?php if (!empty($widget->prefix)) print $widget->prefix; ?>
                <div class="views-exposed-widget">
                    <?php if (!empty($widget->label)): ?>
                        <label for="<?php print $widget->id; ?>">
                            <?php print $widget->label; ?>
                        </label>
                    <?php endif; ?>
                    <?php if (!empty($widget->operator)): ?>
                        <div class="views-operator">
                            <?php print $widget->operator; ?>
                        </div>
                    <?php endif; ?>
                    <div class="views-widget">
                        <?php print $widget->widget; ?>
                    </div>
                </div>
                <?php if (!empty($widget->suffix)) print $widget->suffix; ?>
            <?php endforeach; ?>
            <div class="views-exposed-widget">
                <?php print $button ?>
            </div>
        </div>
    </div>
</fieldset>

```
> 21 votes

# Answer
You can copy views-exposed-form.tpl.php from sites/all/modules/views/theme to your theme path to override the template.
> 7 votes

# Answer
Also take a look at the Better Exposed Filters module. You'll need the -dev release to get the collapsible filters option, though I'm hoping to get a proper 1.1 release out soon...
> 3 votes

# Answer
You should look into what's in the `form['#theme']` item. Better way to do this (better than `var_dump()`) would be using `dsm($form)` or even `kpr($form)`, these functions will be availible after you install the devel module (http://drupal.org/project/devel). `form['#theme']` should be an array of about 7 elements. These elements are names of theme hooks that are called when this form is being rendered. you can use them to implement you own way of themeing a form.

One of the items will be called `views_exposed_form__VIEW_NAME__DISPLAY_ID`.

In your module (if you have one) there should be an implementation of hook\_theme()

```
function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'views_exposed_form__VIEW_NAME__DISPLAY_ID' => array(
      'function' => 'my_exposed_form_theme_function',
      'render element' => 'form',
    )
  );
}

// somwhere later in code

function my_exposed_form_theme_function($vaiables) {
  //$vaiables['form'] contains a form array
  //to display a form element call drupal_render($vaiables['form']['some element'])
  //don't forget to call drupal_render($form)
  //after you are done with rendering individual elements
  //
  //you can use template_preprocess_views_exposed_form() from
  // views/theme/theme.inc as an example

  return "concatenated results of multiple drupal_render() calls";
}

```
> 3 votes

# Answer
In previous situations I have used Hook\_form\_alter() to add prefix and suffix to form elements to wrap them up in div which can then be styled. Not sure about wrapping in fieldsets though.

eg.

```
$form['submitted']['full_name']['#prefix'] = '<div class="background">';
$form['submitted']['message']['#suffix'] = '</div>';

```
> 2 votes

# Answer
Use Drupal's hook\_form\_FORM\_ID\_alter to modify the form. This is what solved my problem of prefixing a £ character to my price field (put this in your custom module):

```
function THEME_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
   // check this is the right form
   if ($form['#theme'][0] == 'REPLACE_THIS') {
      // add the prefix
      $form['price']['min']['#prefix'] = "£";
   }
}

```
> 1 votes

# Answer
Views exposed form layout (D7) module will help you with views exposed form theming.
> 1 votes

# Answer
in the edit page of a view we can check theme information (bottom right corner). It gives the information regarding the template files used by Drupal to render the different parts of the view on screen. By default the template files provided by the views module(inside its theme folder) is used, but in case, where we want to modify the way a view is displayed we can override those template files with custom template files that we can put inside our own custom theme folder (or the theme that is going to be used to display this view)

This theme information shows us how to name a file according to the hierarchy (or the scope of the effect of the template file you are going to override the views own templates.)

Now, this theme information may not show all the template files that the view uses to render this specific view.

so, go to sites/all/modules/views/theme and copy the views-exposed-form.tpl.php (because in this case we want to override the default for rendering filters!)and paste it inside your own theme folder, now you have to follow the same method to control the effect of this overriding template file that you have put inside your own theme folder by renaming it accordingly. e.g. views-exposed-form--your view name-pane name.tpl.php (you will understand the nomenclature by looking at theme:information in the view's edit page)

now you can add css to individual widgets (generated by filter handlers) in this template file and those settings will be applied to the filters.

visit http://eureka.ykyuen.info/2011/07/25/drupal-theme-the-exposed-filter-in-views/
> 0 votes

---
Tags: views, 6, theming
---


# Question
Title: Drupal 7 Query database and display results same page in custom module template
I want to see the results on the same scree after submit.

But my results php error:

> Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /var/www/html/includes/form.inc on line 368

I have tried to raise the memory limit in `ini_set` did not change. I think that it is the cause the wrong my code.

My goal

1. Display the search results and input form on the same screen.
2. Search the external database with the value of the input form.
3. Keep the value of the input form.

Please help me with this.

Here is my code.

custom\_search.module

```
function custom_search_menu() {
    $item['customsearch'] = array(
            'title'         => t('Form and Result'),
            'page callback' => 'custom_search_callback',
            'access arguments' => array('access content'),
            'type'          => MENU_CALLBACK,
    );
    return $item;
}

function custom_search_theme() {
    $path = drupal_get_path('module', 'custom_search');
    $rtn = array(
            'custom_search_template' => array(
                    'path' => $path,
                    'template' => 'node--customsearch',
            ),
    );
    return $rtn;
}

function custom_search_form($form, &$form_state) {
    $form = array();

    $form['my_checkbox']=array(
            '#type'=>'checkboxes',
            '#title'=>t('checkbox'),
            '#options'=>array(
                    '1'=>t('option1'),
                    '2'=>t('option2')
            ),
    );
    //There are some $ form[]

    $form['submit']=array(
            '#type'=>'submit',
            '#value'=>t('Submit')
    );

    return $form;
}

function custom_search_callback() {
    return theme('custom_search_template');
}

function custom_search_form_submit($form_id, &$form_state) {
ini_set('memory_limit', '512M');
    $options = $form_state['input']['my_checkbox'];
    //external database query use input options
    //The external database has already connected and got data
    $results[] = array('1','2','3'); //sample results
    $results[] = array('2','3','4'); //sample results
    return theme('custom_search_template',array('results' => $results));
}

```

node--customsearch.tpl.php

```
<div class=“row”>
<div class="col-md-4">
        <?php $form = drupal_get_form('custom_search_form') ?>
        <form role="form" id='<?php echo $form['#id'] ?>'
                            action="<?php echo $form['#action'] ?>"
                            method="<?php echo $form['#method'] ?>">
          <div class="row">
            <?php echo drupal_render($form['my_checkbox']) ?>
            <?php echo drupal_render($form['form_id']);?>
            <?php echo drupal_render($form['form_build_id']);?>
            <?php echo drupal_render($form['form_token']);?>
            <?php echo drupal_render($form['submit']); ?>
          </div>
        </form>
</div>
<div class=“col-md-8”>
  <h2>results</h2>
  <table class=“table">
      <!— I want results here —>
      <?php
      if(isset($results)) {
        foreach($results as $row) {
           echo "<tr><td>";
           echo $row[0];
           echo "</td></tr>";
        }
      }
      ?>
  </table>
</div>
</div>

```

# Answer
> 1 votes
I got it.

```
    $form_state['storage']['results'] = $results;
    $form_state["rebuild"] = TRUE;

```

(I do not know whether this method is correct.)

Modified code.

custom\_search.module

```
<?php
function custom_search_menu() {
    $item['customsearch'] = array(
            'title'         => t('Form and Result'),
            'page callback' => 'custom_search_callback',
            'access arguments' => array('access content'),
            'type'          => MENU_CALLBACK,
    );
    return $item;
}
function custom_search_theme() {
    $path = drupal_get_path('module', 'custom_search');
    $rtn = array(
            'custom_search_template' => array(
                    'path' => $path,
                    'template' => 'node--customsearch',
            ),
    );
    return $rtn;
}

function custom_search_form($form, &$form_state) {
    $form = array();

    $form['my_checkbox']=array(
            '#type'=>'checkboxes',
            '#title'=>t('checkbox'),
            '#options'=>array(
                    '1'=>t('option1'),
                    '2'=>t('option2')
            ),
    );

    $form['submit']=array(
            '#type'=>'submit',
            '#value'=>t('Submit')
    );
    if(isset($form_state['storage']['results']))
    {
            $form['results'] = array
            (
                    //'#value' => array('results' => $form_state['storage']['results']),
                    '#value' => $form_state['storage']['results'],
            );
    }

    return $form;
}

function custom_search_callback() {
    return theme('custom_search_template');
    //return theme('custom_search_template',array('results' => $results));
}

function custom_search_form_submit($form_id, &$form_state) {
    $options = $form_state['input']['my_checkbox'];
    //external database query use input options
    $results[] = array('1','2','3'); //sample results
    $results[] = array('2','3','4'); //sample results
    $form_state['storage']['results'] = $results;
    $form_state["rebuild"] = TRUE;

}

```

node--customsearch.tpl.php

```
<div class=“row”>
<div class="col-md-4">
        <?php $form = drupal_get_form('custom_search_form') ?>
        <form role="form" id='<?php echo $form['#id'] ?>'
                            action="<?php echo $form['#action'] ?>"
                            method="<?php echo $form['#method'] ?>">
          <div class="row">
            <?php echo drupal_render($form['my_checkbox']) ?>
            <?php echo drupal_render($form['form_id']);?>
            <?php echo drupal_render($form['form_build_id']);?>
            <?php echo drupal_render($form['form_token']);?>
            <?php echo drupal_render($form['submit']); ?>
          </div>
        </form>
<?php
?>
</div>
<div class=“col-md-8”>
  <h2>results</h2>
  <table class=“table">
      <!— I want results here —>
      <?php
      if(isset($form['results']['#value'])){
        $results = $form['results']['#value'];
        foreach($results as $row) {
           echo "<tr><td>";
           echo $row[0];
           echo "</td></tr>";
        }
      }
      ?>
  </table>
</div>
</div>

```

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


title: taxonomy vocabulary access

text:
# Question
Title: taxonomy vocabulary access
I want a role to have access to

* add and view terms to any vocabulary,
* the overview `admin/structure/taxonomy/foo_vocabulary` for sorting the terms by draging

but deny the access to edit the vocabulary or its fields. its like `administer-taxonomy` permission without the option to edit a vocabulary. TAC wont help.

# Answer
Taxonomy access fix

> This module
>
> -adds 1 permission per vocabulary: "add terms in X"
>
> -changes the way vocabulary specific permissions are handled
>
> -changes the Taxonomy admin pages' access checks
>
> -alters the vocabularies overview table to show only what you have access to edit or delete
>
> The module does what native Taxonomy lacks: more specific Taxonomy permissions (and checking them correctly).
> 1 votes

# Answer
I know, this question is pretty old, but I was looking for a solution by myself.

Maybe someone is looking as well: http://drupal.org/project/vppr This module provides some new permission settings just for viewing terms which is exactly what I was looking for.
> 1 votes

---
Tags: 7, users, taxonomy-terms
---