# Question
Title: Is there a module that can create a Taxonomy out of the installed modules?
Is there a module that can create a Taxonomy out of the installed modules?

I want to create simple configuration tracking system and need to make my modules one of the taxonomies.

In relation to existing configuration management systems I got a suggestion here Is there a module for tracking changes to a Drupal site's configuration? so any other existing options for configuraton management should be answered there.

# Answer
I have decided to use a combination of 3 modules to accomplish the task.

Views System, Views Data Export and Taxonomy import/export via XML

`Views System` is a Views module that lists all the installed modules and themes. `Views Data Export` enables the output of `Views System` to be exported as XML or CSV which `Taxonomy import/export via XML` can then import into a taxonomy.

A module which can update taxonomies from feeds would be nice, there is probably a module for that, but these will do for the time being.
> 0 votes

---
Tags: 7, taxonomy-terms, feeds, importing-exporting, configuration
---


# Question
Title: Where is the template for the promoted to front page items?
I want to add some elements and icons into the promoted items template but I can't find where this template is located.

For example, right now my page is rendering:

```
<article id="node-62" class="node node-blog node-promoted node-teaser contextual-links-region clearfix" about="/sites/sample/content/sample" typeof="sioc:Post sioct:BlogPost">
  <h2 property="dc:title" datatype=""><a href="/sites/sample/content/sample">Sample</a></h2>
  <div class="submitted">
    //blah blah blah
  </div>
  <div class="content">
    //blah blah blah
  </div>
</article>

```

Instead, I would like to add things like:

```
<article id="node-62" class="node node-blog node-promoted node-teaser contextual-links-region clearfix" about="/sites/sample/content/sample" typeof="sioc:Post sioct:BlogPost">
  <i class="icon-menu"></i>
  <div class="something">Maybe some other stuff</div>
  <h2 property="dc:title" datatype=""><a href="/sites/sample/content/sample">Sample</a></h2>
  <div class="submitted">
    //blah blah blah
  </div>
  <div class="content">
    //blah blah blah
  </div>
</article>

```

Or anything else I want in the future.

# Answer
> 1 votes
This is tipically done in node.tpl.php in your theme. Just keep in mind that this template works for any node, so you should introduce some logic to check if the node is promoted, e.g.

```
<?php if ($node->promoted) { ?>
  <i class="icon-menu"></i>
  <div class="something">Maybe some other stuff</div>
<?php } ?>

```

# Answer
> 1 votes
Nodes promoted to front page uses teaser view by default,so looking for an answer how to theme node teaser view might be your answer.

Below are references for how to theme node teaser view.

Or as an option you can have separate template for your node teaser view,in order to make the template recognized by drupal here is some sample code.

```
function mythemename_preprocess_node(&$variables, $hook) {
  if($variables['elements']['#view_mode'] == 'teaser'){
    $variables['theme_hook_suggestions'][]= 'node__teaser';
  }
}

```

and then add `node--teaser.tpl.php` inside your theme/templates,keeping the html the way you want to arrange the elements.

---
Tags: theming
---


# Question
Title: How can I create an "allow anything" field on a node?
We're building a site and need to allow our users to have a field on the node that will allow for ANY content: scripts, iframes, script files, css files, etc; essentially embed codes for mailchimp forms, donation forms, etc.

This HAS to be something the user can do so. Can I create a textarea field and then override a hook or something to prevent that fields contents from going through any sort of filtering?

I also completely understand the risks here. We don't have any public users logging into the site. We know everyone who is logging in.

# Answer
> 0 votes
I would create a new text format for that:

1. Go to `admin/config/content/formats/add`
2. Select the filters you want to add (in your case probably no filters at all)
3. Add a textarea field on your content type and select this text format you just created.

---
Tags: 7, javascript, nodes
---


# Question
Title: Get the latitude and longitude from the user ip
I am trying to get the latitude and longitude from the user who connected to my website to draw or show his position on a map, but it showed him in the wrong postion. Is there any way to get the accurate latitude and longitude?

```
    <?php drupal_add_js('http://maps.google.com/maps/api/js?sensor=true'); ?>
     `<script type="text/javascript">
        //document.write("Hello World!");
        jQuery(document).ready(function () {
            function initialize(att,lon,title) {

            var mapOptions = {
                zoom: 8,
                center: new google.maps.LatLng(att,lon),
                mapTypeId: google.maps.MapTypeId.ROADMAP //TERRAIN
            };
            map = new google.maps.Map(document.getElementById("map_canvas2"),mapOptions);
            map.disableDefaultUI = true;

            var marker = new google.maps.Marker({
                map: map,
                icon:Drupal.settings.basePath+'themes/bartik/logo.png',
                position: map.getCenter()
            });

            var infowindow = new google.maps.InfoWindow();
            infowindow.setContent('<div class="title-map">'+title+'</div>');
            jQuery('.title-map').parent().removeAttr('style');

            google.maps.event.addListener(marker, "click", function() {

                infowindow.open(map, marker);

            });
        }
        jQuery.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) {
            initialize(data.latitude,data.longitude,'title');
        });
    </script>
    <?php

     echo "<div id="map_canvas2" style="width:605px; height:465px"></div>";
?>

```

# Answer
Converting an IP to a latitude and longitude isn't a good idea since the user could be using a proxy. A better way would be to use HTML5 geolocation, which tries to get a location based on a couple of parameters: IP, wireless connection, cell tower location, GPS ...

Try:

```
navigator.geolocation.getCurrentPosition(show_map);

function show_map(position) {
  initialize(position.coords.latitude, position.coords.longitude, 'title');
}

```

More info on HTML5 geolocation here, make sure you have a fallback in case the browser doesn't support geolocation or the user declines your request to share his/her location (graceful degradation).
> 7 votes

# Answer
The implementation I currently use I've seen in a couple other questions, but I haven't seen it as the selected answer.

**It is explained detailed in blog thenullreference.com, but here it is in short:**

---

Essentially all you need to do is load Google's API loader script:

```
<script type="text/javascript" src="http(s)://www.google.com/jsapi"></script>

```

Then you have access to several properties that give you detailed location info.

The object you want to look at is **google.loader.ClientLocation**

* ClientLocation.latitude
* ClientLocation.longitude
* ClientLocation.address.city
* ClientLocation.address.country
* ClientLocation.address.country\_code - ISO 3166-1 country code
* ClientLocation.address.region - country specific region in US this is state

\*Note some of these can be null

For more info on this API check out here

Does anyone else use this? Does anyone have something that they use that is as simple and better? Are there issues with this approach?

I'm unaware of the coverage/accuracy of this solution, but I would think that Google keeps it updated and is probably pretty good.
> 1 votes

# Answer
My app requires certain functionality to be enabled when location changes, so I needed to not rely on HTML5 implementations of getting the user location. I found www.telize.com as well as www.iptolatlng.com to be helpful what I'm doing bc they return JSON results.
> 0 votes

---
Tags: 7, javascript, google-maps
---


# Question
Title: Views - get nodes flagged or created by me
I want to list nodes flagged or created by me. You can think this as an "or" filter in views. is there a way to do in in views and flag ?

# Answer
> 3 votes
Views 3 supports groups of filters joined by OR.

1. Edit your View.
2. Under "Filter criteria" click the little down arrow next to "Add" and select "And/or, rearrange".
3. Create a new filter group with the filter(s) you want.
4. Change "operator" to "OR".
5. Save.

If you're using Drupal 6:

> Views Or allows Views to combine filters or arguments with OR and fields with COALESCE.

---
Tags: views, flags
---


# Question
Title: Advantages of using context for sitewide blocks?
As far as loading time is concerned I haven't seen anywhere, including the documentation, if there is a real advantage in using the context module to display sitewide blocks over the Drupal default block page.

For D7, some say Drupal loads all blocks for every page but displays only those that are visible. If so, then using context could dramatically speed up a site with many blocks. Others say D7 only loads the visible blocks.

But, which is it? Is it worthwhile to switch to context for block display? Does any one really know?

Thanks. :)

# Answer
Yes you should. It is worth while to switch to Contexts (Irrespective of your case about site wide context blocks)

Reasons

1. When you have blocks which appear only on a certain pages, the time taken for loading the block is saved.
2. In one page you can have a block in region A and on other page you can have the same block in region B.
3. When you change your themes you need not worry a lot about changing all the settings. You just need to make sure that they have common regions.
4. You can think on a page by page and then assign blocks.
5. Context has a simple and clean UI of its own, including drag and drop facility.
6. It is not path dependent. It means you can use conditions other than the path to set a context.
7. Can be extended with Context UI which can be a replacement for Panels and light weight too :)
8. In addition to placing Blocks there are many more reactions as well.
9. Contexts can be stacked meaning there can be multiple contexts for a single page. So you can have a site-wide context to place the headers and footers, then a node context which will perform something only on node pages and then one more context which will be active only on say node/33.
10. In short think of it like Rules module for the Layouts.
> 4 votes

# Answer
Yes, it is definitely useful to use Context for block display versus the core Block module for the very reason that you mentioned - Performance will be gained when Drupal is not forced to render blocks for all Theme Regions, even if they are not displayed on the page.

I was shocked to learn that a resource intensive, Image Style dependent Views Slideshow block that appears only on my homepage was being generated by the system on every single page load in the site. In Context, I set a Condition of type "Path" to "front" and set the Views Slideshow block in the appropriate region and the block stopped being generated for all page requests.

Context can be a very handy tool to display blocks more efficiently and with finer granularity than core Blocks module.
> 1 votes

---
Tags: blocks, 7, theming
---


title: copy a site to another installation

text:
# Question
Title: copy a site to another installation
Read this documentation https://drupaltraining.stanford.edu/node/111

But I was under the impression the sql database file has to be edited before you can do this?

"Before importing SQL file to new database, find and replace old URL and site name with new one." but I cannot find url or site name in sql file.

# Answer
> 0 votes
If you want to replace the old URL then you may do that before taking a dump of existing database:

* Search the OLD\_URL\_VALUE in the database from the phpmyadmin. (It may be possible that you will get no value in result, that would be the case when you have no hard coded value of your Old domain)
* Build the query to replace the OLD URL something like:

// Example: Replacing OLD\_URL\_VALUE (from the "body" column of the "node\_revisions" table):
update node\_revisions
set body = REPLACE(body, 'OLD\_URL\_VALUE', 'NEW\_URL\_VALUE')
WHERE body LIKE '%OLD\_URL\_VALUE';

---

Alternatively you may try the Backup and migrate module: Back up and restore your Drupal MySQL database and files or migrate a site between environments.

Also you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.

---
Tags: database
---


title: Cannot find PHP type in Data Format

text:
# Question
Title: Cannot find PHP type in Data Format
I am new to Drupal and using Drupal7.23 in windows7 with XAMPP installed. While I am creating any content I cannot find "PHP type" in the Data Formats. Kindly tell how to add PHP type in Data Format, as I need to add PHP to the content.

# Answer
> 2 votes
Enable the 'PHP Filter' module available in drupal core:

Go to modules list: `/admin/modules` and than in Core you will find PHP filter module as indicated below, so just enable it.

---
Tags: input-formats
---


# Question
Title: my page.tpl.php overrides path of page display of views
I created a view and a page display of it. I set a path for it. this is its path

```
http://localhost/myProject/library

```

but when I copy and paste this url in address bar, it just displays my `page.tpl.php` what I have created for front page. why?

# Answer
> 2 votes
Your issue seems to be in the file name - `page.tpl.php` will be used automatically for display of all pages.

If you want to have separate template, use `hook_preprocess_page()`:

```
function MYTHEME_preprocess_page(&$variables) {
  if (arg(0) == 'library') {
    // This will look for template named page--library.tpl.php in your theme.
    $variables['theme_hook_suggestions'][] = 'page__library';
  }
}

```

# Answer
> 0 votes
Are you providing this complete path as `"http://localhost/myProject/library"`.If so please provide relative path instead of absolute path, so relative path would be "`library`" only and then check again visiting `http://localhost/myProject/library` in your url.

---
Tags: views, theming, uri
---


# Question
Title: Search API Index view shows all content pages, instead of just products commerce Kickstart
I'm using Commerce Kickstart and I have set up a search index using mysql rather than Apache Solr. Faceted search works perfectly. However if no facets are selected the results show all pages, including Terms of Use, 404 and shipping fees, to name but a few. I have tried setting up filters, but then it doesn't show any products. I'm attaching a screenshot of the results. I'm sure this is an easy fix, but I have spent hours testing and reading within the forums to try and find a solution, to no avail. Many Thanks in advance.

# Answer
You want to filter results by content type? If yes, you can just set filter in tab "workflow" of your search index. It's "bundle filter". Good luck.
> 1 votes

---
Tags: views, commerce
---


# Question
Title: Autocomplete field consisting of multiple fields
I am trying something that have been probably discussed already, but I can't seem to find it. I have a node reference field that I would like to use the "Autocomplete field" function with. However, I would like to show an extra (custom) field, not only the Title of the node. Preferably in a comma separated list, like:

TITLE Node 1, custom field TITLE Node 2, custom field

etc.

I'm sure this can be done. But I can't seem to find how (and yes.. I'm a beginner I'm affraid).

Thanks a million!

# Answer
> 3 votes
Instead of using Node Reference (References), I suggest you to use Entity Reference module. It has an option to build the autocomplete options with a view so that you can add other fields.

# Answer
> 1 votes
Assuming you are using references module for node reference.

You can get better hold of how you can do this looking inside sub-module of references module called "node-references".

you need to check if this idea works for you.

1. Implement hook\_field\_widget\_form\_alter() in your custom module,implementing this hook you can change the callback function which provides autocomplete suggestions.

As in node\_refernce.module line number 606 node\_reference\_field\_widget\_form() has been implemented so keeping the same workflow you just have to override `"value_callback"` with your custom function.Lets call you custom as "`custom_autocomplete_suggestions()`"

1. Now in your custom function `custom_autocomplete_suggestions()` copy the code of existing callback function in node\_references module.
2. Clear your caches, check if you getting autocomplete suggestions or not.If so you have overridden it successfully.
3. Now do tweaks inside your `custom_autocomplete_suggestions()` to return what you want as suggestions.

---
Tags: ajax
---


# Question
Title: Make a block display in one page and not in other
I am using Drupal 7 with omega and adminimal theme. I use adminimal theme for my iframe in the site (using entity iframe module). I would like to display a block in the adminimal theme alone, but not in my omega theme.

I used the default block settings, "Only the listed pages", but this display the block in both the themes.

So is there a way to configure the display options per theme?

Any help would be widely appreciated.

# Answer
In the block's `Region settings` you can specify the block to be displayed in which region of respective themes(Admin and site theme) as below:
> 1 votes

# Answer
Go to `admin/structure/block` and then select the **theme tab** that you want to disable the block and then select none for the block you don't want to appear. See the below screen shot for better understanding.
> 0 votes

---
Tags: blocks, theming, 7
---


title: Exclude a node field from loading

text:
# Question
Title: Exclude a node field from loading
I would like to exclude some of node field from loading while viewing nodes. I can hide fields currently, but I want to exclude it completly from loading. I have multivalued fields which have around 2000 records and I don't need to load it on node pages.

# Answer
> 0 votes
On the 'manage display' page of your content type you can set fields as hidden. This will make the field not only hidden also it won't load it at all.

---
Tags: entities, nodes
---


# Question
Title: How do I use the Drupal 7 API to change ownership of a comment
This function `function node_assign_owner_action()` is provided by the Drupal 7 API to allow modules change node ownership,

I've searched, but not found a similar function that let me change the ownership of comments. Does anyone know how to change ownership of a comment without hacking the `{comment}` table directly, and without breaking existing incoming links?

I know that I can update the fields `{comment}.uid`, `{comment}.name` and `{comment}.mail` with the appropriate values, but as I understand things, contributed modules should *never* update tables "owned" by another module directly.

The only method I've found so far is to recreate the comment under new ownership. This is *not* a good solutions because it will invalidate all incoming links that used the permalink associated with the original comment.

# Answer
This changes the comment author details using the core comment API:

```
$cid = 12; // e.g get from db_select
$comment = comment_load($cid);
$comment->uid = 1;
$comment->name = 'admin';
$comment->mail = 'admin@example.com';
comment_save($comment);

```

You could also do something similar with a Rules component for use with VBO.
> 7 votes

---
Tags: comments
---


# Question
Title: The correct and optimal way to check language and print field depending on language, without affecting performance
I have a multilingual site, and for many reasons (don't ask why) I'm not using the Entity Translation module. Instead, I have 3 separate description fields for each language, and I want to print those depending on the current language. I just wanted to ask if this is the correct and optimal way to print render those fields, and whether or not it will have major implications on site's performance?

Inside my custom **node--content-type.tpl.php** at the top I put:

```
<?php hide($content['field_description_nl']); ?>
<?php hide($content['field_description_fr']); ?>
<?php hide($content['field_description_en']); ?>

```

and later inside the **teaser** and then again inside the **full node** I've put:

```
<?php
global $language;
$lang_name = $language->language;
if($lang_name == "nl") {print render($content['field_description_nl']);}
if($lang_name == "fr") {print render($content['field_description_fr']);}
if($lang_name == "en") {print render($content['field_description_en']);}
?>

```

Will this work or will it dramatically slow down the site when the traffic starts pouring in?

# Answer
> 5 votes
That's a reasonable way of implementing an alternative language switcher for specific field output.

To keep the logic out of the template, you could add it to `hook_preprocess_node` instead.

e.g:

```
/**
 * Implements hook_preprocess_node
 */
function MYTHEME_preprocess_node(&$variables){
  global $language;
  $lang_field_name = 'field_description_'. $language->language;
  if(!empty($variables[$lang_field_name])){
    $variables['description'] = render($variables[$lang_field_name]);
  }
}

```

Then you can just use `print $description` in the `node--content-type.tpl.php` file.

Make sure your cache is different for each language.

See also `field_attach_preprocess` for how field language translations are added in core.

---
Tags: theming, performance, i18n-l10n
---


title: #weight doesn't work on submit button

text:
# Question
Title: #weight doesn't work on submit button
I'm trying to add two links on custom user form. The goal is this links to be displayed bellow the submit button. I've tried with weight property, but it's not working.

What do I miss?

This is my code:

```
<?php
      function custom_alter_form_alter (&$form, &$form_state, $form_id) {

        switch ($form_id) {
                case 'user_login':

                $form['name']['#title'] = t('Username');
                $form['pass']['#title'] = t('Password');
                $form['actions']['submit']['#value'] = t('Login');
                $form['actions']['submit']['#weight'] = 0;

                $form['page'] = array(
                '#markup' => '<h2>Login</h2>',
                '#weight' => -10,
                );

                $form['register'] = array(

                '#type' => 'markup',
                '#markup' => '<div class="user-login-register">You don't have an account?
                <a class="user-login-register" href="/user/register">  Click here</a></div>',
                '#weight' => 1,
                );

                $form['password_reset'] = array(
                '#markup' => '<a class="user-login-password-reset" href="/user/password"> You forgot your password</a>',
                '#weight' => 2,
                );

                //krumo($form);
                break;
            }

        }

```

# Answer
This line:

```
$form['actions']['submit']['#weight'] = 0;

```

only sets a submit's weight inside actions container.

To push actions to the top of the page, you need to affect it's own weigh:

```
$form['actions']['#weight'] = 0;

```

and if you want to move only one button, you can restructure your form by moving this button outside actions container:

```
$form['submit'] = $form['actions']['submit'];
$form['submit']['#weight'] = 0;
unset($form['actions']['submit']);

```

Note that this may break some forms that expect submit button in it's exact original place in form structure.
> 9 votes

---
Tags: forms
---


# Question
Title: Is it possible to add custom entries to the language switcher pointing to the same language?
I have a requirement to include Colombia, Peru and Mexico as part of the language switcher. Thing is these 3 countries all speak Spanish so is there a way to cater for this to include them in the language switcher? technically these three languages would have to point to the same spanish sub-domain

Thanks

# Answer
I think you can use the hook\_language\_switch\_links\_alter() to modify the output of the language switcher. I would try to create the needed entries there to maintain the functionality to switch languages properly.
> 2 votes

---
Tags: i18n-l10n
---


title: Can this PHP node leak memory?

text:
# Question
Title: Can this PHP node leak memory?
I have a Drupal 7 installation that apparently leaks memory somewhere. The memory usage of nginx is going up in production until the server fails. This started basically when I added a new node with PHP content to it. My PHP code does basically this:

```
<?php

global $user;
$token = uuid();
$uid = user_load($user->uid);
$myprofile = 'main';
$profile = profile2_load_by_user($uid, $myprofile);
$birth_date= $profile->field_birth_date['und'][0]['value'];

$conn = mysql_connect ("my.sql.server:3306/somedb", "user", "pass");
mysql_select_db("somedb", $conn);
mysql_query("INSERT INTO special_table (TOKEN, USER) VALUES ('$token','$user->name')");
mysql_close ($conn);

echo 'output some html based on birthdate..';

```

In addition I use memcached module. That custom DB connection that I have to open and do a single insert is not the DB of the drupal installation, that is going into a separate database. Surely not the nicest solution, but I guess that should not leak anything.

Do you see anything in this code that can possibly lead to memory leak?

# Answer
It doesn't look like this is causing a memory leak as @tenken said in his comment. However, since this is going in a node, that whole PHP snippet is stored in the database which isn't recommended. It will take more memory to grab this code from the database, then run it.

Try sticking the code in a function in PHP file and then running that function somewhere else on the site, i.e. a custom module. This is a good tutorial on how to do that.
> 3 votes

# Answer
`mysql_connect()` is deprecated. See that big red box in the API docs? So yes, it may cause various unhealthy effects on your site. Use Drupal's built-in multiple database handling to be safe.
> 1 votes

---
Tags: 7
---


title: correct url() request

text:
# Question
Title: correct url() request
I need to make a redirect after a customer added something to his cart so I write this:

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  array_push($form['#submit'], '_MODULE_redirect_to_products');
}

function  _MODULE_redirect_to_products(&$form, &$form_state){
  global $language ;

  $form_state['redirect'] = url('prodotti', array('language' => $language));
}

```

but this code redirect me to

```
/dev/azzurra/?q=it//dev/azzurra/%3Fq%3Dit/prodotti

```

but I need to redirect to

```
/dev/azzurra/?q=it/prodotti

```

according to the language obviously.

**UPDATE:** I'm try to use

```
 $form_state['redirect']

```

but if I display this field before modify it I can see this

```
Array
(
    [0] => prodotti
    [1] => Array
        (
            [language] => stdClass Object
                (
                    [language] => it
                    [name] => Italian
                    [native] => Italiano
                    [direction] => 0
                    [enabled] => 1
                    [plurals] => 2
                    [formula] => ($n!=1)
                    [domain] =>
                    [prefix] => it
                    [weight] => 0
                    [javascript] => a97-0F_JBbaSYaN4XQBbFbhCLCysRpSabTcDmQjB73E
                    [provider] => locale-url
                )

        )

    [2] => 302
)

```

but the form redirect me to 'it/testate/name' because the form 'add product' is displayed in a view so I think that the views module override the $form\_state\['redirect'\] after me so the default redirect \[and mine one..\].

I think I can't use this kind of redirect.. How can I achieve this redirect correctly?

# Answer
> 2 votes
`$form_state['redirect']` does not take full URL. It takes the same set of parameters `url()` does. In your case it should probably look like this:

```
$form_state['redirect'] = array(
  // $path
  'prodotti',
  // $options
  array('language' => $language),
  // $http_response_code
  302,
);

```

---
Tags: uri, redirection
---


title: path to node edit page

text:
# Question
Title: path to node edit page
I am using js injector to add script to my drupal website. But the script is also loading on the admin pages and node edit pages.

I have selected the option

Add tracking to specific pages Every page except the listed pages

and defined admin/\* which removes the script from admin pages but what path should I define to exclude the script from the node edit pages

# Answer
To specify the path match for *node/\[nid\]/edit* pages, you can use

**node/\*/edit**

as the page match string there.
> 2 votes

---
Tags: nodes, uri
---


# Question
Title: Deploying Drupal 7 with read-only DocumentRoot, especially concerning image handling
I'm deploying a Drupal 7 application in an environment where the web server's DocumentRoot is mounted read-only (so Drupals root directories and all directories below are not writable). For storing files a separate directory outside of DocumentRoot is provided which is mounted read/write. This directory is accessible from a separate web server instance (which only serves static files without executing PHP code, e.g. *static.example.com*).

What I did:

* setting file\_public\_path to said writabke directory
* implementing hook\_file\_url\_alter to modify URIs in the *public* scheme to point to the separate web server instance

Everything seems to work fine (CSS, ...), except for delivering images. Drupal's concept for delivering images is whenever a requested image resolution isn't found on disk, the thumbnailing mechanism is invoked instead. The thumbnailer creates a new image, which is delivered to the requesting browser and stored below *sites/default/files*. Subsequent requests deliver the image directly from the disk (using Apache's rewrite rules, so PHP isn't involved any more).

Since we are using varnish in front of the web server, I'd prefer a different way of handling images:

* images are served from a different virtual host (e.g. image.example.com)
* thumbnailed images are never written to disk
* instead a Cache-Control header is sent using a reasonable long max-age value, so varnish's LRU expiration mechanism can keep the often used images in memory and discard unused images

Any ideas how to accomplish this?

# Answer
> 3 votes
When an generated image is not available, the page callback is `image_style_deliver()`. This callback first generate the image (after some access and concurrency checks) and then stream the file as response (through the `file_transfer()` function).

Using `hook_menu_alter()`, you can override the image generation callback to redirect to the static domain once the image has been generated. Ensuring the generated files are always served from the static domain. On the static server, you can add a rewrite rule to redirect request for a not yet generated image to the non-static domain. Ensuring the files are generated, even when requested from the static domain. Because of the redirections, Varnish should be able to cache the files as soon as they have been generated.

Edit: Not creating the image derivatives as files on disk does not seems to be an option. Drupal uses its Image Toolkits wrapper API (GD and ImageMagik are usually used a backend) to generate the image and this API does not seems to offer a way to generate images in memory. If you really want/need to remove the generated files, you can do it in a cron job using `image_style_flush()` via `hook_cron()`.

# Answer
> 2 votes
A response of sorts:

> 1.~images are served from a different virtual host (e.g. image.example.com)

You can use NFS to mount Drupal's `sites/default/files` directory to an `images.example.com` document root, or perhaps an equivalent network directory mount method for your OS.

> 2.~thumbnailed images are never written to disk

I don't know if that is possible in Drupal, maybe you can override the file stream wrapper handler, so that relevant file operations are handled differently.

> 3.~instead a Cache-Control header is sent using a reasonable long max-age value, so varnish's LRU expiration mechanism can keep the often used images in memory and discard unused images

The virtual definition host for `images.example.com` can set the relevant response headers for Varnish to cache those images.

---
Tags: media, proxies
---


# Question
Title: Publishing events on a calendar to an individual/a specific group/ or all
Hey I'm new to drupal and trying to create a calendar that users can publish different items to.

there are different roles involved say: worker, supervisor, manager.

workers are divided into groups.

Are there modules that would allow a supervisor or manager to post an event that 1) only a single worker could see, 2) that only a group of workers could see, 3) that everyone could see.

Would user-relationships handle this?

# Answer
> 1 votes
Events are nothing but nodes so you finding for a solution to have node access for a user, user role, or to all will give you the answer

Might the following modules can do this for you

https://drupal.org/project/nodeaccess\_userreference

https://drupal.org/project/content\_access

---
Tags: datetime, users
---


# Question
Title: how to automatically fill in an entity reference field using rules in Drupal 7?
Since I'm not a coder I'm using the Rules module to automatically create a node of type B when a user creates a node of type A. That works. I used 'create new entity' of 'type B' 'after saving new content of type A'. It also sets a unique name for the title of the newly dynamically created entity. And that's works great. In addition, I've also set the author of the 'entity-created' to a 'generic author' by simply using a specific uid (I just used a specific number as the value so they will always have the same author, that's fine).

So this all works. In my next step of actions I want to fill in the entity reference field in the node created of content type A with the title of the 'entity-created' of type B. And here's where I'm stuck.

I tried: set data value: node:field-entityref:title new value for the specified data: \[entity-created:title\] (that should be different from the \[node-created:title\]) But that doesn't work. I tried many different things as well but it seems that I can't grab that title of that new entity that was dynamically created by Rules. I tried to 'fetch entity by property' but that also doesn't fill in the title in my entity reference field on the node of type A. I don't know why. I hope someone can help me out in my last step. Cheers!

# Answer
All is well. It works. (finally) I had to recreate my sandbox site and it worked. I installed only the necessary modules. So beneath the steps in my rule.

1. After saving new content of type 'story'
2. Create a new entity Parameter: Entity type: Node, Content type: article, Title: article related to nid..., Author: 2 Provides variables: Created article (article\_created)
3. Save entity Parameter: Entity: \[article-created\], Force saving immediately: true
4. Set a data value Parameter: Data: \[node:field-myref\], Value: \[article-created\]

(if I didn't have the action 'save entity' it would override the node that was originally used as the default setting in the reference field on the management of the story content type, just so you'd know)

So what was the problem? I'm not sure, it was probably a conflict with a certain module. I was thinking of the 'clone module'.
> 2 votes

---
Tags: 7, rules, entities
---


# Question
Title: How to automatically capture images from URLs?
My site is a bookmarking site where people share URLs.

First, if the page being submitted has Facebook open graph image information, Drupal should transfer that image to local files and display it (similar to sharing links on Facebook).

Otherwise, display a thumbnail preview of the page.

Thanks for help in advance.

# Answer
Check out Opengraph filter module

> When you post a link on facebook, you get a little summary of that site under your comment or post (with or without thumbnail). This works with OpenGraph metatags. Basicly Facebook scrapes the content of the url and makes a nice little summary.
> 3 votes

# Answer
I think what you actually looking for is the Opengraph Filter module.
> 3 votes

# Answer
I found this on drupal modules page, I googled drupal modules screenshot but I not yet test it.

https://drupal.org/project/website\_screenshot

https://drupal.org/project/pagepeeker
> 0 votes

---
Tags: entities, media
---


# Question
Title: display newly added field value of account settings
I added a new field(First name) in Account settings under Configuration & its machine name is 'field\_first\_name'
I am trying to load this value in home page like this

```
<?php print $user->field_first_name ?>

```

But the above code is not working. Please help. I debug $user and found that this value isn't there. What should I do to show the value of the newly added field in home page.

I've added screenshot.

# Answer
> 2 votes
You should use field\_get\_items:

```
global $user;

$user_contaning_field = user_load($user->uid);

// Check if we're dealing with an authenticated user
if ($user->uid) {

  // Get field value from $user
  $field_first_name = field_get_items('user', $user_contaning_field, 'field_first_name');

  foreach ($field_first_name as $key => $value) {
    print field_view_value('user', $user_containing_field, 'field_first_name', $field_first_name[$key]);
  }
}

```

# Answer
> 2 votes
Small edit with @Beebee asnwer, since it seems he is not logged in so adding it as separate answer

```
global $user;

 // load the user entity so to pick the field from.
$user_contaning_field = user_load($user->uid);

// Check if we're dealing with an authenticated user
if($user->uid) {

  // Get field value;
  $field_first_name = field_get_items('user', $user_contaning_field, 'field_first_name');
  if(isset($field_first_name[0]['value']))
    print $field_first_name[0]['value'];
}

```

# Answer
> 0 votes
Try this for starters

```
<?php
    global $user;
    if ($user->uid) { // if registered...
      //get field value and print it
    }

```

---
Tags: entities, users
---


# Question
Title: How to enable insert module in installation profile?
I want to use the insert module for a file field but I can't get it to be enabled programmaticly. Is there a setting like 'insert' =\> true, or something like that? Is there any documentation about the these settings because I can't seem to find any info on the web?

# Answer
You can enable insert by updating the field instance settings with these two core functions:

for example:

```
/**
 * Enable insert field settings
 */
function MODULE_field_settings_enable_insert($entity_type, $field_name, $bundle){
  // Load field instance
  $instance = field_info_instance($entity_type, $field_name, $bundle);
  // Build insert settings array, these image styles are just examples
  $insert_settings = array(
    'insert' => 1,
    'insert_absolute' => 1,
    'insert_styles' =>
    array (
      'image_236w' => 'image_236w',
      'image_237x147' => 'image_237x147',
      'image_486w' => 'image_486w',
      'colorbox__236w' => 'colorbox__236w',
      'colorbox__237x147' => 'colorbox__237x147',
      'colorbox__486w' => 'colorbox__486w',
      'auto' => 0,
      'link' => 0,
      'icon_link' => 0,
      'image' => 0,
      'image_60x60' => 0,
      'image_62x62' => 0,
      'image_62x82' => 0,
      'image_67x67' => 0,
      'image_69x52' => 0,
      'image_71x44' => 0,
      'image_71x71' => 0,
    ),
    'insert_default' => 'image_237x147',
    'insert_class' => 'caption',
  );
  // Add the insert settings to the field instance widget settings
  foreach($insert_settings as $key => $setting){
    $instance['widget']['settings'][$key] = $setting;
  }
  // Save the field instance
  field_update_instance($instance);
}

// Then you can enable insert on a field instance with
MODULE_field_settings_enable_insert('node', 'field_images', 'article')

```
> 4 votes

# Answer
This is pretty simple to do if you are installing Drupal with an installation profile.

Let's say your installation profile name is `custom_profile`, just add the following line to `custom_profile.info` file to install insert module when Drupal installs:

```
dependencies[] = insert

```
> 0 votes

---
Tags: 7, installation, installation-profiles
---


# Question
Title: Is there a module that can list all the views on a system?
Is there a module that can list all the views installed on a system and their pages as well? If it can specify whether the Views are installed by modules or enduser created that will be helpful.

I am looking for something that create a list along this lines.

Name | Type of View | Page Name | Type of Page | Path

# Answer
I don't think a module already exists for that.

To build it yourself, you'll need to implement `hook_views_data()`, and describe the `views_view`, and `views_display` tables.

These are the columns you'll have available from the `views_view` table:

* name
* description
* tag
* base\_table
* human\_name
* core

And from `views_display`:

* vid (view id)
* id
* display\_title
* display\_plugin
* position
* display\_options

`display_options` is a serialised PHP array of data (containing the path and other specific information), so unless you implement some pretty advanced field/filters/etc handlers you won't be able to filter on those specific elements, or use them as fields.
> 1 votes

---
Tags: views
---


# Question
Title: Drupal 7: Edit/delete is not working on the custom module
I am a newbie to drupal. I am working to create a custom module in the name "course". I have read about the list of hooks to create a custom module. So, what's my problem is that i cant able to see the edit form for the module configure but i can do add management and its working fine. I've used Existing **contact** modules as a reference.

Below are my code: In **course.module**

```
function course_menu() {
  $items['admin/structure/course'] = array(
    'title' => 'Academy\'s courses',
    'description' => 'Create a system contact form and set up categories for the form to use.',
    'page callback' => 'course_list',
    'access arguments' => array('administer contact forms'),
    'file' => 'course.admin.inc',
  );
  $items['admin/structure/course/add'] = array(
    'title' => 'Add Courses',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('course_edit_form'),
    'access arguments' => array('administer contact forms'),
    'type' => MENU_LOCAL_ACTION,
    'weight' => 1,
    'file' => 'course.admin.inc',
  );
  $items['admin/structure/course/edit/%course'] = array(
    'title' => 'Edit Courses',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('course_edit_form',4),
    'access arguments' => array('administer contact forms'),
    'file' => 'course.admin.inc',
  );

  return $items;
}

```

and in **course.admin.inc**:

```
function course_edit_form($form, &$form_state, array $course = array()) {
  // If this is a new course, add the default values.

  $course += array(
    'name' => '',
    'course_id' => NULL,
  );

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Course Name'),
    '#maxlength' => 255,
    '#default_value' => $course['name'],
    '#description' => t("Example: 'Available Course Names'."),
    '#required' => TRUE,
  );

  $form['course_id'] = array(
    '#type' => 'value',
    '#value' => $course['course_id'],
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

function course_edit_form_submit($form, &$form_state) {

  if (empty($form_state['values']['course_id'])) {
        db_insert('courses') // Table name no longer needs {}
        ->fields(array(
          'name' => $form_state['values']['name'],
          'course_url' => $form_state['values']['name']
        ))
        ->execute();
    //drupal_write_record('courses', $form_state['values']);
  }
  else {
     db_insert('courses') // Table name no longer needs {}
        ->fields(array(
          'name' => $form_state['values']['name'],
          'course_url' => $form_state['values']['name']
        ))
        ->condition('course_id', $form_state['values']['course_id'])
        ->execute();
    //drupal_write_record('courses', $form_state['values'], array('course_id'));
  }

  drupal_set_message(t('Course %name has been saved.', array('%name' => $form_state['values']['name'])));
  watchdog('contact', 'Course %name has been saved.', array('%course' => $form_state['values']['name']), WATCHDOG_NOTICE, l(t('Edit'), 'admin/structure/course/edit/' . $form_state['values']['course_id']));
  $form_state['redirect'] = 'admin/structure/course';
}

```

I can't able to find the exact problem, why add is working but not edit & delete? Help me on this.

Below image tells you what exactly i am asking for(Red mark).

If anything additional needed in this please let me know.

# Answer
You are using an Auto-Loader Wildcard in your menu item definition for `admin/structure/course/edit/%course`. This wildcard defines the prefix for the load function of your module. In your case course\_load() will be called which returns a course object from a datasource.

If the function is not found it will fallback in any of your parent menu items. In your case it is `admin/structure/course`.

This could be an example of you load function

```
function course_load($course_id)
{
    return db_query("SELECT * FROM {course} WHERE course_id = :course_id", array(
        ':course_id' => $course_id
    ))->fetchObject();
}

```

Your `course_edit_form` doesn't receive an array of courses but 1 course object as third argument.

```
function course_edit_form($form, &$form_state, $course)
{
     // $course is here your Course object

```
> 1 votes

---
Tags: routes
---


# Question
Title: Is there anything like get_variable storage that doesn't get loaded every page?
I have a custom module and I want to store a long bit of text (~20kB).

I was going to use variable\_get but as I understand all vars accessed this way are loaded for every request, which is a memory waste as this will only be used for one block.

cache\_get is not appropriate because I don't want the data getting cleared on cache clear. It's not really cache.

Is there anything else like that?

# Answer
> 4 votes
Variables are loaded on every page *anyway*, regardless of whether your custom code requests a specific variable be loaded or not.

So, the only extra memory overhead you will incur is whatever PHP packs your 20kB of data into.

If your app is sensitive enough for that to matter, then either create a custom table to store the data, or just write it to a static file and read it back from there. If not (more likely), then just use the standard variables method, it's easier.

---
Tags: configuration
---


title: How do I get the domain name

text:
# Question
Title: How do I get the domain name
How do I get the domain name so that I can put an absolute path for images in my theme? I'm developing on a development server and want to move it live eventually.

I can't figure out a way to get the domain.

# Answer
While `$GLOBALS['base_url']` will give you the domain, it really isn't a good idea to use it directly. URLs should either use `url()` or `file_create_url()`. For example,

```
$path = drupal_get_path('theme', 'MYTHME');

drupal_add_html_head(array(
  '#tag' => 'link',
  '#attributes' => array(
    'href' => file_create_url($path . '/images/touch-icon-iphone.png'),
    'rel' => 'apple-touch-icon',
  ),
), 'MYTHME-touch-icon-iphone');

```

will add the iPhone icon meta to the `<head>` from the images/ directory from a theme. Leveraging the API will allow paths to be altered, which is necessary for module like CDN to do their thing.
> 6 votes

# Answer
You can use the global variable base\_url to get the value of domain, it returns the base URL of the Drupal installation.

```
global $base_url;

```

However if you want to get the path of theme you may use the drupal\_get\_path() as below:

```
drupal_get_path('theme', 'THEME_NAME');

```
> 4 votes

---
Tags: theming
---


title: Skip confirmation page on node delete

text:
# Question
Title: Skip confirmation page on node delete
I'm trying to skip delete confirmation page only for a content type in my site.
I found this question but I can't figure out how to modify this code to affect only a nodes in a content type. This is the code i found:

```
function mymodule_menu_alter(&$items) {
  $items['node/%node/delete']['page callback'] = 'my_node_delete_function';
  $items['node/%node/delete']['page arguments'] = array(1);
  $items['node/%node/delete']['module'] = 'mymodule';
}

function my_node_delete_function($node) {
  // Taken from node modules node_delete_confirm submit handler
  node_delete($node->nid);
  watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
  drupal_set_message(t('@type %title has been deleted.', array('@type' => node_type_get_name($node), '%title' => $node->title)));

  // Do a drupal goto here to preserver the 'destination' parameter
  drupal_goto();
}

```

# Answer
Just checking the node's type should be enough, and you can default to returning the standard deletion form:

```
function my_node_delete_function($node) {
  // If the node is of your custom type, delete it straight away.
  if ($node->type == 'my_type') {
    node_delete($node->nid);
    // ...
    drupal_goto();
  }
  else {
    // Otherwise, serve the standard node delete page.
    module_load_include('inc', 'node', 'node.pages');
    return drupal_get_form('node_delete_confirm', $node);
  }
}

```
> 1 votes

---
Tags: nodes
---


# Question
Title: How to share Redis cache across Drupal servers?
I have configured 2 Drupal servers to share the same Redis cache. One of the Drupal servers is being used for editors within the local network, the second server is used to serve up guest traffic. However, I noticed that Redis is storing cached based on the host key, so each of the two servers is storing separate keys in Redis.

What Redis configuration would be used to have it share the same keys and either override hostname to a single host or have it not use host as the key?

# Answer
> 3 votes
If you use the Redis module for Drupal, you can set the database and prefix used by your sites. The default Redis database is 0 (so multiple sites use the same database) but the default prefix is the HTTP\_HOST variable (so multiple sites use different prefix). You can however, set a shared prefix on both site in their settings.php:

```
$conf['cache_prefix']['default'] = 'mysite_';

```

You can also set prefix per cache bin, to only share a subset of the cache between them. See Redis module's README.txt for more details.

Of course, this should only be done if your are sure the cache can actually be shared. In your case, I guess the sites share the database and are used to balance the load.

# Answer
> -1 votes
I am not sure if thats a good idea and if it will ever work (there might be a reason caches are namespaced per host)

There is nothing you can do at Redis level to do what you want, you have to change the way Drupal creates cache keys (drop the hostname prefix).

---
Tags: database
---


title: How to write data to a custom field

text:
# Question
Title: How to write data to a custom field
I had another question at Save data to custom field columns using entity\_metadata\_wrapper and a similar issue at https://drupal.org/node/2110161, which nobody has been able to figure out yet.

Since entity\_metadata\_wrapper isn't working for writing custom field values, how can I do this manually? I've tried the following code, but when I view the node afterwards, the field value is blank.

```
$fieldname = 'field_device_id';
    $query = db_insert('field_data_' . $fieldname)
        ->fields(array(
          'entity_type' => 'node',
          'bundle' => 'equipment',
          'entity_id' => $new_ent->getIdentifier(),
          'language' => 'und',
          'delta' => 0,
          $fieldname . '_esn_hex' => isset($conversion_values['ESN_HEX']) ? $conversion_values['ESN_HEX'] : NULL,
          $fieldname . '_esn_dec' => isset($conversion_values['ESN_DEC']) ? $conversion_values['ESN_DEC'] : NULL,
          $fieldname . '_meid_hex' => isset($conversion_values['MEID_HEX']) ? $conversion_values['MEID_HEX'] : NULL,
          $fieldname . '_meid_dec' => isset($conversion_values['MEID_DEC']) ? $conversion_values['MEID_DEC'] : NULL,
          $fieldname . '_imei_hex' => isset($conversion_values['IMEI_HEX']) ? $conversion_values['IMEI_HEX'] : NULL,
          $fieldname . '_imei_dec' => isset($conversion_values['IMEI_DEC']) ? $conversion_values['IMEI_DEC'] : NULL,
          $fieldname . '_iccid_hex' => isset($conversion_values['ICCID_HEX']) ? $conversion_values['ICCID_HEX'] : NULL,
          $fieldname . '_iccid_dec' => isset($conversion_values['ICCID_DEC']) ? $conversion_values['ICCID_DEC'] : NULL,
          $fieldname . '_raw_id' => $id,
        ))
        ->execute();
  }

```

This code runs after a submit handler passes in a device id that a user has entered, and converts it to several different formats, which are available in $conversion\_values.

There has got to be a way to programmatically write values to custom field columns defined in hook\_schema.

# Answer
As far as the procedural method is concerned, you would use exactly the same method for a custom field as you would a contrib/core field.

Core field:

```
$node->body[LANGUAGE_NONE][0] = array(
  'value' = '<p>Some body text</p>',
  'format' => 'full_html',
);

```

Your custom field:

```
$node->field_whatever[LANGUAGE_NONE][0] = array(
  'esn_hex' => $some_val,
  'esn_dec' => $some_other_val,
  // etc...
);

```

To persist changes to both, use `node_save()` (or `entity_save()`, or whataver helper method the entity you're using provides).

```
node_save($node);

```

That's all you need to do. Manipulating the field tables manually is not recommended, as you bypass a lot of hooks that need to run, cache management, etc.

To use custom fields with an `EntityMetadataWrapper`, you need to go a bit further and describe the field and its columns to the entity module.

This involves adding `property_type` and `property_callbacks` to your field definition in `hook_field_info()`, and providing appropriate callbacks for those. There's a bit more information in this post
> 1 votes

---
Tags: entities
---


# Question
Title: Override default node form submit handler
I retrieve a node form and replace it's submit callback like this:

```
$node = entity_create('node', array('type' => 'my_type', 'title' => ''));
$node = entity_metadata_wrapper('node', $node);
$node = my_node_handler($node, 'some_operation') // It's an object factory
  ->ekran()
  ->getEntity() // It returns a DrupalEntityWrapper
  ->value() // Node's stdClass from wrapper;

form_load_include($form_state, 'inc', 'node', 'node.pages');
$form_state = array();
$form_state['build_info']['args'] = array($node);
$form = drupal_build_form('my_type_node_form', $form_state);

// Remove save, preview, delete, ....
remove_default_actions_from_form($form);
$form['actions']['send'] = array(
  '#type' => 'button',
  '#value' => t('My Button'),
  '#submit' => array('my_callback'),
  '#executes_submit_callback' => FALSE,
  '#name' => 'name_here',
);

```

But Form API does not care what my submit callback is or even, #executes\_submit\_callback, It always sends the node form to node\_form\_submit and the node is saved.

Even changing the callback like this:

```
$form['actions']['send'] = array(
  '#type' => 'button',
  '#value' => t('My Button'),
  '#submit' => array('some_non_existing_function_hahaha_hohoho'),
  '#executes_submit_callback' => FALSE,
  '#name' => 'name_here',
);

```

Will not produce an error. What's wrong here? I used entity\_form(args...) for retrieving the form and this thing happened, And changed it to drupal\_build\_form, Still the same thing.

Also along all these, I have added:

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

```

Which wont happen (not even an error about die not being callable from call\_user\_func...);

# Answer
Wow, The magic was using form alter along side the menu callback which created and handled the node like this:

```
function my_module_form_node_form_alter(&$f, &$fs) {
  $f['actions']['my_action'] = array(
    '#type' => 'submit',
    '#value' => t('My Button'),
    '#submit' => array('the_submit_func_here'),
  );

dpm($f);
}

```

Notice it's not a button type but is of type "submit". I have no idea how Form API handles submits, I thought I was having issues because of FORM\_ID\_submit but now I have no idea what is happening?
> 2 votes

---
Tags: forms
---


# Question
Title: Drupal commerce order list view - payment status
Is it somehow possible to add payment status and payment method to ordes list view? I tried to use relationship inside orders list view but the commerce payment transaction is not available. Thank you for help.

# Answer
Since Commerce 1.3, views has a new Payment relatioship
> 1 votes

# Answer
It's not impossible, but the amount of Views foo required to do it is beyond most mortals.

The tricky part is that an order can have many transactions, and also several which is completed. That is the data model would allow you to pay half by credit card and half by paypal. Also different payment methods might have different status for complete/incomplete payments. That logic is hard to build into a SQL query, which is the limitations of Views.

That said you could add a custom relationship from the order to the payment transactions and probably make something that can work. Doing this will require that you can create a module, know a bit about Views and have a lot of patience, unless you have done this type of thing before.
> 1 votes

# Answer
You can add field "payment method" or "payment status" to your Order entity. Than you can set value of this field when you are saving order in you payment method.

Of course this field will be available in views.
> 1 votes

# Answer
You can use http://drupal.org/project/views\_field\_view module. More details about it from project page:

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.

Check this comment for details.
> 0 votes

---
Tags: commerce
---


title: how to find Profile module

text:
# Question
Title: how to find Profile module
I cannot find Profile module in the core in drupal7, I want to create a registration page with multiple textboxes. Kindly tell how can I find the profile module.

# Answer
> 2 votes
The Profile 2 module isn't in Drupal 7 core yet. You can download it here.

If you'd like to set up user profiles without Profile 2, you can add more fields to the user profile at **Administration \> Configuration \> People \> Account Settings \> Manage Fields** and play around with Panels and Views afterwards.

You can find more information here too:

# Answer
> 0 votes
Administration -\> Configuration -\> People -\> Account Settings -\> Manage Fields

or in in the URL:

`admin/config/people/accounts/fields`

You should better read some documentation before asking such basic topics to community.

---
Tags: users
---


# Question
Title: Yo Dawg, I heard you like $view->execute()
I've created a View of all the views that Drupal knows about, whether they reside in code or in the DB. It works great, tells the user about each view, its tags, its displays, its base table, its fields if they exist, and its path.

I'm doing this by overriding `execute(&$view)` in a custom query handler. A very truncated version of what I'm doing:

```
foreach(views_get_all_views() as $zview) {
    // Examine each display of each view.
    foreach($zview->display as $display) {
      $row = new stdClass();
      ... // Set the things on $row.
      $view->result[] = $row;
    }
}

```

Now I also want it to tell the user about each View's query.

If I do this it works (for the last of the many Views):

```
      $zxview = views_get_view($zview->name);
      $zxview->set_display($display->id);
      $zxview->pre_execute();
      $zxview->execute();
      dpm($zxview->query->query()->__toString());

```

but I have to do it outside of the `foreach()` that goes through each view. If I try to do `$zxview->execute()` inside `foreach(views_get_all_views() as $zview) { ... }` I get

```
PHP Fatal error:  Maximum function nesting level of '100' reached, aborting!

```

This makes sense, sort of. But, so how can I list the query being executed for each view next to the name of each view, within a view? (I'm already excluding views defined by the module defining this view of views.)

# Answer
> 0 votes
I got around this issue by doing it in the field handler.

First, inside the custom query handler, I set a field in each row to contain an array consisting of the view object and the display ID:

```
    foreach($zview->display as $display) {
      $row = new stdClass();
      // Since we can't render the query here bc of recursion, pass view &
      // display to a field. We'll use a special field handler to get the
      // query for each display.
      $row->views_query = array(
        'view' => $zview,
        'display_id' => $display->id,
      );

```

Then, after telling the field to use my custom handler in `hook_views_data()`, I made my custom field handler:

```
  function render($values) {
    $value = ($this->get_value($values));
    if (is_object($value['view'])) {
      $view = $value['view'];
      $display_id = $value['display_id'] ? $value['display_id']: NULL;
      $view->set_display($display_id);
      $view->pre_execute();
      $view->execute();
      return($view->query->query()->__toString());
    }
    return 'No View object given in field handler.';
  }
}

```

Since it's no longer calling `$view->execute()` from inside `$view->execute()` (and in `render()` instead) it's much happier.

# Answer
> 0 votes
I searched on that error and you can increase the limit from 100 to something larger.

Increase the value of xdebug.max\_nesting\_level in your php.ini:

> xdebug.max\_nesting\_level
>
> Type: integer, Default value: 100
>
> Controls the protection mechanism for infinite recursion protection. The value of this setting is the maximum level of nested functions that are allowed before the script will be aborted.

Try setting it to 200

> xdebug.max\_nesting\_level = 200

Thanks to Stack Exchange for the answer!

---
Tags: views, database
---


# Question
Title: Use Views to delete a record from the database
I have created a view that displays userpoints info. What I need is to create a link that will delete or reset individual records.

# Answer
> 5 votes
Userpoints can not be deleted, at least not through the UI.

Instead, you need to create a reverting transaction that removes the points that the other transaction added, or the other way round.

The only thing that you can currently do out of the box is building a link that points to the add points form with the username pre-filled, by using that as a token in views. Then you just need to add the points and save.

Everything else currently requires custom code, by e.g. writing a custom action.

Userpoints 7.x-2.x will allow this using bulk operations and better rules integration, but there is currently not much progress on that branch. As in, pretty much none.

# Answer
> 0 votes
If you have access to the database where all the information about your website is stored (when you're using phpMyAdmin for example), you can navigate to **your\_database \> userpoints/userpoints\_total/userpoints\_txn** and delete all the granted User Points you want to. There's a nice 'select all' link at the bottom if you'd need to delete a lot of data.

It worked for me, but be careful with this: all deleted data will be lost forever! Therefore, make sure you always back-up before deleting stuff from your database!

---
Tags: views, userpoints
---


# Question
Title: How to make values of fields of newly created node available in Rules
I have a rule which is triggered upon Event: 'After saving new content'.

My Action involves executing custom php code. Please how can i make the values of the fields of my new node available in my php code.

Thanks.

# Answer
You can use fields of node currently being added in two ways

1. Check down the PHP code text field you will find text saying

> "The following variables are available and may be used by your PHP code:". Inside this you will get some site variables as `$site` and node variables as `$node`.

As per requirement you need fields of current added node so $node is the reference for current added node and also contains the fields you need. Find the screen shot to see how it can be used,as in the example I am using drupal\_set\_message to show the title of current added node or with first code of line it is simple dpm($node), which will show you complete insight of node once this rule is saved and devel module is installed.

2. Other way is to use tokens replacement options.

Under replacement patterns you will see "Replacement patterns for saved content". This list provides current node fields as toke replacement. Check the screen shot. For example usage,if you want to show node title using tokens in rules simply add this code

```
`drupal_set_message(token_replace('[node:title]', array('node' => $node)));` in the php code.

```

here in the following screen-shot is a code comparison for the above two ways, you can use any.I usually prefer using `$node`.
> 1 votes

# Answer
You can get the values of fields of newly created node from the `Replacement patterns` available at bottom on "PHP code" of actions as below:
> 0 votes

---
Tags: rules
---


# Question
Title: Prevent name collisions on form value flattening?
> The element's name property is declared in the $form array, at the very end of the array tree. For example, if an element in the form tree was structured like this: $form\['account\_settings'\]\['username'\] ?\>
>
> ...then that element's name property is 'username'--this is the key it will be available under in $form\_state\['values'\], in your validation and submission functions, as the form code flattens the array in this fashion before it passes the key/value pairs. NOTE: if you wish to have the full tree structure passed to $form\_state\['values'\], this is possible, and will be discussed later.

-Source

So, for example, if you have this:

```
$form['details']['admin'] = array(
    '#type' => 'checkbox',
    '#title' => t('Only admin can view'),
    '#default_value' => variable_get('admin', 0),
  );

```

You see that you'd be using variable\_get('admin', 0);

So what's to prevent naming collisions? Say you have another setting:

```
$form['more_details']['admin'] = array(
        '#type' => 'checkbox',
        '#title' => t('Only admin can view'),
        '#default_value' => variable_get('admin', 0),
      );

```

If anyone has a clear explanation as to how this "flattening" works, that'd be great.

# Answer
While it's good practice to use unique field names in your form, you can use the #tree property to preserve the group nesting of parent -\> same child name there.

```
$form['#tree'] = TRUE;

```

That will preserve the nesting of group -\> field values in the form `$form_state['values']` so instead of being flattened it will be

```
$form_state['values']['details']['admin'] = 'foo';

```

and

```
$form_state['values']['more_details']['admin'] = 'bar';

```
> 1 votes

---
Tags: forms
---


# Question
Title: Views module error after migrating to new server
After putting my website (in drupal 7) online today, I got a few strange errors from the 'View' module. On my local machine everything is working fine, but online I just keep getting those errors! I already checked the php version, php limit, hosting space, .. etc, everything is fine. I tried deleting all my views and adding new ones aswell, but this doesn't work either; when I try to save, nothing happens. These are the errors I'm talking about:

```
Notice: Undefined index: fields in views_db_object->init() (line 2175 of /home/kvclinke/public_html/sites/all/modules/contrib/views/includes/view.inc).
Warning: Invalid argument supplied for foreach() in views_db_object->init() (line 2175 of /home/kvclinke/public_html/sites/all/modules/contrib/views/includes/view.inc).
Notice: Undefined index: fields in views_db_object->init() (line 2175 of /home/kvclinke/public_html/sites/all/modules/contrib/views/includes/view.inc).
Warning: Invalid argument supplied for foreach() in views_db_object->init() (line 2175 of /home/kvclinke/public_html/sites/all/modules/contrib/views/includes/view.inc).
Notice: Undefined index: fields in views_db_object->init() (line 2175 of /home/kvclinke/public_html/sites/all/modules/contrib/views/includes/view.inc).
Warning: Invalid argument supplied for foreach() in views_db_object->init() (line 2175 of /home/kvclinke/public_html/sites/all/modules/contrib/views/includes/view.inc).

```

After checking my serverlogs, I also found this:

```
[Thu Oct 10 13:08:17 2013] [error] [client 213.224.29.86] ] [notice] EACCELERATOR(12762): PHP crashed on opline 3689348415265695042 of form_execute_handlers() at /home/kvclinke/public_html/includes/form.inc:1465, referer: http://www.kvclinkeroever.be/admin/structure/views/view/test

```

Anyone knows a fix for this or what the cause of this problem is? Thanks in advance!

# Answer
> 0 votes
Update: Disable eAccelerator on your server. It is caching the views module code and somehow that deletes the table name property of the views\_object which causes this error. No idea how to fix it other than not using eAccelerator.

I am afraid I have no answer, but also have the same problem on one of my clients servers. It seems to me server configuration related, since I have installed the Views module successfully on my test server, but on the client's server even installing the Views module on a fresh Minimal install of Drupal creates the same error messages. I have been comparing server settings between the test and client servers, but so far found nothing significant.

If I am reading the code correctly, the problem is most likely due to a problem retrieving a schema object - the retrieved object is not a schema object (thus has no 'fields' property) but at the same time is not an empty object, as this would terminate the function early before generating this error.

Have you gotten any further with this?

# Answer
> 0 votes
Are you sure all the modules are same in your local environment and live site?..There might be cases, if one of such module is missing, views will show missing handlers and will through these kinds of errors. Please try and see if some required module is missing.

This seems a database migration issue. Did your database migration go smooth?..It is strongly suggested you use Backup & Migrate module to deploy database to produciton. You can try to migrate your database through the module once. In the past this had helped me in fixing similar issues.

---
Tags: 7, views, migrations
---


# Question
Title: How to prevent comment posting when it has specific words in it?
I´ve searched for all Drupal 7 modules that try to give some SPAM protection, but haven´t found what I need, maybe I´ve overlooked something?

I need to **prevent anonymous comment posting when comment has specific -configurable- spammy words**. How may I do that?

# Answer
You can try Spam module.

It runs filters on posted content, for example using regexps.

Another way is to write a Rule that examines posted comments and deny them if certain words are found, but unfortunately this module is only available for Drupal 6.

And also you can write a validate function to the comment form, examine the content on submission and use form\_set\_error if you detect those words. To do this just implemente the hook\_form\_alter (or the hook form alter with form id), add your valditation function:

```
$form['#validate'][] = 'you_custom_validate_function';

```
> 1 votes

# Answer
I think you're looking for Mollom built by the same gentleman who created Drupal.

> Mollom is an "intelligent" content moderation web service. By monitoring content activity on all sites in the Mollom network, Mollom is in a unique position to determine if a post is potentially spam; not only based on the posted content, but also on the past activity and reputation of the poster. In short, Mollom handles incoming posts intelligently, in much the same way a human moderator decides what posts are acceptable. Therefore, Mollom enables you to allow anonymous users to post comments and other content on your site.
> 1 votes

# Answer
You can try word filter module

> For example, you can set the filter to find the word "work" and when found, change it to "play". You may toggle whether the filter applies to node titles as well as the body

It also has filtering for comments.
> 1 votes

---
Tags: comments, advertising
---


# Question
Title: Is drupal able to handle technical data sheets?
I already posted a similar question on webapps.stackexchange.com and was redirected here, since I mentioned Drupal. Here is the slightly updated question:

---

I am a php developer and didn't have the chance to work with a CMS for ages, and I couldn't find any decent solution for my problems throughout my internet searches.

For a new project I am working on, I need to provide an application which can allow a few users to create and handle numerous technical datasheets (around 1-2k). The application should be able to handle a few different kind of sheets, whose structure and contents are known and static: few lines of text, some geographical data, numeric coefficients and pictures. It should also be possible to attach files to one sheet (let's say a .zip, a .doc, or whatever).

Users should be able to:

* Create and edit sheets.
* Search through them
* Export them to various formats (pdf, doc, xls, etc.)

Administrators should be able to:

* Create and manage users.
* Create new types of datasheet.

One important feature is the non-concurrent editing (i.e. a sheet should be locked if someone is editing it).

At first glance, I was willing to create all that from scratch, with my little hands and a decent php framework. But then I started to think (it happens...), and was wondering if a CMS wouldn't to the trick, since this is what I'm searching for: a (specific) content management system.

I had some little experience with drupal, which allowed to create custom nodes. Wouldn't that answer my problems? A node would then be a specific type of datasheet. The different possible actions of users and administrators (create, update, search, export, etc.) being handled by drupal core functionalities. Am I right?

If so, is there any specific module I should look into?

Thanks in advance for your help!

# Answer
According to me you have half answered your question, yes node is what your data holder for the datasheets. consider nodes as container for your data so to change the way you to present them you can use views module.views module will allow you to present your nodes the way you like also you have option to export your views in different formats.

Here are some modules which can be helpful for exporting your views in different formats

**Update:**

For content locking for concurrent content edit you can check Content locking (anti-concurrent editing) contributed module.

**Update:**

About having different types of datasheets,

* If you are looking are categorizing your nodes/sheets, core shipped taxonomy is there.
* If you need to have separate types of sheets in structure, permissions to create/edit/view them, having separate content types will be the solution.
> 2 votes

# Answer
Without seeing examples of the different data sheets you are referring to I am guessing you could use a "data sheet" content type `Administration >> Structure >> Content types`.

Add the Fields you would need to that content type, make them searchable, and then add a module for exporting the entity as a PDF, doc, xls ... you may want to investigate https://drupal.org/project/views\_data\_export or another similar modules.

As previously mentioned you could use views for displaying these and Drupal Taxonomy for the different data sheet types.
> 1 votes

# Answer
I created a system for technical datasheets in VBA some years ago, it took data from several sources including excel spreadsheets, word documents and sage accounting. It took a while and doing it in VBA was frustrating.

What you specify is far simpler and with the right combination of modules and a well thought out data architecture should entirely be possible in Drupal, Views may cope with the complexity of the different data but you may need to use Views Field View which can create a summary of views (so like sub-queries in a complex SQL query and Entity Reference to link a related information back to a product.
> 0 votes

---
Tags: 7, importing-exporting, nodes
---


# Question
Title: Content exists in Drupal but unseen in PHPMYadmin?
I have a content type which I enter data to by means of a csv file. Everything works fine as I have multiple content-types set up like this.

However, I'm trying to clean-up the database and remove data that is from 2012 and before.

Within Drupal at the /admin/content/filter url, I set the parameters for the content-type and such as:

```
node type is Print Data
and is created before 2013-01-01
and node status is published

```

(note, I just used the code indicator to set-off the options for this post)

Upon return, I have pages of content with each page showing 500+ results. I can delete them from within Drupal, but only at 500 at a time so I went to phpMyadmin but in there, I can only see/find data that is from 2013.

So where is Drupal storing all that other data if not in the database?

# Answer
First of all allow me to say that you should not delete from db directly unless you are really aware of drupal's architecture and how the db tables are organized. (basically have in mind drupal store information for an entity in multiple tables not only one.)

Secondly have in mind in case you are looking through node table for a node created prior 2013-01-01 m the actual date is saved as unix timestamp (1357020000)

Thirdly allow me to recommend you VBO (View Bulk Operation) module for the exact scenario you are looking for , it will let you bulk delete, unpublish, publish (even has an API for custom bulk operations). I would create a simple view accesible for admins only, exposed filters for node creation date and some basic bulk operation. Please consider using this
> 3 votes

# Answer
As you cannot go with VBO(View bulk operation), I would suggest you to create a custom script for deleting the code rather than deleting manually from the database:

* Can take the reference from devel\_generate\_content\_kill(), this function is called by the devel generate module to delete the multiple nodes.
* As the function provides a way to create the script, you need to modify only field condition as per you need.
* It would be wise to keep the backup of the existing database(so in case anything goes wrong you can rollback easily).

function custom\_node\_delete\_op() {
// Define the time value , Example of 10 mins.
$time\_since = time() - 600;

// This will provide the node ids of nodes older than 10 min. $results = db\_select('node', 'n')
-\>fields('n', array('nid'))
-\>condition('type', 'CONTENT\_TYPE', 'IN')
-\>condition('created', $time\_since, '\<')
-\>execute();
foreach ($results as $result) {
$nids\[\] = $result-\>nid;
}

// Execute the code to delete the nodes.
if (!empty($nids)) {
node\_delete\_multiple($nids);
drupal\_set\_message(t('Deleted %count nodes.', array('%count' =\> count($nids))));
}
}
> 1 votes

---
Tags: nodes, database
---


title: How to move "Add new comment" link

text:
# Question
Title: How to move "Add new comment" link
How would I go about moving the "Add new comment" link above certain items in my content type display? Here's an example: http://www.jcpenney.com/women/fall-trend-shop/boyfriend/ana-boyfriend-cardigan-/prod.jump?ppId=pp5002961049&catId=cat100300005&subcatId=cat100250027&deptId=dept20000013&dimCombo=null&dimComboVal=null&colorizedImg=DP0705201317172824M.tif

In the link above you'll see the "write a review" link. This is where I want to place the "Add new comment" link.

# Answer
You can create the node template for your content type. You can review the template suggestions link for reference.

You can add below code in your template file to generate a link for the comments.

```
print render($content['links']['comment']);

```

Kindly see that you need to uncheck 'Show reply form on the same page as comments ' checkbox in the comment settings for your content type.
> 2 votes

---
Tags: nodes, comments, entities
---


title: How to capture all clicks from user

text:
# Question
Title: How to capture all clicks from user
I need to track all clicks by a user (even with no JavaScript enabled. What is the best hook\_ function to use to track these requests so I may log them?

# Answer
You can use Google Analytics Event Tracking module to track mouse click and other events. This module provides a hook where you can track click events.

From module page:

> Event Tracking is a way to track user interaction with out registering a page view.
>
> This module allows an interface for Google Analytics event tracking capabilities. It provides a hook for other modules or "glue code" and also has some handy drush commands.
> 1 votes

# Answer
Looks like hook\_exit() is what I want. It is called after cached and non-cached page requests, everything is loaded, and cleanup happens. This seems like the right place to make a logging call.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: How to get custom line item's custom attribute's value after order complete
Using this guide I added a custom line item type to my Drupal Commerce installation and have allowed the customer to add extra data when purchasing an item. When the order is complete I need to get hold of that extra data and use it to build some database rows that will grant them access to the service they have just purchased. I have implemented **hook\_commerce\_checkout\_complete($order)** but I haven't been able to find the data within $order. I know it is there somewhere because I can view the order on the customer's account and have modified the View to show the data next to Unit price, Quantity and Total columns.

# Answer
You can use the `entity_metadata_wrapper` on `commerce_order`

```
/**
 * Implements hook_commerce_checkout_complete
 */
function package_designer_commerce_checkout_complete($order) {

  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
    if(isset($line_item_wrapper->field_package_configuration)){
      $package_configuration = $line_item_wrapper->field_package_configuration->value();
      // You can also get the raw value like this:
      // $package_configuration = $line_item_wrapper->field_package_configuration->raw();
    }
  }

}

```
> 1 votes

# Answer
This is the solution I have so far, but I'm new to Drupal and expect to be corrected. The extra field I added to my custom line item is called \*package\_configuration\*

```
function package_designer_commerce_checkout_complete($order) {
    $ow = entity_metadata_wrapper('commerce_order', $order);

    foreach ($ow->commerce_line_items as $line_item) {
        $lineItemId = $line_item->line_item_id->value();

        $result = db_query("select * from field_data_field_package_configuration where entity_id = $lineItemId");

        foreach($result as $record){
            $customValue = $record->field_package_configuration_value;
        }
    }
}

```
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Which are the differences between hook_node_view_alter and hook_preprocess_node?
I have to remove some elements from a node before show it, but I can't understand where it's better to put the code. Mainly I can't understand the differences between `hook_node_view_alter` and `hook_preprocess_node`. It seems they do the same thing as they receive a render array as parameter.

I think the best option should be to use the `hook_node_view` but it isn't the right way to do this because in this hook only `$node->content` is editable.

# Answer
`hook_preprocess_node` is more generic, and thus more limited, and happens after `hook_node_view_alter`.

Both operate on the similar array, basically, but hook\_node\_view\_alter operates at earlier stage. So, first reason is ordering of actions, second is accessing a bit different data sets, as they changes between stages of execution. `dpr()` or `var_dump()` their arguments to see exact differences. That's all. Nothing much to it, really.
> 1 votes

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


# Question
Title: Can Drupal's search index external tables?
Can Drupal's search system index external tables? I have looked up how external tables can be linked to Drupal using the Data module, hook\_views\_data etc., Can the content of the external tables be indexed and searched by Drupal's search system?

# Answer
Yes, you can use the search api to specify your additional content. In particular you will need
> 1 votes

---
Tags: 7, search, database
---


# Question
Title: How to make weights continous with db_update?
With pure MySQL, I can do something like:

```
SET @weight:=0;
UPDATE mymodule_table
  SET mymodule_weight=@weight:=@weight+1
  ORDER BY mymodule_weight, mymodule_id;

```

Is there a Drupal way to achieve similar result? Can I avoid calls to `db_query` and push it with `db_update` or `db_merge`?

MySQL solution adapted from this answer.

# Answer
Adding the expression is no problem, but neither `UpdateQuery` nor `MergeQuery` implement an `orderBy()` method. Neither will support setting a local variable first either, as far as I can tell (I'm not even sure a standard query will let you do that actually).

So I think it's safe to say that the answer is no, unless you subclass either `UpdateQuery` or `MergeQuery`, and add the sorting and variable declaration functionality yourself.
> 2 votes

---
Tags: 7, database
---


# Question
Title: Disabling the media browser private download option , showing public download as an option
In the media module when we upload an image it asks us how to store a file (as public or private). But I don't want to show the user these options. Moreover, the user should not see that option box and the file uploaded should be saved as public file only. How can I implement this?

# Answer
Upgrade to the latest 2.x version of the media module and file entity module.

This issue was addressed in https://drupal.org/node/2001074

There is now admin configuration at the file system settings page.

In my opinion the configuration ability still needs some improvement but it dos the job for now.
> 1 votes

---
Tags: media
---


# Question
Title: List all available items with Apache Solr if the search keyword is empty
I have created 2 search pages with Apache Solr module one with content type filter and another for search in taxonomy terms. By default if the keyword string is empty the search pages don't return any results. How can I list all available items with certain content type or with taxonomy term in this case? Thanks

# Answer
> 3 votes
Thanks Letharion, to answer your question I have found this option in the Advanced options region for the search pages. Here is how to get there:

admin/config/search/apachesolr/search-pages

Create a new search page for Solr search with content type filter or enable one for taxonomy/term/%

Select "Show enabled facets' blocks in their configured regions and first page of all available results" under the Advanced options for this page

# Answer
> 0 votes
check "Custom Filter" text box and add text : bundle:content type, content type is your specific content type name

---
Tags: 7, search
---


title: Use panel url for Solr result

text:
# Question
Title: Use panel url for Solr result
I am using Apache Solr on my website and the search form block is configured to use Apache Solr. I also use the Apache Solr panels module to panelize my page.

I create a panel on search/my-search/!query, when I use it manually all works fine but when I search via the form search block, I am redirected on the default Apache Solr result page (search/site/!query).

How can I change this behavior ?

EDIT : Okay, I found the solution by searching a little bit more !

I just disabled the default search block form and put the "Search form (Apache Solr Panels)" in the section I wanted. I only have to restyling my input.

I will put it in a separate answer tomorrow (because of my reputation, I can't answer in the next 8hrs after posting my question)

# Answer
Sorry for delay, I post here my answer separately from the question :

Okay, I found the solution by searching a little bit more !

I just disabled the default search block form and put the "Search form (Apache Solr Panels)" in the section I wanted. I only have to restyling my input.
> 0 votes

# Answer
use

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "search_block_form") {
    $form['#submit'] = array('custom_search_redirect');
  }
}

function custom_search_redirect($form, &$form_state) {
  $search_data = $form_state['values']['search_block_form'];
  $form_state['redirect'] = "search/my-search".$search_data;
}

```
> 1 votes

---
Tags: search, panels
---


# Question
Title: Is there any way to see the content of the theme registry?
I was wondering if there is a way to see (print out) the content of the theme registry.

I've looked in the database; it seems to be stored in the cache table, if I understand things right, but the theme registry itself is stored as a blog.

When I looked at the blog, I couldn't seem to make any sense of what was there. It all seemed to look like hex values.

# Answer
> 4 votes
If you want to see the content of the theme registry, you can use \_theme\_load\_registry(). The first argument could be the global `$theme` for the currently used theme, or one of the objects returned by list\_themes(). As the function name is prefixed by an underscore, I would suggest to use it only for debugging purposes. (Theoretically, future Drupal versions could drop those *private* functions, and that would not probably be taken as API change.)

If you have installed Devel, you can use the following code:

```
global $theme;

$registry = _theme_load_registry($theme);
dsm($registry);

```

You can also simply visit the devel/theme/registry page which shows you the theme registry content.

# Answer
> 1 votes
See theme\_get\_registry()

This simple function returns an array of theme registry

# Answer
> 0 votes
hook\_theme\_registry\_alter can help in this regard.

```
function mymodule_theme_registry_alter(&$theme_registry){

```

`$theme_registy` would result entire theme registry information.

The hook is invoked as the theme cache is re-built

---
Tags: theming
---


# Question
Title: Domain Access but isolated user and content perfectly
I try domain access module for different domains. But when using user reference in contents every user sees other users. Is it possible to isolate every domain users from other domains users.

# Answer
Use the References modules and enable user reference submodule.

Add a user reference field to your content. Then, in the "Views - Users that can be referenced" section of your field options select a View that filters users by current domain. You must create this view before add the field to see the view.
> 1 votes

---
Tags: domain-access
---


title: altering a hook_form_alter function

text:
# Question
Title: altering a hook_form_alter function
Is it possible to use `hook_form_alter()` on a `hook_form_alter()` function already defined in another module?

For example, if I want to alter the output of the following hook from the menu module, can I define a function which allows me to alter the renderable array?

```
function menu_form_node_type_form_alter(&$form, $form_state) { ... }

```

I have looked at the documentation but can't seem to find anything that suggests this is allowed/possible.

# Answer
> 7 votes
If you create your own hook\_form\_alter function in a custom module, you can modify the same form.

All of the $form variables that are passed into all of the form alter hooks are the same. You will need to specify the form you want to modify by checking for $form\_id. $form\_id happens to be the third argument passed in!

For example:

```
function MODULE_form_alter(&$form, $form_state, $form_id)
{
    if ($form_id == "YOUR_FORM_ID)
    {
        //modify form here.
    }
}

```

There is also the order of execution for the hooks, that you can modify using hook\_module\_implements\_alter. Using this hook, you can set your module to be executed last.

For example:

```
function MODULE_module_implements_alter(&$implementations, $hook)
{
    if ($hook == 'form_alter')
    {
         $group = $implementations['my_module'];
         unset($implementations['my_module']);
         $implementations['my_module'] = $group;
    }
}

```

That should do exactly what you need to do.

# Answer
> 7 votes
Not as such, but you can just implement your own version of that alter hook to make the changes you need to, and make sure your implementation runs later on.

To do that you'll need to implement `hook_module_implements_alter()`:

```
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Push your module's implementations of hook_form_alter(), and derivatives,
    // to last in the list. This will make it run after menu_form_node_type_form_alter()
    // so you can alter whatever you need to.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

function MYMODULE_form_node_type_form_alter(&$form, &$form_state, $form_id) {
  // Make changes as usual
}

```

---
Tags: forms, theming
---


title: Ctools modal close breaks page JS

text:
# Question
Title: Ctools modal close breaks page JS
I have created a custom module which opens modal with a specific Url Pattern. I'm using the url in a view and it works well.

The only problem is that I also load another piece of jQuery to create a basic accordion which breaks after the modal has been loaded. The javascript is still called but it toggles twice instead of once.

```
/**
 *  Implements of hook_menu()
 */
function mymodule_menu() {
  $items['modals/%ctools_js/%'] = array(
      'title' => 'Product Modal',
      'page arguments' => array(1, 2),
      'page callback' => 'mymodule_modal_page',
      'access callback' => TRUE,
      'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}
/**
 * A modal static page callback.
 * @param $js
 *   boolean CTools determination whether the user's browser is javascript enabled.
 * @param $nid
 *   string The node ID of passed as an argument from the hook_menu() path
 * @return
 *   string The contents of the node, that will fill the modal window.
 */
function mymodule_modal_page($js = NULL, $nid = NULL) {
  if ($nid == NULL) {
    return 'No node id was sent. Error.';
  }
  if ($js) {
    ctools_include('modal');
    ctools_include('ajax');

  }
  $node = node_load($nid);
  $contents = render(node_view($node, 'modal', NULL));
  return ctools_modal_render($node->title, $contents) ;
}

  /**
   * Implements hook_views_pre_render()
   */
  function mymodule_views_pre_render(&$views) {
    if ($views->name == 'my_view') {
      //add accordion script
        ctools_include('ajax');
        ctools_include('modal');
        ctools_modal_add_js();

        $product_style = array(
          'product-modal-style' => array(
            'modalSize' => array(
              'type' => 'fixed',
              'width' => 400,
              'height' => 400,
              'addWidth' => 10,
              'addHeight' => 10,
              'contentRight' => 1,
              'contentBottom' => 1,
            ),
            'modalOptions' => array(
              'opacity' => .9,
              'background-color' => '#424242',
            ),
            'animation' => 'fadeIn',
            'modalTheme' => 'product_modal',
          ),
        );
      drupal_add_js($product_style, 'setting');
      ctools_add_js('product', 'mymodule');
      ctools_add_css('product', 'mymodule');
      drupal_add_js(drupal_get_path('module', 'ukgproducts') . '/js/product_accordion.js','file');
    }
  }
  }

  /**
  * Implements hook_theme().
  */
  function ukgproducts_theme() {
    return array(
      'views_view_unformatted__my_view' => array(
        'variables' => array('view' => NULL, 'options' => NULL, 'row' => NULL),
        'template' => 'views-view-unformatted--my_view',
        'base hook' => 'views_view_unformatted',
        'path' => drupal_get_path('module', 'mymodule') . '/theme',
      ),
    );
  }

```

accordion JS

```
(function($, Drupal)
{
  // Drupal.behaviors is the Drupal onload function:
  Drupal.behaviors.ukgproducts = {
    attach:function()
    {
      $('h2').click(function(e)
      {
        e.preventDefault();
        $(this).closest('.binder').find('.product-list').toggle('slow');
      });
    }
  }
}(jQuery, Drupal));

```

# Answer
> 4 votes
You should pass the context in and use the `once()` function to make sure your events are only bound once, and in the right context. Something like:

```
(function($, Drupal) {
  Drupal.behaviors.ukgproducts = {
    attach: function(context, settings) {
      $('h2', context).once('myaccordian').click(function(e) {
        e.preventDefault();
        $(this).closest('.binder').find('.product-list').toggle('slow');
      });
    }
  };
})(jQuery, Drupal);

```

---
Tags: views, theming, chaos-tool-suite, javascript
---