# Question
Title: Hide errors from users but show to admin?
Under 'Error messages to display' I can hide errors (as is recommended for production sites). However is it possible to hide errors for everyone except a certain role?

# Answer
Preface: This answer was first posted as an answer to "How do I suppress a warning or error message for site users?".

# Disable Messages module

You could use the Disable Messages module for this. Here is a quote from its project page:

> Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Some of its features are:

> * Filter out messages that match a full text string exactly.
> * Filter out messages that match a regular expression.
> * Permissions to specifically hide all messages of a given type from any role.
> * Disable all filtering for specific users.
> * Disable all filtering for specific paths.
> * Apply filtering only for specific paths.
> * Debug system to get messages in the HTML without showing it to the end users.

Available for either Drupal 6, Drupal 7 or Drupal 8.

# About using regular expressions

If you're using its '***regular expression***' feature, you have to make sure that you use a regular expression that "catches" the error message you want to intercept, as explained also in the Community documentation.

Below "*Tip: Keep it simple.*" on that page, there is a great sample, which looks like so:

> Be aware that something that appears very straightforward like:

```
Notice: Undefined index: field_txt_student_id in ctools_entity_form_field_content_type_render() (line 96 of [...]entity_form_field.inc).

```

> Has a lot more unseen characters in it than one might expect:

```
<em class="placeholder">Notice</em>: Undefined index: field_txt_student_id in <em class="placeholder">ctools_entity_form_field_content_type_render()</em> (line <em class="placeholder">96</em> of <em class="placeholder">[...]entity_form_field.inc</em>).

```

> So just wrap the meat of the grep with a simple "any character" regex: ".+" as in:

```
.+Notice.+Undefined index:.+ctools_entity_form_field_content_type_render.+entity_form_field.inc.+

```

So the "clue" to come up with a correct message, is to shrink the error message you want to catch, and putting "**.+**" characters where appropriate.

Talking about shrinking, note that the `field_txt_student_id` has been omitted in the regular expression also (to make it NOT depend on the field name).

# Example

As another example, assume you want to catch this error message:

> PDOException: in dblog\_watchdog() (line 160 of /home/dbuser/public\_html/yoursitesname.com/modules/dblog/dblog.module).

In this case a possible regular expression should look something like so:

```
.+PDOException.+in dblog_watchdog().+(line 160 of.+/modules/dblog/dblog.module).+

```

Note how I intentionally did not include part of the path before `/modules/dblog/dblog.module` (so that it can be reused in another site where the very same error occurs ...).

Also note that you have to give it some thought to yes or no include the `160` part of it: if the module ever changes a bit so that in the error message it (eg) becomes line `161`, your error will not be intercepted anymore. To avoid that, omit the 160 part of it, if that's what you prefer (personally I would rather first see the error coming back then, and then re-adapt my regular expression).

If your regular expression doesn't work at first (= the message still appears), then it might be because there is some typo in the regular expression. To pinpoint such typo, first try with a less restrictive regular expression, even if it was only to try with something like so (to catch **ALL** messages containing `PDOException` and `dblog_watchdog`):

```
.+PDOException.+dblog_watchdog.+

```

Or even like so (to catch **ALL** messages containing `PDOException`):

```
.+PDOException.+

```

These last 2 expressions would probably suppress way too much messages, so you'd want to narrow it down to that single one you're after.

# Unstable alternative

There is also the Better Messages module as an alternative. However, for D7 (which is what this question is about), it only has an Alfa version.
> 17 votes

# Answer
You can check the user role by using the in\_array() function. In your template:

```

<?php global $user; ?>
<?php if (!in_array('YOUR_ROLE', $user->roles)): ?>
  <?php if ($messages): ?>
    <div id="messages">
      <?php print $messages; ?>
    </div> </div>
  <?php endif; ?>
<?php endif; ?>

```

Or you can do it in your preprocess function (not sure is the message variable is called correctly but it can give you an idea)

```

function MYTHEME_preprocess_page(&$variables, $hook) {
  global $user;
  if (!in_array('YOUR_ROLE', $user->roles)){
    // This has to be checked, could be something similar.
    unset($variables['page']['content']['messages']);
  }
}

```
> 6 votes

# Answer
To remove notice from a Drupal website please follow below steps:

* Go to admin/config/development/logging.
* You have three choices:
    1. `None` will disable all error reporting.
    2. `Errors and warnings` will display on the most serious problems.
    3. `All messages` will display all problems and is probably only useful for developers.

Another way to disable notice and error message through code. Add following code to the `settings.php` file:

```
$conf['error_level']=0;

```

You can also configure Drupal to only log the errors following these instructions: go to `Administration > Configuration > Development > Logging and errors` or go directly to the path `/admin/config/development/logging` and set "Error messages to display" to **none**. Drupal then still logs errors but doesn't display them to users.

If you require more control use the **`Disable Messages`** module.
> 6 votes

# Answer
Actually this is not really doable.

You can hide all messages for users or roles but the main problem lies in the way drupal categorizes errors.

A form error is the same as a database exception for the messages function, so if you hide errors you also hide the error messages of a comment form.

I would love for someone to prove me wrong because I have not managed to achieve hiding php notices but showing form notices at the same time.
> 4 votes

# Answer
You can use the better message module. It offers role based configuratoin and/or regular expression matching to filter out some notifications.
> 3 votes

# Answer
You may to comment this code in your theme

```
<?php if ($messages): ?>
    <div id="messages"><div class="section clearfix">
      <?php print $messages; ?>
    </div></div> <!-- /.section, /#messages -->
  <?php endif; ?>

```

or status\_messages theme element serves this you may write own theme function in template.php

```
MYTHEME_status_messages(&$variables){}

```

This could effect only to notice and warning errors
> 2 votes

---
Tags: 7
---


title: entity reference filter condition

text:
# Question
Title: entity reference filter condition
I have created view and I have added the fields like entity reference fields followed by content fields, then I added the entity reference field in filter condition, but its not displaying the table data. Following methods I followed to create the filter conditions,

1\] created new view added the entity reference and other content fields.

2\]added the contextual filters as shown in screen attachment, also the relationship as entity reference of the field.

3\]in the left view page-\> clicked on -\>add filter condition-\>chosen the field and relationship but still its not able to filter the data of table please help me on this.thanks in advance

# Answer
> 0 votes
In my observation it appears you are mixing some configurations here. Normally when you add **Content: Nid**, you are telling the view to get the NID from your URL like animal-info-view/% where "%" represents the node ID or somewhere else like Panels but notice that you don't have that. The view will now be asking "Where is my nid? I can't find it.". So now you're having issues with no data being displayed.

If you need a listing page, sometimes you won't need the Contextual and Relationship fields anymore. Just directly add the entity reference field into Filter Criteria and it should look like the Gender filter.

If you need a content/node view page, now you will need the Contextual fields but kinda not need the filter because you're just displaying one content.

**EDITED**

Apologies for the late reply. So on my research I found a module called Views Reference Filter that enabled you to assign a View to provide the selections for your filter. So install an enable the module.

## Create the Entity Reference filter view

1. Create a new View.
2. Add a new Views Display called Entity Reference.
3. Select the Lab content type for the **Show** field.
4. Add the Lab Nid and Title/Name.
5. Under Format, replace it with **Entity Reference List**
6. Under the format's settings, choose **Nid** for Search fields.

You should have something like:

## Tweak your Animal Info View

1. Remove all the Contextual filters and Relationships you have and the **(Content entity referenced from field\_lab\_idc) Content: LAB ID** filter you added.
2. And add the **Content: LAB ID** field that's in your *Animal Info* content type
3. On the LAB ID's settings pop-up, you will notice something new, it's the **View used to select the entities**. Select the entity reference view that we created a while ago.
4. You can leave the default **Operator** setting to **Is one of**.
5. Check the **Expose this filter to visitors, to allow them to change it**.

This would look like:
6. And click Apply.

Your Animal Info View should have something like this:

Hope this helps you.

**NOTE:** Please include your requirements so that people would know what you want the result to be like.

# Answer
> 0 votes
Have you tried Views Autocomplete Filters module ..it should be work for applying filter with view relationship.

To configure this watch the following tutorial by Daily Dose of Drupal "Watch here"

---
Tags: views
---


# Question
Title: How do I get the list of all group members?
I have created one group using the Group module, then I added some members in that group. Now I want to get list of all members in the group from some custom code.

How do I get the list of all group members?

# Answer
> 0 votes
Use the Group module API.

```
$group->getMemberCount()

```

# Answer
> 0 votes
You can build a view using the Views UI, then export the view, and integrate that exported View in your custom code.

For the actual view, you should create a view of "***Group Memberships***", and optionally add a filter by Group ID (=`gid`).

For an example of such view, refer to my answer to "How to add a column to the list of group members or create a Views equivalent of it?", which includes a view (in export format), which should be pretty close to what you're asking for.

---
Tags: 7, log-messages, group
---


# Question
Title: How to render a menu_block in a specific language (i18n)
I have a special menu that is part of the page. I include it in the template like

```
$block = module_invoke('menu_block', 'block_view', DEF_BOOKLETS_MBID);
print render($block['content']);

```

Menu's are part of the interface, not of the content. If I use i18n, the translated menu will appear fine if the *interface language* switches.

However, the client does not want that. The interface is supposed to be one language, but the content can switch languages. That works too - apart from the menu block inside the content.

Is there a way to render a menu\_block inside a template in the current *content* language ?

# Answer
ok - this is extremely ugly, but seems to work

```
global $language,$language_content;
$org_language = $language;
$language = $language_content;
$block = module_invoke('menu_block', 'block_view', IAF_BOOKLETS_MBID);
$language = $org_language;

print render($block['content']);

```

Feel free to boo me on this one :-D
> 0 votes

---
Tags: theming, i18n-l10n, blocks
---


# Question
Title: Create node template only for default view-mode
I created a node template for my content type which I only want to use for my default view mode and keep the standard view of the teaser. My file is named like node--customnode.tpl.php. As I read I can create a template file for the teaser by adding node--customnode--teaser.tpl.php but it does not work for default in the same way. Does anybody have an idea?

# Answer
Try adding the following code to your theme's `template.php` file:

```
function THEMENAME_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']->type) && isset($vars['view_mode']) && $vars['view_mode'] == 'default') {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type . '__default';
  }
}

```

Replace "THEMENAME" with the machine name of your theme.

This should allow you to use a template file called `node--customnode--default.tpl.php` (assuming your content type is called "customnode") which will apply only on the default view mode.

n.b. You will need to flush your caches after adding both this functino and the template file.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How do I allow access to my custom module to "anonymous user"
**case :**

1. I have created a custom module
2. Implemented a hook\_menu() as shown

> function my\_custom\_menu() {
>
> ```
>   $items = array();
>   $items['my/custom/link'] = array(
>     'title' => t('My Custom Form'),
>     'page callback' => 'drupal_get_form',
>     'page arguments' => array('my_custom_user_form'),
>     'access arguments' => array('access content'),
>     'access callback' => TRUE,
>     'type' => MENU_NORMAL_ITEM,
>   );
>     return $items;
> }
>
> ```

But problem is that "anonymous users not able to access link"

Please guide me...

# Answer
```
$items['your/menu/link'] = array(
    'title' => t('Your menu Title'),
    'page callback' => 'your_callback_page',
    'access arguments' => array('your arguments access'),
    'type' => MENU_LOCAL_TASK,
    'weight' => -1, // as per your requirment
  );

```
> 0 votes

# Answer
I would suggest you gain more control over the access, by switching to "access callback" =\> "my\_custom\_function".

Then in my\_custom\_function() you can write just "return true" which will make it always accessible.

You could also add a log before "return true" so you can tell whether the function is being called. If it isn't, then you know access is being blocked further up, before you get to that stage.
> 0 votes

# Answer
If the link is meant to be accessible by everyone then you can remove 'access arguments' from the array. Also change 'type' to MENU\_CALLBACK. Finally, clear the caches.
> 0 votes

---
Tags: 6, forms, users, routes
---


# Question
Title: Will Migrating Content Between Sites Preserve CKEditor Styles?
I have been entering content on my dev site using CKEditor, but now I'm worried that moving to the live site will erase all the styling I have done to these articles. Maybe that is a dumb question, because I have not found anything addressing this topic online. If I have the CKEditor module installed on the live site, when I transfer my content there, will all their fonts/colors/styling/etc be preserved? Thanks in advance

# Answer
**Yes, as long as you keep your database integrity when migrating.**

CKEditor basically adds HTML tags and attributes to your data, which are saved in your fields' tables in the database. So, for example, if you have a *body* field that contains text formatted like "Hello, **body**", and take a look at your field\_data\_body table, you will see something like this:

```
<p>Hello, <strong>body</strong>...

```
> 1 votes

---
Tags: wysiwyg
---


# Question
Title: Profile pictures not displaying in forum
I am making my first forum using Drupal and have very little web development experience. My forum is very basic so far, mostly using core modules.

I tried adding a profile picture for my admin account (and also a picture for a test user account), but the image doesn't show anywhere. I only get the thumbnail that indicates a missing file or broken link. I have tried reloading the page, clearing the cache, and installing the profile2 module, but of course I still do not see images. I have since uninstalled profile2 just because I want to keep the forum as simple as possible until I learn more.

I'm working in version 7.39 and the site is hosted on my university account.

Thanks in advance for any suggestions.

Eric

# Answer
> 1 votes
I had also posted my question to my university drupal help list and managed to find an answer. I don't know how much of this applies to the general community (it may only apply to my specific Drupal install at my university because they include automated configuration adjustments), but here is the solution that worked for me:

My main folder is called simply drupal. In the file

*/drupal/.htaccess*

I had changed the line

*Options +FollowSymLinks*

to instead read

*Options +SymLinksIfOwnerMatch*

The problem was that I had not changed a second copy of this file in another location:

*/drupal/sites/default/files/.htaccess*

I made the same changes to this file and now the images show. I did not simple copy one file to the other location, because the files contain different options and only the one line needed a change. Again, my drupal install might be unique to my university, but these edits are so minor that I think someone else could try them without getting into too much trouble. Maybe someone else could lend more insight if needed.

---
Tags: media, users
---


title: Simplenews category approval

text:
# Question
Title: Simplenews category approval
I've got multiple newsletter purposes: some newsletters are for publicly available content and other newsletters are for example for journalists only or retailers only.

Is it possible to have each type as a Simplenews newsletter category? It doesn't seem to be out of the box, but I'm thinking it should be possible right?

My dream scenario would be to have these newsletter categories on admin/config/services/simplenews:

* General news (open for all)
* System news (mandatory for registered users)
* Press releases (admin approval required)
* Retail news (admin approval required)

Any suggestions on how to achieve this?

The long term idea is to add similar user roles for the restricted newsletter subscribers enabling restricted content, wholesale prices etc.

# Answer
Probably not possible out of the box.

You'll need to implement access for them, see for example https://www.drupal.org/node/1140606 for some discussions/ideas.

In 7.x-1.x, categories are terms, in 7.x-2.x they are separate entities.

However,I doubt that simplenews, in either 7.x-1.x or 7.x-2.x fully respects whatever access you define there, but patches to improve that are welcome.
> 1 votes

---
Tags: users, emails
---


# Question
Title: How to refresh all views in Panels with a time interval without page refresh?
I have some views that I want to refresh in a time interval (15sec) OR if there is changes in the content. For that I tried to use module "Views Auto Refresh". It works fine for a time interval but only if I have one view in a page.

If I have multiple views inside a panel (using Panels module), only one of the views is refreshed.

Is there any other way (module or custom code) to achieve this behaviour?

Thanks!

EDIT: As suggested, I tracked the ajax requests. In my case I'm refreshing every 15seconds. In a panel with 2 views I notice that I have only one request every 15sec, should I have two?!?!? Anyway, below is the piece of code I get when clicking in the function in red in the picture (I think is this one). The debug highlights the following line:

```
$(anchor).trigger('click');

```

```
Drupal.views_autorefresh.timer = function(view_name, anchor, target) {
  Drupal.settings.views_autorefresh[view_name].timer = setTimeout(function() {
    clearTimeout(Drupal.settings.views_autorefresh[view_name].timer);

    // Turn off "new" items class.
    $('.views-autorefresh-new', target).removeClass('views-autorefresh-new');

    // Handle ping path.
    var ping_base_path;
    if (Drupal.settings.views_autorefresh[view_name].ping) {
      ping_base_path = Drupal.settings.views_autorefresh[view_name].ping.ping_base_path;
    }

    // Handle secondary view for incremental refresh.
    // http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object
    var viewData = Drupal.settings.views_autorefresh[view_name].ajax.submit;
    var viewArgs = Drupal.settings.views_autorefresh[view_name].view_args;
    if (Drupal.settings.views_autorefresh[view_name].incremental) {
      if (!viewData.original_view_data) viewData.original_view_data = $.extend(true, {}, viewData);
      viewData.view_args = viewArgs + (viewArgs.length ? '/' : '') + Drupal.settings.views_autorefresh[view_name].timestamp;
      viewData.view_base_path = Drupal.settings.views_autorefresh[view_name].incremental.view_base_path;
      viewData.view_display_id = Drupal.settings.views_autorefresh[view_name].incremental.view_display_id;
      viewData.view_name = Drupal.settings.views_autorefresh[view_name].incremental.view_name;
    }
    viewData.autorefreshRequest = 'autorefreshRequest';
    Drupal.settings.views_autorefresh[view_name].ajax.submit = viewData;

    // If there's a ping URL, hit it first.
    if (ping_base_path) {
      var pingData = { 'timestamp': Drupal.settings.views_autorefresh[view_name].timestamp };
      $.extend(pingData, Drupal.settings.views_autorefresh[view_name].ping.ping_args);
      $.ajax({
        url: Drupal.settings.basePath + ping_base_path,
        data: pingData,
        success: function(response) {
          if (response.pong && parseInt(response.pong) > 0) {
            $(target).trigger('autorefresh_ping', parseInt(response.pong));
            $(anchor).trigger('click');
          }
          else {
            Drupal.views_autorefresh.timer(view_name, anchor, target);
          }
        },
        error: function(xhr) {},
        dataType: 'json',
      });
    }
    else {
      $(anchor).trigger('click');
    }
  }, Drupal.settings.views_autorefresh[view_name].interval);
}

```

# Answer
You need to use Views Auto-Refresh module with this patch
> 0 votes

# Answer
I have done this in the past with the help of Views Auto-Refresh

Try the module and let us know if it work.
> 0 votes

---
Tags: views, panels
---


title: Add class in panels region

text:
# Question
Title: Add class in panels region
I am trying this for long time. I am trying to add additional class in panels region. I am using panel page to display one of my node. I want to add region class but I am not getting success. Is there any way to achieve this? Is it possible to rewrite layout template in my theme? If so I can achieve this quickly. For example I wonder if it is possible to override layout template based on my node content type.

Thanks a lot.

# Answer
> 1 votes
You can create custom layouts in your theme for panels, there's a fairly good how to guide here: https://drupal.org/node/495654

If you wanted to use different layouts for different nodes, you can add a variant to your panel pages, and under "selection rules, select "node:type" and select the content type you want. Then you can assign different panels layouts to each respective variant under the layout tab.

# Answer
> 1 votes
If you just want to change the markup and classes of Panel regions and panes without changing the entire layout, check out the following modules:

* Clean Markup

> This module aims to clean up, enhance and facilitate the customization of markup for Drupal core and several popular contrib modules such as Panels.
* Semantic Panels

> It's a CTools style plugin that gives you full control over the HTML output of Panels panes. With it you can individually add/remove the:
>
> + Html element
>     + Classes
>     + Other attributes
>
> On the pane title, pane content, and pane wrapper.

# Answer
> 1 votes
I came across the same problem this morning, and after some googling found an answer. It comes down to finding the right **tpl.php** file and copying it to your own theme.

If you're subtheming from a base theme (in my case, for example, adaptivetheme), the base theme may provide its own layouts. Template files will be included there. The base theme may also implement a `template_preprocess` function that you can use to add classes, if that's supported within the **.tpl.php**.

Panels ships with some built-in layouts. I think that the template files located in the panels module directory under **plugins/layouts/\<layout\>/panels\_\<layout\>.tpl.php** will be what your're looking for. I haven't used them specifically, but they appear to follow the same pattern.

If you want to provide a different layout depending on node content type, however, you'd probably want to explore using panels page variants in the node\_view panels page. You can change layout and add pane-specific classes there through the UI.

---
Tags: 7, panels, theming
---


# Question
Title: Custom css is not applying to bootstrap subtheme
I followed the step by step to create a subtheme of bootstrap theme. Now, I am not able to apply my custom css to my page.

I took the below steps:

A) Downloaded Bootstrap project (7.x-3.0). Placed the bootstrap folder in sites/all/themes/.

B) Downloaded jQuery Update project, which is required by Bootstrap. In ../admin/config/development/jquery\_update and set the default jQuery version to 1.10.

C) From bootstrap folder, moved the bootstrap\_subtheme folder to sites/all/themes/ and name it bootsub

D) In bootsub directory, renamed the bootstrap\_subtheme.info.starterkit file to bootsub.info. I edited the content and it looks as below:

```
name = bootsub
description = A Bootstrap Sub-theme.
core = 7.x
base theme = bootstrap
;;;;;;;;;;;;;;;;;;;;;
;; Regions
;;;;;;;;;;;;;;;;;;;;;

regions[navigation]     = 'Navigation'
regions[header]         = 'Top Bar'
regions[highlighted]    = 'Highlighted'
regions[help]           = 'Help'
regions[content]        = 'Content'
regions[sidebar_first]  = 'Primary'
regions[sidebar_second] = 'Secondary'
regions[footer]         = 'Footer'
regions[page_top]       = 'Page top'
regions[page_bottom]    = 'Page bottom'

;;;;;;;;;;;;;;;;;;;;;
;; Stylesheets
;;;;;;;;;;;;;;;;;;;;;

stylesheets[all][] = css/bootsub.css

; For information on choosing the desired method, please read the Drupal
; Bootstrap sub-theme "how-to" documentation:
; https://drupal.org/node/1978010

; ;----------------------------------
; ; METHOD 1: Bootstrap Source Files
; ;----------------------------------
;
; ;;;;;;;;;;;;;;;;;;;;;
; ;; Scripts
; ;;;;;;;;;;;;;;;;;;;;;
;
; scripts[] = 'bootstrap/css/style.css'
; scripts[] = 'bootstrap/js/affix.js'
; scripts[] = 'bootstrap/js/alert.js'
; scripts[] = 'bootstrap/js/button.js'
; scripts[] = 'bootstrap/js/carousel.js'
; scripts[] = 'bootstrap/js/collapse.js'
; scripts[] = 'bootstrap/js/dropdown.js'
; scripts[] = 'bootstrap/js/modal.js'
; scripts[] = 'bootstrap/js/tooltip.js'
; scripts[] = 'bootstrap/js/popover.js'
; scripts[] = 'bootstrap/js/scrollspy.js'
; scripts[] = 'bootstrap/js/tab.js'
; scripts[] = 'bootstrap/js/transition.js'
;
; ; Disable BootstrapCDN if using Bootstrap source files in your sub-theme.
; settings[bootstrap_cdn] = ''

; ;-------------------------
; ; METHOD 2: Bootstrap CDN
; ;-------------------------
;
; Method 2 uses BootstrapCDN, the only thing you might need to provide here
; is overrides to Bootstrap theme settings. Copy them here from the base theme
; to override.

```

E) I enabled the bootsub subtheme.

F) Sites/all/themes/bootsub/css, I added bootsub.css file. I added some styling in the css file.

G) I inspected my page using chrome and I see that styling is not coming from bootsub.css file and instead it is coming from

"netdna.bootstrapcdn.com.......bootstrap.min.css.."

Do you know why custom css file is not applying the styling on my page?

*Further Notes*

* Using CDN method
* Cache has been cleared
* Aggregation is OFF
* "View source" in browser does not show bootsub.css had been loaded
* Using shared hosting

---

link

I found the link which does not allow me to comment. Link says:

> I had the same issue few days ago and I fixed with the template preprocess function. Just put the following function inside your template.php
>
> ```
> function YOUR_THEME_preprocess_html(&$variables) {
>  drupal_add_css('/PATH_TO_THEME/custom-style.css'); }
>
> ```

I tried to follow the above steps and did not work. I have the subtheme in sites\>all\>themes. In sites\>all\>themes\>subtheme, I have template.php. I added the below code in template.php:

```
<?php
function subtheme_preprocess_html(&$variables) {
  drupal_add_css('/sites/all/themes/subtheme/css/subtheme.css');
}

?>

```

Do you know if i followed the steps correctly or anything else you would like to recommend to resolve this issue?

site

# Answer
> 2 votes
In the Theme settings Under Bootstrap Settings, Go to Advanced -\> BootstrapCDN and choose Disabled from the dropdown.

Then in the theme info file uncomment the Method 1 section. Download the bootstrap files from Bootstrap Download and extract it to the subtheme folder. The extracted folder should be named - bootstrap and should contain all the necessary bootstrap js, css files.

You may get more info from this link Bootstrap sub-theming "how to"

---
Tags: theming
---


# Question
Title: How to implement arbitrary editable content areas
I'm trying to figure out the best way to implement pages with multiple editable content areas, each area on each page having a different set of HTML markup. The only solution I've found so far is to add a content type for each area so that I can create a custom block.

For example, on the homepage I have a mantle with image, title, and content:

Here's some example HTML I'd like to use for the structure of the editable content:

```
<div class="content content--who">
  <div class="container">
    <div class="row">
      <div class="col-xs-12 col-sm-10 col-sm-offset-1">
        <div class="content-wrap">
            <h2><?= $title ?></h2>
            <?= $content ?>
        </div>
      </div>
    </div>
  </div>
</div>

```

I'd like for the user to be able to edit the image, the title, and the content, without editing the HTML that makes up the structure of the page. Each page on the site will have a different HTML structure, as well as different content areas that need to be editable.

# Answer
> 0 votes
Take a look at the Panels and Panelizer modules; they'll provide the basic building blocks you need for the kind of layout and editing experience you want.

They'll let you create arbitrary layouts (Panels comes with a few...creating new ones is easy) and embed panes of content including just custom HTML (called a custom content pane) at arbitrary URLs or, using Panelizer, by customizing individual nodes on a per-node basis.

Use the Fieldable Panels Pane (FPP) module, or the Bean module, to let you define fieldable components that can be placed into a layout using Panels or Panelizer. So you could create an "image" FPP that has a field for a user to attach an image. You would then control the actual rules for how that image is output, and the markup that surrounds that image, by configuring the view modes for that FPP. Rinse and repeat for all the different sorts of elements you want users to be able to create.

---
Tags: 7
---


# Question
Title: How to update content type field programmatically
I try to update content type field `MYFIELD` with code

```
$update = db_update('field_data_field_MYFIELD')
    -> fields(array('field_MYFIELD_value' => $result))
    -> condition('entity_id', $nid)
    -> execute();

```

I see changes in database but they not reflected in node view. Also I applied this code to `field_revision_field_MYFIELD`table and got the same result. How can I update `MYFIELD` programmatically?

# Answer
> 1 votes
Better( and simpler) solution is using with drupal Node load and Node save API

```
$node=node_load($nid);
$node->field_data_field_MYFIELD['und'][0]['value'];
node_submit($node);
node_save($node);

```

# Answer
> 1 votes
It's better to use Drupa API to do that instead of missing with the database directly. you can use field\_attach\_update to update your field value

```
$node = node_load($nid);
$field = field_language('node', $node, 'field_your_field');
$node->field[$field_language][0]['value'] = 'Your New value';
field_attach_update('node', $node);

```

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


# Question
Title: Placing block inside a node (positioning block between specific elements in node's content)
Basically I created a webform and enabled it as a block, now I want to put that block inside a specific node. I can do that by placing it in a 'content' region and defining the specific node BUT it displays at the end of the content. Now how can I move it between specific elements inside the content?

The node is using a page-type....tpl.php which is used by 5 other nodes as well so I cannot change the code.

To visualize it looks like:

\[ content \]

-description text-

-list of videos-

\[ end of content \]

and I need to put my webform between the text and the video list. Is there a way?

# Answer
Give the Block reference module a try.

> Defines a field type Block reference which creates a relationship to a block and allows the block to be displayed as the content of the field.
> 1 votes

# Answer
You provide only little information but here are some suggestions:

* You could put the list of videos in a custom block and place it after the webform block.
* You could put the list of videos in a view and output it in a block and place it after the webform block.
* You could use panels
* You could use Semantic Fields for your CT and output the needed fields as blocks

I guess there are more options for sure, but that comes to my mind right now.
> 0 votes

---
Tags: nodes, blocks
---


title: Is form data cached?

text:
# Question
Title: Is form data cached?
Is form date cached? I have an interesting bug on my site. There is a form for logged in users and it is used very frequently. Sometimes, after long time usage, some data doesn't change when it should (another node..). It looks like it is cached.

How can i disable this "form cache" or force form on creation to load new data, not cached (old)?

thanks

# Answer
As far as I know, Drupal doesn't cache submitted form data. However, generated HTML Code is cached in many places.

I've come upon this problem when rendering a form in a block produced by a custom module. If block caching is active and the form is sometimes rendered with some fields pre-filled (The user's name, the previously used search term), that version of the form might be cached and displayed to other users. This particular case is easily fixed by setting `$block['my_block']['cache'] = DRUPAL_NO_CACHE;` in your module's implementation of `hook_block_info`.
> 0 votes

---
Tags: forms, caching
---


# Question
Title: how acces admin theme without /admin in url?
I try to have an admin theme for admin user and custom theme for user logged in without /admin/.... in the url.

I create an entity content module, the routing is like that :

```
    # AnnonceEntity routing definition
entity.annonce_entity.canonical:
  path: '/admin/annonce_entity/{annonce_entity}'
  defaults:
    _entity_view: 'annonce_entity'
    _title: 'Gestion des annonces'
  requirements:
    _entity_access: 'annonce_entity.view'

entity.annonce_entity.collection:
  path: '/annonce/liste'
  defaults:
    _entity_list: 'annonce_entity'
    _title: 'Liste des annonces'
  requirements:
    _user_is_logged_in: 'TRUE'

entity.annonce_entity.add_form:
  path: '/annonce/ajout'
  defaults:
    _entity_form: annonce_entity.add
    _title: 'Ajouter une annonce'
  requirements:
    _user_is_logged_in: 'TRUE'

entity.annonce_entity.edit_form:
  path: '/annonce/{annonce_entity}/edit'
  defaults:
    _entity_form: annonce_entity.edit
    _title: 'Edit Gestion des annonces'
  requirements:
    _user_is_logged_in: 'TRUE'

entity.annonce_entity.delete_form:
  path: '/annonce/{annonce_entity}/delete'
  defaults:
    _entity_form: annonce_entity.delete
    _title: 'Delete Gestion des annonces'
  requirements:
    _user_is_logged_in: 'TRUE'

annonce_entity.settings:
  path: 'admin/structure/annonce_entity'
  defaults:
   _form: '\Drupal\annonce\Entity\Form\AnnonceEntitySettingsForm'
   _title: 'Configuration des annonces'
  requirements:
    _permission: 'administer gestion des annonces entities'

```

I remove all /admin/ path for get better url for the simple user.

If i do that, it's ok for user admin and simple user but url is not good

```
entity.annonce_entity.collection:
  path: '/admin/annonce/liste'
  defaults:
    _entity_list: 'annonce_entity'
    _title: 'Liste des annonces'
  requirements:
    _user_is_logged_in: 'TRUE'

```

All is good but the path is /admin/annonce/liste, i prefer /annonce/liste.

Anyone have a suggestion ?

i have take a look into the user module, for the edit profil but i can't find the way to do same, admin theme for user admin and site theme for simple user.

edit: i have a way with AdminsNegociator service i check that

# Answer
What you are looking for is the `_admin_route` option.

For example:

```
entity.annonce_entity.collection:
  path: '/annonce/liste'
  defaults:
    _entity_list: 'annonce_entity'
    _title: 'Liste des annonces'
  requirements:
    _user_is_logged_in: 'TRUE'
  options:
    _admin_route: TRUE

```
> 0 votes

---
Tags: routes, 8
---


# Question
Title: Why are default values in a checkboxes $form not displayed?
I'm having a drupal form (7.x) of type `checkboxes`.

I have an array of values for my checkboxes.

```
$options = array(
    'uid'         => 'UID',
    'name'        => 'Name',
    'mail'        => 'E-mail',
    'created'     => 'Created',
    'edit_node'   => 'Edit',
    'cancel_node' => 'Cancel',
);

```

I have an array of default selected values.

```
$defaults = array(
    'uid'         => 'UID',
    'name'        => 'Name',
);

```

And now I try to make the default values selected by default, like this:

```
$form['dynamic_user_fields'] = array(
    '#type' => 'checkboxes',
    '#title' => t("Dynamic User Fields"),
    '#options' => $options,
    '#default_value' => $defaults,
    '#description' => t("Select the fields to display in the view."),
);

```

But this is not working, all checkboxes are unchecked by default. Where is my mistake?

---

**What is not working so far**: I've seen this related question but the answers do not work.

What I've tried:

(1) using numeric keys does not work.

```
'#default_value' => array(1, 2),

```

(2) using array keys does not work.

```
'#default_value' => array('uid', 'name'),

```

(3) using array structure does not work.

```
'#default_value' => array('uid' => 'UID', 'name' => 'Name')

```

Any ideas?

---

**References**

I stepped up to maintain this module but the code base is a migrated D6 module.

# Answer
For form elements expecting multi-value defaults, Drupal expects an array where keys and values are equal to the keys in your options array. Something like the following should work:

```
$defaults = array(
    'uid' => 'uid',
    'name' => 'name',
);

```

You may also use `$defaults = drupal_map_assoc(array('uid', 'name'));`.
> -1 votes

---
Tags: forms
---


# Question
Title: Use hook form alter to change input type
I am trying to change the input type on an ubercart checkout form using `hook_form_alter`. I added an extra field using the uc cart extra fields pane module but there is no option to add e-mail - only text - and I need the field I added to validate as an e-mail.

The field in question is:

```
<input type="text" id="edit-panes-billing-address-billing-ucxf-bill-to-email" name="panes[billing][address][billing_ucxf_bill_to_email]" value="" size="32" maxlength="255" class="form-text required">

```

The code I am using but with no success is:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'uc-cart-checkout-form') {
    form['panes-billing-address-billing-ucxf-bill-to-email'][LANGUAGE_NONE][0]['type'] = 'email';
  }

```

Thanks for any assistance!

# Answer
> 0 votes
If you want alter a form via an ID check you should be using `$form_id == 'uc_cart_checkout_form'`. Drupal form generation functions don't use "-" characters like generated CSS id/class attributes.

---
Tags: ubercart, forms
---


# Question
Title: Can I add my own if statement to node.tpl to test if field groups are null?
I have a content type with 4 different field-groups utilizing the Field Group module. I want to test to see if those groups are empty and render them and some additional HTML if they are NOT empty, and not render them, and additional HTML, if all the fields in the group are empty.

I'm not sure of the syntax to test if field groups contents are NULL, any pointers there?

So far this still isn't working for me. I have a field group that I know is empty `group_factory_images`

When trying to use the code from the answer:

```
<?php if(!isset($node->group_factory_images))
print 'Yep, Empty';
?>

```

It just prints the "Yep, Empty" string.

# Answer
For example:

1. I created content type
2. In display settings for `Full content` display created group `group_mygroup`

If group elements are empty then group wil not be displaying. In this case you should check it:

```
//if node's group_mygroup does not exist
//in our case it means that all elements in group are empty
if(!isset($node->group_mygroup))
        print 'Group elements are empty';
print render($content);

```

As you can read in node template help part - block of comments:

```
 * Other variables:
 * - $node: Full node object. Contains data that may not be safe.

```

Now, what you can do to understand solution more clearly:

1. Install Devel module

> Helper functions for Drupal developers and inquisitive admins. This module can print a summary of all database queries for each page request at the bottom of each page. The summary includes how many times each query was executed on a page (shouldn't run same query multiple times), and how long each query took (short is good - use cache for complex queries).

2. Somwhere in your template's code use `dpm($node);`
3. Create content of your type and see how it is displaying. You should see same picture
4. Click on header of appeared block and you can see structure of `node` object

If you want to check if some field doesnt exist - use same construction:

```
if(!isset($node->field_name))
print 'Field is empty';

```
> 4 votes

---
Tags: theming, entities
---


# Question
Title: "skip_process_on_empty" plugin does not exist
I'm trying to migrate entities from a D7 to a D8 site using this tut: http://www.metaltoad.com/blog/migrating-taxonomy-drupal-7-to-drupal-8

When I execute the migration I get the error:

> The "skip\_process\_on\_empty" plugin does not exist.

And then it just hangs.

I have this in my migrate yml file:

```
parent:
    -
      plugin: skip_process_on_empty
      source: parent
    -
      plugin: migration
      migration: custom_taxonomy_term

```

I tried changing it to `skip_row_on_empty` but get the same error regarding "skip\_process\_on\_empty".

Here's the contents of \[mymodule\]/config/install/migrate.migration.custom\_taxonomy\_term.yml

```
id: custom_taxonomy_term
label: Drupal 7 taxonomy terms
dependencies:
  enforced:
    module:
      - monster_migrate_7
migration_groups:
  - Drupal 7
source:
  plugin: custom_taxonomy_term
process:
  tid: tid
  vid:
    plugin: migration
    migration: custom_taxonomy_vocabulary
    source: vid
  name: name
  description: description
  weight: weight
  parent:
    -
      plugin: skip_on_empty  <--changed this per suggestion
      method: process
      source: parent
    -
      plugin: migration
      migration: custom_taxonomy_term
  changed: timestamp
destination:
  plugin: entity:taxonomy_term
migration_dependencies:
  required:
    - custom_taxonomy_vocabulary

```

And here's what I get when I try to execute it:

```
> drush migrate-manifest sites/all/modules/monster_migrate_7/manifest.yml --legacy-db-url=mysql://[user]:[pass]@localhost/monster
Running custom_taxonomy_vocabulary                                                                                [ok]
Processed 0 items (0 created, 0 updated, 0 failed, 0 ignored) - done with 'custom_taxonomy_vocabulary'                                                                                [status]
Running custom_taxonomy_term                                                                                [ok]
The "skip_process_on_empty" plugin does not exist.                                                                                [error]
>

```

# Answer
skip\_process\_on\_empty and skip\_row\_on\_empty were combined into a single plugin. Try this:

```
plugin: skip_on_empty
method: process

```

To skip a row:

```
plugin: skip_on_empty
method: row

```

Hope this helps!
> 2 votes

---
Tags: drush, 8
---


# Question
Title: Cannot alter clientside validation error messages for fields added with the field UI module
I am adding some custom fields to a registration page using the field UI module. I'm also using the clientside validation module to display error messages on required fields. I am able to change the error messages for the default fields I have not added using the field UI, but not for the fields added with the field UI. I have tried many different ways of targeting the fields to no avail. I'm using Drupal 7.

I can see the custom rule is actually being set when I `kpr($js_rules)`:

`$js_rules['field_first_name']['messages']['required']
<span data-thmr='thmr_13' class='devel-themer-wrapper'>Please enter your first name.</span`

...but the default error message still shows. I have a feeling this is due to the `<input>` element's name attribute being `field_first_name[und][0][value]`, but I was even unsuccessful in targeting this rule using that string in the `_clientside_validation_set_required()` function.

The difference between the default fields and my custom fileds are the custom fields values are very heavily nested within multiple arrays.

However, I'm unsuccessful in changing the input element's name attribute using any of the following:

`$form['field_first_name'][#name], $form['field_first_name'][#field_name], $form['field_first_name']['und'][0]['value'][#field_name], $form['field_first_name'][#name], etc.`

My custom rules:

```
_clientside_validation_set_required(
  $element['#name'],
  $element['#title'],
  isset($element['#required']) ? $element['#required'] : FALSE,
  $js_rules,
  t('Please enter your company email.')
);

```

Which works for the drupal default email field. However, this (or any of the many ways I've tried referencing the element's name) does not change the error message for my custom "first name" field:

```
_clientside_validation_set_required(
  $element['#field_name'],
  $element['#title'],
  isset($element['#required']) ? $element['#required'] : FALSE,
  $js_rules,
  t('Please enter your first name.')
);

```

**Update**

It turns out it **IS** the name attribute. When I hard code the name as `field_first_name` using `theme_textfield()`, my custom error message shows up. The problem with this is it prevents the proper values from being written to the database. Is there a way to escape the brackets in `field_first_name[und][0][value]` in order to use that as the first argument of `_clientside_validation_set_required()`?

# Answer
> 0 votes
I was able to set the rule by referencing the nested `#name` and `#value` keys:

```
_clientside_validation_set_required(
      $element['field_first_name']['und']['0']['value']['#name'],
      $element['field_first_name']['und']['0']['value']['#title'],
      isset($element['field_first_name']['und']['0']['value']['#required']) ? $element['field_first_name']['und']['0']['value']['#required'] : FALSE,
      $js_rules,
      t('Please enter your @field_name.', array('@field_name' => strtolower($element['field_first_name']['und']['0']['value']['#title'])))
    );

```

---
Tags: entities
---


title: Transactions in Drupal 6

text:
# Question
Title: Transactions in Drupal 6
I am running drupal 6.22 with MySQL. There is no drupal 6 API for using transactions. Since I am new to drupal, I do not know which is the best way to use transactions using the existing drupal APIs? Can anyone guide me on this?

# Answer
> 6 votes
Transactions are done with SQL and in Drupal 6 you need to write all your SQL. So to use transactions, all you need to do, is to use `db_query(SQL)` and include transaction in the SQL you create.

This could look like this:

```
$sql = 'START TRANSACTION;
       SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
       UPDATE table2 SET summary=@A WHERE type=1;
       COMMIT;';
db_query($sql);

```

Remember to use an engine that supports transactions like `innodb`.

# Answer
> 0 votes
You can actually initiate a transaction with a db\_query() run many db\_query()'s and then either do a commit or rollback with another db\_query() as in:

```
// start transaction
db_query("START TRANSACTION");

// repeat the following as required
db_query("SELECT ...");
db_query("UPDATE ...");

// end transaction
db_query("COMMIT");  - or -  db_query("ROLLBACK");

```

With this be very careful, you cannot return in the middle of your function without first making sure that you do a COMMIT or ROLLBACK. The safest way to do that is to create a transaction object and use RAII (i.e. the destuctor of that object makes sure one of COMMIT or ROLLBACK is sent).

---
Tags: 6, database
---


# Question
Title: How can I escape the brackets so they are seen as literal characters
I am using clientside validation along with the field UI module in a Drupal 7 site to request some custom input fields on user registration. I need to set some custom error messages using the clientside validation `modulename_clientside_validation_rule_alter()` function. The problem is, the field UI module creates fields with brackets in the name attribute like so: `field_first_name[und][0][value]`. When I use this as the first argument of `_clientside_validation_set_required()`, the proper error message is not being shown. I believe this is because the brackets are not seen as part of the string. How can I make the brackets literally brackets and not look like an array to drupal?

# Answer
The problem wasn't the brackets—I was able to set the rule by referencing the nested `#name` and `#value` keys:

```
_clientside_validation_set_required(
      $element['field_first_name']['und']['0']['value']['#name'],
      $element['field_first_name']['und']['0']['value']['#title'],
      isset($element['field_first_name']['und']['0']['value']['#required']) ? $element['field_first_name']['und']['0']['value']['#required'] : FALSE,
      $js_rules,
      t('Please enter your @field_name.', array('@field_name' => strtolower($element['field_first_name']['und']['0']['value']['#title'])))
    );

```
> 1 votes

---
Tags: entities
---


# Question
Title: Add a non-base field to a content entity form
What is the proper way to add a non-base textarea field to the entity form of a custom content entity?

comment and user modules have non-base fields that display in their entity form (comment\_body and picture), but it appears these fields are added to the form somewhere besides the main entity form method they use.

In my module, I've created a field and instance inside `hook_install` like this:

```
<?php
function mymodule_install() {
  $field = array(
    'name' => 'myfield',
    'entity_type' => 'myentitytype',
    'type' => 'text_long',
    'module' => 'text',
    'settings' => array(),
    'cardinality' => 1,
    'locked' => FALSE,
    'indexes' => array(),
  );
  entity_create('field_entity', $field)->save();

  $instance = array(
    'field_name' => 'myfield',
    'entity_type' => 'myentitytype',
    'bundle' => 'myentitytype',
    'label' => 'Field title',
    'description' => t('Field description.'),
    'required' => TRUE,
    'default_value' => array(),
    'settings' => array(
      'text_processing' => '0'
    ),
  );
  entity_create('field_instance', $instance)->save();
}

```

I think if I could be pointed to how comment\_body gets added to the comment entity form, or picture to the user entity form, I'd be able to resolve this.

# Answer
> 3 votes
You can ship a locked Field with yml only, see core/modules/forum/config/field.\*. Ie just make the fields in the ui and copy the yml files from your active store to a config folder inside your module.

This ships a locked boolean field for the container flag. You'll also need form and entity display entities, but you can create them in the ui and grab the yml for them too.

# Answer
> 2 votes
Parts of how to do this have chanaged or are deprecated. The arrays are mostly correct (name is now field\_name) (look in the yml for example values if you don't know what to use) but the functions are now:

```
\Drupal::entityManager()->getStorage('field_storage_config')->create($field)->save();

\Drupal::entityManager()->getStorage('field_config')->create($instance)->save();

```

You can find out how this all works including setting the field on form displays and view displays in /core/modules/field\_ui/src/Form/FieldStorageAddForm.php.

# Answer
> 1 votes
The solution is to add the following code after the field instance is created.

This is what the config files named `entity.form_display*` are based on.

```
entity_get_form_display('myentitytype', 'myentitytype', 'default')
->setComponent('myfield', array(
  'type' => 'text_long',
  'settings' => array(
    'text_processing' => '0'
  ),
  'weight' => 5,
))
->save();

```

---
Tags: entities, 8
---


title: User email verification link

text:
# Question
Title: User email verification link
Is there a way to store/save the user verification email link in the database after a new user creates an account?

# Answer
Yes, `hook_mail_alter()` enables you to alter any email messages sent out from `hook_mail()` if you know the specific key associated with the email. In this case, the key is `user_register_no_approval_required`. From that point, all you have to do is parse the email message body for the relevant URL and save it to your desired location.

```
function MYMODULE_mail_alter(&$message) {
  if($message['id'] == 'user_register_no_approval_required') {
    //@TODO: Parse $message['body'] for email verification link and save it
  }
}

```
> 2 votes

---
Tags: users, emails
---


# Question
Title: Views, show block on nodes where the node author has specific role(s)
I am trying to display a few views blocks on nodes of authors that have specific roles. So far I used contextual filter Content: Author uid with the following settings:

Provide default value: User id from url (Also look for a node and use the node author checked) Specify validation criteria: validator user, Restrict user based on role checked and I checked the roles for which I want the block to show up.

Although it seems to work with some blocks, it does not with all.

A good example is this page. The Featured listings block has the same settings (contextual filter as described above) as the Similar listings one but it does not show up. I used the same filter for another page (diff role of the author) with exactly the same config except the role and seems to work fine as well.

Any idea anybody how this could work for all use cases? Is content author uid the correct filter and is the setup correct?

Any help will be much appreciated.

THanks

# Answer
> 1 votes
Change access settings from access:Permissions to access:Roles and select the desired roles you want.

And for users use the contextual filters.

---
Tags: views, nodes, users
---


# Question
Title: Why doesn't All Products show all my products in Drupal Commerce?
I've set up a Drupal Commerce site without the sample products, and have created new products in a new product displays that I've created.

I've created Main menu items for the new displays, and the products show up when these menu items are clicked, but All Products shows no products.

How do I make All Products work? Is there a special View for this?

# Answer
I know this is old, but I recently encountered the same issue. Bojan Zivanovic's suggestion ave me an idea though. The search index indicated all products were indexed, but clearing the search index and rebuilding it resolved the issue.
> 1 votes

# Answer
Due to the way the Kickstart installation was built all products are not visible by default in the product view. You can modify this view by going to /admin/structure/views/view/commerce\_backoffice\_products/edit and changing the filter and field information for your particular installation.
> 0 votes

---
Tags: commerce
---


# Question
Title: Retrieve argument in hook_menu() item url
On my custom module, I defined the following hook\_menu() function.

```
function motel_events_menu() {

    $items['ajax/pastevents/%'] = array(
        'title' => 'Get Past Events',
        'page callback' => '_motel_events_get_pastevents(%)',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

```

In this function, how can I retrieve the % argument that is passed in 'ajax/pastevents/%' so I can send it to my \_motel\_events\_get\_pastevents() function?

# Answer
'page callback' =\> '\_motel\_events\_get\_pastevents(%)',

should be

'page callback' =\> '\_motel\_events\_get\_pastevents',

then insert

```
 'page arguments' => array(2),

```

immediately after. ajax is at position 0, pastevent is at position 1 and the wildcard % is at position 2. Counting for arguments starts at 0. The callback function will have a variable to pass in the wildcard value argument.

```
function _motel_events_get_pastevents($arg){

```

Some folks like to use the arg(n) form for arguments as its always present whether declared or not but I tend to use formal declarations.
> 2 votes

# Answer
You don't need to defined % in page callback you get url parameter within your function by calling **arg(2)**.
> 0 votes

---
Tags: 7, ajax, routes
---


title: Database system table problem

text:
# Question
Title: Database system table problem
I read this article. Where is the location of "system" table.

Is the image "system" table?

phpMyAdmin

To disable a module via phpMyAdmin you must login to phpMyAdmin. Then you must locate the database where Drupal is installed. Once you have done so look for the "system" table. Click and open it. Click to browse the table. Find the record for the module that is causing the problems and select the edit function. Set the status to "0" and save.

# Answer
> 1 votes
Yes, that is the `system` table, which stores details about available modules, themes and theme engines.

For more information about the system table schema, refer to the technical documentation at:

`system_schema`

from:

```
 $schema['system'] = array(
    'description' => "A list of all modules, themes, and theme engines that are or have been installed in Drupal's file system.",

```

and also, it's usage by:

`system_list`

> Builds a list of bootstrap modules and enabled modules and themes.

# Answer
> 0 votes
To address problems in the system table (as in the title of your question), you may also try to use contributed module "Registry Rebuild". That module integrates with Drush via the `Drush RR` command. It will then rebuild the system table.

DrupalEasy Podcast #133 further explains how this module / drush cmd can be used.

---
Tags: database
---


title: Create a View of Books

text:
# Question
Title: Create a View of Books
I'm using the core Book module for organizing meeting notes and documentation. How do I create a list of books with the views module? That is, I'd like a list of *only* the top-level Books, not all the book pages.

An example of what I want in core is at `admin/content/book` which looks like this:

Thus far, all I've been able to get is a hierarchical list of books *and* all book pages. Current view:

# Answer
> 0 votes
* Create a taxonomy term and defined in your content type
* Use Simple hierarchical select or Hierarchical Select to create new term when you add new book "book name is taxonomy term"
* Create a view using taxonomy term and select those terms whose parents has value = 0

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


# Question
Title: How to print date in image in Event List in Drupal
How can I print a date like `JAN 28` in the provided Event list, using Drupal Views?

The example image taken from the Drupal website is attached below

# Answer
> 0 votes
Navigate to `/admin/config/regional/date-time/formats/add` and add a new date format. For the replacement pattern use: `M t` then click save.

then navigate to: `/admin/config/regional/date-time` and create a human readable name for your custom date format, then select the date format you created inside the select box. click save.

Create your view add your date field and then in the field settings give it your custom date format for the format section.

Style with CSS. You're done.

*You may need to create two different date formats to achieve the styling you want. One for `M` and one for `t`. Then add your date field to the view twice and add the date formats on the fields, then you can easily target the two different date elements and use css to position them the way they are in the image you provided.*

# Answer
> 0 votes
1. Create a new content type for events (e.g. 'events') and add starting and ending date fields. You can create now create your desired event content.
2. Add a new calendar view from the existing template in the calendar module(admin/structure/views add-template). From the list, you should select "A calendar view of the 'field\_yourfieldname' field in the 'node' base table."(Display type of the view: Month)
3. In the edit mode of your calendar view, under filter criteria, select the event content type that you created above. Also add a contextual filter - 'Content: Nid'. Save the view.
4. Create a new view for your event listing. This view should have a page display. Under filter criteria, select the event content type that you created above. Add 'Content: Nid' as a new field and tick the option 'Exclude from display' in the configuration page. Add another field, 'Global: PHP', for grabbing the current date and passing it as argument to the calendar view. you should write 'print date("Y-m")' in the Output Code field and tick the option 'Exclude from display' in the configuration page.
5. Embed the calendar view in your event listing by adding a new field: 'Global: View'. (See the attached image for the configuration of this field.) Here you should specify the name of your calendar view in the View setting section and also specify the views display type. Then, you should add '\[%php\]/\[%nid\]' as a contextual filter for the calendar view. Save the view. Your customized event listing is now ready!

---
Tags: views, datetime
---


# Question
Title: Views Exposed filter text search for multiple value field
I have 6 fields (in Profile2) I want to combine into an exposed "`Global: Combine field filter`":

* Field 1 = text field with 1 value (text)
* Field 2 = text field with 1 value (text)
* Field 3 = text field with 1 value (text)
* Field 4 = text field with 1 value (text)
* Field 5 = long text field with 1 value (long text)
* Field 6 = text field set to **unlimited number of values** (text)

That last one is the problem. I want the user to be able to add several distinct values in this field, and I want to be able to create a combined field text search that includes the text from all of these fields, including all the separate values in Field 6.

If I *isolate* Field 6 and give it it's own exposed filter search field, it works fine. **But** if I try to make it one of the combined fields (using the `Global: Combine fields filter`), searches don't see the various text values in Field 6.

\[BTW, I'm using **Better Exposed Filters**, though I don't think they are in use for the `Global: Combine fields filter`.\]

# Answer
You will probably want to add a (7th) Text field filtering on the same data as Field 6 and group it with an OR to Field 6. Then, you can use Field 7 in the `Global: Combine fields` filter and not have it overwrite the use-supplied values in Field 6.
> 0 votes

---
Tags: views
---


# Question
Title: How to apply a sequential number pattern in Pathauto?
If the path name is same, I want to show display as below.

I want:

```
example.com/blog/path001
example.com/blog/path002
example.com/blog/path003 ...

```

currently:

```
example.com/blog/path
example.com/blog/path-1
example.com/blog/path-2 ...

```

But I don't know how to apply these patterns? What should I do?

# Answer
You need an additional module for this – Serial Field.

> Unlike Drupal's built-in auto-increment node ID, which is global and shared by nodes belonging to all content types, serial fields are managed per content type (D6) / entity (D7). For example, the serial field of an Invoice instance will generate a unique sequential number (starting at 1, then 2, etc.) exclusively for Invoice instances.

You then can use Serial Field + Token + Path Auto - to create serial numbers in urls, for example: http://www.example.com/issue/10 (where 10 is a type scope serial number).
> 5 votes

---
Tags: path-aliases
---


# Question
Title: How do I send an email containing the user password?
I'm implementing a function that send the password to users who forgot it.

This is the code I developed so far.

```
function my_module_lost_password($email) {
  global $language;

  $response = array();
  $account = user_load_by_mail($email);
  $params = array(
    'subject' => "hi",
    'body' => "hello",
  );
  $from = "The_admin@gmail.com";
  $to = $email;
 drupal_mail("???", "???", $to, $language, $params, $from);

```

}

This function is called by a POST query (web service).

How do I use `drupal_mail()` to send a mail to users containing the password from the users table?

# Answer
> 1 votes
First thing, you cannot send the password. You can only send a reset/one-time-login link. Passwords in Drupal are a one-way street, they can never be retrieved. To send the link is pretty easy. Use \_user\_mail\_notify()

```
_user_mail_notify('password_reset', $account);

```

---
Tags: services
---


# Question
Title: How to reverse a drupal patch on netbeans
Is there a way to reverse a patch on Netbeans?

Does simply copying the target file and repasting it will work?

Or can the patch affect mutliple modules and code?

# Answer
Use patch to reverse

```
patch -p1 -R < path/to/patchfile

```

Use git to reverse

```
git apply -R path/to/patchfile

```
> 0 votes

---
Tags: version-control
---


# Question
Title: hook_preprocess_views_view not loading view when records are empty
I am trying to add some css and js files using the hook\_preprocess\_views\_view\_unformatted Hook in template.php

Here is my code :

```
function mytheme_preprocess_views_view_unformatted(&$vars) {
$view = $vars['view'];
if ($view->name == "my_view_name"){

        drupal_add_css(drupal_get_path('theme', 'mytheme') .'/css/sample.css', array());
        drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/sample.js');

}}

```

My problem is that when the view is empty or when does not have any records the view is not loaded and thus I am unable to get the $view-\>name and neither are the css,js files being applied for the page.

It is working fine when the view displays a few records. So is there any other hook or method to fetch the view name or get it loaded when the records are empty ?

# Answer
---

I found out the solution to add files to specific 'View Pages'. Need to use hook\_preprocess\_page in template.php and check the view\_name. Here is the code that worked for me.

```
function mytheme_preprocess_page(&$variables){
if($variables['page']['#views_contextual_links_info']['views_ui']['view_name'] == 'my_view_name'){
    drupal_add_css(drupal_get_path('theme', 'mytheme') .'/css/sample.css', array());
    drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/sample.js');}

```
> 1 votes

---
Tags: views, theming, hooks
---


# Question
Title: Is it possible to publish from my local computer a node in my drupal page remotely?
I wonder if it is possible from a SH script on my local computer, publishing content on a remote installation of drupal.

Why have a gammu sms gateway and when a new sms on my local computer I want to be published in my drupal page.

This is an example of a script that warns of a new sms

```
    #!/bin/sh
INBOX=/path/to/smsd/inbox
PROGRAM=/bin/cat
for ID in "$@" ; do
    $PROGRAM < $INBOX/$ID
done

```

Could you do something similar to send this SMS to my remote drupal page?

# Answer
If you need to receive the sms on your local computer, and wish to create a new node on your production server using ssh rather than web APIs, then I would recommend that you do this with a custom Drush command that you write.

Start off by installing the drushify command on your local system (`drush dl drushify`).

Define the options and arguments for your command; for example, you might want to put the contents of the sms message in the command argument (name the argument variable `$body`), and specify any metadata in the options.

Next, fill in the implementation of your Drush command with your own code. This will look something like:

```
$node = new stdClass();
$node->type = 'my_sms_content_type'; // presumes you already made one of these with cck
node_object_prepare($node);
$node->body[$node->language][] = array('value' => $body, 'format' => 1);
$node->status = TRUE;
node_save($node);

```

Test the command locally with `drush @mysite.dev sms-add "Test sms"`

When satisfied, copy the Drush command to $HOME/.drush on the remote machine (where $HOME is the home folder of the remote user you define in your Drush alias), put a ssh public key in the appropriate .ssh directory, and run the command remotely with `drush @mysite.live sms-add "Test sms"`. Be sure to run `drush cc drush` when adding new Drush commands.

Your script then becomes:

```
for ID in "$@" ; do
    drush @mysite.live sms-add "$(cat $INBOX/$ID)"
done

```

You might be able to replace the custom Drush command with Drush Entity. Give it a try.
> 1 votes

# Answer
Do you already know this module : https://drupal.org/project/gammu
It seems to fit your needs :

> This module support Gammu database using same or separate Drupal database, even located on different server.

And it's provide with example.

Hoping that help.
> 1 votes

# Answer
See also: Code Server \- https://www.drupal.org/project/codeserver

> *Code Server* provides a framework for calling PHP functions on a Drupal site from code running on a different Drupal site.
> 1 votes

---
Tags: nodes
---


# Question
Title: drush sql-sync tries to rsync unknown dump file
Since I upgraded drush 5.10 -\> 7.0-dev today, sql-sync fails to work with my existing alias file.

Using the command `drush sql-sync @limelive @limedev` fails.

The `%dump-dir` paths on both local and remote aliases correctly address existing directories. --debug shows the remote sql dump success:

```
 Database dump saved to /home/aegir/drush-backups/limetreethornfor/20140411235252/limetreethornfor_20140411_235252.sql.gz

```

but later reports

```
rsync: link_stat "/var/aegir/platforms/aventura-2014-04-11-1/Array" failed: No such file or directory

```

This suggest new command syntax incorrectly diagnosed. What am I doing wrong?

# Answer
This is a bug in Drush master. Please put an issue in the queue on Github.
> 2 votes

# Answer
The bug has been reported here.

I used this workaround (dump remote db and import it to local db):

```
drush @example.prod sql-dump > /tmp/example.sql
drush sql-drop -y
drush sql-query --file=/tmp/example.sql
drush cc all

```
> 1 votes

# Answer
This is still a bug for me even in the Drush 7 stable release. I had to go back to Drush 6.6 and it works fine.
> 0 votes

---
Tags: drush
---


title: Node preview in a POPUP

text:
# Question
Title: Node preview in a POPUP
I Want to open node preview in popup,

Is it possible to display Node Preview in a pop up like colourbox or light box?

If anyone has solution Please let me know

Thanks..!!

# Answer
Take a look at the Colorbox node module. you could show any node or view in a colorbox.
> 0 votes

---
Tags: nodes, entities, javascript
---


title: Optimizing of DB resources

text:
# Question
Title: Optimizing of DB resources
I'm pretty excited about Drupal capabilities in general and consider it as probably the most solid free CMF with a really powerful API. One of the things I'm concerned about is the resources it takes. A basic installation with localization generates about 90 database tables (WordPress generates 11). Can this be optimized or, if it cannot be, does it really matter, does it affect performance?

# Answer
> 1 votes
Table count is not an indicator of optimization. It is actually opposite of what someone might think. Good database design breaks data up into multiple related tables that are kept small in field count. Drupal core has a very efficient relational database design compared to WordPress. I have experience with both platforms and your statement highlights what you must realize about Drupal. Drupal really is a content management framework, WordPress is a content management system. They are vastly different in their capabilities.

So to answer your question plainly, no optimization is required. It already is optimized for a relational database.

As always, choose the right tool for the project. Even though I am a Drupal developer I have recommended Wordpress to several clients. Because their needs and requirements could be satisfied with a simple Wordpress site.

---
Tags: performance
---


# Question
Title: Why aren't the options in my dynamically inserted webform showing up?
I've created a webform with one question that includes a list of checkboxes.

I made the webform available as a block, and am rendering the block in my template using:

```
<?php
$block = module_invoke('webform', 'block_view', 'client-block-#####');
print render($block['content']);
?>

```

However, when the form renders, I see the title of the question and the submit button, but the options are not visible. How can I debug why the checkbox options aren't showing up?

# Answer
I checked admin/reports/dblog and it turns out the select\_or\_other plugin wasn't properly installed, stopping the options from showing up at all.
> 0 votes

---
Tags: 7, blocks, webforms
---


# Question
Title: taxonomy image as background image on node
I have taxonomy images attached to node that I would to make me background image. Previously I used the images uploaded to the node as a background image.

This is the code I used to print out the image:

field\_image\[LANGUAGE\_NONE\]\[0\]\['uri'\]); ?\>);"\>

This what I thought it would be but I keep getting errors field\_departimage\[LANGUAGE\_NONE\]\[0\]\['target\_id'\]\['field\_image'\]\[LANGUAGE\_NONE\]\[0\]\['uri'\]); ?\>);"\>

Here's my array. Field\_image is the field name attached to the node that links to the taxonomy

# Answer
Looks like that field\_image is not under `target_id` try this:

`field_departimage[LANGUAGE_NONE][0]['entity']->field_image[LANGUAGE_NONE][0]['uri']); ?>);">`

However this not the best way to load field value, you should use field\_get\_items
> 1 votes

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


# Question
Title: Unable to view Taxonomy term page: Access denied
I am unable to view/see any Taxonomy term page in the front (Access denied).

I can edit Taxonomy in the admin backend.

**Example:**

http://localhost/{Taxonomy-group}/car

**Result:**

Page "Access denied - You are not authorized to access this page."

**Setup**

Alias URL (Taxonomy term paths)

Default path pattern (applies to all vocabularies with blank patterns below) `[term:vocabulary]/[term:name]`

**Tried but didn't work**

* Clear cache
* Rebuild permissions
* Update alias

Does anyone have any idea how to fix this issue?

# Answer
> 1 votes
Check out the Access Denied Backtrace module.

# Answer
> 1 votes
I'm encountering a similar issue on a localized site. The ADB module records an "Access Denied" occurence, but gives bo backtrace.

Workaround in my case: Overwrite the taxonomy term display with a view. It's not what I want, but I couldn't resolve the issue otherwise.

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


# Question
Title: How to use a between operator in an entity field query?
I wanna use a between operator. Can anyone tell how to use this? I am using it like this

```
$query->propertyCondition('nid', array(4, 3), 'between');

```

But it is also including node id 4 and 3, and I want to show only "2", which falls in between. How can this be done?

# Answer
If you want to include 2 then simply pass 2.

```
$query->propertyCondition('nid', array(2));

```

While using between operator, it includes the range values too. So you can just pass the range values you want to include. Still if you want to exclude these range then add one more condition like :

```
$query->propertyCondition('nid', array(1, 3), 'BETWEEN'); // 1, 3 to get the nid 2
$query->propertyCondition('nid', array(1, 3), 'NOT IN'); // exclude these nids

```
> 2 votes

---
Tags: database
---


# Question
Title: How to add Replace (mysql) function in view query condition field
I am using EntityReference Autocomplete with filter by entity reference view. And I want to ignore space in search filed.

For example, column `username` in DB has value `first name` it should popup when user types `first` or `firstname`. To achieve this I wrote `hook_views_query_alter` to change the condition, I would like to pass the condition as `REPLACE(username, ' ', '') LIKE '%firstname%'`.

Even if I set field value in condition to `REPLACE(username, ' ', '')` its getting changed to `REPLACEusername`. Even I tried running the query separately, like below in node,

```
$query = db_select('node', 'n')
              ->fields('n', array('title'))
              ->condition('type', 'article', '=')
              ->condition('REPLACE(n.title, \' \', \'\')', $category, 'LIKE')

```

When I output query prints like below,

```
    SELECT n.title AS title FROM {node} n WHERE (type = 'article') AND (REPLACEn.title LIKE '%articleone%' ESCAPE '\\')

```

How can I set it correctly? Is there any other way to do?

# Answer
> 1 votes
I don't think `condition` is what you want, rather `expression`. And then, to use that expression as a condition, you might need to use `havingCondition`-- but I'm not sure, test it out. Also note that you need `%` for a wildcard matching in SQL, so you might have to do `->havingCondition('title', '%' . $category . '%', 'LIKE');`.

So, your final code might look something like this:

```
$query = db_select('node', 'n')
  ->addExpression('REPLACE(n.title, \' \', \'\')', 'title')
  ->condition('type', 'article', '=')
  ->havingCondition('title', '%' . $category . '%', 'LIKE');

```

---
Tags: 7, database, views
---


# Question
Title: How to add a page redirect in Drupal htaccess file or otherwise?
I've built a Drupal website to a replace an old website (not in Drupal) and some of the pages changed urls. I need to create redirects for those pages.

I've thought of using Drupal's `.htaccess` file and have the following:

```
RewriteCond %{HTTP_HOST} ^www.example.com/old-page-name$
RewriteRule ^$ http://www.example.com/new-page-name [L,R=301]

```

But that didn't work.

I've added those lines inside the redirect block in Drupal's htaccess:

```
<IfModule mod_rewrite.c>
</IfModule>

```

Just under these rules:

```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

```

This will be a temporary solution until I install the redirect or some other module.

# Answer
> 1 votes
I'd suggest you consider the Rules module as that "other module" you are looking for. Using an approach as described in my answer to the question "How to use the Rules module to implement a custom redirect for an outdated URL?" ...

Using that technique, you can also solve your requirement about it being "temporary" (that's just a matter of some appropriate rules **Condition** to be added in your case).

---
Tags: 7, redirection, .htaccess
---


title: Instance based date field granularity

text:
# Question
Title: Instance based date field granularity
In my web application (Drupal 7) I'm using a date field with year-month-day granularity, but I would like, for a specific content type, to add also hours and minutes.

1. Is this possible to achieve? How?
2. Is this safe or it'll mess with the other content types, existing views etc.?

I've thought of adding an extra time only field, so I've checked some modules like CCK Time or Timefield, but they don't seem maintained anymore (last release is about two years old).

**Use case:** I have an "Absence" content type. When a student is absent, the teacher selects the day when the student is absent, hours and minutes aren't needed. I'm now creating an "Early exit" content type: if a students has to go out from school before the regular school day end, in that case the teacher need also the time when the student left the school. As an alternative I was thinking on two integer fields (hours and minuter), but it doesn't sound as an optimal solution to me.

# Answer
> 0 votes
Date module has the ability to add time field with the same field , I think you need to enable that in the field settings. see screenshot:

---
Tags: 7, entities
---


title: How do I render field outside node

text:
# Question
Title: How do I render field outside node
For custom content type page I used this:

```
function MYTHEME_preprocess_page(&$vars, $hook) {
    if (isset($vars['node'])) {
      // If the node type is "blog_madness" the template suggestion will be "page--blog-madness.tpl.php".
      $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
    }
}

```

So now it means I can use page.tpl.php for my custom content type pages. So for the default Basic Page the template page is page--page.tpl.php and I did test it and it works. Except this:

I am trying to render some field outside . So I used this: `<?php print render($content['field_banner']); ?>` right outside `<div id="content" class="column" role="main">` but it's not printing.

I was told this has something to do with node\_load. But I'm not experienced with that.

# Answer
> 0 votes
You will need to load the node object to get the field value, something like this:

```
$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

```

# Answer
> 0 votes
You can load node again in other place and render it fully or partially. Via block or something else. Node load is hard operation, use module entitycache to load the same nodes faster.

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


# Question
Title: Create user programatically after e-mail verification
I am programatically creating user with this code:

```
    $new_user = array(
        'name' => $state['unique_name'],
        'mail' => $state['values']['email'],
        'pass' => $state['values']['password'],
        'status' => 1,
        'init' => $state['values']['email'],
        'roles' => array($role->rid => $role->name),
    );

    $account = user_save(NULL, $new_user);
    _user_mail_notify('register_pending_approval', $account);

```

This code is creating user and should send verification email, after which user should be able to log in. Problem is that users are able to log in immediately.

> Please note that I work on localhost and cannot send email from localhost. I will have very little time to test site on real server, so I would like to know the solution in advance.

The solution could be this approach:

> The only way I was able to accomplish this was by setting the users' status to 0, then sending a custom email with a link to a custom verification page. The link contains the ID of the user and a hash of a private key concatenated with the user's email. On the verification page, I pull the user's email from the database based on the ID in the URL, concatenate the private key to the email and hash it, if the hash matches the hash in the URL, I set the user's status to 1, enabling the user to login.

But the next question is how to generate that "private key" from user database datas and from email link. I can't see any private key of user in drupal database.

# Answer
> 1 votes
you don't get private keys from the database because Drupal doesn't store them.

try looking up in `settings.php` for the `$drupal_hash_salt` variable. that's the one used to encode/decode strings.

hope this helps.

cheers

# Answer
> 1 votes
I found out by exploring user.module that this "private key" can be generated by user\_pass\_rehash function.

# Answer
> 1 votes
I suggest you use SMTP module to allow your site to send email using your GMAIL account.

Secondly you encrypt the user id(uid) using any symmetric key algo (here) and send the link to confirm. During confirmation just decrypt the uid and enable it. So simple!

# Answer
> 0 votes
I may be obvious, but the problem is that you are sending the wrong email to the user. You should use

```
_user_mail_notify('register_no_approval_required', $account);

```

You are currently sending an email to the user that is pending administrative approval. Also for `user_save()`, pass an empty string for the account instead of NULL `user_save('',$new_user)`. It should not have an effect, but most of the user save code uses `empty()`.

---
Tags: users, emails
---


# Question
Title: How to render specific block from template without rendering entire region
I'm attempting to render a specific block on a page without rendering the region. I'm assuming the machine name of the block is 23 based on the URL I get when configuring the block.

```
example.org/admin/structure/block/manage/block/23/configure

```

I'm attempting to grab the block using the information I've found here

https://www.drupal.org/node/26502

My attempt at it is

```
$block = module_invoke('block','blockview',23);
print render($block['content']);

```

But I'm not having any luck.

# Answer
> 2 votes
Almost there it's `block_view` not `blockview`

```
$block = module_invoke('user', 'block_view', '2');
print render($block['content']);

```

---
Tags: 7, blocks
---


# Question
Title: Describing an Entity Reference relationship
I'm wondering how to describe, or add extra information to a Entity Reference relationship between two content types.

I have 'event' and 'people' content types. An event can have many people, and each person can be an either an organizer, presenter, facilitator, etc.

How can I model this relationship? Do I need to have an Entity Reference field for each type of relationship, or can I add the type of relationship as a parameter of a single Entity Reference?

Thanks!

# Answer
If you want to stick with Entity Reference, you'll need to have a field for each type of relationship. ER relationships don't have the capacity for meta data.

If you can change, check out the Relation module.

> Relation is an API module and storage model for both simple and the most complex relations between entities. The module can handle both directional and symmetrical relations very well.
>
> **Relations are entities and can therefore have fields**. This makes Relation the most flexible and powerful relation model out there. (Still, using Relation with anything but the default SQL storage will not work in most cases.)

(emphasis mine). You could, for example, attach a field to the relation entity type, that linked to a vocabulary containing the event role.
> 1 votes

---
Tags: entities
---


# Question
Title: How can we assign points to users in the site?
I want to give points to users in the site, like if a user creates an account then he should be awarded some points even if I want to award points for the activities like if user visits a page, if a user posts a comment etc.

# Answer
> 3 votes
There is a module for that, userpoints

Also using Rules to assign them for certain actions is common with that module.

---
Tags: users
---


# Question
Title: What is the good way to pass a value from form creation function to its submit handler?
I am newbie in Drupal, I have a query that i want to pass some value from form creation function to its submit handler.

Right now, I am saving that value in a form element of hidden type.

```
$form['product_nid'] = array(
 '#type' => 'hidden',
 '#value' => 12,
)

```

But this is not safe, anyone can change value on client side.

# Answer
> 2 votes
It is easy to do by using $form\_state\['storage'\],

Just define $form\_state\['storage'\]\['something'\] = ; This value will not show in browser and You will get this value in submit handler. see this code you will understand.

```
/**
 * Returns the form.
 */
function my_module_form() {
  return drupal_get_form('my_module_my_form');
}

/**
 * Returns the render array for the form.
 */
function my_module_my_form($form_state) {

  $form_state['storage']['product_nid'] = 12;

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

/**
 * Add a submit handler/function to the form.
 *
 * This will add a completion message to the screen when the
 * form successfully processes
 */
function my_module_my_form_submit($form, &$form_state) {
  $product_nid = $form_state['storage']['product_nid'];
}

```

# Answer
> 2 votes
Use `value` instead, like this:

```
$form['product_nid'] = array(
 '#type' => 'value',
 '#value' => 12,
)

```

Elements of `value` type are never send to HTML, they are there just for what you are doing - passing values not meant to be changed by your user or scripts.

For complicated data, use answer by Akash Jain instead. Way he proposed is the only practical one for objects and arrays. On the other hand, for simple strings or integers it's too complicated. Especially if later they are meant to be treated in the same way as user input. Then, use `value` fields.

---
Tags: 7, forms
---


# Question
Title: How to create a redirect to point to the user's id?
I'd like to create a redirect so when the user hits `mydrupal.com/my-account` its redirected to `mydrupal.com/users/3`

I'm using Pathauto and I know I can go to `admin/config/search/path/add` to add the redirect but I can't get it to point to the user id as variable. For instance, in the `existing system path` option I thought I could add `users/[uid]` but that didn't work.

Any suggestions?

# Answer
Instead of redirecting the `mydrupal.com/my-account` to particular user ID as `mydrupal.com/users/3`

You should redirect them to `mydrupal.com/user` which will lead them to thier profile page if the user is logged in.
> 5 votes

# Answer
As an alternative, you could also use the Rules module for this.

Here is the rule you'd need for it (in Rules export format, just use copy/past to import it in your own setup):

```
{ "rules_redirect_an_old_path_to_a_new_path" : {
    "LABEL" : "Redirect an old path to a new path",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "the_old_path",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Sorry, the old path (= /the_old_path) is no longer in use, you will be redirected automatically to its corresponding path (= /the_new_path)" } },
      { "redirect" : { "url" : "the_new_path" } }
    ]
  }
}

```

A few more tweaks to make it fit your exact scenario:

* change all occurences of `the_old_path` to `my-account`.
* change all occurences of `the_new_path` to `user`.

Whenever such redirect actually happens, the user will also receive an informational message like so:

> *Sorry, the old path (= `/my-account`) is no longer in use, you will be redirected automatically to its corresponding path (= `/user`)*

If you don't want such message to appear, then just delete the line containing `drupal_message` in the exported rule above.

**Note**: No Pathauto involved using this approach, just Rules.
> 3 votes

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