# Question
Title: Changing the confirm delete message for comments
I have a website where I have comments on certain content but I am not allowing any replies to these comments. When deleting a comment the confirm delete message shows as

'Any replies to this comment will be lost. This action cannot be undone.'

This is not ideal because obviously there will never be any replies.

I have found the function which creates the text for the message on line 257 of comment.admin.inc

```
function comment_confirm_delete($form, &$form_state, $comment) {
  $form['#comment'] = $comment;
  // Always provide entity id in the same form key as in the entity edit form.
  $form['cid'] = array('#type' => 'value', '#value' => $comment->cid);
  return confirm_form(
    $form,
    t('Are you sure you want to delete the comment %title?', array('%title' => $comment->subject)),
    'node/' . $comment->nid,
    t('Any replies to this comment will be lost. This action cannot be undone.'),
    t('Delete'),
    t('Cancel'),
    'comment_confirm_delete');
}

```

How would I go about changing this text. Could I use template.php? If so how would I find the correct preprocess function. And then what is the way in which I could best find the variable in its current state in order to change it?

# Answer
You can do this with hook\_form\_alter(). https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_form\_alter/7

Just add an if statement to check if the $form\_id is 'comment\_confirm\_delete', then you can alter anything in the $form object, including the text.
> 0 votes

---
Tags: comments
---


title: Devel's dsm & dpm not working

text:
# Question
Title: Devel's dsm & dpm not working
I am trying to print out the $view object using devel and dsm.

My function in function.php is

```
function my_theme_views_pre_render(&$view) {

  if ($view->name == 'my-view') {
     dsm('$view');
  }
}

```

But I just get this message below, there is nothing inside the message, the html is

```
<div class="alert alert-block alert-success" data-thmr="thmr_137">
  <a class="close" data-dismiss="alert" href="#">×</a>
  <h4 class="element-invisible">Status message</h4>
  <ul>
    <li><pre>$view</pre></li>
  </ul>
</div>

```

# Answer
You are dsm'ing a string, try `dsm($view);`
> 2 votes

# Answer
use dpm() instead like written here dsm()
> 0 votes

---
Tags: debugging
---


# Question
Title: How to change term reference field according to role?
I have the following challenge: I have 4 roles, let's call them **Group1** ... **Group4**. I have different content types and I segregate access of those types using the Taxonomy Access Control module. So users from Group1 can only view and edit nodes that have term Group1.

Now, I have the challenge to change a term reference field of these content types automatically. So if a user from role **Group1** creates a new node, that node will have a term reference field with term **Group1**.

I don't want users to edit on their own to avoid human errors.

# Answer
> 0 votes
All you need to do is create separate fields for respective roles. Use Field permissions module. Or if you want to have role wise access like from editor -\> moderator -\> pulisher etc. Use workfolw module.

# Answer
> 0 votes
Use the Rules module to create 4 similar rules (1 for each group), which would look like so (for Group1):

* Event: before saving content
* Condition: user has role Group1
* Action:
    1. Set a data value.
    2. Select the taxonomy term reference field to set.
    3. Select the taxonomy term 'Group1' (if needed: use the "Switch to the direct input mode" button to reveal the terms available in your taxonomy).

Repeat the above steps for Group2, 3 and 4 to create a similar rule.

You might want to try to consolidate those 4 (similar) rules in a single rule, by using the Rules Conditional module: the condition for each group would be replace by a similar "if condition" (contained in the rules action), and the Rules action for each group would only be executed if the "if condition" would be true. For a sample using the Rules Conditional module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

---
Tags: taxonomy-terms
---


# Question
Title: I can rsync with drush but not `drush @remote status`
I know it's not equivalent, but I can `drush rsync @local @remote` but not `drush @remote status -v`. So my ssh keys are in place, I'm on the right port etc.

I get:

```
Loaded alias @remote from file /Volumes/Users/blah/.drush/aliases.drushrc.php
Begin redispatch via drush_invoke_process().
Calling proc_open(ssh -p 22009 BLAH@xxx.xxx.xxx.xxx 'env COLUMNS=238 drush  --verbose --root=/home/REMOTE/d7 --uri=d7.REMOTE.co.uk  core-status 2>&1' 2>&1);

env: drush: Permission denied

```

What do I need to set on @remote to make it work? Drush is installed there (same version) and works happily.

Is there are Drush error log or will I need to get the hosting company to have a look through logs?

Here is my alias:

```
$aliases['REMOTE'] = array(
   'root' => '/home/REMOTE/SUBDIRECTORY',
   'uri' => 'http://REMOTE.co.uk',
   'remote-host' => 'xx.xx.xx.xx',
   'ssh-options' => '-p 22009',
   'remote-user' => 'SSH_USER',
   'path-aliases' =>
   array (
      '%drush' => '/home/REMOTE/.composer/vendor/drush/drush',
      '%site' => 'sites/default/',
      '%dump-dir' => '/home/REMOTE/drush.dbdumps',
   ),
   'databases' =>
   array (
      'default' =>
      array (
         'default' =>
         array (
            'database' => 'xxx',
            'username' => 'xxx',
            'password' => 'xxx',
            'host' => 'localhost',
            'port' => '',
            'driver' => 'mysql',
            'prefix' => '',
         ),
      ),
   ),
);

```

# Answer
> 1 votes
The first thing to do is to ensure that the 'remote-user' in your site alias is the same user that you use when you log in to the site.

The next thing to check is whether or not `drush` is on your $PATH on the remote site. You have probably set this up explicitly in a .bashrc file, since it is working when you log in locally. However, often, .bashrc files exit early when called in non-interactive mode, as Drush does.

Perhaps the easiest way to get around this is to figure out what the correct full path to the `drush` script is, and set '%drush-script' in the 'path-aliases' of your site alias to point at the correct executable. See example.aliases.drushrc.php.

**UPDATE:** Use '%drush-script', not '%drush'.

'remote-user' is the user that Drush will use to log in via ssh. It should be a user that has permission to use Drush. Some people use the webserver user for this, but if you have a separate web admin user, that would be a preferable choice.

---
Tags: drush
---


# Question
Title: How to style a webform like a spreadsheet?
I've been asked to develop a webform to look like a spreadsheet. Unfortunately, the site is written in D6 and I've only really developed in D7.

Can anyone recommend a module / method to achieve this?

# Answer
It sounds like you're looking for Webform Table Element that will render your webform inside a table.

> This module will add a new component to Webform module that allows you to render multiple components inside a table element.
> 1 votes

---
Tags: 6, webforms
---


title: trigger colorbox on view page load

text:
# Question
Title: trigger colorbox on view page load
What if I just want to trigger the first colorbox on a view page? maybe with js injector module.

```
  Drupal.behaviors.commerce_kickstart_theme_custom_mytest = {
    attach: function(context, settings) {
        $(document).ready(function() {
            $('.view-promoted-to-front-2 .views-row-1 > .views-field-rendered-entity .node-product-display .field-group-colorbox-trigger').trigger('click');
         });
    }
  }

```

# Answer
> 1 votes
You may not use the js injector module. Colorbox integrates seamlessly well with views. If you are displaying content as fields in the view (which I think you are) you can use the :

Fields -\> Add

option to introduce a colorbox trigger.

For example, Lets consider the below fields :

The first item "Content : Gallery Image Upload" has the following settings

The second item "Content : Gallery Image Upload" has the following settings

and you set up your colorbox trigger like below :

The replacement pattern is all that matters here. If you are confused what to put for **popup**, scroll all the way down to Replacement Patterns and select appropriate field and paste it in the **popup** box. Here the trigger field is the the first "Content : Gallery Image Upload" field and when somebody clicks it we are introducing a colorbox trigger to start the colorbox slideshow configured for the second "Content : Gallery Image Upload" field.

In short, we are setting up a Gallery here. :)

---
Tags: views, javascript
---


# Question
Title: best practice for email validation in form alter drupal 7
What is the best recommended drupal way to validate an email is input on a new field I added in drupal settings page? Here is the code I have now:

```
function MYMODULE_form_uc_order_settings_form_alter(&$form, &$form_state, $form_id) {   $form['MYMODULE_uc_order_template_email'] = array(
'#title' => t('Template Email'),
'#default_value' => variable_get('MYMODULE_uc_order_template_email', 'test@example.com'),
'#description' => t("Template Email"),
'#type' => 'textfield',
 );

```

}

# Answer
The function `valid_email_address($mail)` in D7 validates any email passed into it. If you need to validate a new email field from a form altered form, you can add a validation handler to your newly add email field to ensure that it is valid. Just append to the `$form['#validate']` array the function you want called for validation.

```
function MYMODULE_form_uc_order_settings_form_alter(&$form, &$form_state, $form_id)
  //@TODO: Other form modifications
  $form['#validate'][] = 'MYMODULE_form_uc_order_settings_form_validate';
}

```

Then in your form validation function, check the value of the submitted field with `valid_email_address($mail)`.

```
function MYMODULE_form_uc_order_settings_form_validate($form, &$form_state) {
  if (!valid_email_address($form_state['values']['MYMODULE_uc_order_template_email'])) {
    form_set_error('MYMODULE_uc_order_template_email', 'Not a valid email address');
  }
}

```
> 1 votes

---
Tags: forms
---


title: How to override hook_page_build?

text:
# Question
Title: How to override hook_page_build?
I have below code coming from External Link module in Drupal 7:

```
/**
* Implements hook_page_build().
*/
function extlink_page_build() {
   $path = drupal_get_path('module', 'extlink');
   drupal_add_js($path .'/extlink.js', array('every_page' => TRUE));
   drupal_add_js(array('extlink' => array(
     'extTarget'     => variable_get('extlink_target', 0),
     'extClass'      => variable_get('extlink_class', 'ext'),
     'extLabel'      => check_plain(variable_get('extlink_label', t('(link is external)'))),
     'extImgClass'   => variable_get('extlink_img_class', 0),
     'extSubdomains' => variable_get('extlink_subdomains', 1),
     'extExclude'    => variable_get('extlink_exclude', ''),
     'extInclude'    => variable_get('extlink_include', ''),
     'extCssExclude' => variable_get('extlink_css_exclude', ''),
     'extCssExplicit' => variable_get('extlink_css_explicit', ''),
     'extAlert'      => variable_get('extlink_alert', 0),
     'extAlertText'  => variable_get('extlink_alert_text', 'This link will take you to an external web site. We are not responsible for their content.'),
     'mailtoClass'   => variable_get('extlink_mailto_class', 'mailto'),
     'mailtoLabel'   =>   check_plain(variable_get('extlink_mailto_label', t('(link sends e-mail)'))),
   )), 'setting');
}

```

I want to add below code from above function only if my some condition is true (which will be based on some user filed) , without overriding files of module it self:

`drupal_add_js(array('extlink' => array(
 'extTarget' => variable_get('extlink_target', 0),)), 'setting');`

I am not getting any solution how to override this function thorough my custom module, Please suggest !

To make more clear I just want to add condition in above function so that js will only get added if condition according to user field is true.

**UPDATE: I have tried like below code but its not working, please suggest what I am doing wrong** My custom module name: `custom_overrides`

```
function custom_overrides_page_alter(&$page) {
   global $user;
   $userid = $user->uid;

    if($userid){
        $path = drupal_get_path('module', 'extlink');
        drupal_add_js($path .'/extlink.js', array('every_page' => TRUE));
        drupal_add_js(array('extlink' => array('extTarget' => variable_get('extlink_target', 0),)), 'setting');
  }
}

```

Thanks!

# Answer
Finally I found solution to my question in this way:

```
function news_js_alter(&$javascript) {

   $path = drupal_get_path('module', 'extlink');
   global $user;
   $userid = $user->uid;
   if (!$userid) {
    unset($javascript[$path . '/extlink.js']);
   }
}

```

Module was adding js settings, so I wanted to add only when user was loged in, so now in my theme **news** I have added above code in **template.php** and it worked. May this help other users trying to solve similar conditions.

Thanks!
> 0 votes

# Answer
In hook\_page\_alter you can override *js* settings just by using *drupal\_add\_js* like you pasted above.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: Delete permissions not working with Domain Access instaled
I have a site with Domain Access module installed. I have created an Admin View, which lists types of content (exposed filter). My surprise is that a role, which is Editor (a kind of Authenticated user), and which in permissions has only Edit permissions for that kind of content, is able to Delete the node, when he/she would not be allowed according to the permissions. I have rebuilt permissions, and there appears the Delete link, and it also performs the deletion. How can I check it, maybe at low level database?

# Answer
> 0 votes
For some unknown reasons, I had this option checked under Permissions: `Delete any content on assigned domains`. Obviously, it overrided every other permission filtered by content type. Unchecking it, the "Delete" link only appeared on the Admin role, which is what I wanted.

---
Tags: users
---


title: Login Process Redirect Back to Page

text:
# Question
Title: Login Process Redirect Back to Page
I'm working on a process to prompt users to a login when clicked on a link first. For instance, if click on http://www.example.com/tester, the user will be prompted to log in. After loggin in, the user will be redirected to the current page http://www.example.com/tester.

I've tried LoginToboggan as well as Login Destination.

Login Destination should allow for "current" but it doesn't work.

Both of the modules have similar ways to do it i'm sure.

# Answer
> 0 votes
Check Redirect 403 to User Login

> Redirect the HTTP 403 error page to the Drupal /user/login page with an optional message

# Answer
> 0 votes
The CustomError module allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without creating nodes for each of them. Some more details about its features (from its project page):

> * Configurable page title and descriptions.
> * There are no author and date/time headers as with normal nodes.
> * Any HTML formatted text can be be put in the page body.
> * The error pages are themable.
> * Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
> * Allows custom redirects for 404s.

You'll probably be interested mostly in the part about "*Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.*".

# Answer
> 0 votes
Possible duplicate

Looks like your solution lies in getting the previous URL from `$_SERVER['HTTP_REFERER']);` Which will get the previous page the user was on.

However the way you word it makes it sound like you want to go from example.com/a when a user clicks a link to go to example.com/b and they aren't logged in you intercept that request to login then continue on to example.com/b

In which case wouldn't it make sense to

1. check if user logged in?
2. if false store the url that was clicked in a cookie
3. present the login screen you have
4. manually set the redirect URL upon success

---
Tags: users, redirection
---


# Question
Title: How do I hide nodes that shouldn't be directly accessed from users and search engines?
I've found that there are times I have a node that simply contains content that will be displayed somewhere else, but shouldn't be viewed directly. That is, no one should ever go to node/1234, but the content in node 1234 should be displayed somewhere else. For example, I create an about page with tabbed content using views. So there are "About Me", "About Us" and "About Them" pages. All of these are displayed in a single page with tabs using Views. So I don't want people to get directly to the "About Us" node because then they wouldn't see the tabs for the other pages. At the same time, I don't want Google giving people a direct link to this node, I want to limit access so users can only get to it through the View (i.e., the tab).

So I need to restrict access to the node, remove it from the Drupal search results, and make sure Google doesn't pick up on it. Any suggestions?

# Answer
This sounds to me like a good use case for the Panels module because you can create panels that will override node pages, and can set the context for the panel in a way should guarantee users see the page you want them to see it as well as access rules for panel pages if you need them. For further details, see this post on d.o.
> 28 votes

# Answer
The Rabbit Hole module provides this feature.

> Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
>
> Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.
> 32 votes

# Answer
One option may be to never publish the node but have the *consumer page* ignore their publication status. So in your example, your *About* view may just ignore the publication status of your *About-xxx* nodes. Since the nodes are not published, they shouldn't be indexed by the search engine.

Another solution is to use `hook_nodeapi('view')`/`hook_node_view()` to issue a `drupal_goto()` or `drupal_access_denied()` when the node page is visited by an unauthorized users. Be aware that `hook_nodeapi()`/`hook_node_view()` are used in many cases and not only when viewing a node page.

`hook_menu_alter()` can also be used to alter the access callback of the node pages to deny access to the *hidden* nodes.

The best is probably not to base the filtering on hard-coded node ID but to use either a custom field on the node (using CCK/Field API or a custom table) or a list of *hidden* nodes stored in a variable.
> 12 votes

# Answer
For Drupal 7, the Rabbit Hole provides this feature.

> Rabbit Hole is a module that adds the ability to control what should happen when en entity is being viewed at its own page.
>
> This works by providing multiple options to control what should happen when the entity is being viewed at its own page. You have the ability to
>
> 1. Deliver an access denied page.
> 2. Deliver a page not found page.
> 3. Issue a page redirect to any path or external url.
> 4. Or simply display the entity (regular behavior).

How to :

Enable **Rabbit Hole nodes** submodule Then we will get config section associated with every form in Drupal CODE
> 6 votes

# Answer
Solved. First I tried Pierre Buyle answer, but if you unpublish a node, it can't be propper accessed and those nodes become useless. In my case I have parent and child nodes, only child nodes (for admin purposes) are the ones to be hidden and NOT be indexed by crawlers. What I did it with page manager made a url redirect (hiding these nodes to all users but admin) with a http response according to this tuturial by http://www.wunderkraut.com/ and no-index nodes by crawlers is handleled by Node no-index module. This will work even if you don´t have paret-child node relationship. Link to tutorial:
> 5 votes

# Answer
In Drupal 7, it should also be possible to use hook\_node\_access(), this is a normal hook in D7 which can be implemented by all modules for all node types. Then you can deny access if the user is trying to view the node on his own node/nid.

You probably also need to implement hook\_query\_node\_access\_alter() and add a check there to hide the node in search results. This might even be enough on it's own and you don't need hook\_node\_access(). And it might even work in D6 because you can alter the query there too but it's much easier in D7 because of the query builder.
> 3 votes

# Answer
Simply set those node as 'unpublished', then, in the view add the filter 'node published: no'.

As seo note, is a good practice to create a custom content type for those 'ghost' nodes, and tell pathauto to give them specific urls (i use `/dev/null/[title-raw]` ;): even if the node is unpublished, it will have its own url alias, so in your example if you create first the ghost node 'about us', and then the view page 'about us', the second's url will be `example.com/about-us-0` becose `example.com/about-us` has been taken from the ghost one (however, you can set the paths manually)
> 2 votes

# Answer
You could use any kind of node-access system and use views3. There you can't disable sql rewrite on the query settings and so you can disable the node access system on this view.
> 2 votes

# Answer
You can do by using the rules modules.
\+ Create new rule with "Content is viewed" event.
\+ Add a couple conditions for example: User has role(s) : anonymous, Path has URL alias : node/xyz (this is the node that you want to limit for anonymous user). Remember add "and" or "or" condition if it is needed.
\+ Create action for redirect to another page or do something else. This is the sample code that i exported for you

```
{ "rules_limit_viewing_some_nodes" : {
  "LABEL" : "Limit viewing some nodes",
  "PLUGIN" : "reaction rule",
  "REQUIRES" : [ "rules", "path" ],
  "ON" : [ "node_view" ],
  "IF" : [
     { "user_has_role" : {
       "account" : [ "site:current-user" ],
       "roles" : { "value" : { "1" : "1" } }
      }
     },
     { "AND" : [] },
     { "path_has_alias" : { "source" : "node\/28" } }
   ],
   "DO" : [ { "redirect" : { "url" : "error" } } ]
 }
}

```
> 2 votes

# Answer
I think the easiest way to accomplish what you want is to use Page manager (Ctools), is really simple to use, all you have to do is to specify which node to redirect where (in this case, from one node to another)
> 1 votes

# Answer
The Content Access module will suite your requirement perfectly.

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

It also has a good documentation to help you get started.
> 1 votes

# Answer
If your "included content" nodes need to stay inaccessible, then consider blocking /node/\* on the **webserver** "location = /node/\*" **level**. Default deny access to all /nodes. Default allow access to nodes that received a path-auto path like /pages.

(The basic .htaccess password for subdirectories is a decent way of blocking accidental search indexing by external crawlers, too.)

You can never guarantee that a node will not become accessible via a contributed module that happens to be installed in the future, or one that you do not fully understand yet. (Search results, listings, default views, taxonomy category overview ...)

It is what nodes are for.

Is the privacy of your "included content" that important to you? If so, then ...

1. **Everything that has an URL will eventually be hit by google.**

Because search engines do not rely on link spiders alone. They also evaluate browser feedback etc. No robot.txt, or pathauto, globalredirect, rabbithole module will help you sleep in peace. If the node can be accessed, then it will be indexed. Maybe by your own browser/addons.
2. **Reconsider if "content that is to be included" should really be a node**, *if noone should access it as a page*?

If your "included content" would be stored inside a mini-panel/block/snippet/bean/..., then you are at a much lower risk of it ever being listed, or ever appear as a page *with an automatic URL you don't know about*, yet. (taxonomy overview pages, search, views ...)
> 1 votes

---
Tags: nodes
---


# Question
Title: How to show/hide "printer-friendly version" link according to workflow states?
There's a review content type on my site with a workflow: I use '**draft**' and '**completed**' workflow states.

I'd like to create a printer-friendly and pdf-version of '**finished**' reviews only, so I'd like to hide the links generated by Print module in any other case. I tried to modify `MYTHEME__preprocess_node()` to achive this with this code, but it didn't work:

```
if($vars['field_review_workflow'][0]['value'] == '13'){ //sid of 'finished' state
  show($vars['elements']['links']['print_html']);
}else{
  hide($vars['elements']['links']['print_html']);
}

```

How could I do it properly?

# Answer
> 2 votes
One way of doing it is by using hook\_node\_view\_alter(). For example, you would put the following code in a custom module called `hideprint` (see many tutorials online on how to create a custom module). **Be sure** to `dpm()` the array `$build` when you are testing the module to correctly check the value of field\_review\_workflow.

```
function hideprint_node_view_alter(&$build) {
  if ($build['field_review_workflow'][0]['#value'] == TYPE_VALUE_FOR_NOT_FINISHED){
    hide($build['links']['print_html']);
    hide($build['links']['print_pdf']);
  }
}

```

# Answer
> 1 votes
There's a module for that! Workflow Fields

> This module extends Workflow by allowing CCK node fields to be made invisible or read-only depending on the current workflow state. The workflow state form is extended to show all node fields with appropriate controls to hide and/or disable each field for that particular state.
>
> This functionality is useful when a workflow moves among users who have different permissions regarding the document flowing through them. Which is the case in most every workflow we've encountered.

# Answer
> 1 votes
After all, my approach has been proved to be useful too. Hiding of these links can be done in `MYTHEME_preprocess_node()` but `content` array should be used:

```
if($vars['field_review_workflow'][0]['value'] == '13'){ //sid of 'finished' state
  show($vars['content']['links']['print_html']);
}else{
  hide($vars['content']['links']['print_html']);
}

```

Anyways, thank you all for the input.

---
Tags: 7, theming, workflows
---


# Question
Title: hide field based on its value or value of another hidden field
I need to hide a radio button field of a content type (not a form) only on the edit view based either on its own value or based on the value of another field that is already hidden.

Dependencies does not work, I think because the other field is already hidden and because it does not allow the dependent and dependee field to be the same field.

Any ideas?

# Answer
> 0 votes
You can give a try to this module: https://www.drupal.org/project/ffc

# Answer
> -2 votes
You may want to try hook\_form\_alter on that particular form. For example i had a case where i wanted a field to only show if it had more than one taxonomy term

```
    function members_form_members_node_form_alter(&$form, &$form_state,$form_id){
if(count($form['field_church_']['und']['#options']) > 1){
 $form['field_church_']['und']['#required'] = TRUE;}
     else{
    unset($form['field_church_']);}
return $form;}

```

---
Tags: entities
---


# Question
Title: How make a standalone field with no Entity or Bundle?
I want to add a custom configuration form to my module; I don't know if making a custom schema is better or if I should make a standalone field and use its different field APIs to deal with the value.

Can I create a standalone field with no entity or bundle? If I can't, what would be the alternatives?

# Answer
Take a look at system\_settings\_form and how it is used by other modules to create a basic form and field for module configuration. It'll generally use variable\_get and variable\_set to get and store it's value.
> 1 votes

---
Tags: entities
---


# Question
Title: How can a site programmatically detect if cron has not run in a long time?
I'm developing a module intended to proactively warn the admin if there are problems with the site. The idea is to periodically check the system status report and sends an email notice if certain statuses have gone from REQUIREMENT\_OK to REQUIREMENT\_WARNING or REQUIREMENT\_ERROR. I'm planning on firing this check in hook\_cron().

But what if the problem with the site is that cron is broken? What is a safe and performant way for the site to periodically check if the 'cron\_last' variable is too old, that doesn't rely on cron?

I would like to keep the module self-contained and avoid external dependencies or "phone home" solutions.

# Answer
> 3 votes
> What is a safe and performant way for the site to periodically check if the 'cron\_last' variable is too old, that doesn't rely on cron?

As said before by @Clive, you a script running periodically to do this check for you. Having said so, the simplest way is to create a basic module that checks the last time Drupal Cron ran succesfuly and acts based on that. You could include a drush command so you can call it via a server cronjob. E.g.

## Check if cron hasn't run in X minutes and send e-mail if so, using Drush

1) Create a file named `cronwatch.drush.inc`

2) Create the drush command that you will invoke via a crontab / automated task in your server. For instance, you would be running `drush cronwatch` every X minutes.

```
/**
 * Implements hook_drush_command().
 */
function cronwatch_drush_command() {
  $items = array();
  $items['cronwatch'] = array(
    'description' => dt('Check last time Drupal cron ran and send an email if necessary.'),
  );
  return $items;
}

```

3) Add a function to check *if Drupal Cron hasn't run in longer than X minutes, send an alert email.*

```
/**
 * Callback function for drush cronwatch command.
 */
function drush_cronwatch() {
  // Minutes since the last time cron run.
  $last_cron = variable_get('cron_last', 0);
  $minutes_ago = (time() - $last_cron) / 60;

  // How many minutes to allow without having run the cron.
  // This number should be larger than the frecuency of Drupal cron. E.g. If
  // Drupal cron is set to run every 60m, this number could be 70.
  $tolerance = 70;

  // If the cron last ran longer than tolerance minutes ago, it means that it
  // probably failed.
  if ($minutes_ago >= $tolerance) {
    $to = 'you@example.com';  // E-mail to get the alerts
    $message = t('Drupal cron could not run successfuly. Last succesful run was !minutes minutes ago.', array('!minutes' => floor($minutes_ago)));
    drush_mail_send_email($to, 'Drupal Cron failed', $message);
  }
}

```

4) Finally, this is the function to send an e-mail via drush:

```
/**
 * Send an e-mail to a specified e-mail address from within Drush.
 * @see http://drupal.org/files/mail.drush_.inc__0.txt
 */
function drush_mail_send_email($to, $subject = '', $body = '') {
  // Define $from and headers
  if (!$from = drush_get_option('from')) {
    // E-mail to send the alerts from. Replace here if desired.
    $from = ini_get('sendmail_from');
  }
  $headers = array();
  $headers['From'] = $headers['Sender'] = $headers['Return-Path'] = $headers['Errors-To'] = $from;

  // D7 implementation of drupal_mail
  if (function_exists('drupal_mail_system')) {
    // Prepare the message.
    $message = drupal_mail('drush', 'key', $to, NULL, array(), $from, FALSE);

    $message['subject'] = $subject;
    $message['body'] = array();
    $message['body'][] = $body;
    $message['headers'] = $headers;

    // Retrieve the responsible implementation for this message.
    $system = drupal_mail_system('drush', 'key');
    // Format the message body.
    $message = $system->format($message);
    // Send e-mail.
    $message['result'] = $system->mail($message);
    $result = $message['result'];

    // D6 implementation of drupal_mail_send
  }
  else {
    $message = array(
      'to' => $to,
      'subject' => $subject,
      'body' => $body,
      'headers' => $headers,
    );
    $result = drupal_mail_send($message);
  }

  // Return result.
  if ($result) {
    drush_log(dt('E-mail message sent to !to', array('!to' => $to)), 'ok');
  }
  else {
    drush_set_error('DRUSH_MAIL_ERROR', dt('An error occurred while sending the e-mail message.'));
    watchdog('cronwatch', 'An error occurred while sending the e-mail message with Drush.', array(), WATCHDOG_ERROR);
  }
}

```

And there you go. If Drupal Cron is set to run -let's say- every 60 min, and for some reason failed, the next time this script is executed, it will send you an alert e-mail and you can act based on that.

---- EDIT: Added code to check without depending on Drush / Server Cronjobs ----

## Check if cron hasn't run in X minutes and send e-mail if so (no Drush / Server cronjobs)

You could also run the checks without Drush nor server cronjobs. For this, you will necessarily need to hook your checks to a certain event in your website (e.g. every page load).

In your `cronwatch.module` file:

1) In this case, we check on every page load, that is almost guaranteed to run periodically. However, you can use any other hook to trigger your checks.

Let's find out when the Drupal cron check was last executed.

```
/**
 * Implements hook_page_alter().
 *
 * Finds out when was the last time Drupal cron check was executed. If it's
 * been longer than the desired frequency, proceeds with a new check.
 *
 * We depend on page loads in order to emulate a 'periodically running' event,
 * as an alternative to a server cronjob / scheduled task.
 */
function cronwatch_page_alter() {
  // Defines how often we want to run the checks (in minutes).
  // We need this flag variable, since we don't want to make a check on
  // every single page load.
  $frequency = 60;

  // Only proceed if it's been longer than 60 minutes since the last check.
  $last_check = variable_get('cronwatch_last_check_timestamp', 0);
  $minutes_ago = (REQUEST_TIME - $last_check) / 60;

  if ($minutes_ago < $frequency) {
    return;
  }

  // More than 60 min have passed since the last check. So, let's proceed with
  // a new check.
  if (cronwatch_check()) {
    // Check was succesful. Now update the 'last check timestamp' variable so
    // the next check runs an hour from now.
    variable_set('cronwatch_last_check_timestamp', REQUEST_TIME);
  }
}

```

2) Make the actual check for the last time Drupal cron ran. If more than X minutes have passed, send an email.

```
/**
 * Checks the last time Drupal cron ran, and acts based on that.
 */
function cronwatch_check() {
  // Minutes since the last time cron run.
  $last_cron = variable_get('cron_last', 0);
  $minutes_ago = (time() - $last_cron) / 60;

  // How many minutes to allow without having run the cron.
  // This number should be larger than the frecuency of Drupal cron. E.g. If
  // Drupal cron is set to run every 60m, this number could be 70.
  $tolerance = 70;

  // If the cron last ran longer than tolerance minutes ago, it means that it
  // probably failed.
  if ($minutes_ago >= $tolerance) {
    $to = 'you@example.com';  // E-mail to get the alerts
    $message = t('Drupal cron could not run successfuly. Last succesful run was !minutes minutes ago.', array('!minutes' => floor($minutes_ago)));
    $mail_sent = cronwatch_mail_send_email($to, t('Drupal Cron failed'), $message);

    if ($mail_sent) {
      return TRUE;
    }
  }
  return FALSE;
}

```

3) Function to send an e-mail

```
/**
 * Sends an e-mail from the cronwatch module.
 */
function cronwatch_mail_send_email($to, $subject, $body) {
  // Let's get the mail ready to be sent.
  $module = 'cronwatch';
  $key = 'alert_mail';
  $from = variable_get('site_mail', ini_get('sendmail_from'));
  $language = language_default();

  // Build the mail, but don't send it yet.
  $message = drupal_mail($module, $key, $to, $language, array(), $from, FALSE);

  // Prepare the message.
  $message['subject'] = $subject;
  $message['body'][] = $body;

  // Retrieve the responsible implementation for this message.
  $system = drupal_mail_system($module, $key);

  // Format the message body.
  $message = $system->format($message);

  // Send e-mail (Drupal will log any error).
  $message['result'] = $system->mail($message);

  return $message['result'];
}

```

Only drawback is you depend on page loads, so accuracy would be affected by a website with very few or no visits (in that case, do you even need this?). And, of course, this code could be refactored, but this should do the trick.

# Answer
> 0 votes
This is a pretty heavy handed solution, but you could implement a hook in a module that runs this check for you. Try to find a page that isn't hit very frequently and run it whenever that page is loaded.

Another possibility would be to install the Services module then hit a url from a remote script that kicks off your module to do the check. This introduces a pretty big dependency as well (another server), but it might not be bad if you do have another server. You could have servers checking on each other across a number of projects (maybe I'm overthinking this...)

---
Tags: cron
---


# Question
Title: How to hide row cell when using table in forms?
I have a field widget that has multiple values per field and some are values or other form types that do not render any visible data. I want to use the table element to encapsulate these fields into proper structure.

The issue I have is that for each field within the "field"(ie. table row) a table cell is created, even for values, which resutls in empty `<td></td>`. Sure, I can use the colspan on headers but that also requires adding some css styling to hide those empty cells to avoid padding/margin offsets from those empty cells.

So I am wondering if it is possible to somehow tell the row which fields to put together into one cell or maybe render them outside of the table itself. I could use a custom template but I need to use the tabledrag so I don't want to reinvent the wheel.

I also don't want to alter the structure of those fields since it is very important the structure stays the same. although I could probably fiddle with array parents, I'd rather not.

So ss there a simple way I can get rid of those empty cells that hold values and hidden fields?

-- I have found an old Drupal issue when I was going through the Table code https://www.drupal.org/node/1248940

# Answer
> 0 votes
I've just implemented it using a theme preprocessor to alter the tag from `<td>` to `<span>` and I've added the `hidden` and `aria-hidden` attributes. Hidden by itself works but it isn't supported by \< IE10.

So as to prevent the loops on every table I've added a class to the table as well so I'm checking for `'form-table'` first.

```
/* Implements MODULE_preprocess_HOOK */
function mymodule_preprocess_table(&$variables) {
  if ( ! in_array('form-table', $variables['attributes']['class']) )
    return;

  // Iterate the variables looking for form elements that have the type hidden
  foreach ($variables['rows'] as $key => &$row ) {
    foreach ( $row['cells'] as &$cell ) {
      if ( $cell['content']['#type'] == 'hidden' ) {
        $cell['attributes']['hidden'] = TRUE;
        $cell['attributes']['aria-hidden'] = 'true';
        $cell['tag'] = 'span';
      }
    }
  }
}

```

---
Tags: forms, 8, theming
---


# Question
Title: How to load terms in alphabetical order or in the same order they are in CMS?
I am loading terms programmatically but I am hoping to load them in the same order as they show in the CMS (weight). If not that, I just want them to load in alphabetical order.

This is what I am doing:

```
$vocabulary = taxonomy_vocabulary_machine_name_load($name);
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));

```

Any idea how to achieve that?

# Answer
> 4 votes
For getting all child terms in a vocabulary try the following code.

```
$cc=array();
$tax=taxonomy_vocabulary_machine_name_load($name);
$vid= $tax->vid;
$child_terms = taxonomy_get_tree($vid);
foreach($child_terms as $values) {
  $tname=$values->name;
  $cc[] = $tname;
}

```

The above code will give you child terms of that vocabulary in array `$cc`. For sorting in alphabetical order use `asort($cc);`

Hope this will help you.

# Answer
> 3 votes
To expand on @longboardnode's comment, you can use EntityFieldQuery to retrieve the desired results set in the order that you specify.

You can then get the Term IDs from the results set, and pass that into entity\_load() to get your term entities.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'taxonomy_term');
$query->entityCondition('bundle', $machine_name);
$query->propertyOrderBy('weight');
$query->propertyOrderBy('name');
$result = $query->execute();

$tids = array_keys($result['taxonomy_term']);
$terms = entity_load('taxonomy_term', $tids);

```

---
Tags: taxonomy-terms
---


# Question
Title: How to calculate the sum for each option of all webform results in a Drupal webform grid?
I created a webform in drupal, and added a grid component in it. The grid has 13 questions and 3 options (good, bad, terrible). It's like a poll and people come and answer the questions.

In results, I already have the sum for each option in each question. What I also need is the sum for each option for all questions togehter. For example I need a sum row in grid footer!

I tried webform submissions in views, but it does not give me the data stored in grid.

Be aware that I'm noob in PHP and I don't know how to make TPL files.

image in this link says it all:

thanks

# Answer
> 1 votes
Create a 'webform submission' view. By using the Views Calc module you can display the sum of each field at bottom of the table/grid.

> This module adds simple calculations to a views table. Requires the Views module.
>
> You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

Image from module page

# Answer
> 0 votes
The answer as suggested by Krishna Mohan is indeed a valid approach, here are some more suggestions to further enhance it.

The table in the OP is similar to this one:

The Views Calc module can be used to transform that table so that the calculations in the last rows (with **Count**, **Sum** and **Max**) get added to it (as shown in the answer as suggested by Krishna Mohan).

By replacing the columns '# Fish', 'Weight' and 'Big Fish' with 'good', 'bad' and 'terrible' (as in the question), and by asking for only the 'sum' to be added, it should answer the question I think, no?

To ask for the 'sum', just select it from the selection list, similar to what is shown in this screenshot:

For more details (step-by-step instructions), refer to the community documentation about the Views Calc module.

Disclosure: I'm a **co**-maintainer (not owner ...) of this module,
I hope this does not violate the site's policy on self-promotion.

# Answer
> 0 votes
If you would like to sum every column, the alternative module that you can use is Views Aggregator Plus.

---
Tags: webforms, theming
---


# Question
Title: Form with Multiple fields in table format
I have a requirement to design this type of form for a custom **content type**. This is one part in a large form.

At first what I did is made a **Field Group** called ***Income Information***

Inside the Field Group I made new fields:

* ***Age*** as *textfield Integer*
* ***Sex*** as *select list*
* ***Description*** as *Long text*
* ***Family Income*** *as Field Collection*

***Family Income*** field collection field would have a collection of fields like Family Member, Income, Savings and Loan.

My question is here how to present this part ***Family Member, Income, Savings, Loan*** in a table format as the picture below.

In Family Member: Father, Mother, Spouse are just listed by default. If users want to add some other then there is textbox for that, but the total family member will not increase from 5, that means **no add more field** button there.

# Answer
> 3 votes
You have multiple questions, so answering the title one: "Form with Multiple fields in table format"

You can do it with custom code by themeing the form and printing the fields in a table (I can elaborate on this if you want). One thing to note though is that if you want the user to be able to add more rows to the table this solution gets trickier.

If you do want to add more rows or if you don't want to do custom themeing for your form you you can use the field collection module along with the field collection table module.

It works pretty well, however I currently recommend using the latest dev version of the field collection table module as there are some bug fixes in there you will want.

There are also a few patches in the issue queue that you might need depending on your specific needs, so if you run into bugs (I did when I used it) try searching the issue queue for patches.

# Answer
> 2 votes
This is not going to be pretty, but I've managed to achieve this before by using the '#prefix' and '#suffix' properties of the form elements.

First make sure all the form elements are in the right order, then begin by adding the table html to these properties.

Here's an example:

```
// This code will give you a table with two columns and two rows:
// one header row and a row with the form fields.
$form['first_form_elment'] = array(
  '#type' => 'textfield',
  '#title' => t('Can have a title'),
  '#prefix' => '
    <table id="my-table">
      <tr><th>' . t('Header 1') . '</th><th>' . t('Header 2') . '</th></tr>
      <tr><td>
       <!-- Space for this element -->
    ',
  '#suffix' => '</td>',
);

$form['second_form_elment'] = array(
  '#type' => 'textfield',
  '#title' => '', // <-- Can leave title blank.
  '#prefix' => '
      <td>
       <!-- Second element is on the same row as the first -->
    ',
  '#suffix' => '</td></tr>
    </table>
    ', // Don't forget to close the table rows, and finally the table.
);

```

As I said it's not a pretty solution but it gets the job done. You can apply it in a form\_alter hook.

# Answer
> 1 votes
I personally used Matrix field to achieve something similar but I needed to use the multi value settings module too which is still buggy and poorly maintained.

Matrix field: https://www.drupal.org/project/matrix

Multivalve settings: https://www.drupal.org/project/multivalue\_settings

This is what my form looks like:

# Answer
> 0 votes
One method to achieve this is with a lot of css work.

Conceptually, each row would be a Field Collection (https://drupal.org/project/field\_collection) of 4 fields, which would give you the ability to Add More as needed. If the person's Father has a lot of dependents, this 'table' could get very big.

For achieving the table appearance, I would recommend the illusion of a table. Create a Markup field with the table header (https://drupal.org/project/markup), hide the Field Collection labels with css, make everything display: inline-block; with solid 1px borders ... etc. You should then have a content type form with a table that can grow as needed. A save button for an incomplete form used to mean Required For Publishing (https://drupal.org/project/required\_for\_pub) but I have not had to find the Drupal 7 equivalent yet.

I doubt that you can nest field collections, so Age, Description, and Gender will need to be moved out to the Field Group.

Making the Description Requirement depend on the fields inside the field collection is not easy with php and drupal, so javascript would be the better choice for that.

# Answer
> 0 votes
Try this module, https://drupal.org/project/tablefield. Once you add this field in your content type, add number of rows and columns required in field settings. Look for default value settings for the field and add father, mother, spouse in it. Hope this helps ....

---
Tags: 7, forms
---


# Question
Title: Code to add node add form to a custom block (not working)
I am trying to use code below to display node add form for a custom content type in a custom block.

Any guidance on why the code below may not be working is sincerely appreciated.

```
function stories_block_info(){
  $blocks['post_story'] = array(
    'info' => t('Post a Story - Neil Block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function stories_block_view($delta = ''){
  switch ($delta) {
    case 'post_story':
      $block['content'] = drupal_get_form(stories_node_form);
      // $block['content'] = block_contents($delta);
      break;
  }

  return $block;
}

```

# Answer
> 0 votes
You can try form block module for such tasks. Though it is in Dev version for Drupal 7, but from the review of other users, you can try it out.

Check it out here

Your code seems also good but i think you are missing quotes around **stories\_node\_form**.

Try this one:

```
/** Implements hook_block_info() */

function stories_block_info(){
    $blocks['post_story'] = array(
        'info' => t('Post a Story - Neil Block'),
        'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}
/** Implements hook_block_view() */

function stories_block_view($delta = ''){
     switch ($delta) {
        case 'post_story':
            $block['content'] = drupal_get_form('stories_node_form');
            //$block['content'] = block_contents($delta);
            break;
    }
    return $block;
}

```

# Answer
> 2 votes
For people still having trouble with the above code when using anything AJAX-related (e.g. 500 errors) or simply trying to open up the 'blocks' tab in Panels without some error (e.g. some Entity Translation functions) you might want to try the following module code instead in Drupal 7 (but some parameters may still need to be added for your purposes).

```
function custom_example_block_info() {

    $blocks['example_node_form'] = array(
       'info' => t('What an example'),
    );
    return $blocks;

```

}

```
function custom_example_block_view($delta = ''){

    $block = array();

    switch ($delta) {
        case 'example_node_form':
            global $user;
                        //Note: 'type' is your node content type and 'language' must be included
            $node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'example', 'language' => LANGUAGE_NONE);

            $form_state['build_info']['args'] = array($node);

            form_load_include($form_state, 'inc', 'node', 'node.pages');
            $block['content'] = drupal_build_form('example_node_form', $form_state);

            break;
    }
return $block;

}

```

The important difference is that drupal\_get\_form cannot load the $form\_state so we use `function form_load_include(&$form_state, $type, $module, $name = NULL)` to ensure the include file is loaded whenever the form is processed and `function drupal_build_form($form_id, &$form_state)` instead of drupal\_get\_form to pass $form\_state. The lines above create the $form\_state.

# Answer
> 0 votes
Try this in your block.tpl.php :

```
global $user;
  $node = array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => 'story',
    'language' => '',
  );
  $form = drupal_get_form('story_node_form', $node);
  drupal_prepare_form('story_node_form', $form, $form_state);
  print_r($form);

```

# Answer
> 0 votes
All you are missing to **include node.pages.inc file**. Blow is a demo function which returns node\_type\_form.

```
/**
 * @param string $type
 * @return string
 */
function _custom_work_get_node_form($type = 'page') {
  global $user;
  module_load_include('inc', 'node', 'node.pages');
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE
  );
  $form = drupal_get_form($type . '_node_form', $node);
  return $form;
}

```

---
Tags: nodes, blocks
---


# Question
Title: How to create the history of particular field of content
I have a content type called Fruitera, which has a select list **field\_fruits**, which has these possible options:

1. Apple
2. Banana
3. Orange
4. Pineapple

For this I have created a view, and now I want to see the history of particular **field\_fruits**.

Whenever we edit the content it will replaced by another fruit, I want to see previous history of **field\_fruits** for content created in a view.

Any suggestions know how to do this?

# Answer
Track Field Changes is a module that allows you to easily enable tracking/auditing on changes to fields, and has views integration.

I hope this will make your work.
> 1 votes

---
Tags: views
---


title: entity reference and exposed filter

text:
# Question
Title: entity reference and exposed filter
Hello I would like to ask about **views and exposed reference filters**. I have problem with displaying my custom view for exposed filter. Can you please help?

> Its kind of complex so I will try to describe the structure. I made view which should be used as exposed filter and this view works fine, but cant push it to appear in other view as exposed filter.
>
> All of my users have some cateogies as taxonomy terms. Also every content has this category so I want to show to user only the content which is in category assigned to specific user. There can be more than one category assigned to user. Content has also single value entity reference to manufacturer.
>
> And now I need to have a page for every content type where and I want to display all content in users category with exposed filter of manufacturers. In this filter must not be all manufacturers but only which ,there is content created with this manufacturer and the content is assigned to same category as the user.

Little example for one content type:

* user1 - category: dj, profi video
* user2 - category: hifi
* user3 - category: dj, hifi

* content1 - manufacturer: m1; category: dj, hifi
* content2 - manufacturer: m2; category:dj
* content3 - manufacturer: m2; category: profi video
* content4 - manufacturer: m3; category: hifi

In this point the exposed filter for user1 should display: m1, m2. Or for user2: m3. Or for user3: m1, m2, m3.

# Answer
> 0 votes
You need to set up relationships between the three content types in your View. Essentially, you have to set up relationship user-\>category, then relationship category-\>manufacturer, at which point the manufacturer fields will become available in the exposed filters section. There is a great tutorial here how to do this.

# Answer
> 0 votes
Thanks. Im attaching image how the structure look like. The result should be the page for every content type except Manufacturer, where the user can filter the content by manufacturer. So there will be exposed filter with list of avaliable manufacturers who is assigned to current content type according to users categories.

Now just came in my had that Manufacturer can be taxonomy eather. But Im not shure if it will be easier to make this happen.

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


title: How to add User edit link in main menu

text:
# Question
Title: How to add User edit link in main menu
Site link

here, in this 9 is the user id.it is different according to register users.

When add link in main menu there is an option Path textbox in that text box if i add "**user/9/edit**" then link is created but here 9 is login user id. then it is accessible only whose user id 9. but other not access. I want to add link dynamic which user are login then that user access that user edit page.user/\*/edit

# Answer
> 1 votes
Install me aliases module.

> Provides shortcut paths to current user's pages, eg user/me, blog/me, user/me/edit, tracker/me etc.

# Answer
> 0 votes
Menu token

> Menu Token module provides tokens, that could be used in title or in path of menu items (links). For example, if you create a menu item with path: "user/\[current-user:uid\]", the url will be changed "on fly" to: "user/1" (assuming you are user 1).

or you can do it by using hook\_menu\_alter

```
/**
 * Implements hook_menu_alter.
 * Check access for forum menu item.
 */
function MYMODULE_menu_alter(&$items) {
  $items['forum']['access callback'] = '_accesscheck';
}
/**
 * Callback to disallow access for the anonymous user.
 */
function _accesscheck(){
  global $user;
  return $user->uid;
}

```

---
Tags: routes, navigation
---


# Question
Title: Is it possible to create stacked bar charts in views?
I'm using the Charts module with hightcharts to create charts in views, but I'm unable to create stacked one's.

Is this possible in views? Or is there any way I can override it with a custom module to achieve the same result?

Here is an example of what I need.

Also, my view:

```
$view = new view();
$view->name = 'stackedchart';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'StackedChart';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'My Stacked Chart';
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'views_bootstrap_table_plugin_style';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'field_x_qc_testset',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['style_options']['columns'] = array(
  'field_x_qc_week' => 'field_x_qc_week',
  'field_x_qc_status' => 'field_x_qc_status',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'field_x_qc_week' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_x_qc_status' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['style_options']['bootstrap_styles'] = array(
  'striped' => 0,
  'bordered' => 0,
  'hover' => 0,
  'condensed' => 0,
);
/* Field: Content: x_qc_week */
$handler->display->display_options['fields']['field_x_qc_week']['id'] = 'field_x_qc_week';
$handler->display->display_options['fields']['field_x_qc_week']['table'] = 'field_data_field_x_qc_week';
$handler->display->display_options['fields']['field_x_qc_week']['field'] = 'field_x_qc_week';
$handler->display->display_options['fields']['field_x_qc_week']['label'] = 'Week';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'xreport_qc' => 'xreport_qc',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_2');
$handler->display->display_options['defaults']['group_by'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['library'] = 'highcharts';
$handler->display->display_options['style_options']['type'] = 'column';
$handler->display->display_options['style_options']['label_field'] = 'field_x_qc_week';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_x_qc_status' => 'field_x_qc_status',
  'field_x_qc_week' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'field_x_qc_week' => '#2f7ed8',
  'field_x_qc_status' => '#0d233a',
);
$handler->display->display_options['style_options']['data_labels'] = 'TRUE';
$handler->display->display_options['style_options']['tooltips'] = 'TRUE';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: x_qc_week */
$handler->display->display_options['fields']['field_x_qc_week']['id'] = 'field_x_qc_week';
$handler->display->display_options['fields']['field_x_qc_week']['table'] = 'field_data_field_x_qc_week';
$handler->display->display_options['fields']['field_x_qc_week']['field'] = 'field_x_qc_week';
$handler->display->display_options['fields']['field_x_qc_week']['label'] = 'Week';
/* Field: Content: x_qc_status */
$handler->display->display_options['fields']['field_x_qc_status']['id'] = 'field_x_qc_status';
$handler->display->display_options['fields']['field_x_qc_status']['table'] = 'field_data_field_x_qc_status';
$handler->display->display_options['fields']['field_x_qc_status']['field'] = 'field_x_qc_status';
$handler->display->display_options['fields']['field_x_qc_status']['group_type'] = 'count';
$handler->display->display_options['fields']['field_x_qc_status']['separator'] = ', ';
$handler->display->display_options['defaults']['sorts'] = FALSE;
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'xreport_qc' => 'xreport_qc',
);
$handler->display->display_options['path'] = 'stackedchart';

```

If it can't be made with views, doing it with a custom module using EntityFieldQuery is also a good solution. My only issue is how to show the data in different x-axis values (field value) not knowing all the values of that field.

EDIT: Tried Pierre suggestion. dsm is outputing the name of the chart and I use it as $chart\_id. No stack is produced in the chart.

The fields I have are `week` and `status`. I have multiple nodes, with different weeks and status and I need to stack the status for each week. Below is the chart WITHOUT stacking.

# Answer
# Option 1

Refer to the issue about Stacking column/bar charts for an example of how you can do this with a custom module. Comment #3 in it contains a sample like so:

```
<?php
function MYMODULE_chart_alter(&$chart, $chart_id) {
  dsm($chart_id); // Need Developer module enabled for dsm to work
  if ($chart_id == 'MYCHARTVIEW__DISPLAY') { // Watch out for those double underscores
    $chart['#stacking'] = TRUE;
  }
}
?>

```

This should work for both Google Charts and Highcharts as the charting library (engine).

# Option 2

Your `x_qc_status` is like the equivalent of "Joe" in the sample you referred to. But you don't have any equivalent of at least "John" (and maybe also "Jane")? In other words: I think you only have 1 dataset to be shown in your "stacked" bar chart, and that your problem is not in the chart, but in the related "view" for which you want to create a "stacked" chart.

Therefor try the "bonus tip" mentioned in Steps to create charts using the views UI. That may help to refine your view before actually creating the chart.
> 1 votes

---
Tags: charts
---


# Question
Title: Error running a PHPUnit test only under run-tests.sh
I'm working on an 8.x module that uses PHPUnit tests. I've been running these from the command line using the embedded phpunit script that's installed with Drupal 8:

```
../vendor/bin/phpunit PATH/TO/MY/FILE.php

```

Both of my tests work w/o any problems under both PHP 5.5 and PHP 5.6.

But the Drupal testbot is failing both of my tests with the error

```
Fatal error: Trait 'Drupal\Tests\my_module\MockSessionTrait' not found in /var/www/.../PATH/TO/MY/FILETest.php

```

Using phpunit from the command line, this same trait is found w/o any trouble.

If I run the tests myself from the command line, but this time using run-tests.sh, I get the same error the testbot gets:

```
php scripts/run-tests.sh --url http://192.168.88.42/drupal --class 'Drupal\Tests\my_module\Unit\FILETest'

```

The stack trace looks like this:

```
PHP Stack trace:
PHP   1. {main}() /var/www/drupal/core/scripts/run-tests.sh:0
PHP   2. simpletest_script_get_test_list() /var/www/drupal/core/scripts/run-tests.sh:76
PHP   3. class_exists() /var/www/drupal/core/scripts/run-tests.sh:807
PHP   4. spl_autoload_call() /var/www/drupal/core/scripts/run-tests.sh:807
PHP   5. Symfony\Component\ClassLoader\ApcClassLoader->loadClass() /var/www/drupal/core/scripts/run-tests.sh:0
PHP   6. require() /var/www/drupal/vendor/symfony/class-loader/ApcClassLoader.php:114

```

I'm guessing that I need to help run-tests.sh to find my files, somehow.

Any advice from anyone as to why run-tests.sh behaves differently here from stock phpunit?

# Answer
@Berdir is completely correct here:

> I'm not sure but you might not be able to have a non-test class in the tests/src location, try moving that to module/src/... and change the namespace accordingly (Drupal\module...

While PHPUnit doesn't mind if a test class uses a trait that's in a Drupal\Tests namespace, the simpletest test runner run-tests.sh will be unable to find the trait if you do this.

So don't do that.

Even if a trait is used only with your test classes, if you want your code to get past the Drupal testbot, the trait needs to live somewhere in your Drupal\your\_module\ namespace. Do this, and both phpunit *and* run-tests.sh will be happy.
> 2 votes

---
Tags: testing, 8
---


# Question
Title: Posting the main url of drupal site on facebook wall
When pasting the URL of the Drupal site in question as a facebook message, the message, title and image that are being fetched from that drupal site are not the ones that are supposed to come up. From what I gather, Facebook module and OpenGraph stuff seems needed in order to figure this out which seems overkill for this problem...

The homepage of the Drupal site is a view with some blocks in the sidebars. When you paste the URL of the site (www.mysite.com) in a facebook message, it fetches some text out of a block, and an image from some other node. Instead, I want to be able to choose which text it fetches from the site.

The answer to this question How to change facebook og:image to post image link? seems to come close and is telling me I need to use the metatag module. It doesn't explain how to go about it, but I installed the module and changed some of the values in the configuration, but didn't have any effect. Also flushed caches many times.

Also installed the fb module, I read the README.txt from the `fb`module from the beginning until the end (as asked).

I have a feeling like I don't necessarily have to get a degree in the the huge Facebook API/Opengraph rabbithole in order to get this sorted, do I? I mean, there has to be one place where you can just determine when the text, image and title should be on the wall without too much of a huge construction around, no?

# Answer
You have a two part question here.

One, the best way to deal with OG info on your site is with the Metatag module:

> The Metatag module allows you to automatically provide structured metadata, aka "meta tags", about a website. In the context of search engine optimization, when people refer to meta tags they are usually referring to the meta description tag and the meta keywords tag that may help improve the rankings and display of a site in search engine results. In addition, the module provides support for meta tags (Open Graph Protocol from Facebook, Twitter Cards from Twitter) that allow control of how content appears when shared on social networks.

When you install and enable this, you can customize what OG info appears where, and it has full token support for dynamically creating the meta elements pages on a page's content. You can also hardcode values for specific cases, like the home page.

The second part of your question has to with the fact that FB heavily caches page contents. The provide a debug tool for dealing with this:

https://developers.facebook.com/tools/debug/

In addition to seeing exactly what OG info it is pulling in about a URL you provide, it has the side effect of clearing the cache for that particular URL.
> 3 votes

# Answer
First of all I would check the Facebook Guide to Sharing for Webmasters, which will tell you exactly which metatags you should be using.

Now make sure you have the metatag\_opengraph module enabled and edit the property you want in admin/config/search/metatags. Be aware that editing the Global OG settings will set the image, title etc. for ALL of your site.

Finally do not forget that the content type MUST be set to 'article' for Facebook to find it, as it says in the Guide.
> 1 votes

---
Tags: 7, social-network
---


# Question
Title: How to get details like duration, type, etc from uploaded videos and store them in fields?
I'm building a site that will handle a lot of media files, both image and video. Currently, I have video and image content types setup along with the ability to bulk-upload them.

I'm wondering if there is a way to scrape details from an uploaded video—such as duration, type, etc and store these in fields. I'm not sure how to approach this.

# Answer
> 2 votes
Presumably we are talking mp4/webm video here? Start with checking out getID3. Then it is pretty simple to do:

```
$id3 = new getID3;
$file = $id3->analyze($filename);

```

Must always have "new getID3".

---
Tags: media, files
---


title: #states in add node form

text:
# Question
Title: #states in add node form
How to use `#states` in add node form? I don't experience any problems when use them with exposed filters (on user side), but cannot do the same when additing new nodes. I tried the following code:

```
function custom_module_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['field_coordinate']['und'][0]['#default_value'] = t('1');
    $form['field_name_tag']['und']['0']['#states'] = array(
      'invisible' => array('select[id="edit-field-location-tag-und"]' => array('value' => '1')),
    );
  };
}

```

Where is my mistake?

# Answer
> 1 votes
You need to set the state in the "value" key, so one level deeper as you tried. E.g.:

```
$form['field_yourfieldname'][LANGUAGE_NONE][0]['value']['#states'] =
  array('visible' =>
    array('input[id="edit-field-otherfieldname"]' => array('checked' => TRUE))
  );

```

# Answer
> 0 votes
The #states array has the following structure.

```
array(
  STATE1 => CONDITIONS_ARRAY1,
  STATE2 => CONDITIONS_ARRAY2,
  // ...
)

```

The condition array has the following structure.

```
array(
  JQUERY_SELECTOR1 => REMOTE_CONDITIONS1,
  JQUERY_SELECTOR2 => REMOTE_CONDITIONS2,
  // ...
)

```

JQUERY\_SELECTOR is a selector that is valid in jQuery, such as `:input[name="foo"]`.

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


# Question
Title: Allowed memory size of 134217728 bytes exhausted in system\image.gd.inc reported for styled images
There is a content type in my website that has an image field. Some contents have images that are larger than 20MB.

I created an `image_style` called `fp` which scales and resizes the images in 800**X**400px it works well but when the browser displays this resized version it reports the following error

> Allowed memory size of 134217728 bytes exhausted (tried to allocate 73834563 bytes) in modules/system/image.gd.inc on line 237

*I know by increasing the `memory_limit` the problem will be solved (even though it is not recommended).*

From what I know Drupal creates a distinct file of the original image for every image style, so in `sites/default/files/styles/fp` there is a resized version of the original image. It means when browser displays the resized image, the PHP needs no process to resize the image, it only displays another image which is the resized version. But why it displays the above error while it only needs to display an image (styled version) which its size is about 200kb ?

# Answer
128M is somewhat low for a Drupal install. It may work well for front end pages, but I have found that it needs to be raised for admin pages. I do not know where you get the recommendation that anything over 128M isn't recommendation. That PHP variable is a holdover from custom PHP to prevent infinite loops from crashing a system. And remember, it is a max value. Page requests that use less will not get the full amount.

You are running into the problem because GD needs to load the image into memory to process it down to 800x400 before saving it to disk and serving it up for display. The problem isn't as much the file size, as what it will decompress to and occupy in memory. When you start doing the math on big images (multiple width x height x 4), you will see that, 128M is way too low. When the style has already been made, PHP never gets involved.

I believe the ImageMagick library will end up using the CLI convert utility, which can save PHP memory, but I don't recall the last time I actually tested this to be sure.
> 3 votes

---
Tags: 7, media
---


# Question
Title: How to add a new row to the registration form?
I'm using LoginToboggan module. Via this module user can register or login.

And now I want to add another row to this form. For example: *Phone number* or *Age*.

How can I achieve this? Or is there another way of achieving this?

# Answer
> 4 votes
Without using LoginToboggan also you can achieve you requirement.

1. Goto **Configuration** \> **Account settings** \> **Manage Field** and then add field.
2. In field configuration **Display on user registration form** checkbox.

---
Tags: users
---


title: Continuous migration

text:
# Question
Title: Continuous migration
I would like to know what is the best way to achieve a continuous migration from external DB (via Migrate).

Basically, there are several migration classes that need to be to repeatedly migrated in an ordered way (the external DB is also updated). This said, exception management is welcomed/required during the run.

I was trying to find a solution for this but found nothing concrete. From gathered information some approaches are to use Jenkins/Drush combination, but I wonder if adding Jenkins would be an overkill in my case.

Is there a good way to achieve this via Drush only?

Thanks

# Answer
> 0 votes
Set up a script to call drush at regular intervals. There are several drush commands to manage migrations, such as `drush migrate-status`.

---
Tags: 7, drush, migrations
---


title: How to correct url path

text:
# Question
Title: How to correct url path
I am using a key to connect with it's *node nid* but when I click on *Next* it gives path `/node/node/256` instead of `node/256`. Here is my code:

```
$key = array_search($nid , $nids);
print $key;
$next = ($key + '1');
$previous = ($key - 1);
$total=count($nids);
$next_link =    "<a href='node/$nids[$next]'>Next</a>";
$previous_link = "<a href='node/$nids[$previous]'>Previous</a>";

```

*$nids* is an array. How to handle this situation?

# Answer
> 2 votes
Use `l()` to construct URLs in Drupal.

```
$next_link = l('Next', 'node/' . $nids[$next]);
$previous_link = l('Previous', 'node/' . $nids[$previous]);

```

# Answer
> 0 votes
Alternatively if you wanted just the alias, but not the whole link then you could use drupal\_get\_path\_alias:

```
$alias = drupal_get_path_alias('node/'.$nid);

```

# Answer
> 0 votes
Correct next and prev node url by content type

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load($nid);
  $type = $node->type;

  $prev = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('n.status', 1, '=')
    ->condition('n.type', $type, '=')
    ->condition('n.created', $node->created, '<')
    ->orderBy('n.created', 'DESC')
    ->range(0, 1)
    ->execute()
    ->fetchField();

  $next = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('n.status', 1, '=')
    ->condition('n.type', $type, '=')
    ->condition('n.created', $node->created, '>')
    ->orderBy('n.created', 'ASC')
    ->range(0, 1)
    ->execute()
    ->fetchField();

  if ($prev) {
    $prev_link = l('Previous', 'node/' . $prev);

  }
  if ($next) {
    $next_link = l('Next', 'node/' . $next);
  }

}

```

---
Tags: 7
---


# Question
Title: Webform submissions to be seen on Drupalgap
I am making a DrupalGap application to view Webform submission.

I have made a view in Drupal as a table to list the submissions, now I want to see that table in DrupalGap.

How do I do that?

# Answer
Use a DrupalGap Views Render Array. With it you will:

1. Create the Views JSON page display in Views with contextual filter(s)
2. Create a page in the app to display the view
3. Use the Views Render Array to send up the contextual filter(s)
4. Build the render function to render each row of the table
> 1 votes

# Answer
The Services Views module can help with that:

> Views support for the Services module version 3.x and later.
>
> It has currently two features:
>
> * Create view based resource creating Services display in a view
> * Execute any view of the system via views resource call

The second feature will allow you to query a resource for a particular View's data, with arguments, and you can code your Drupalgap application to do whatever you like with it.
> 0 votes

---
Tags: webforms, javascript
---


# Question
Title: How to embed and choose entityform in custom content type?
I have a D7 Website, and I am using entityforms module. I want to include those entityforms which I created in my custom content type so that users can submit their details. For example: a node with multi-field comments box. To achieve this, I added a field in custom content type of type "Entity reference" -\> List. As an admin, I get to choose all available entity forms but not as a custom user role for which it shows "access restricted" while choosing entity form type.

Please guide.

# Answer
OK, so I gather the problem you are trying to solve is the fact that a non-administrator cannot pick an entityform from the list? The solution: go to /admin/structure/entityform\_types, choose "Edit" for each Entityform and be sure to check the boxes in "Roles" for "authenticated user". That way anyone logged in should be able to see and use the form.
> 0 votes

---
Tags: entities
---


# Question
Title: How to pass parameter to 'options list' attribute in hook_rules_condition_info?
I am declaring a condition in which I have the following parameters:

```
            'node_type' => array(
            'type' => 'text',
            'label' => t('the node type'),
            'options list' =>/*'entitystep_get_list_node_types'*/ 'node_type_get_names' ,
            'restriction' => 'input',
        ),
        'node_field' => array(
            'type' => 'text', //TODO: find or create node_field datatype? *node_element?
            'label' => t('the node its field to be checked'),
            'options list' => 'entitystep_get_fields'

```

// TODO: check how to pass a parameter to the entitystep\_get\_fields!!! ($node\_type) ),

In the 'entitystep\_get\_fields (on the bottom) I have to pass the selected node\_type (=the first parameter)

These are the functions I need to call:

```
function entitystep_get_list_node_types() {
    $types = db_query("SELECT n.type FROM node_type");
    return types;
}

```

function entitystep\_get\_nodes\_by\_type($node\_type) { $nodes = db\_query("SELECT * FROM node WHERE type=" . $node\_type ); return $nodes; }

# Answer
> 0 votes
Have a look to the entity condition "entity\_is\_of\_bundle"

In this example there are three parameters and they are displayed through a multistep form. To do this, you will need to alter the form. In this example, it is `rules_condition_entity_is_of_bundle_form_alter`

You can notice that depending on the form state, some elements are hidden. When you go to the next step, you can access form values. In this example, we can access entity bundles of the entity type as do the function `rules_entity_bundle_options`. The type of the entity is within `$element->settings['type']`

I hope it is clear for you.

---
Tags: 7, rules, database
---


# Question
Title: How to build a dynamic user-page from LDAP (Active Directory) and show this page after logged in?
I have Open Atrium 2 with Drupal 7. User are able to login over the active directory using the Lightweight Directory Access Protocol (LDAP) module, which works pretty well.

After login the user should come to its own personal page. In which the user can see his/her personal data and so on. But how to create a dynamic page like a template for this personal page?

I couldn't find any similar on the net. Any help I would appreciate.

**Edit**:

My first step is: After Login over LDAP (active directory) getting all personal data and lead every person to his own page with all this personal data in it.

Can I do this with some appropriate modules or do I have to script this in php or a mix of both (scripting and modules)? And which modules or plugins for Drupal with Open Atrium 2 can help me to get this?

# Answer
> 1 votes
> After login the user should come to it's own personal page.

Whatever page you want to send the user too (different from the default user profile page) can be achieved by using the Login Destination module:

> The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.

Then you said:

> In which he can see his personal data and so on. But how to create a dynamic page like a template for this personal page??

You didn't mention if this page should be the user's profile or a different page simply showing all the account details from LDAP (and possibly other pieces of content). You can embed the user profile on any path you want, see similar question(s) and example solutions at:

How to show custom user profile fields in a view?

Or, you can create a View that uses an LDAP Query and simply show information from LDAP on a custom view page, which the ldap module supports. See the LDAP Query documentation.

---
Tags: authentication-authorization
---


# Question
Title: What's the "Best Practice" approach for disabling secure pages on local Dev?
Wondering what the "best practice" approach would be for disabling secure pages on local dev. I'm running a site on Acquia Cloud and have access to the environment variable **AH\_SITE\_ENVIRONMENT** and I could easily do something like:

```
if (isset($_ENV['AH_SITE_ENVIRONMENT'])) {
  switch ($_ENV['AH_SITE_ENVIRONMENT']) {
    // case 'dev':
    //   // do something on dev
    //   break;

    // case 'test':
    //   // do something on staging
    //   break;

    case 'prod':
      // do something on prod
      break;
  }
}
else {
    $conf['securepages_enabled'] = 0;
}

```

Is that the best approach or is there a better, cleaner way? Also, are there negative implications for filling up settings.php with stuff like this?

# Answer
It's a best practice to create a `settings.local.php` file which is included at the end of the default `settings.php` file. Then within that file you can place whatever logic you want per server as you've done, or make the content of `settings.local.php` be specific per server host you're deploying too (and keep settings.local.php basically outside of version control).

This is a good practice for Drupal 7 development -- so good in fact Drupal 8 ships with such code in settings.php by default, which you can uncomment to make use of:

```
/** In settings.php for a drupal 8 site */

/**
 * Load local development override configuration, if available.
 *
 * Use settings.local.php to override variables on secondary (staging,
 * development, etc) installations of this site. Typically used to disable
 * caching, JavaScript/CSS compression, re-routing of outgoing emails, and
 * other things that should not happen on development and testing sites.
 *
 * Keep this code block at the end of this file to take full effect.
 */
# if (file_exists(__DIR__ . '/settings.local.php')) {
#   include __DIR__ . '/settings.local.php';
# }

```
> 2 votes

# Answer
It's better to maintain separate site folders if you want different configs depending on the server role. In the simplest set-up, name each folder after the domain. Eg:

```
sites/
      dev.example.com/
          settings.php
      www.example.com/
          settings.php

```

If you need a more flexible mapping, you should use sites.php to hold the code used to determine which folder should apply.
> -1 votes

---
Tags: configuration
---


# Question
Title: CSS for Display Suite Fields not applied
**I'm attempting to place text next to the top of images inline for a content type using CSS on fields through Display Suite with a built-in layout in Panels (Two column bricks)**

I am using a subtheme for the professional\_theme.

* I have tested and ensured the style sheet is over-ridden to my subtheme
* I have inserted the css shown below (and tried several other css codes)
* I have inserted the css names into the CSS Classes of Display Suite
* I tried applying the styles to several different fields as well as the region independently and together.

That all being said I think there is extra CSS code being inserted that is throwing off the style being pulled in but I have no idea where it is coming from.

**The code below displays Source Code with the CSS style I applied to the image and a text field:** The names of the only styles I applied are: **.floatleft .floatright**

```
<div id="block-system-main" class="block block-system">

<div class="content">
<div class="panel-display panel-2col-bricks clearfix" >
<div class="panel-panel panel-col-top">
<div class="inside"><div class="field field-name-title field-type-ds field-label-hidden">
<div class="field-items"><div class="field-item even"><h2>Are you the Kind to be Kind</h2></div></div></div><div class="field field-name-field-date-good-news field-type-datetime field-label-hidden">

<div class="field-items"><div class="field-item even"><span class="date-display-single">Tuesday, October 27, 2015 - 09:30</span></div></div></div>
<div class="field field-name-field-image-positive-news .floatright"><img src=".../sites/default/files/styles/medium/public/positivenews/476950.jpg?itok=uIGCBUH2" width="220" height="165" alt="" /></div>
<div class="field field-name-field-inspirational-thought-oday field-type-text-long field-label-hidden .floatleft"><div class="field-items"><div class="field-item even"><p>You are in charge of your own destiny, don’t try to control theirs.</p>
</div></div></div></div>
</div>

```

**CSS CODE:** Keep in mind that I have tried other CSS codes

```
.floatleft {
clear: both;
vertical-align: top;
float: left;
padding: 4px 10px 4px 0;
}

.floatright {
clear: both;
vertical-align: top;
float: right;
padding: 4px 0 4px 10px;
}

```

Any help is greatly appreciated. I tried finding CSS documentation for Display Suite with little luck. WO

# Answer
First of all, remove the `.` from your classes in your HTML code, e.g. you should have `<div class="floatright">` and not `<div class=".floatright">`.

If you want to have one element next to another by using `float`, your combined element's width should be smaller than their container's. And since both your image and the text are inside divs and a `div` has 100% width by default, you have to specify a smaller width to each.

```
.floatleft {
    float: left;
    width: 40%;
}

.floatright {
    float: right;
    width: 30%;
}

```

Just change the widths accordingly.
> 0 votes

---
Tags: panels, display-suite
---


# Question
Title: How to display custom table data inside views?
I have a custom table created using .install file in my custom module.

```
+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| id            | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| first_name    | varchar(255)     | NO   |     | NULL    |                |
| last_name     | varchar(255)     | YES  |     | NULL    |                |
| email_address | varchar(255)     | NO   |     | NULL    |                |
| user_country  | varchar(50)      | NO   |     | NULL    |                |
| user_city     | varchar(50)      | NO   |     | NULL    |                |
| address       | varchar(600)     | NO   |     | NULL    |                |
| gender        | varchar(10)      | NO   |     | NULL    |                |
+---------------+------------------+------+-----+---------+----------------+

```

And in same module, created form for reading inputs from user and a submit handler for inserting those values inside this schema. It works fine. But now I need to fetch the data and display in Views. How can I do that? I have created a hook\_views\_api as:

```
   function MY_MODULE_views_api() {
  return array(
    ‘api’ => 3,
  );
}

```

In hook\_view\_data(),

```
<?php
function my_module_views_data()
{
$data=array();

 $data['myuser']['id'] = array(
    'title' => t('id'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

$data['myuser']['first_name'] = array(
    'title' => t('First Name'),
    'help' => t('To get first Name.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

$data['myuser']['last_name'] = array(
    'title' => t('last Name'),
    'help' => t('To get last Name.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

$data['myuser']['email_address'] = array(
    'title' => t('Email Address'),
    'help' => t('To get Email Address.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

$data['myuser']['user_country'] = array(
    'title' => t('User Country'),
    'help' => t('To get User Country.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

$data['myuser']['user_city'] = array(
    'title' => t('User City'),
    'help' => t('To get User City.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

 $data['myuser']['address'] = array(
    'title' => t('Address'),
    'help' => t('To get ADdress.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

 $data['myuser']['gender'] = array(
    'title' => t('Gender'),
    'help' => t('To get Gender.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

}

```

but now this is not showing up in Add View. What else I have missed? I am searching this days and today its dead line for finishing this. Please need some help on this.

# Answer
Just use the Data module that gives you a UI to create a new simple table with fields you have above. Or, you can "adopt" existing MySQL tables into data. Data will then let you easily make Views of the mysql table and setup the `hook_views_data` properly for you.

If you want to do all that yourself because you cant use Data or 'alpha' contrib modules I recommend looking at Data modules source code to see how they implement the hook functions you're having trouble with.

Also note that in your `hook_views_data()` you forgot to return `$data` as in the official API documentation. That could be your problem. Still, you would have custom code that basically is part of the Data module.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to disable or make fields unpublished, but not delete them
I have some fields I need to disable from user registration, but no delete them, just make them unpublished or disable them temporarily, is there a way to do that?

# Answer
> 1 votes
The easiest solution offhand is to make the fields non-required for registration. And then setup the Field Permissions module temporarily to not give `Edit permission` to Role(s) you don't want to see those fields.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

# Answer
> 0 votes
Alternatively a shameless (but effective) hack is to use Field Group to create a fieldset with a specific CSS class. Make sure the class has a `display: none;` property. Put the field inside that fieldset, and sit back and relax.

Something else you could try is Display Suite "Extras" (/admin/structure/ds/list/extras). Try using the "Hidden region" option (not sure if it works only for view or both view and form).

Now, if your visibility option is temporary and dependent on other factors ( other fields, etc), you will need to write a custom module or use something like, for example, Field Conditional States.

# Answer
> 0 votes
You could use Display Suite and move the fields to the "Hidden" section. This would remove them from the form, and you can also do this with any content type.

---
Tags: entities
---