# Question
Title: Do not want <footer> HTML tag when using footer region
After running W3 Markup Validator on a site of mine, I received the following error:

> Line 219, Column 57: element "footer" undefined
>
> `<footer id="footer" class="region region-footer">`

Whether or not this is actually an issue, bad style, or what, I've decided that I *don't* want Drupal using the HTML footer tag. Is there a way that I can change this and have it just create yet another div?

# Answer
> 1 votes
If you are using zen theme there is a 'region--footer.tpl.php' in the templates you can change it from there. ( i don't know about other themes maybe they have it too)

# Answer
> 2 votes
did the validator know you where using an HTML5 site? http://www.w3schools.com/tags/tag\_footer.asp

... anyways you can always edit `page.tpl.php` or `html.tpl.php` for your theme to change global page markup like this to however you want.

---
Tags: theming
---


# Question
Title: views Filter field equal to the value of another field
Is there a way or a module to filter a vie by a field against the value of another field. For example uI'd is equal to the value of another field that's given.

# Answer
From what I understand of your request you are adding a view on a node display page and want to use a field on that page as an argument in the view, if this is the case you want to add a contextual filter and under default value select php and then do a node\_load or db\_select to load the field from the node being viewed.
> 1 votes

# Answer
Not sure if this is what you are looking for - https://www.drupal.org/project/views\_dependent\_filters \- this allows you to use a view as a filter in another view
> -1 votes

---
Tags: views
---


# Question
Title: Outputting the sum of multiple fields into a new view that then gives a grand total
I have a view right now that takes data such as # of properties owned and Square footage total by region. So for example if someone clicks the northeast region of a map they'll get the number of buildings and square ft of properties in that specific region, displays them, then at the bottom totals them.

I'm trying to come up with a way to take the totals of those regions, display them in another view and then add THEM up for a grand total.

Is this something that can be done with views? If not, is there another solution that can work with the view already implemented?

# Answer
> 0 votes
Probably the simplest way to do this via Views is to add the Computed Field module to your site, and build a new content type (maybe "summary"), and add a summary for each kind of property you'd want to add in the view, and then use the computed fields to calculate all the grand totals. Display the computed fields in a new view, and it should work fairly well.

However, that wouldn't be all that dynamic. There are probably ways to do this in views itself by adding groupings, relationships, and calculated fields, but you'll end up with a view that's fragile and a real pain to maintain via the UI. You might want to approach adding a views attachment, or a display after the view, or just use some plain old custom code to generate a block (or within a block if you use the PHP filter, but I would not recommend this approach).

Another possible solution (if it's simple feature set gives you what you'd need) is the Views Summarize module.

# Answer
> 0 votes
You should be able to:

* first under the View's advanced settings, switch "Use aggregation" to Yes
* select the Region as a field, and under the Aggregation settings, set it to "Group results together"
* then for the other fields (num of buildings and square ft), use Aggregation settings "Sum"

You might need to also Sort by Region, and also aggregate the Sort Criterion as "Group results together"

That should give you the subtotals for each reason. Then you can use Views Summarize to get the grand totals.

---
Tags: views
---


# Question
Title: Manage photo default settings in Node gallery module
I am using Node Gallery module to work with albums and photos uploaded by user. When a user views his album there is a tab called **Manage Photos** which displays table with headings **Delete**, **Preview**, **Edit** and **Cover**.

I want to change the text of 'Cover' as 'Album Cover' and display 'Delete' column at the end.

How to do this??

# Answer
There is a Theming Function inside the **theme.inc** (\node\_gallery\theme\theme.inc) file:

```
theme_node_gallery_api_manage_items_form($variables)

```

In there is everything you need. Copy this whole function to your template.php, rename the function to `YOURTHEMENAME_node_gallery_api_manage_items_form($variables)` and change the desired text. I think this should to the trick.

Paste the below code inside your active theme template.php file and **make sure to change to you theme name.**

```

    /**
     * Theme function for Manage Items form.
     */
    function elegant_theme_node_gallery_api_manage_items_form($variables) {
        $form = $variables['form'];

        if (empty($form['items'])) {
            return t('This gallery is empty.');
        }
        // Pull in the multi-select functionality from core.
        drupal_add_js('misc/tableselect.js');
        // Get fieldname to retrieve the filepath for the thumbnail without
        // loading the node.
        $relationship_type = node_gallery_api_get_relationship_type($form['#gallery']->type);
        $enable_rotation = FALSE;
        if ($relationship_type->settings['manage_items']['enable_rotation'] && (image_get_toolkit() != 'gd' || function_exists("imagerotate"))) {
            $enable_rotation = TRUE;
            drupal_add_library('system', 'ui.dialog');
            drupal_add_library('system', 'ui.draggable');
            drupal_add_library('system', 'ui.resizable');
            drupal_add_js(drupal_get_path('module', 'node_gallery') . '/js/ng_manage_images.js');
        }
        $header = array(
            t('Album Cover'), //changed from Cover to Album Cover
            t('Preview'),
            t('Edit'),
            array(
                'data' => t('Delete'),
                'class' => 'select-all',
            ),
        );
        if ($enable_rotation) {
            $header = array(
                t('Album Cover'), //changed from Cover to Album Cover
                t('Preview'),
                t('Edit'),
                t('Rotation'),
                array(
                    'data' => t('Delete'),
                    'class' => 'select-all',
                ),
            );
        }
        $rows = array();
        foreach (element_children($form['items']) as $nid) {
            $element = &$form['items'][$nid];

            $row = array();
            //Cover checkbox
            if ($form['is_cover']) {
                $row[] = drupal_render($form['is_cover'][$nid]);
            }
            //preview
            $file = $element['item_file']['#value'];
            if (!empty($file)) {
                $file_object = (object) $file;
                $file_view = file_view($file_object, 'node_gallery_api_admin_thumbnail');
                $row[] = drupal_render($file_view);
            }
            else {
                $row[] = '';
            }
            //edit link
            $edit = drupal_render($element['edit_form']);
            if (!empty($element['ngid'])) {
                $edit .= drupal_render($element['ngid']);
            }
            $row[] = $edit;
            //Rotation
            if ($enable_rotation && !empty($file) && $file['type'] == 'image') {
                $row[] = drupal_render($element['rotate']);
            }
            elseif ($enable_rotation) {
                drupal_render($element['rotate']);
                $row[] = '';
            }

            $row[] = drupal_render($element['remove']);
            $rows[] = array('data' => $row);
        }
        $output = theme('table', array(
            'header' => $header,
            'rows' => $rows,
            'attributes' => array('id' => 'upload-attachments'),
            )
        );
        $output .= theme('pager');
        $output .= drupal_render_children($form);
        return $output;
    }

```
> 2 votes

---
Tags: media
---


# Question
Title: Update user via REST (and under AngularsJS)
I need to update a user fields via REST SERVICE. I'm under AngularJS, so this is my function into my .service()

```
setMyUtx: function (params) {
            return $http({
                method : 'PUT',
                url : 'http://XXXXXXXX/rest/user/'+params.uid,
                data : {'data' : params.value},
                headers : { 'X-CSRF-Token' : $cookies['csrftoken'],'Content-Type': 'application/json;charset=utf-8'},
                cache : false
            })
        },

```

where params.value is :

```
var data = {};
      data.field_primary_aircraft = {};
      data.field_primary_aircraft.und = [{value:1}];
      ProfileService.setMyUtx({'uid' : $scope.datiUtente.uid, 'value' : data});

```

If I exec this function, my drupal site return no error with this output:

```
{"field_primary_aircraft":{"und":[{"value":0}]},"uid":"7","roles":{"2":"authenticated user"}}

```

But no update is done (I know it because the original value of field\_primary\_aircraft is 1).

Why this ? Where is my error ?

# Answer
I suggest you first try to test it with a browser REST application extension. I would recommend this for Firefox: https://addons.mozilla.org/he/firefox/addon/rest-easy/

If you still doesn't get any error, check your watchdog... there is no reason this shouldn't work.
> 1 votes

---
Tags: 7, services, javascript
---


# Question
Title: jQuery slideshow behaving oddly in Drupal
I have a jQuery slideshow that worked fine when it was running in a site built with standalone PHP files, but now that I've rebuilt the site in Drupal, it has a problem. The slideshow is running in the header of this page:

http://oaklandoctopus.org

There are five images in the slideshow, the first of which is selected randomly. The first time the script loops back to the beginning, the first image does not appear. Then, on subsequent loops, everything is fine. Here is the jQuery script:

```
var x = Math.floor(Math.random() * $(".home-page-header-images .view-content .header-slideshow-image").length);
$(".home-page-header-images .view-content .header-slideshow-image:eq(" + x + ")").addClass("active").css({opacity: 1.0});

    setInterval(homepageSlideshow, 4000);

    function homepageSlideshow() {
        var activeImg = $(".header-slideshow-image.active");
        var nextImg = activeImg.next(".header-slideshow-image");
        console.log($(".header-slideshow-image:first"));
        if (nextImg.length == 0) {
            nextImg = $(".header-slideshow-image:first");
            }
        nextImg.addClass("next").animate({opacity: 1.0}, 1000, function() {
            activeImg.removeClass("active").css({opacity: 0.0});
            nextImg.removeClass("next").addClass("active");
        });
    }

```

Here is the relevant CSS:

```
.home-page-header-images .header-slideshow-image, #footer-slideshow .header-slideshow-image {
opacity: 0;
position: absolute;
z-index: 0;
/* Early IE */
filter: alpha(opacity=0);
}

.home-page-header-images .header-slideshow-image.active, #footer-slideshow .header-slideshow-image.active {
z-index: 1;
display: block;
}

.home-page-header-images .header-slideshow-image.next, #footer-slideshow .header-slideshow-image.next {
z-index: 2;
display: block;
}

```

I am so thoroughly stumped its not even funny. Any help is greatly appreciated. Happy to provide any additional information. I'm relatively new to Drupal theme development, just FYI.

# Answer
This because you have two slider block in your durpal website. The second one is hidden in the footer section. Block id is : **block-multiblock-7**.

Both of these block are having same DOM structure, so in the following scenario your slider will break.

Breaking Scenario: **Main slider** -\> 5th Image is active. **Footer Slider** -\> 3th Image is active

Then your condition fails:

```
if (nextImg.length == 0) {
            nextImg = $(".header-slideshow-image:first");
            }

```

Hope you are clear with my point.

Thanks
> 1 votes

---
Tags: views, javascript
---


# Question
Title: How do I connect to an external database and specify the schema to use?
I want to connect Drupal to an external Database and I need to specify the schema on the settings.php file, otherwise Drupal schema module connects by default to the 'public' schema. I tried, without success, with the following code.

```
 $databases['conservation']['default'] = array(
   'database' => 'conservation',
   'schema' => 'projects_test1',
    'username' => 'xxxxxxxxxxx',
    'password' => 'xxx',
    'host' => 'xxx.xxx.xxx',
    'port' => '5432',
    'driver' => 'pgsql',
    'prefix' => array(
      'default'   => 'projects_test1.',
      'users'     => 'shared.',
      'sessions'  => 'shared.',
      'role'      => 'shared.',
      'authmap'   => 'shared.',
    )
  );

```

I have done some googling, but I haven't found anybody trying to do this.

# Answer
> 0 votes
You can specify a PGSQL schema using the `prefix` setting in `settings.php`

```
 * You can also use a reference to a schema/database as a prefix. This may be
 * useful if your Drupal installation exists in a schema that is not the default
 * or you want to access several databases from the same code base at the same
 * time.
 * Example:
 *   'prefix' => array(
 *     'default'   => 'main.',
 *     'users'     => 'shared.',
 *     'sessions'  => 'shared.',
 *     'role'      => 'shared.',
 *     'authmap'   => 'shared.',
 *   );

```

More info: https://api.drupal.org/api/drupal/sites%21default%21default.settings.php/7 \> "View Source"

If that's not working for you, make sure the rest of the database connection details are correct. (e.g you're using 'shared.' presumably that schema also exists)

---
Tags: configuration
---


title: Update url query upon form submission

text:
# Question
Title: Update url query upon form submission
I am trying to append a variable on the URL through a custom submit function. Is that possible?

My issue is that I am coming to the node/%/delete from different pages. I want to modify the delete form if the user comes to it from the node/%/edit. How can I detect this?

As @Clive suggested I'll try to add a query param in the following structure:

```
actions (Array, 5 elements)
  #type (String, 7 characters ) actions
  submit (Array, 5 elements)
  preview (Array, 5 elements)
  delete (Array, 4 elements)
    #type (String, 6 characters ) submit
    #value (String, 6 characters ) Delete
    #weight (Integer) 15

```

# Answer
You should use the hook\_node\_access in your custom module.

For Example -

```
/**
 * Implements hook_node_access().
 */
function MODULE_node_access($node, $op, $account) {

  if ($op == "delete") {
    // If no user object is supplied, the access check is for the current user.
    if (empty($account)) {
      $account = $GLOBALS['user'];
    }
    // You can add your own condition check here...
    return user_access("delete content", $account) ? NODE_ACCESS_ALLOW : NODE_ACCESS_DENY;
  }

  return NODE_ACCESS_IGNORE;

}

```
> 0 votes

---
Tags: forms
---


# Question
Title: Double click quickly on the entity save form two entity get created
I am using Entity Construction Kit 7.x-2.0-rc2. I have created one entity type with some manage field as title,message. if i double click quickly on creating entity then it will save entity form two or more entities get created.

# Answer
> 1 votes
Try Hide Submit

> Features:
>
> Hide or disable the submit button after it has been clicked
>
> Display a message and/or image while waiting

---
Tags: entities
---


# Question
Title: How to add a placeholder to a form element using a twig template override
I enabled twig debug and realized I needed to add block--search.html.twig to my theme. Then I used dump(content) to see if I could add a placeholder to search input field

```
{% extends "core/modules/block/templates/block.html.twig" %}
{% block content %}
  {{ dump(content) }}
  {{ content }}
{% endblock %}

```

How can I change the content array and add a new **'#placeholder'=\>'bla'** to the search input?

dump(content) returns something like this:

```
array (size=23)
  '#action' => string '/search/node' (length=24)
  '#method' => string 'get' (length=3)
  'keys' =>
    array (size=26)
      '#type' => string 'search' (length=6)
      '#title' => string 'Search' (length=6)
      ...

```

# Answer
Altering forms in Drupal 8 is the same as in Drupal 7 - you have:

Always use an alter/preprocess hook to change variables *before* they get to the template file, it's bad practice to change them once you're in the template file itself.
> 6 votes

---
Tags: theming, 8
---


# Question
Title: How to add the Terms and Conditions to custom form,not using any profile 2 or webform module?
How to add the Terms and Conditions to custom form?
i have made a module and willing to add a "read me / terms and conditions " type of thing to my form .
Whole code can be seen here , just dont wanted to write it again .
Custom module error, does'nt show on the page

Please suggest.

# Answer
> 2 votes
You can just add another element to the form like so:

```
$form['terms'] = array(
  '#type' => 'checkbox',
  '#title' => t('Terms & Conditions'),
  '#prefix' => "<p>Your terms go here</p>",
  '#required' => TRUE,
);

```

That will just stick the text before the checkbox, and then use CSS to position it however you want.

You might also want to put a validate hook in there and remove the `#required` attribute so you can write your own text in the `form_set_error`.

# Answer
> 2 votes
Use the Legal module

> Displays your Terms & Conditions to users who want to register, and requires that they accept the T&C before their registration is accepted.

---
Tags: 7, forms
---


# Question
Title: alter/remove taxonomy term path if no related nodes
I'm using taxonomy menu and nice menus to generate the page main menu. Not every term has related nodes, but the customer wants them all to be in the menu, but the "empty" terms not clickable. And when he creates nodes related to these terms, the terms should turn in to links. Can I achieve that with hook\_page\_alter? Or is there a better hook to use. I first tried hook\_url\_outbound\_alter, and I was able to rewrite the path, but it's still a link, and I want to avoid that. I know how to use rendered arrays, but this one is a bit tricky for me.

# Answer
I found the right hook in nice menus module. With hook\_nice\_menus\_build($variables) I'm able to check every menu item about referenced nodes. Then I can add a class like 'js-no-nodes' and use javascript/jquery to replace the with .
> 0 votes

# Answer
I would do that using `hook_menu_link_alter()` and Special Menu Items module, which provides special menu items like `<nolink >` and `<separator>`.
> 0 votes

---
Tags: hooks, taxonomy-terms
---


title: Show a product field programmatically

text:
# Question
Title: Show a product field programmatically
I created some fields such as Color called field\_color (taxonomy terms) in the product content type but whatever I do, when I create a product and set the field\_color, the color name doesn't show up on the product page. I also tried to create fields programmatically with hook\_install and hook\_schema\_alter but to no avail. Maybe I'm doing something wrong as I have never created any fields/schema before.

# Answer
Here's how you create a term reference field to a CONTENT\_TYPE:

1. Create a taxonomy vocabulary called, say, "Color" at admin/structure/taxonomy/add.
2. On admin/structure/taxonomy, click "add term" next to your new vocabulary.
3. Add terms, such as, say, "blue", "red", etc.
4. Go to /admin/structure/types/manage/CONTENT\_TYPE/fields
5. Add a new field called, say, "Color", and, set its "field type" to "term reference". Select an appropriate widget, such as "select list".
6. Go to /admin/structure/types/manage/CONTENT\_TYPE/display and set the field's display to, say, "link". You can try different display options, such as "plain text" too.

Hope that helps.

Appendix:

To create a node and save this field programmatically, follow this example, which has instructions for saving term reference fields.
> 0 votes

---
Tags: entities
---


# Question
Title: Which hook to use to reorder multi-value field values before saving content
I have a multi-value field added to my content type. It is actually a field collection.

The users can add unlimited items to this field, and rearrange the items using Drupal's drag-and-drop utility.

However, I want to add some custom logic to the arrangement of field values according to the content.

Which hook should I use, to modify the arrangement of field values before the node saved into the database.

For example, I have the following structure:

```
My Content Type
|
|-- Field Collection Field // unlimited values
    |
    |-- Name // Text field
    |-- Surname // Text field
    |-- Company // Select list

```

Let's say a user created a content with the following values:

* John - Doe - ACME
* Jane - Doe - Ace
* Bob - X - ACME
* Fred - Something - Ace

I want to sort them with a custom logic in a hook, so that they are arranged like that:

* Bob - X - ACME
* John - Doe - ACME
* Fred - Something - Ace
* Jane - Doe - Ace

My question is NOT how to write the logic, BUT which hook to use to modify the arrangements so that I can put my function into it.

# Answer
> 1 votes
I would suggest you hook\_node\_presave to modify node edit form submitted values before saving it into DB.

# Answer
> 0 votes
Attach a custom validate handler for the **element** and make sure it will be called first. Then in your validate function you can change the field weight in `$form_state`.

---
Tags: hooks, entities
---


title: Drush memory exhaustion

text:
# Question
Title: Drush memory exhaustion
hi guys any of you experience having problems regarding memory exhaustion when running a drush command? I made a batch to add taxonomy and do a node\_save after to all nodes (a lots of nodes) i've set the limit on settings.php to 1GB and still no luck, it always throws an error regarding memory exhaustion.

# Answer
> 2 votes
Drush includes a sample php.ini file (there's an online copy here) with instructions on how to override your the php.ini file that Apache uses.

Just copy the contents of the example file into one of the three locations listed in the sample file and save the new file as `php.ini`. I would recommend using either option except for your Drush installation as this will require you to re-create a php.ini every time you update Drush.

Running `drush status` shows you which PHP configuration file it is using in case you're unsure if your changes took effect.

# Answer
> 1 votes
Drush is usually using different php.ini than your Apache, therefore you need to modify your configuration file separately.

To test what is the limit set for drush commands, you may run:

```
drush eval "var_dump(ini_get('memory_limit'));"

```

If you're not happy with your limit, then you may change it either in php.ini

```
$ drush status | grep php.ini
 PHP configuration               :  /etc/path_to_your/php.ini

```

by modifying the right line into (-1 for unlimited):

```
memory_limit = 1G      ; Maximum amount of memory a script may consume (default: 8MB)

```

or by setting the limit in drushrc.php (e.g. sites/all/drush/drushrc.php) or in settings.php by adding the following line to the end of the file:

```
ini_set('memory_limit', '1G');

```

---
Tags: drush
---


# Question
Title: How can I check the fields I've created?
I've got a basic question - in Drupal 7 is there a way to simply manage the fields you've created through some sort of UI that is not admin/structure/types/manage/NODE\_TYPE/fields?

I'm getting an error:

```
FieldException: Cannot change an existing field's type. in field_update_field() (line 234 of /var/www/vhosts/server_path/modules/field/field.crud.inc).

```

I'm trying to track down why this error is occurring and so far I've had no luck. I've checked some stuff on drupal.org, but I've not been able to find anything definitive to clear this up.

And help would be greatly appreciated.

# Answer
> 1 votes
You can activate "Field UI" module in your modules list.

# Answer
> 0 votes
The error is happening because you have content with field values of that field. You could create a view that shows you what content is using the field and then go and either delete that content or the field value from the content.

---
Tags: 7
---


title: ALL input doesn't work

text:
# Question
Title: ALL input doesn't work
I installed Drupal on my VPS, but it seems that all input on website doesn't work from web interface. What I mean by that:

* I cannot login by using web interface
* I CAN login by using one-time login link generated by Drush, but then strange things happen, I guess consequences of not working input - like Admin Menu disappears after refresh, and editing any content is impossible, after sending change - the edit page simply refresh with old values,
* I have Redmine installed on this server and it works ok, so it seems to be Drupal specific.
* The problem doesn't exist with "?q=/user/login" - it exists only with rewritten links. I'm pretty sure I have unmodified .htaccess.
* The problem exists when I remove from .htaccess everything, with the exception of: `ErrorDocument 404 /index.php` and `RewriteEngine on` (which is bare minimum for rewriting to work it seems).
* There are absolutely **no errors** in logs of Drupal, Apache and MySQL.

My Virtual Host: http://pastebin.com/R5hRQMWc

My .htaccess: http://pastebin.com/xM5Kj1yd

System: Ubuntu 14.04, Apache 2.4.7, PHP 5.5.9-1ubuntu4.2 , mysql Ver 14.14 Distrib 5.5.37

Any ideas what is going on and why only Drupal is affected?

# Answer
Maybe Apache server doesn't include "mod\_rewrite".

Try do below code in the console:

```
sudo a2enmod rewrite
sudo service apache2 reload

```

I think this help to you!
> 1 votes

# Answer
1. Check that mod\_rewrite is enabled by going to ?q=admin/reports/status/php and searching for mod\_rewrite. If it isn't in the list of "loaded modules", ssh into your server and do "sudo a2enmod rewrite", and then "sudo service apache2 restart".
2. If that didn't help, go to /etc/apache2/sites-available and locate and edit the .conf file for your site. using, say "vi FILENAME.conf". Make sure it contains something like:

`<Directory /path/to/drupal>
AllowOverride All
 Order allow,deny
 allow from all
</Directory>`

If you change the .conf file, you'll have to restart apache again, to make it take effect.
> 1 votes

---
Tags: 7, uri
---


# Question
Title: Dynamically creating menu links from a node's fields
I have to first, create a menu-like block based on the information in a content type. Below every link, there is a text area field from a content type (*Conference*) except for upcoming conferences and archived conferences. So basically, each link in the menu is a view that shows only one particular field from a node. I pretty much got that part down.

Next I needed the ability for these menus to be dynamically created whenever I created a piece of content. So the 8th annual conference should have a menu created due to the fields in the *Conference* content type being populated.

Does anyone know an approach to dynamically create these menus links when a node is added? The approach I took so far was trying to add arguments that could be used in the view based on the node ID.

# Answer
You can do it with Field Group module and also use Display Suite which gives lot of options to display your content. Check out the image, it was created using field group.
> 0 votes

# Answer
Though this may not be the best practice, I wound up creating views that had exposed filters using the node ID. From there I just added the field I wanted visible then overrode the output link to include the exposed filter.
> 0 votes

---
Tags: views, nodes
---


title: Add blur effect to images in drupal 7?

text:
# Question
Title: Add blur effect to images in drupal 7?
basically I want to add the ability to add a blur effect style to the image styles in Drupal 7.

I tried the imageCache custom action module but I am not able to add own php code since saving any code causes an error. Ive read that people guess the module itself seems to be buggy.

Is there any way I can add my own effect, a function like those listed in image.inc and add that effect to the dropdown?

EDIT:

thanks to the help of Clive I've actually managed to add a blur effect - wicked! :)

Here's the code:

```
function image_blur_image_effect_info() {

    return array(
        'image_blur' => array(
            'label' => t('Gaussian Blur'),
            'help' => t('Gaussian blur the image by a given amount.'),
            'effect callback' => 'image_blur_gaussian_blur'
        )
    );
}

function image_blur_gaussian_blur(stdClass $image) {
    $amount = 30;

    for ($i = 0; $i < $amount; $i++) {
        imagefilter($image->resource, IMG_FILTER_GAUSSIAN_BLUR);
    }

    return imagefilter($image->resource, IMG_FILTER_GAUSSIAN_BLUR);
}

```

I just wondered whether this could be done nicer somehow?

Next question: Is it possible to add an input field once the effect is selected sothat the user can type a custom amount of blurriness?

Like so:

```
function image_blur_gaussian_blur(stdClass $image, $CUSTOMAMOUNT) {
    $amount = $CUSTOMAMOUNT;

    for ($i = 0; $i < $amount; $i++) {
        imagefilter($image->resource, IMG_FILTER_GAUSSIAN_BLUR);
    }

    return imagefilter($image->resource, IMG_FILTER_GAUSSIAN_BLUR);
}

```

# Answer
Sure, you'll need to write a custom module and implement `hook_image_effect_info()` to register your effect with the system, e.g.:

```
function MYMODULE_image_effect_info() {
  return array(
    'mymodule_blur' => array(
      'label' => t('Blur'),
      'help' => t('Blur an image.'),
      'effect callback' => 'mymodule_blur_effect',
    )
  );
}

```

Then implement your callback function (`mymodule_blur_effect()`) to manipulate the image. Try following the function trail from `image_resize()` to get some inspiration on exactly how to access the image stream data.
> 4 votes

# Answer
There are a couple of modules that are probably worth experimenting with: FiltersIE and Image effect kit.
> 0 votes

---
Tags: media
---


# Question
Title: Drupal, how to display only specific content
I'm on Drupal 7, I have a menu like :

* HOME
* NEWS
* BLOG

For now, when I click on HOME, i can see all contents.

I want, when I click on NEWS, redirect the user to /news and only display contents of type NEWS. I want exactly the same for BLOG

I have no idea how can I do that.

Thanks !

# Answer
If you have used Blog modules to create you blog content type, you would be able to use the default View from blog.

Otherwise you can create your own view and add Filter Criteria: Type. You can do this using the module Views You can give the path blog to the view.

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

# Answer
You can install and use Views module.

It will allow you to **create a page** (and define the path, for example "*/blog*" or "*/news*") on which you can display **a list of specific content-type**. You can also tell **which fields** you want to display in that list (maybe you don't want to display all your content-type's fields). You can rearrange it as you want, etc.

If it seems good for you, here is an example for you to create your NEWS page:

> Delete all menu items you've created because it will be **created automatically**!
>
> **Install** Views and **activate** it.
>
> Go to **Admin\>Structure\>Views** and "**Add new View**".
>
> Set your View name as "**News**".
>
> Set "Display **CONTENT** of type **NEWS**" and maybe set a **sorting** rule if it pleases you.
>
> Check "**Create a page**" and give it a name, like "**news**", and a path, like "**yoursite/news**".
>
> Choose a display format, like "**Unformatted list**", which I think will suit perfectly for a list of news. If your news contents are long, maybe choose to display only "**teasers**" or "titles" previews. The users could access the entire content by clicking on the titles if they want to.
>
> Choose to display comments links or not.
>
> Set the **number of news** you want to display per page (there will be a pager system if you let "**Use a pager**" checked).
>
> Check "**Create a menu link**" and choose in which menu you want to display it (maybe "Main Menu"?).
>
> Don't check "Create a block" for now. You only want a **page** initially.
>
> **Save & exit** for now, and check the result by clicking on your new menu item "**NEWS**".

That's how you create **a very basic View** of content-type. You can do a lot of configuration after that in your View panel but it could be very specific and complex so I suggest you to read the documentation and find by yourself.

*Please excuse me if my answer sounds child but I understand that you're still pretty new to Drupal and I just wanted to help "step by step".*
> 2 votes

---
Tags: views
---


# Question
Title: What should I name my overriding render-function?
I'm just starting out with drupal and need some custom html for an intricate menu system. My plan is to override the html-generating functions in template.php.

My theme name is "Drupal subtheme" and the navbar I would like to target has the machine name "menu-usm-navbar-small". What should I name the functions that overrides the default html-printouts?

I think I have tried every possible combination of these. Some examples of what I've tried:

```
function drupal_subtheme_menu_link($variables) {
    return "foo";
}

function drupal_subtheme__menu_usm_navbar_small($variables) {
    return "foo";
}

```

# Answer
It depends on what you want to target.

If it's the tree of the menu you can use theme\_menu\_tree :

```
function drupal_subtheme_menu_tree__menu__menu_usm_navbar_small($variables) {
   return '<ul class="menu">' . $variables['tree'] . '</ul>';
}

```

if it's the link, you can use theme\_menu\_link :

```
function drupal_subtheme_menu_link__menu__menu_usm_navbar_small($variables) {
   $element = $variables['element'];
   $sub_menu = '';

   if ($element['#below']) {
     $sub_menu = drupal_render($element['#below']);
   }
   $output = l($element['#title'], $element['#href'], $element['#localized_options']);
   return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

These functions need to be in template.php
> 0 votes

---
Tags: routes, theming
---


title: user/ content management/ membership

text:
# Question
Title: user/ content management/ membership
I am just researching something for a client and membership functionality

Rather than allowing visitors/ unregistered users the ability to see a teaser and then full access to content if they register we would like visitors to see say 3 articles and when they click on the 4th they then have to register.

SO rather than restricting content by type or category the restriction is quantity before you have to register.

Does anyone know of any modules which deal with this type of functionality?

Thanks in advance

# Answer
You'll need to install the ACL and Content Access modules as well as uc\_node\_access.

Every site is different, but the general workflow goes something like this:

Create a new content type, and use the content access features to make nodes of this content type inaccessible to users by default Create your 'paid content' node using the new content type. These nodes will not be viewable by site users by default. Create a node of type 'product' (an ubercart node type). Users who purchase this product will gain access to the 'paid content' node. Add a feature to the product node of type 'node\_access' (Edit the product node, click the features tab, and add a node\_access feature). Here's where you specify the node that purchasers of this product will gain access to. Repeat steps 2 thru 4 for each node that you want to offer for purchase. If you've done everything correctly, then users who purchase the product node will gain access to the corresponding 'paid-access' node.

I've used the D6 version of uc\_node\_access on a few sites, and it works flawlessly for me. Can't speak for the D7 version of uc\_node\_access, but I'm guessing it works equally well. Takes a bit of setup, but it does work.

For track anonymous viewing the only thing I know is use the browser's cookies, but that method will only work in the actual session if the user do not registers and clear his browser's caches then he can see 3 nodes again, I think you should look for alwasy force the user to register, or show only a teaser of the nodes for anonymous and force them to register for see the full node, then you can only let registered users see 3 nodes, then they have to pay, that way is possible and better. Its just a suggestion
> 0 votes

# Answer
If you have `n` number of nodes and you want the anonymous user to able to see **any** three nodes out of these, then that is not possible, though you can use IP details or Cookies to track, it is not reliable, the user can always find a way to see other nodes too.

**Simply, it is not possible to keep track of anonymous user.**

Rather you can make three nodes to be publicly visible using node access settings, and remaining nodes to be seen only by authenticated persons. But all anonymous users can see the same three nodes.

**Update** : I am not aware of any modules which can provide this functionality, but you can write a custom module and restrict the user based on IP details or Cookie, though the user can easily find a way to see other nodes.

Write a custom module, create a schema with two columns IP address, count.

Implement `hook_node_view()` and check `$view_mode=='full'` and insert/update record to your custom table.

Implement `hook_node_access()`, query your custom table to see the count for this IP, If the count is three then deny access.

Similarly you can use cookies instead of custom table, or you can use both cookies & custom table.
> 0 votes

---
Tags: users, nodes
---


# Question
Title: How can I include a dropdown in menu_local_tasks tabs?
I am trying to include a Bootstrap style dropdown in the local\_tasks tabs on a section of my website. I thought I might be able to accomplish this with the 'theme callback' option of 'HOOK\_MENU', but it doesn't run the custom callback. Any ideas on a good way to accomplish this?

Menu:

```
    $items['module/submenu/tab'] = array(
    'title' => 'Title',
    'page callback' => 'mymodule_menu_callback',
    'access arguments' => array('access content'),
    'theme callback' => 'mymodule_menu_local_task_dropdown',
    'type' => MENU_LOCAL_TASK,
);

```

Callback:

```
function mymodule_menu_local_task_dropdown($variables) {
 $link = $variables['element']['#link'];
 $link_text = $link['title'];
 $classes = array();

 if (!empty($variables['element']['#active'])) {
 // Add text to indicate active tab for non-visual users.
 $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';

 // If the link does not contain HTML already, check_plain() it now.
 // After we set 'html'=TRUE the link will not be sanitized by l().
 if (empty($link['localized_options']['html'])) {
  $link['title'] = check_plain($link['title']);
 }
 $link['localized_options']['html'] = TRUE;
 $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));

 $classes[] = 'active';
}

$classes[] = 'dropdown';

//haven't written this part yet
$dropdown = 'build dropdown';

return '<li class="' . implode(' ', $classes) . '">' . l($link_text, $link['href'], $link['localized_options']) . $dropdown . "</li>\n";
}

```

What I'm looking for:

# Answer
For the drop-down menu you need include drop-down JavaScript in the "page callback". See drupal\_add\_library() function.

And I recommend for you pay attention to "CTools module".

"Drop-Down Menu" Code from CTools module:

```
  // Show examples of ctools javascript widgets
  $output .= '<h2>' . t('CTools Javascript Widgets') . '</h2>';

  // Create a drop down menu
  $links = array();
  $links[] = array(
    'title' => t('Link 1'),
    'href' => $_GET['q'],
  );
  $links[] = array(
    'title' => t('Link 2'),
    'href' => $_GET['q'],
  );
  $links[] = array(
    'title' => t('Link 3'),
    'href' => $_GET['q'],
  );

  $output .= '<h3>' . t('Drop Down Menu') . '</h3>';
  $output .= theme('ctools_dropdown', array('title' => t('Click to Drop Down'), 'links' => $links));

```
> 0 votes

# Answer
I have figured out a way to do it for now, but doesn't seem like a great solution and adds two calls to every tab rendered. Since I wasn't able to get the custom callback to work, I overrode theme\_menu\_local\_task with some ideas from https://stackoverflow.com/questions/2716787/how-to-get-all-the-menu-items-below-a-certain-parent-in-drupal. Basically I test the path for children and output the dropdown if they exist.

```
    function mymodule_menu_local_task($variables) {

    $link = $variables['element']['#link'];
    $link_text = $link['title'];
    $classes = array();

    if (!empty($variables['element']['#active'])) {
        // Add text to indicate active tab for non-visual users.
        $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';

        // If the link does not contain HTML already, check_plain() it now.
        // After we set 'html'=TRUE the link will not be sanitized by l().
        if (empty($link['localized_options']['html'])) {
            $link['title'] = check_plain($link['title']);
        }
        $link['localized_options']['html'] = TRUE;
        $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));

        $classes[] = 'active';
    }

    //check to see if menu item has children
    $parent = menu_link_get_preferred($variables['element']['#link']['path']);
    $parameters = array(
        'active_trail' => array($parent['plid']),
        'only_active_trail' => FALSE,
        'min_depth' => $parent['depth']+1,
        'max_depth' => $parent['depth']+1,
        'conditions' => array('plid' => $parent['mlid']),
    );
    $children = menu_build_tree($parent['menu_name'], $parameters);

    //if item has children, output as a dropdown
    if (!empty($children)) {
        $classes[] = 'download';
        $link['localized_options']['html'] = TRUE;
        $link['localized_options']['attributes']['data-toggle'] = 'dropdown';
        $link['localized_options']['attributes']['class'] = 'dropdown-toggle';
        $dropdown = '';
        foreach ($children as $item) {
            $dropdown .= '<li>'. l($item['link']['link_title'], $item['link']['link_path']) .'</li>';
        }
        $dropdown = '<ul class="dropdown-menu" role="menu">'. $dropdown .'</ul>';
        return '<li class="' . implode(' ', $classes) . '">' . l($link_text.'<span class="caret"></span>', $link['href'], $link['localized_options']) . $dropdown . "</li>\n";
    } else {
        return '<li class="' . implode(' ', $classes) . '">' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";
    }
}

```
> 0 votes

---
Tags: 7, routes
---


title: help users to populate fields

text:
# Question
Title: help users to populate fields
I am making a drupal 7 site and one of the content type has multiple fields, I was wondering if there was a way to assist my users in editing the pages. I looked at the edit function but could not get the fields links to display.

Any alternative suggestions would be great, even something were I can add a graphic to the edit page showing the layout of the page.

Thanks,

# Answer
> 1 votes
I think Panelizer is what you are looking for

Here a very useful webinar https://www.youtube.com/watch?v=vy6fnsawNjE where you will understand what is Panelizer and all its features, also there is quite documentation in the web about this module.

If i missunderstood the question let me know, I will update it if that is the case

---
Tags: users, entities, navigation
---


# Question
Title: How to call a custom function when Migration(Import) is done?
I am using migration to import nodes from a csv. I want to change the file name when import is done. How can I call a custom function when Import/Migration is done from a specific file to change its name?

I knwo about the postimpot but I am looping thorugh directories to import data from each csv file in each directory. So postimport is called every time a file has been imported. But in posImport I cant use argument to change the last imported file name only.

# Answer
> 0 votes
use a static variable in postimport to do a check that you're on the last folder or task or the import, there has to be some value you can track. You could even set a variable of all the csv files to do (in-order) within your migration class -- and check which file you're on in postimport.

---
Tags: 7, migrations
---


# Question
Title: Loop trough a list of referenced nodes in order to get a specific field value
I am using Computed Field to get some values;

I have a Template node that holds an Entity Reference multivalues field to a series of other nodes, all referenced nodes of the same type. The referenced nodes have a text field which value I need to get.

Until now I've managed to get the "target\_id" of the referenced nodes, but I can't manage to get the values:

```
$tpl = field_get_items($entity_type, $entity, 'field_plan_tpl_select_trainings');
$nids = array();

foreach ($tpl as $field_item) {
            $nids[] = $field_item['target_id'];
}

```

What is the next step in order to get the values of a specific field for all the referenced nodes? I mention that the field has only one value.

# Answer
> 0 votes
the "target\_id" is the nid (node id) of the referenced entity, now if you want to get the values of a specific field of the referenced entities you can do the following:

```
$values = array();

foreach($tpl as $field_item){
$values[] = node_load($field_item['target_id'])->field_your_field;
}

```

you just need to load the entity and then get the field you are looking for. Devel module will make your life easier in that purpose

If the entity you are referencing is not a "node" so you can load the entity using entity\_load() and then use entity\_metadata\_wrapper() for get the fields and all the info you need from each entity.

---
Tags: entities
---


title: Getting '#default_value' from $form

text:
# Question
Title: Getting '#default_value' from $form
I have this code:

```
$form['custom'] = array(
'#title' => t('Some title'),
'#type' => 'select',
'#options' => $custom,
'#default_value' => isset($option->name) ? $option->name_id : '',
'#description' => t('Some text goes here.'),

```

Now when i do print\_r i get data from option and the name\_id of the selected one. No how can i get this data (name\_id) from "#default\_value" ??

In submit function i have this:

```
$custom=$form_state['values']['custom'];

```

But this only gets me the name not the name\_id .

# Answer
> 2 votes
You can get it from the form itself:

```
$custom = $form['custom']['#default_value'];

```

---
Tags: forms
---


# Question
Title: Drupal 7 : Programmatically validate form by form ID
Intro - i am trying to implement Sales Force form within Drupal FAPI but now it requires to add captcha so i need to send first request to internal page so i could validate captcha and only after this i can redrect user to Sales Force.

So I want to do such thing :

1. i have page /contacts and usual form coming from my module that was created within FAPI
2. the form has some standard validators
3. when it is submitted to the same page where the form is, e.g. /contacts, the validation works fine i can get the errors, but i want to send first POST request to e.g. /forms URL and validate it there, but /forms knows nothing about the form and thus validation is not called

**The question is :**

Basically, i need to validate form separately without rendering it on a new page. Can i do something like this :

```
drupal_get_form($formId)->validate() ?

```

**Update #1 :**

I am already using Captcha module but Sales Force usually is implemented this way - there should be a form on my site with the fields which SF is aware of, when this form is submitted to SF page (external site) SF gathers needed data from the POST request and redirect user back to my site ... but in this case there will no be any validation because right after submit user will be redirected to SF site, Drupal will not process such requests.

Now i really need this validation before submit so i created new page (internal) and want to trigger validation on this page but the issue is that form is located on the page "Contacts" and i am trying to send and validate data to the empty page "Forms".

If i simply send POST to Contacts (where the form is) then validation works fine, Forms does not trigger validation at all.

And as i already said i have form array that describes all fields and validators for them, then i render this array as a form on a Contacts page so i cannot understand why do i need to add hook\_form\_alter and create some extra validation function on a Forms page if i already described all validation rules on Contacts page?

**Update #2 :**

Seems that i already got the answer from Wolwerine, i would like to explain why i so willfully wanted to have initial form on a Contacts page and validate it on a Forms page.

I have Parallax site, i.e. single-page-application, which means that eveything in this application should be done without page reloading including those two requests for the issuing form :

* validation request
* final request to Sales Force after validation

As a result all requests are done within AJAX.

Page Contacts contains main layout and HTML form and any request to this page will return me tons of HTML which i will not be able to analyze in JS and understand whether this request and validation were successful or not.

Of course i can parse these HTML results and try to find some validation errors in this HTML but IMO this is not the case.

So i created separate page that does not include main layout and neither content, i.e. some kind of page that will work only with AJAX request and return exact type of response that i can get in this case HTML, JSON and so on without messing them up.

Thanks, i appreciate your help and upvoted all answers that look helpful.

P.S. This is how i do validation on a Forms page now :

```
<?php

$data = $_POST;
$form = drupal_get_form($data['form_id']);
$errors = form_get_errors();

if ($errors) {
    print json_encode(array('errors' => $errors));
    die();
}

$c = curl_init();
curl_setopt($c, CURLOPT_URL, $data['destination']);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, $data);
curl_setopt($c, CURLOPT_HEADER, 0);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($c);
curl_close($c);

```

# Answer
> 1 votes
Calling `drupal_get_form()` itself will process your form, i.e. validate & submit, but for that your `$_POST` should contain the **form\_id** and other data.

# Answer
> 2 votes
You can add an extra validation function using hook\_form\_alter.

If all you need is to add a captcha to the contact form you could try simply using the captcha module, or the mollom module.

If you've created the form yourself using a form builder function, you can add a validation function (with all your validators) to that:

```
function YOURMODULE_YOURFORM_form_validate($form, &$form_state) {
// Your validation code.

}

```

---
Tags: forms
---


# Question
Title: How to keep <font> or <style> tags from getting in WYSIWYG editor with ckeditor?
Seems simple, but I haven't been able to find any way to do it.

To be clear, I want ALL other tags for this text format, just not font or style tags.

Thanks.

# Answer
> 1 votes
Use a text filter (format) that allows all tags you want and doesn't allow font and style tags. I also recommend removing toolbar buttons that add these tags, such as font, font color, font size etc. You could add custom styles that add CSS selectors rather than inline style tags.

# Answer
> 0 votes
There is a long thread discussing this problem here: http://dev.ckeditor.com/ticket/9998 \- CKEditor is working on a fix for it even though it appears to be a browser bug.

A temporary workaround you might try is here: http://ckeditor.com/forums/CKEditor/ckeditor-4.01-inserting-span-elements-everywhere-with-a-line-height-of-1.6em

Nutshell: search for and remove/edit the following line from the CKEditor CSS: .cke\_editable { font-size: 13px; line-height: 1.6em; }

I have not fully tested it, but so far it appears to be working.

---
Tags: wysiwyg
---


# Question
Title: Trivial Example of a Module that Creates a Content Type
I want to write a module that creates a content type with a title and one or more textfields. I'm having a very hard time simplifying the roles of each hook function call in the documentation of the node\_examples module.

Right now I'm trying to figure out what the next function should be and what it will do with the form data. So far I've gotten the content type and the forms to show up in the add content section of my site but when I save the "votable" content none of the form data is stored, just a blank piece of content with content type "votable". Could someone point me towards the next step?

```
function votable_form($node, &$form_state) {
    $type = node_type_get_type($node);
    $form = array();
    $form['votable_title'] = array(
        '#type' => 'textfield',
        '#title' => check_plain($type->title_label),
        '#default_value' => !empty($node->title) ? $node->title : '',
        '#required' => TRUE,
        '#weight' => -5,
    );

    $form['votable_results'] = array(
        '#type' => 'textarea',
        '#title' => t('Results'),
    );

    return $form;
}

 function votable_node_info() {
    return array(
        'votable' => array(
            'name' => t('Contestant'),
            'base' => 'votable',
            'module' => 'votable',
            'description' => t("Select this content type to create a Contestent Page"),
            'help' => 'add content',
            'title_label' => t('Contestant Name'),
            'has_body' => FALSE,
        ),
    );
 }

```

# Answer
> 1 votes
Flex Slider creates a content type for a slider image and a view to make the slider itself, so you could look at that for an example module.

---
Tags: 7, nodes
---


# Question
Title: Can I have a body apply to a different page than the current content type?
I want to give the editor user a good experience where he/she can edit everything about one news article in one content type. I have a gallery that takes a content type where he/she can place an image, caption, and a link. I desire this link to be pointing to the page where the body wysiwyg would be. I would like the body to be in the same content type, just displayed on a different page. I hope I am clear. Thanks for your help!

# Answer
I'm not totally clear on what you are asking, but I will try to help anyway (and maybe with more clarification I can help further)).

It sounds like you have a gallery content type. Do you need these gallery images for anything else? Because it also sounds like you want an image to show up on the news article page. If that is the case, why not just have fields for the images, caption, and link in the news article content type? That way, when the person goes to edit the news article, everything is write there - both the fields related to the news article itself as well as the fields related to the gallery ones. I feel like this would make more sense to the person editing it anyway.

And then if you still need a separate gallery or something using the images that have been added, you can still use the images in the news article content type to make a separate view.
> 0 votes

---
Tags: views, nodes, wysiwyg
---


# Question
Title: display nodes of types on a menu item : drupal 7
I have created some nodes of type books and now I want to display some of them on a menu item. How can I do that without using views?

Mome | Books | Atricles |

node type: (Machine name: books)

For example above is my menu structure. And when a user click books it will show some of the books I have created.

# Answer
> 0 votes
Is it just the book name? Like a list of the names and then you can click on it and view more information? In that case, you could just put those book links in the menu itself (if you have a drop-down).

Otherwise, and the more doable option is to just use Views and have it create a page that displays the names of all of the books you've entered.

Is there a reason why you are opposed to using Views to do this?

---
Tags: nodes
---


# Question
Title: How to set up a train schedule content type in Drupal 7?
I'm trying to set up a site in Drupal 7 to list train schedules.

My concept is this: create a content type to manage each train. I'm setting up each train like an airplane flight. Each train leaves station A at a certain time, stops at a few other stations and ends at station X.

The content type needs to be able to handle which stations it will stop at (Taxonomy terms since values will be re-used) & what time it will stop at each station.

As I said, the station names can be Taxonomy terms but I'm having trouble with the times. While station names can be re-used, times each train stops at each station will vary.

Is there a module that will allow me to select a taxonomy term (individual station) and then allow an additional field to be edited on-the-fly to input a time?

I'm also open to alternative suggestions for setting this up. Thanks!

# Answer
This post is pretty old at this point, so it may no longer be an issue for you, but I'll try to answer it anyway.

The type of solution I'm imagining for this is what the Double Field module sounds like it does (though I cannot be certain since I have never used it). *If* this module would be able to do it, you'd want a field with taxonomy with a Date field to select the stop and time of that stop (and then be able to have multiple values for this field so you can select multiple stops and their times).

Otherwise, you *could* use Taxonomy if the trains have set times that they arrive (like they always arrive on the hour, quarter after, etc.). Otherwise, yeah, it wouldn't be realistic to use that if they can arrive at 12:53, 3:38 - if any time is possible.
> 0 votes

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


# Question
Title: In Rules, how can I use a set the value of a taxonomy term reference field to multiple values?
How can I set a taxonomy term reference field to two values using Rules? The "Number of values" for the field is already set to two.

I set up a workflow in rules that works for setting a single value. I tested this several times and encountered no problems. However, when I changed the "Number of values" for the field from "1" to "2" and then edited the action to add two terms instead of just one, I got the following error message:

> * Warning: Missing argument 2 for taxonomy\_options\_list() in taxonomy\_options\_list() (line 1375 of /srv/bindings/e87a1e62cfd24fea9dd67cfd074d146c/code/modules/taxonomy/taxonomy.module).
> * Warning: Missing argument 3 for taxonomy\_options\_list() in taxonomy\_options\_list() (line 1375 of /srv/bindings/e87a1e62cfd24fea9dd67cfd074d146c/code/modules/taxonomy/taxonomy.module).
> * Warning: Missing argument 4 for taxonomy\_options\_list() in taxonomy\_options\_list() (line 1375 of /srv/bindings/e87a1e62cfd24fea9dd67cfd074d146c/code/modules/taxonomy/taxonomy.module).

When I attempt to set a value by triggering the rule, it fails and the rules debug log has the following output:

> * 3.235 ms Unable to get a data value. Error: Invalid data value given. Be sure it matches the required data type and format.
> * 4.254 ms Unable to evaluate action data\_set.

What is the correct way to assign two terms at once to a single taxonomy term reference field?

# Answer
> 2 votes
As it turns out, this is actually fairly easy to do in Rules. By updating to the latest version of the Entity API (rc3-- I was stuck on rc1 due to a different bug that I resolved earlier today) with Rules 2.1, I was able to do this in the following way:

1. Choose the action "Set a data value".
2. Choose the taxonomy term reference field to set.
3. Control-click to select the taxonomy terms to add.

That's all there is to it, but there is one potential gotcha: these values didn't always save correctly for me. This may be because I opened multiple tabs in Firefox and tried to save many different rules at once; for whatever reason, sometimes only one of the two values got saved. I fixed this by simply checking all the values again manually and re-saving them until the values stuck.

# Answer
> 1 votes
Elaborating on @Patrick Kenny's step #3.

You may need to click the button "Switch to the direct input mode" button to reveal the terms available in your taxonomy field.

---
Tags: taxonomy-terms, rules
---


# Question
Title: Generating a random number without duplicates on blog comment
A section of my site is a blog where I allow comments. Each comment has a thumbnail associated with it. If the commenter is a user, then their profile photo is used. If they are anonymous I have a pre-determined photo in place. I want to be able to randomly generate a thumbnail for these anonymous users, but also have no duplicates.

I asked this question here and now have a random thumbnail being generated, but the problem is that there are still duplicates. And it looks like because the comment.tpl.php file is being read on each comment that the random numbers are not being remembered.

How can Drupal remember the number so that it doesn't use it again?

My Code:

```
$numbers = range(0, 19);
shuffle($numbers);

print "<div id='commenter-picture'>";
print "<img src='member_default_" . array_pop($numbers) . ".png' />";
print "</div>";

```

# Answer
> -1 votes
Haven't tested this, but I think this should work. Remove your first two lines of code and place the following in your theme's `template.php` file (replace MYTHEME with the machine name of your theme):

`function MYTHEME_preprocess_comment(&$vars){
 $max = 19;
 $numbers = $_SESSION['MYTHEME_comment_numbers'] ?: range(0, $max);
 shuffle($numbers);
 $vars['number'] = array_pop($numbers);
 $_SESSION['MYTHEME_comment_numbers'] = count($numbers) ? $numbers : range(0, $max);
}`

This makes available a $number variable inside your comment.tpl.php file.

Then, replace your last three lines inside comment.tpl.php with:

```
print "<div id='commenter-picture'>";
print "<img src='member_default_" . $number . ".png' />";
print "</div>";

```

This will remove already used numbers from your $numbers array until there's none left, and then reset to use the full array again.

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


title: Dynamic Block View

text:
# Question
Title: Dynamic Block View
I'm trying to create a **Block View** to display a second node's **Body** based dynamically on the node currently being displayed.

Example: node/1 is currently being displayed, and the block in the sidebar loads the body (Contact information for example) of a secondary node, say node/12. But if node/2 is being displayed, the block will instead load the Body of an entirely different node.

Can I create an integer field in the Content Type that identifies the secondary, "Contact Block", node to display, and how would I create the View to use this field? Or do I need to create a relationship, and if so, which Content Type needs the relationship, the primary node, or the secondary node?

# Answer
> 0 votes
EntityReference was what I was looking for and I found a good walkthrough here: http://www.wunderkraut.com/blog/overview-of-entity-reference/2011-10-11

---
Tags: 7, views
---


title: Drush 5.9 - unable to untar

text:
# Question
Title: Drush 5.9 - unable to untar
Using the command:

```
 drush arr ~/drush-backups/site.tar.gz --db-url=mysql://df_database:password@localhost/df_databaseuser --destination=~/domains/site.kz/public_html/temp

```

(archive size is ~5gb),

I get this error:

```
 Unable to untar /home/user/drush-backups/site.tar.gz.                [error]
 Unable to extract site archive tarball to                            [error]
 /tmp/drush_tmp_1384866055_528b6107d88d6.

```

Why does it happen? However, when I try to untar archive lower than 1gb I'm not getting any errors.

# Answer
> 4 votes
By default the command **drush archive-restore** creates a unique temporary folder under **/tmp** (\*/tmp/drush\_tmp\_1394487346\_531e303223...\*) where it will extract the archived tarball content, and later will move the $doc\_root into the $destination - with the option **overwrite**.

I guess your **/tmp** folder resides on a separate partition, ~4GB in size; restoring a 3GB archive worked well, but it fails for 5BG. It looks like **drush archive-restore** works only when the system's temp folder is large enough to accommodate the extracted tarball.

PS. **drush archive-restore** is defined in `archive.drush.inc` :

```
function "drush_archive_restore" (drush_tarball_extract($file, $tmp)), where $tmp = drush_tempdir();

```

`Funtion drush_tempdir()` is defined in filesystem.inc - creates a unique temporary directory and returns its path. `drush_tempdir()` uses `drush_find_tmp()` which more likely returns `/tmp`

# Answer
> 0 votes
I got this **exact** error when I tried the following from a script:

```
drush arr ${DUMP_DIR}/`ls ./ | grep *.tar.gz` --destination=/home/foo/bar

```

with a single .tar.gz file in the directory. It turns out my filename was like: \`some-file-MM-DD-YY-HH:MM:SS.tar.gz

in this case the `:` (colons) are not escaped by my shellscript and I get that generic extract error. Renaming my dump file to something simple like `dump.tar.gz` allows the drush command to complete.

---
Tags: drush
---


title: Send email with custom tokens on event?

text:
# Question
Title: Send email with custom tokens on event?
I am trying to make a rule which when acted upon will send an email with custom details based on the rule arguments.

I made my rule event and that's all working fine it shows up, but when I add an action to "`Send mail`" and then look at all of the `Replacement patterns` non of my tokens show up, only site-information tokens show up.

Token Functions

```
/**
 * Implementation of hook_token_list()
 */
function mahjong_token_list($type = 'all') {
  if ($type == 'all' || $type == 'mahjong') {
    $tokens['mahjong'] = array(
      'package_name' => t('The name of the package'),
    );
  }

  return $tokens;
}

/**
 * Implementation of hook token api
 */
function mahjong_token_values($type, $object = NULL, $options = array()) {
  $tokens = array();
  var_dump($object);
  if ($object) {
    if ($type == 'mahjong') {
      $tokens = array(
        'user_name' => $object->name,
        'user_email' => $object->email,
        'user_score' => $object->score,
      );
    }
  }

  return $tokens;
}

```

Rules Function

```
function mahjong_rules_event_info() {
  return array(
    'mahjong_won' => array(
      'label' => t('A person won the mahjong game.'),
      'module' => 'mahjong',
      'group' => 'Rules',
      'arguments' => array(
        'user' => array('type' => 'mahjong', 'label' => t('The user who won the mahjong game.')),
      ),
    ),
  );
}

```

What am I doing wrong? How can I get the data from the rules argument pass to the action to send an email?

# Answer
> 1 votes
If "mahjong" is just an arbitrary object type, you need to declare it to Rules using hook\_rules\_data\_info and specify the "token type" so that Rules knows what to pass to the token API.

But if the "mahjong" object is a Drupal User entity, you shouldn't need to implement hook\_token\_\* at all.

Instead, when you define your Rules event, the argument should be of type "user". Rules will then know what fields are defined on the entity.

---
Tags: 7, rules, tokens
---


title: Is there a way to delete unused fields?

text:
# Question
Title: Is there a way to delete unused fields?
I created many fields for content type.Now I don't need these fields anymore. I deleted the fields from the content type but the fiels data remains in the database.

How can I delete the field and all its related data?

# Answer
> 0 votes
Sometimes running cron does not entirely delete a field, especially if the field was ever used in a field collection. First, make sure the field isn't used anywhere else. Check all content types, field collections, custom user fields, etc. if the field is really not used but running cron does not delete the field table from the database, you may have to delete it manually. You can do this manually with a SQL query or via phpmyadmin.

---
Tags: entities, nodes, database
---


# Question
Title: Problem with images not displaying because domain is incorrect
I have recently installed a Drupal site on our web server and this is the default host (replaced an old website with static files). This server also hosts another virtual host for another domain name and that installation is WordPress.

On blog posts on the Drupal site (regular pages are fine), images will eventually show broken icons and when you check the URL of the image, it's replacing the domain name for the Drupal site with the domain name for the WordPress site.

Clearing the cache within Drupal immediately fixes everything, and the images reappear and with the correct URL.

An additional oddity is that the images are broken inside our network, but from the outside they will show up even though using the incorrect URL. On the inside, it resolves to the internal IP address and on the outside to the public.

I'm using Apache 2.2.22 with Drupal 7.28.

I realize it could be an Apache issue or DNS issue, but I'm checking all avenues... is there a configuration for the Drupal cache that I should be taking a look at that could be causing this problem?

# Answer
> 1 votes
The first thing you need to do is stare at your Apache access logs for a while and see if you have inbound requests to the wrong URL. You may need to configure per virtual host logfiles to see which vhost is handling which.

You may also want to disable Drupal caching (both page and block) to see if the problem persists.

My ***guess*** is that everything with your Drupal configuration is correct, but that you have inbound requests that Drupal is handling because it is the default site, and these are getting cached.

If the Apache logs indicate that Drupal is getting the wrong URL, then I would do the following:

1. Configure both virtual hosts to respond to the canonical URL, and the redirections. Something like

```
ServerName www.example.com
ServerAlias example.com *.example.com
```

This will make sure the proper vhost is responding to the proper domain (which is ***guess*** is the root cause of your problem, ie you need a `ServerAlias`).

1. Configure httpd.conf or .htaccess to set up canonical URL redirection for both the Wordpress and Drupal sites. Something like

```
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com$1 [L,R=301]
```

These help ensure that Drupal and Wordpress only ever see requests for a single hostname.

These two things make good sense on most live sites, too.

If you still have the wrong URLs and you are 100% positive about the traffic, then my next **guess** would be that you have a misconfigured settings.php somewhere in your organization, and you have two sites / servers running out of the same database (eg, DEV and LIVE are actually using the same database). To fix this, you would need to find the offending site.

---
Tags: media, caching
---


# Question
Title: Template files do not work when in "Templates" directory
I have a custom theme that I have created, that contains a .info file, and various .tpl.php files. The problem is that these templates wont be recognized by Drupal (7). I've tried clearing all of the caches and re-uploading the files with no avail, as well is restoring the database.

This theme works fine on a local server, but whenever the site is migrated to my staging server, the template is not recognized. The theme will show up in the admin interface under the appearance tab however and is enabled as default.

There are no errors in "recent log messages"

# Answer
It turns out there were more .tpl.php files in a different directory that was not obvious, thus overriding the templates I intended to use.
> 0 votes

---
Tags: theming
---


# Question
Title: How to put "Advanced form block" in a twitter bootstrap modal?
I want to add an Advanced Form Block into a modal. So far I've been partially successful, the block is added to the modal but the form is outside the modal markup.

The area marked in red is the form which should be in the **div** with the class `modal-body`. How do I make this work?

# Answer
The problem was that the Advanced Form Block, has a `CSS` class of `.node-form` and this is not encapsulated in the standard block content div `.block-content`. So when the Twitter Bootstrap Modal Block module tries to add the `.modal-body` CSS class to the `.block-contents` div, it will not find the div and the form will be left outside the modal body.

For me the easiest way to solve this was to edit `Twitter Bootstrap Modal Block` JavaScript file, i.e. `sites/all/modules/twitter_bootstrap_modal/twitter_bootstrap_modal_block/twitter_bootstrap/modal_block.js`, as follows:

Change the line that reads

`$(this).children('.block-content').addClass('modal-body'); //line 29`

to

`$(this).children('.block-content, .node-form').wrapAll('<div class="modal-body" />');`

This will put the `advanced from block` into the modal body.
> 1 votes

---
Tags: javascript
---


# Question
Title: How do I pass a string from a PHP field to the PHP filter?
Is there any way to pass a string from php field to php filter?

on the PHP FIELD I can tell if a product has discount or not ( i think because the field formatter render the field\_price in a way that triggers the discount rules) and if there is a discount I can set a variable on/off based on the output of this formatter.

This custom discount variable created with PHP FIELD I need to pass it to the PHP FILTER to control if a product must needs to be shown or not (sorry for my bad English)

**PHP FIELD CODE**

```
<?php

// $var1 will take value 0.00E or -94.99E (the last value is an example)
$var1 = strip_tags($data->field_commerce_price[0][rendered]);

// $var2 will take value 0 or -
$var2 = mb_substr($var1, 0, 1, 'utf-8');

// set $static = 0 or 1, if PHP FILTER can see this then can filter discount products
if ($var2=="-") { $static = "1"; echo "DISCOUNT!"; } else {$static = "0"; }

?>

```

**PHP FILTER CODE**

```
// all 4 variables gives output nothing
dpm($row->_field_data['nid']['entity']->field_commerce_price[0][rendered]);
dpm($data->_field_data['nid']['entity']->field_commerce_price[0][rendered]);
dpm($data->field_commerce_price[0][rendered]);
dpm($static);

if ($static=="1") { return FALSE; } else { return TRUE;}

```

So how PHP field send a string to PHP FILTER??? OR Is there any to create a filter function using the PHP FIELD?

# Answer
You can copy the code from the php field and add some logic to it to return false or true depending on the result but no there is no current way to transfer it.

EDIT: This may seem a bit backwards, though if you made a $\_SESSION variable as an Array() you could maybe do something with that. Maybe not very helpful. views\_php has always been entirely buggy for me and it comes in handy sparingly.
> 1 votes

---
Tags: views, commerce
---


title: AJAX autocomplete

text:
# Question
Title: AJAX autocomplete
I am trying to implement an auto-complete text field:

```
hook_menu()
{
  $items['products/autocomplete'] = array(
    'page callback' => 'json_list_products',
    'access arguments' => array('access products')
  );

  return $items;
}

```

This appears to work but when I access the *products/autocomplete* I see the resulting JSON data but it's embedded in the HTML template?!?! This is going to cause part of my problem

I am generating the form like so:

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

  $form['keyword'] = array(
    '#type' => 'textfield',
    '#description' => 'Enter keywords (ie: Fat free milk)',
    '#autocomplete_path' => 'products/autocomplete'
  );

  return $form;
}

```

And finally the json query function:

```
function json_list_products() {

  $keywords = 'fat free milk';   // TODO: Swap keywords from parameter list from HTML on client

  $items = array();
  foreach(_sql_select_products($keywords) as $product) {
    $items[$product['Product_ID']] = $product['Product_Name'];
  }

  return drupal_json_encode($items);
}

```

Anyway, nothing seems to happen...i've managed to do this before so I am not sure why this isn't working now. Any ideas? json\_list\_products() currently hardcodes the keywords and the results are correct.

Alex

# Answer
> 1 votes
```
function modulename_menu() {
  $items['products/autocomplete'] = array(
  'page callback' => 'json_list_products',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK
  );
 return $items;
}

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

  $form['keyword'] = array(
  '#type' => 'textfield',
  '#description' => 'Enter keywords (ie: Fat free milk)',
  '#autocomplete_path' => 'products/autocomplete'
  );

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

  return $form;
}

function json_list_products($string) {
  $matches = array();

  // DB table which holds products
  $query = db_select('products', 'p');

  // Select rows that match the string
  $return = $query
  ->fields('p', array('product'))
  ->condition('p.product', '%' . db_like($string) . '%', 'LIKE')
  ->range(0, 10)
  ->execute();

  // add matches to $matches
  foreach ($return as $row) {
    $matches[$row->product] = check_plain($row->product);
  }

  drupal_json_output($matches);
}

```

# Answer
> 0 votes
In your hook\_menu you need to set the type to menu\_callback as the default is MENU\_NORMAL\_ITEM.

```
hook_menu()
{
  $items['products/autocomplete'] = array(
    'page callback' => 'json_list_products',
    'access arguments' => array('access products'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

Also, you may want to use the drupal\_json\_output function instead of drupal\_json\_encode in your json\_list\_products function. the drupal\_json\_outpur set the correct header.

Also make sure you have the access products permission set correctly.

Not sure if these things will fix your problem, but it's all I can see.

# Answer
> 0 votes
I try this one. You must try this

```
hook_menu()
    {
     $items['products'] = array(            //say you have a menu
     'page callback' => 'drupal_get_form',
     'page arguments' => array('form_search_products'),
     'access arguments' => array('access products')
      );

      $items['products/autocomplete'] = array(
        'page callback' => 'json_list_products',
        'access arguments' => array('access products')
      );

      return $items;
    }

 function form_search_products($form, &$form_state){

  $form['keyword'] = array(
    '#type' => 'textfield',
    '#description' => 'Enter keywords (ie: Fat free milk)',
    '#autocomplete_path' => 'products/autocomplete'
  );

  return $form;
    }

function json_list_products($enteredstring){

$yourvalue = $enteredstring;

  $result = db_select('products', 'c')
    ->fields('c')
    ->condition('productname','%'.db_like($yourvalue) . '%', 'LIKE')
    ->orderby('productname')
    ->execute();
}

  $items= array();
  foreach ($result as $items) {
   $title=$items->title;
   $items[$title]=$title;
  }
drupal_json_output($items);

  }

```

It works well.

---
Tags: ajax
---


# Question
Title: How to combine different node in single views
I'm currently doing recruitment system by using drupal 7..

First.. In my system, applicant need to fill up the "Applicant Profile" (node) before they can apply for the job.

Second.. i am using flag module..if applicant want to apply the job, they must flag the job..after that, they need to fill up their "name" and make some "pitch" (Flagging form)..

Third.. In my views, i add "flag" at relationship so i can add the flagging form details in the fields.At filter criteria, i add the "content:type (Applicant Profile)"

**My question..**
how i want to combine the details in **flagging form** and **applicant profile** in single views? because currently the views fields only can display the flagging form details..

i already add two different "content:type" at filter criteria. but it does't work..it only show the details on one content type only..
Thank You in advance..

# Answer
> 1 votes
For `Applicant Profile` use Profile 2 module instead of node. Then when you create the `View` of `Job List`, add relation to `Flags`, `Content: Author` and `User:Profile`, in that way you will get all the fields you need.

# Answer
> 0 votes
Click the Filter for Content Type and checkbox the other content type you need.

---
Tags: views, nodes, flags
---


# Question
Title: Construct the src in a javascript tag from node fields
I have a drupal 7 instance where I would like to create nodes that call reports from a separate site using javascript.

Currently I construct the HTML tags myself which look something like this:

```
<script type="text/javascript" src="http://URL.goes.here/JsAPI?reportUUID=[REPORTID]&yfFiltera5d74aca-4396-41c2-9376-d68fd57de81a=[FILTERVALUE]&display=[DISPLAY]&canChangeDisplay=[CANCHANGEVALUE]&showPageLinks=[SHOWPAGESVALUE]&showInfo=[SHOWINFOVALUE]&showFilters=[SHOWFILTERSVALUE]&showSections=[SHOWSECTIONSVALUE]"></script>

```

Note that there are a bunch of parameters in the url shown in square brackets: \[VALUE\]

What I want to do is have a node creation interface for admin users that allows them to set all of the parameter values and constructs that URL, then constructs a string using those parameters and uses it as the node's output when viewed.

I haven't been able to find any kind of module for this, maybe I am describing it wrong - or maybe it's a very rare use-case. Any ideas would be wonderful, even if it's 'hire a developer, this has never been done before'.

# Answer
You can do this in a *node.tpl.php* file in your theme or to be specific to one content type.

Duplicate the default node.tpl.php file found in */modules/node/* and rename it to *node-NODETYPE.tpl.php* NODETYPE being the machine name of the node which you can find at *structure -\> content types*, in the CMS.

Install the devel module and enable it, then do a `dpm($node);` in your copied *node.tpl.php* file to get the variables you need. Of course you would need to have a custom theme so it doesn't get overridden on an update.

To do this in a module you'd need be somewhat familiar with hooks.

And since the *dpm* is called after the output is rendered you need to reload the page twice. Don't forget to clear cache after you add in the *node.tpl.php* to your theme.
> 1 votes

---
Tags: nodes, javascript
---


# Question
Title: Creating multiple views from Entityform Submissions
I would like to create multiple views containing filtered/ordered results from submissions made into forms created using EntityForm.

In the documentation and in question on DA(The Entityform module allows me to create forms that any user can submit and the forms fields are available for me to use in views, similar to how a content type would work. it seems this is possible but I cannot figure out how.

Fields created and submitted in the forms are not listed under "add field" in views, nor in "add relationship".

So the question is:

How is it possible to fully interrogate Entityform submitted data using views?

**THE SOLUTION:** As per Wolverine's answer it is very simple to do, displayed in the picture:

No idea how I missed it before!

# Answer
> 4 votes
It should be available, create a view of `Entityform Submission` and add the filter `Entityform Type`, if you want. Add the fields that you want to display, make sure you have selected `Show : Fields` under **Format** section.

By default entity form module creates two views, Entityforms & Entityform Type List, you can edit the `Entityforms` view instead creating a new view, if you want.

---
Tags: views, entities
---


# Question
Title: How to change default message from user relationships module?
I am using User Relationships module. Its working fine. But I want to change a default message which get displayed on user site after getting request.

The message is like

> "John has requested to be your Friend. View your pending relationship requests to approve or decline."

I want same message to be displayed as

> "John has requested to be your Friend. View your pending friend requests to approve or decline."

Just want to replace the word relationship with friend. How can I do that?

# Answer
> 0 votes
`User Relationship` module allows you to set your own message, you can override the default message by settting a variable using `variable_set("user_relationships_msg_{$key}", "Custom Message")`, check the functions `user_relationships_get_message()` and `_user_relationships_default_messages()`.

---
Tags: users
---


# Question
Title: Text field formatter with link to the entity?
I have a text field that I use to store an entity title. It is not the "native" entity title, but just a field named field\_title.

Now I want to display this text field as a link to the entity (e.g. product/123). (I am working with Display Suite here, but the question is not limited to that)

I know I could simply create a custom formatter for this. But isn't there an easier way? I think I even did this once, just can't remember.

I also found the Field Value Link Formatter module , but this doesn't seem to be it.

EDIT: There are some known solutions like DS custom fields, or Custom Formatters, or hook\_field\_formatter\_info() in a custom module, or node template override, or field template override, or the awesome hook\_ds\_field\_theme\_functions\_info().

However: This seems such a recurring use case that I consider to write a new (reusable) module and publish it. So, I am looking for a solution so easy that it invalidates the desire to write a new module :) I think I saw something like this once, just can't remember.

# Answer
> 1 votes
you could do this with a Display Suite custom field and use the tokens to build the link.

I would do it like that if I wouldn't like to write a custom template. Or, as already mentioned, create a template for that node. Due to the fact that you don't use the native title, you will have it available in the node template and you can change the markup there.

---
Tags: entities
---


title: Database Synchronisation Manually

text:
# Question
Title: Database Synchronisation Manually
I have a situation where I need to check the changes (what tables) were done at database level after a particular date as the two databases have to be merged now. Is there any tool or module in Drupal that can fulfill this requirement.

**Scenario:** My client has given me the database (code also) of his current site to work on. He also did some changes meanwhile (at database level only maybe content) on his live site.

Now I need to integrate these changes into my database, but he did not record the changes that were done. What would be the best solution?

**What I have done:** I wrote a query fetching records from node table showing all the changes done after the particular date and manually updated his changes into mine. Am I missing something else?

# Answer
> 0 votes
There are a couple of ways I could think I would approach this issue:

1. If the changes made by me in the old database are reproducible easily to the new database, I'd go for it first. And in most of the cases if you follow Drupal best practices like using update hooks, alter functions, etc. they could be easily done to the new database by (sometimes) running only update.php
So, I'd recommend to move all the custom changes to the update hooks if you have time. Because, considering that the site is live, you could expect more changes to the database. And your code should be flexible enough; unless off course if you could convince the client to stop updating the live site.
2. If you are sure no database level changes would be done (which I doubt, Drupal being a database driven framework), you could use some tools for comparing the changes between the two databases. Check this stackoverflow question for list of tools that could be used. Take a diff of the database, find out the tables which have differences. From the tables, find out which entities are added/removed from the database. And then make the changes to as required.
*I would not recommend this method over the first.*

---
Tags: database
---


title: Trigger when a user clicks on a link

text:
# Question
Title: Trigger when a user clicks on a link
I have a menu listing different links and on some of the links, I want to trigger a notification to the User. I'm working on drupal 7. Also please let me know what modules I would need in the process.

Thanks!

# Answer
Have you looked into the Rules module? It's great for making conditional actions and can do stuff like sending out mails.
> 2 votes

# Answer
Just if someone come across it and not able to solve.

Steps:

Download the Rules module

1. Go to `admin/config/workflow/rules`
2. Create a rule
3. Event: Drupal is initializing
4. Condition: Data comparison:
    * Data to compare :\[site:current-page:url\]
    * Operator: equals
    * Data value: any URL you want
5. Action: page redirect / popup load / send email / etc...

Hope it helps.
> 1 votes

# Answer
Just to expand on the above for anyone that finds this post, I achieved this following danbohea's directions and using Text comparison as the condition

Parameter: Text: \[site:current-page:url\], Matching text: home
> 0 votes

---
Tags: navigation, rules
---


# Question
Title: How do I add HTML to my module's custom admin page?
I have set up a new page in my admin for my module like so:

```
/**
 * Implements hook_menu().
 */
function scraper_menu() {
    $items = array();

    $items['admin/scraper'] = array(
        'title' => 'Scraper',
        'description' => 'The main action page in the admin area where we control our scrapers.',
        'page callback' => 'scraper_page',
        'access arguments' => array('administer users'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

/**
* Page callback: Scraper page
*
* @see scraper_menu()
*/
function scraper_page() {
    return '<p>Hello world</p>';
}

```

When I navigate to admin/scraper I get the following error:

Fatal error: Unsupported operand types in /######/includes/form.inc on line 1079

So how do I create a custom HTML page in the admin?

# Answer
> 2 votes
What you have tried is the right way to do. I have checked the same code snippet and its working for me in my D7 installation. Hopefully the issue will be with some other form element (probably custom block ) that has be assigned in this page, might have some syntax error.

Thanks

# Answer
> 0 votes
```
function scraper_page() {
  return array(
    '#markup' => '<p>Hello world</p>'
  );
}

```

try that.

---
Tags: 7, hooks, routes
---


# Question
Title: Email sent using rules chops characters off email from address
I'm sending out an email using rules. I'm leaving the from field blank, so that it just uses the site-wide address.

For some reason it seems like Drupal is cutting characters off the from address. This is on my local dev machine so the email looks like this: admin@website.meeples

When the email is supposed to get sent, I simply get a message saying "Unable to send e-mail. Contact the site administrator if the problem persists." so I checked my syslog, and all the from headers say "someone@website.meep" and the email can't send because my machine can't resolve that domain.

What the hell? Why has it modified the from address? I've tried changing the site email to "admin@test.com" and when I do that nothing gets modified (IE I see admin@test.com in my syslog). So why is it changing my website.meeples domain?

# Answer
I tracked the problem down to the mimemail module.

In mimemail.inc there is a function called mimemail\_headers which contains this:

```
  if (preg_match('/[a-z\d\-\.\+_]+@(?:[a-z\d\-]+\.)+[a-z\d]{2,4}/i', $from, $matches)) {
    $headers['Return-Path'] = "<$matches[0]>";
  }

```

The {2,4} at the end of the regex caused it to chop the les off of meeples. Changing it to + fixed the problem.
> 2 votes

---
Tags: 7, rules, emails
---


# Question
Title: Modify and add of unlimited collection field
I have a content who contains an unlimited collection field. Via a custom module, how can I get and set the informations which are in field collection in the content (nid) ?

I have read the api documentation of field collection but I don't understand how it works (I'm french..) By example I see this function : field\_collection\_item\_load, the parameter is an item but...what is an item ? xD

Another question, my field collection contains an another field collection. Is there a particular way to get and set this "sub"-field collection ?

If you can me a very sample example of get and set, I thank you very much

# Answer
Suppose we are in a `hook_node_view()`, a `hook_preprocess_node()` or something and we have access to $node, and my collection field is 'field\_collection\_field':

```
<?php
if (!empty($node->field_collection_field)) {
  $collection_fields = field_get_items('node', $node, 'field_collection_field');

  // Extract the field collection item ids
  $ids = array();

  foreach ($collection_field as $fc_field) {
      $ids[] = $fc_field['value'];
  }

  //Get the entities
  $collections = field_collection_item_load_multiple($ids);
  // dpm($collections); Devel output the items
  //Loop over the array - if you have more than one entity
  foreach($collections as $collection) {
    //Iterate over all member vars of the FieldCollectionItemEntity object
    foreach($collection as $key => $value) {
     // DO STUFF WITH COLLECTION FIELDS VALUES
    }
   }
 }//end if

```
> 0 votes

---
Tags: entities
---


title: Menu block goes crazy after 4th level

text:
# Question
Title: Menu block goes crazy after 4th level
When I click on a 4th level link of a Menu block, the 3rd level disappear. This is the menu:

* Services
* + Accommodation
* + - Building A
* + - * Apartment 1
* + - * Apartment 2

I have 3 blocks to show this menu:

1. 1st level block (Starting level 1st, max depth 1): is ok
2. 2nd level block (Starting level 2nd, max depth 1): is ok
3. 3rd level+ block (Starting level 3rd, max depth 9): it's not ok

When I click on a third level link (Building A) the 3rd block shows:

* Accommodation
* + **Building A**
* + - Apartment 1
* + - Apartment 2

but when I click on any 4th level links (i.e. Apartment 1), the 2nd level link disappears and it shows:

* Building A
* + **Apartment 1**
* + Apartment 2

I need to see the third level links even if I click on the 4th+ levels. What I need is this:

* Accommodation
* + Building A
* + - **Apartment 1**
* + - Apartment 2

Thank you.

# Answer
Solved. In the menu block configuration, **Advanced Options**, I checked **Make the starting level follow the active menu item**.
> 1 votes

---
Tags: routes
---


# Question
Title: Alternative to creating large number of fields via UI for a content type
We need to create a content type with large number of fields(50+). Adding fields one by one via UI is one option but it seems unnecessary that so many tables get created when adding fields via UI.

Other option that I tried was Matrix field module which allows inclusion of multiple fields with widget options for select, checkbox, text etc. However it does have few issues with display.

The other alternative is the TableField module. But then it only provides text options.

Are there any other modules that allow creation of multiple fields without the overhead of creating multiple tables at the same time.

Note: A webform cannot be used in this case due to design considerations.

# Answer
> 1 votes
There are two ways you can accomplish this:

1. Write a custom field, with the 50 necessary fields compounded into the field's columns (this will create 50 columns in the field data and revision tables, but obviously you've got to store your data somewhere). There's an excellent example of writing a custom field in the Examples module.
2. Write a custom entity. This is probably more work, but using this method you can make your 50 fields entity *properties* (rather than fields in the Drupal sense), and the data will all be stored in the base table for the entity. Again, that's a large-ish number of cols for a table, but your data needs to live somewhere.

Both methods give you the flexibility to create the input forms yourself, so either will let you achieve whatever UI you think is most appropriate for inputting that amount of data in one go.

Note that using the standard field API is considered best practice, which is probably why you're struggling to find modules that do it differently.

# Answer
> 0 votes
One of the ways to resolve can be via Field Collection as suggested by @Krishna Mohan for fields requiring similar widget for data storage.

Ex: This can be used if multiple fields are of let's say Yes/No selection type. A field collection allowing multi-value can be created with 2 fields. The first field would provide a list allowing for selecting the parameter(which is the name of the fields of similar type in the list) and the other field would provide an option for Yes/No.

Fields of various categories can be clubbed into multiple field collections.

---
Tags: 7, entities, nodes
---