# Question
Title: How to generate a **uid** whenever a form is submitted, and want to pass it in every form I made to update specific user results
I have created a form with the menu item url like this.

```
$items['/component'] = array(
    'title' => 'Component',
    'page callback' => 'drupal_get_form',
     ....
);

```

my form structure is so,mething like this:

```
function _my_component_add_form($form, &$form_state) {
$cid = "";
$form['id'] = array(
        '#type' => 'hidden',
        '#value' => $cid,
    );
$form['human_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Component name'),
    '#required' => TRUE,
    '#size' => 32,
    '#maxlength' => 255,
  );
  ......

```

now when I submit this form, I see **form\['id'\] = blank**

Now, what I want is, when I submit my result my url should become like

> admin/component/1

I have made anotjher url to show results. Its url become `/component/show` But I have given edit/delete links in front of every submitted entry, so user can edit and delete too.

My Question is I want to generate a **uid** whenever a form is submitted, and want to pass it in every form I made in my module, so each and every form has a parameter "uid". and form will work for specific user who only submits his form.

Say, If I want to update his submitted results, I need an ID of that user, so that no other user submissions will get updated.

Hope, I am able to express my confusion for "UID".

# Answer
> -1 votes
suggestion : First of all never use 'id' as id in any drupal form or anywhere.

set "global $user;" $user\_uid = $user-\>uid;

set your URL like

\['admin/component/'.$user\_id\]

---
Tags: forms
---


# Question
Title: How to create a rule which asks the user whether to proceed or not?
With the D7 version of the Rules module, is there any way to create a rule which asks the triggering user whether to proceed or not?

Specifically, I'm trying to set up an "After updating existing content" rule but I would like it to ask the user "Do you wish to \<action\>? Yes/No" then continue executing if they choose "Yes" or halt and return to the node view if they click "No".

I was hoping it could be done within the rules UI somehow but if I have to code a custom module, so be it.

I've looked through all the modules in the "Rules" category on drupal.org and I've looked at all the available rule conditions in the rules UI but I haven't found anything useful so far.

# Answer
> 2 votes
You might want to check, and experiment with, the Rules Link module. Here is an excerpt from its project page:

> ... lets you create links which trigger arbitrary functionality with the help of Rules.
>
> There are three types of links (usages):
>
> * Javascript - Links that will trigger the rules using Ajax.
> * Token - This are basic links, that will reload the page after calling them.
> * Confirmation link - Show a confirmation form before executing the rule

The module's Readme.txt contains some more documentation about how to use it.

### Example Configuration

1. Define a rules\_link with a "Link type" of "Confirmation" and make sure to define a "Path" for it, e.g. http://example.com/`confirmation-page`.
2. Edit the rules\_link you created and go to "Configure rules" then create a "Reaction" rule containing all the actions you want to take if the user clicks "Confirm" on the confirmation page.
3. Create a normal rule for the particular event you want to trigger the confirmation page on (in this case we're using an "After updating existing content" event).
4. Add whatever conditions you might require then add a single "Page redirect" action where the "URL" is defined as the path to the rules\_link confirmation page plus a node ID token and a destination parameter, e.g. `confirmation-page/[node:nid]?destination=node/[node:nid]`.

With this configuration, when the user updates a node with nid 12345 they are redirected to "http://example.com/confirmation-page/12345?destination=node/12345". If they click "Confirm" the rest of the required actions are executed before returning to the updated node. If they click "Cancel" they return directly to the updated node without any further actions executing.

# Answer
> 1 votes
Under action Check **Execute custom PHP code** under PHP. May be it will be useful or do it using custom js

# Answer
> 1 votes
This can be done with the contrib module Popup ON Load. It has rules integration. Specifically here are instructions.

Some more details about this module (from its project page):

> ... allows to display a popup once after a certain delay on a page load. This fills a gap in popup modules family (Popups, Popup), which are designed to show popups only after a click on an HTML element, or to implement a complex behavior like modal dialog forms.

---
Tags: 7, rules
---


# Question
Title: How to redirect form to a url having wild card character in drupal?
How to redirect form to a url having wild card character in drupal? For example, can I do like this below shown?

```
$form_state['redirect'] = 'admin/component/%/edit'

```

or any other alternative approach to do like this?

# Answer
You cannot do this in a form because the redirect has to be definitive. You much know the variable being put into the % via some means.
> 1 votes

# Answer
Sure it can be done , but % is not used in this case , % is used when you want to read an element from url not to create a url . to do that you can rewrite your code as follows :

```
$form_state['redirect'] = 'admin/component/SOMEVARIABLE/edit';

```

this is an example to get it better , for redirecting to a node edit form we have :

```
$form_state['redirect'] = 'node/'.$node->nid.'/edit';

```

so you must find a way to make a proper variable for that.
> 1 votes

---
Tags: forms
---


# Question
Title: How to format views table using open outreach theme
The Views preview of my table looks like this.

Using Open Outreach it appears like this.

Neither are exactly what I'd like to see. How can I change the displayed table format (on my site) without fooling with php and CSS? I'm new to Drupal. I really don't want to get into CSS and php.

# Answer
You could transform the **tabular** display by using the DataTables **module**, which uses the datatables **plugin**.

In doing so, you get all the typical dataTables widgets available, such as sorting for appropriate columns, but also a search box, pagination, etc.

Here is an excerpt from the module's project page:

> ... integrates the jQuery plugin DataTables into Drupal as a views style and a callable theme function. DataTables lets you add dynamic features to tables, including:
>
> * Variable length pagination
> * On-the-fly filtering
> * Sorting with data type detection
> * Smart handling of column widths
> * ... (1)

(1) = there are more features (i.e. "*Themeable by CSS*"), but that requires "*fooling with php and CSS*" ...

PS: Works great for both D6 and D7 ...

**Update** (related to that issue you ran into as mentioned in your comment):

Consider reviewing/testing if that patch in comment nr 1 might work for you. The patch looks like so:

```
diff --git a/datatables.module b/datatables.module
index 193c892..3b66932 100644
--- a/datatables.module
+++ b/datatables.module
@@ -244,11 +244,8 @@ function theme_datatable($variables) {
 function template_preprocess_datatables_view(&$vars) {
   // Run views table preprocess function to handle putting rows in columns,
   // classes, etc.
-  template_preprocess_views_view_table($vars);
-
-  // No need to add anything if there are no rows.
-  if (!$vars['rows']) {
-    return;
+  if(!empty($vars['rows'])) {
+    template_preprocess_views_view_table($vars);
   }

   $view     = $vars['view'];

```

The most elegant / straight forward way to "apply" that patch is to use GIT. However, this seems like only a few lines in 1 module are changed by the fix. You could also "apply" that fix by simply editing that module to be patched, by reading what the patch content is, and then editing the module with your favorite editor, to achieve the same result. Here are the steps involved:

* navigate to the folder in your site that contains file `datatables.module`.
* make a backup copy, eg to something like `datatables.module.backup`.
* open `datatables.module` in your favorite editor, and scroll to the line around line 244. If you can, turn line numbers on.
* You should then see a few lines of code identical to the lines near the top of the patch (not preceeded by '-' or '+' signs.
* around line 247, there should be a line like `template_preprocess_views_view_table($vars);`, but without that '-' sign as in the patch
* DELETE that exact line, and then next 4 lines entirely (which is indicated in the patch with the '-' sign at the start of each line).
* then INSERT those 2 lines preceeded by a "+" in the patch (but make sure to replace the "+" signs at the start of those 2 lines with a blank).
* save your (module) file, and rerun your test to see what effect/result you now get.
* after you finished testing it, decide what you want to do with this edited version of the module. Continue to use it? If not rename the edited file to something like `datatables.module.edited`, and then rename the `datatables.module.backup` file back to `datatables.module`. That will have restored the original version.
> 0 votes

---
Tags: theming
---


# Question
Title: Better way to manually load a view of nodes other than with "views_get_view_result" > "node_load"?
I've got a d7 site on a shameful shared hosting account.

Since I am a pseudo haxxor, I want to load up my front page view and manually output all of my nodes. My Front Page takes about 30 seconds to load in the worst case. I am tears.

Here is what I am doing:

```
$view = views_get_view_result('main_feed');
foreach($view as $item){
    $node = node_load($item->nid,NULL, TRUE);
    /* assorted display code */
}

```

Any thoughts? 2.7 trillion thanks to all!

**EDIT:**

Well @Druplaist was right - this SHOULD work - after reading my own question I thought "If somebody else were asking this, I'd suggest that the problem was inside of /\* assorted display code \*/ - and it is - probably some truncating method I grabbed. It's still Drupal slow, but not 30 seconds till the server gets back to me slow.

Thanks for answering my stupid question, people!

# Answer
Since you need to load all of the nodes on your front page, Not that much difference does it make how you implement it, whether using code or loading View in a page or block or ....

views\_embed\_view do the same thing and loads a View but it doesn't reduce the load size!

I recommend you to to use Ajax. The Views Load More module is exatcly what you need. This module

* Provide ajax/no-ajax views load more
* Works with views default ajax implementation, no hacks (check/uncheck ajax)
* Supports the Waypoints module for loading on various points, Such as when the scroller is visable on the page.
* Supports the Fade effect when loading new content.

Instead of loading all of your content, simply just load 100 or 200 of them then use Ajax to load more.

Views Show More module is another solution. This module

* Works both views ajax and no-ajax mode (developed mainly for the ajax mode).
* Option for result display method. Can choose Append or Replace method.
* Option to override 1st page or initial item count than others page.
* Basic and advance animation system for result impression for ajax mode.
* Ability to define custom animation timing.
* Advance settings for content area and pager area selector. If default html

In the aggregate, create a View of all of the content types that their nodes must be included in the front page, include that view in the front page and use one of the above modules to use load more.
> 1 votes

---
Tags: views, performance, nodes
---


# Question
Title: TB Mega Menus: Image block doesn't show anything
I'm building my first page with Drupal, creating a subthem of Omega 4, and for the menus I chose to use TB Mega Menu. The problem is that I want one of the columns of the drop down to contain an image. For that, I create a block and add that image to it, having it this HTML code:

```
<p><img alt="" src="http://localhost:81/www.mysite.com/sites/all/themes/mytheme/images/myimage.jpg" /></p>

```

But when I add that block to a column, it shows nothing. If I check the option to show the block title, it shows the block title, but no image.

Any help on that? I have searched for any issues like mine, but no luck.

Thanks in advance.

# Answer
> 1 votes
I would suppose that you need to choose "FULL HTML" format for your block content.

---
Tags: blocks, navigation
---


# Question
Title: Module WYSIWYG with the 4.4.7 Ckeditor library stopped working
What I got in Drupal 7:

```
WYSIWYG module 7.x-2.2

CKEditor library 4.4.7.3a35b3d

```

Changes I made:

**1.** This get's ckeditor library to work with WYSIWYG:

In .../modules/wysiwyg/editors/ckeditor.inc change line from function wysiwyg\_ckeditor\_version($editor)

```
if (preg_match('@version:\'(?:CKEditor )?([\d\.]+)(?:.+revision:\'([\d]+))?@', $line, $version)) {

```

to

```
if (preg_match('@version:\"(?:CKEditor )?([\d\.]+)(?:.+revision:\"([\d]+))?@', $line, $version)) {

```

This changes version number search from single quotes version: '4.0' to double quotes version "4.0"

This changed error in console log about jquery version.

**2.** In .. Wysywig .../modules/wysiwyg/wysiwyg.js change function

```
$('.wysiwyg', context).once('wysiwyg', function () {

```

to

```
 $('.wysiwyg:not(.processed)', context).addClass('processed').each(function() {
       if (!this.id || typeof Drupal.settings.wysiwyg.triggers[this.id] === 'undefined') {
         return;
       }

```

**3.** Iv'e cleared caches.

**4.** Added Full HTML format to /admin/config/content/formats

**5.** Added buttons at /admin/config/content/wysiwyg

**6.** Tried to "downgrade" to the 3.6.x version of CKEditor

**7.** Tried Ckeditor module https://www.drupal.org/project/ckeditor without wysiwyg module

**8.** Tired TinyMc library with wysiwyg

**9.** !Solution! need lines of kode at sites/all/templates/html.tpl.php to load wysiwyg.js .:

```
<?php print $page_top; ?>
<?php print $page; ?>
<?php print $page_bottom; ?>

```

# Answer
> 0 votes
I would "downgrade" to the 3.6.x vrsion of CKEditor (such as CKEditor version 3.6.6.1.7696), since the WYSIWYG module does not support the 4.x version yet ...). In this case, you may also want to experiment with the various '*cleanup and output*' options within `/admin/config/content/wysiwyg/profile/your_txt_fmt/edit` (with '`your_txt_fmt`' the text format you're using, eg '`filtered_html`').

Another option is to switch to the CKeditor module (which is in core in D8 now ...), and no longer use the WYSIWYG module in combination with the CKEditor library.

---
Tags: wysiwyg
---


# Question
Title: Can behat log in as an administrator for testing while using LDAP?
I'm using the Behat Drupal Extension. When I try to run a behat test on a sandbox server, I see the following. I see that a temporary admin user is being create but it can't seem to log in. **How might I remedy this so that behat can login?**

```
$ behat

Feature: First   Playing with features and exploring

  @api   Scenario: Run cron
# features/first.feature:6
    Given I am logged in as a user with the "administrator" role # Drupal\DrupalExtension\Context\DrupalContext::assertAuthenticatedByRole()
      Failed to log in as user 'ss5vWjZY' with role 'administrator' (Exception)
    When I run cron                                              # Drupal\DrupalExtension\Context\DrupalContext::assertCron()
    And am on "admin/reports/dblog"                              # Drupal\DrupalExtension\Context\MinkContext::visit()
    Then I should see the link "Cron run completed"              # Drupal\DrupalExtension\Context\MinkContext::assertLinkVisible()

```

I've changed my LDAP configuration back to mixed mode:

>

And only admins are allowed to create a new account

>

# Answer
I had this issue as well. It turned out to be a problem with LDAP. Switching to Mixed Mode allow the DrupalExtension to function properly. Since we don't want mixed by default, I added a pre-test setup function

```
public static function prepare($scope)
     {
        $data = array(
          'sids' => array (
            'directory' => 'directory',
          ),
          'authenticationMode' => 1,
          'loginConflictResolve' => 2,
          'acctCreation' => 4,
          'loginUIUsernameTxt' => NULL,
          'loginUIPasswordTxt' => NULL,
          'ldapUserHelpLinkUrl' => NULL,
          'ldapUserHelpLinkText' => 'Logon Help',
          'emailOption' => 3,
          'emailUpdate' => 1,
          'allowOnlyIfTextInDn' => array (),
          'excludeIfTextInDn' => array (),
          'allowTestPhp' => '',
          'excludeIfNoAuthorizations' => NULL,
          'ssoRemoteUserStripDomainName' => NULL,
          'seamlessLogin' => NULL,
          'ldapImplementation' => NULL,
          'cookieExpire' => NULL,

        );
        variable_set('ldap_authentication_conf', $data);
     }

```

The key is the line `'authenticationMode' => 1,`
> 3 votes

---
Tags: testing
---


# Question
Title: How to filter admin/structure/block per role
I use block access to determine which block a role can edit. I enabled *Access the block administration page* and *View all blocks* permissions so that my blocks\_editor role now can access the `admin/structure/block` page.

But the page displays the complete and huge list of blocks, with a configure link when allowed to do so, as in screen capture below :

How can I filter/restrict this output to the list of blocks the role has permission to edit ?

Or as an alternative, how can I programmatically generate in a block, the links to blocks a role has access to ?

Thank you.

# Answer
Checking the code, this popped up:

```
  // Remove the block completely if it's not allowed to be viewed
  if (!block_access_can_view($module, $delta)) {
    unset($form['blocks'][$key]);

```

in block\_access\_check\_perms (.module file)

Otherwise it only removes the operations that user doesn't have access to. Now, this function gets called in the form\_alter for the block overview page. So, you have two options as far as I can see.

First, restrict the view permission to be the same as edit (these permissions have no effect on the front-end visibility, as per the project page). This is your best bet I believe.

The other option is to alter the form again after this module has already altered it, run your own checks and then unset the blocks with no operations left.
> 1 votes

# Answer
Nick's answer put me on the right way. I suppose there is a more straight way to theme this in a table than with form markup, but this works just fine.

```
<?php
/**
 * Implements hook_form_FORM_ID_alter();
 */
function MYMODULE_form_block_admin_display_form_alter(&$form, &$form_state, $form_id) {

  global $user;
  if( !in_array('administrator', array_values($user->roles)))  {
    //Prepare new output
    $form['table']= array(
      '#type' => 'markup',
      '#prefix' => '<table>',
      '#suffix' => '</table>',
    );
    $form['table']['header']= array(
      '#type' => 'markup',
      '#markup' => '<thead><th>'.t('Block name').'</th><th>'.t('Operations').'</th></thead>',
    );

    foreach ($form['blocks'] as $key => $value) {
      $module = $form['blocks'][$key]['module']['#value'];
      $delta = $form['blocks'][$key]['delta']['#value'];
      //My custom permissions checks, with block access functions
      if ( block_access_can_config_description($module, $delta) || block_access_can_config_body($module, $delta) ) {

        $form['table'][$delta] = array(
          '#type' => 'markup',
          '#prefix' => '<tr><td>',
          '#suffix' => '</td>',
          '#markup' => $form['blocks'][$key]['info']['#markup'],
        );
        $form['table'][$delta.'link'] = array(
          '#type' => 'markup',
          '#prefix' => '<td>',
          '#suffix' => '</td></tr>',
          '#markup' => l(t('edit'), $form['blocks'][$key]['configure']['#href']),
        );
      }
    }
    //I don't need the standard form anymore
    unset($form['blocks']);
    unset($form['block_regions']);
    unset($form['actions']);
  }
}

```

This gives following output in the altered `admin/structure/block` page, depending on the user's permissions and the permissions checks done :
> 1 votes

# Answer
I done this once with Block Access. Here is what I did.

1. Under admin/people/permissions, check "Access the block administration page" and "View all blocks" permissions for who has access to edit blocks.
2. Inside each block edit: set all permission for administrator only, except those specific setting you allow them to change. Like "Role Specific Config\_Body Setting", "Role Specific Config\_Desc Settings" and "Role Specific Config\_title Settings".
> 0 votes

---
Tags: blocks
---


# Question
Title: How to alter rendered commerce line item on order entity view?
I need to add a column(a "checking logistics picking" link) to each line item on order page(i.e. user/%user/orders/%commerce\_order page), but I cannot make it done. I tried hook\_entity\_view\_alter and hook\_block\_view\_alter, but seems they can only alter order entity view, cannot alter line items part of the order.

How to alter line item on order page? It became urgent, please help! Thanks.

# Answer
> 1 votes
I know it is a bit late, but here is what I did to modify the line items on an order view.

For my example, I wanted the type field to be displayed, so I altered the view of the `commerce_line_item` entity using `hook_views_pre_view(&$view)`. Here the code that have:

```
switch ($view->name) {
    case 'commerce_line_item_table':
        $view->display['default']->handler->options['fields']['type']['exclude'] = FALSE;

```

This is all I needed to do since type was already there in the `commerce_line_item_table` view defined in commerce\_line\_item.views\_default.inc, but if you want to add a field to the view, it would look something like this

```
        $view->display['default']->handler->options['fields']['type']['id'] = 'type';
        $view->display['default']->handler->options['fields']['type']['table'] = 'commerce_line_item';
        $view->display['default']->handler->options['fields']['type']['field'] = 'type';
        $view->display['default']->handler->options['fields']['type']['relationship'] = 'commerce_line_items_line_item_id';

```

Please note, that when you later the view for the user/%user/orders/%commerce\_order page, it also alters admin/commerce/orders/%commerce\_order/view since they both use `entity_view`

---
Tags: commerce
---


# Question
Title: Advanced Aggregation: Should I disable core's aggregation?
I know that AdvAgg's bundler will, by default, disable core's *grouping logic*, but I'm unclear as to whether core's aggregation should be enabled or disabled (at admin/config/development/performance) for AdvAgg to be able to aggregate files in the first place.

Basically, I can't tell if AdvAgg is actually aggregating things itself (and thus core should probably be disabled under admin/config/development/performance), or if AdvAgg is taking core's aggregated files and only handling the bundling aspect of aggregation, in which case core's aggregation would need to be enabled. I suspect the former is the case, but I can find no explicit information on this.

Can anyone tell me what the general best practice here is?

# Answer
> 3 votes
> Should I disable core's aggregation?

No; AdvAgg uses the core aggregation setting as part of its own on/off switch. If core aggregation is disabled, AdvAgg aggregation is implicitly disabled.

In fact if you do disable it, you get this helpful error in the status report:

You can tell whether or not AdvAgg is producing your files from the path - it will contain `/advagg_(css|js)/`.

---
Tags: 7, css-js-aggregation
---


# Question
Title: How do I redirect example2.com to example.com
My website has 2 domain, example.com and example2.com.

**example.com/node/1** and **example2.com/node/1** are the same link.

**How do I redirect example2.com to example.com.**

When people open the linke example2.com/node/1, it will redirect to example.com/node/1

# Answer
Another method here, if you're using Apache, is to perform the redirect before it starts executing Drupal code. Place this in your site root's **.htaccess** file somewhere below the `RewriteRule ^ - [E=protossl:s]` line.

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

```

Note: this will redirect *every request* so if you're just looking to redirect URLs with valid nodes it might not be the best solution here.
> 0 votes

# Answer
There are many ways to do this. I just give you the most straightforward (of course for me!) and simplest one.

In `hook_preprocess_html` use this code

```
THEME_preprocess_html(&$var){
      $host = $_SERVER['HTTP_HOST']. request_uri();
      if(strpos($_SERVER['HTTP_HOST'],'example2') !=false)
           header("location:example.com/".request_uri());
}

```

I can't test this code right now, but this is the main idea:

Get current url components separately, the host (`$_SERVER['HTTP_HOST']`) and what comes after it (`request_uri()`), if its `$_SERVER['HTTP_HOST']` contains `example2` as a substring, then redirect the user to `example.com/request_uri()`

For redirection you can also use `drupal_goto` or anything else you want I just gave you the pure PHP.
> 0 votes

---
Tags: redirection
---


# Question
Title: Need help Converting a jQuery event to a Drupal Behavior
I have a Drupal 7 web site that is using jQuery animations to fadeIn div tags. I need an event to capture a fadeIn when it is completed. I have found a sample jQuery example that does what I need it to, but I have not been able to successfully convert it to a Drupal 7 behavior and I'm not quite sure what I might be missing.

Fiddle Example

Below is my Drupal JS file, `fadeInEvent.js`.

```
Drupal.behaviors.fadeInEvent= {
    attach: function (context, settings) {

        var _old = jQuery.fn.fadeIn;

        jQuery.fn.fadeIn = function() {
            var self = this;
            _old.apply(this.arguments).promise().done(function(){
                self.trigger('fadeIn');
            });
        };

        jQuery('.tab-pane').bind('fadeIn', function() {
             alert('fadeIn Done.');
        });

    }
};

```

In the above JS code, I never get my alert that the fadeIn has finished on the item I have selected.

# Answer
> 1 votes
Alter don't show because in your code:

```
jQuery('.tab-pane').bind('fadeIn', function() {
             alert('fadeIn Done.');
        });

```

this function mean that when selecter **.tab-pane** fadeIn done, alert will show. But You don't call fadeIn =\> don't have event fadeIn. You need call that same:

```
jQuery('.tab-pane').fadeIn(2000);

```

And better function **jQuery.fn.fadeIn** need outside Drupal.behaviors.fadeInEvent

```
(function ($) {
    var _old = $.fn.fadeIn;
    $.fn.fadeIn = function(){
        var self = this;
        _old.apply(this,arguments).promise().done(function(){
            self.trigger("fadeIn");
        });
    };

    Drupal.behaviors.fadeInEvent= {
        attach: function (context, settings) {

            $('.tab-pane').bind('fadeIn', function() {
                alert('fadeIn Done.');
            });
            $('.tab-pane').hide();
            $('.tab-pane').fadeIn(2000);
        }
    };
})(jQuery);

```

then you call fadeIn() every where and have event fadeIn.

---
Tags: javascript
---


# Question
Title: "Add another item" using #ajax in hook_field_widget_form
I'm trying to create a custom widget for my module which will contain a textfield to hold a question(textfield), Question style (select box), potential answers (typed into textarea).

I'd then like an "add another item" button so the client can add as many questions as they like.

I've got a basic ajax widget working but i'm not sure if I've constructed it correctly because when I want to validate the data in hook\_field\_validate I don't seem to be able to access each question seperately.

I thought i'd be able to validate each question before the next is added by ajax but this doesn't seem to be working.

Asssuming this code (below) is correct, can you please advise how I can validate each time the "add another item" is clicked.

**My hook\_field\_widget\_form looks like this:**

```
    function keep_warm_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $element['question_wrapper'] = array(
    '#type' => 'fieldset',
    '#title' => t('Questions'),
    // Set up the wrapper so that AJAX will be able to replace the fieldset.
    '#prefix' => '<div id="names-fieldset-wrapper">',
    '#suffix' => '</div>',
  );

  if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }
  for ($i = 0; $i < $form_state['num_names']; $i++) {

    //other form elements
    $element['question_wrapper'][$i]['question'] = array(
      '#type' => 'textfield',
      '#title' => t('Question number '. $form_state['num_names']),

    );

  }

  $element['question_wrapper']['add_question'] = array(
    '#type' => 'submit',
    '#value' => t('Add another question'),
    '#submit' => array('ajax_example_add_more_add_one'),
    // See the examples in ajax_example.module for more details on the
    // properties of #ajax.
    '#ajax' => array(
      'callback' => 'ajax_example_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  if ($form_state['num_names'] > 1) {
    $element['question_wrapper']['remove_name'] = array(
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => array('ajax_example_add_more_remove_one'),
      '#ajax' => array(
        'callback' => 'ajax_example_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
      ),
    );
  }

return $element;
}

```

**And my ajax callback**

```
function ajax_example_add_more_callback($form, $form_state) {
  $form_state['num_names']++;
  return $form['field_question'];
}

```

# Answer
> 1 votes
Looks like you're just missing a `#tree` property:

> Used to allow collections of form elements. Normally applied to the "parent" element, as the #tree property cascades to sub-elements. Use where you previously used \]\[ in form\_ calls. For more information, see #tree and #parents in the handbook.

e.g.

```
$element['question_wrapper'] = array(
  '#type' => 'fieldset',
  '#title' => t('Questions'),
  // Set up the wrapper so that AJAX will be able to replace the fieldset.
  '#prefix' => '<div id="names-fieldset-wrapper">',
  '#suffix' => '</div>',
  '#tree' => TRUE,
);

```

And then in the validate handler:

```
foreach ($form_state['values']['question_wrapper'] as $key => $value) {
  if (is_numeric($key) && something_is_wrong_with($value['question'])) {
    form_set_error("question_wrapper][$key][question", 'Error');
  }
}

```

# Answer
> 0 votes
If you want multiple questions , then you can use UI and define your field as multiple value field when creating an instance of it. This way is easy and drupal will handle the rest. just because I think you have misunderstood I tell you that using field API we use to define a Field type not an Instance , I don't say you are completely wrong but what if your field type wants to be used in a situation that it always used single value?

but if you still persist you can write a validation function and call it in "ajax\_example\_add\_more\_callback" function.

to access your fields data you can use this code :

```
foreach($form_state['values']['question_wrapper'] as $key => $value) {
  //do something with $item
  //Code was stolen from @Clive . just for not representing a false answer
}

```

---
Tags: ajax, entities
---


title: Multiple instances of item in View row

text:
# Question
Title: Multiple instances of item in View row
I am getting five instances items in my View row when I wrap image field inside my link field. This is what I have in the template file:

```
    <?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php //print $field->content; ?>
    <div class="myRow">
        <div class="myImg">
            <span class="featuredVideo"></span>
            <a href="<?php print $fields['field_news_link']->content; ?>" target="_blank"><?php print $fields['field_news_image']->content; ?></a>
            <?php //print $fields['field_news_image']->content; ?>
        </div>
        <a href="<?php print $fields['field_news_link']->content; ?>"><?php print $fields['field_news_source']->content; ?></a>
    </div>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>

```

If I uncomment `<?php //print $field->content; ?>` and remove the linked image and the rest of my mark up, I don't get multiple instances of the item.

# Answer
The field template prints all the fields as a row. If you want to output the row of fields manually you need to remove the `foreach` iteration of the fields.

See views-view-fields.tpl.php for more info.
> 1 votes

---
Tags: 7, views, theming
---


# Question
Title: When should I use collect an end date for a field, instead of using 2 separated date fields?
I need to make a content type with a *Start Date* and an *End Date*. I know that I can handle this in two ways:

1. Have two separate field
2. Have one field with a option of *"collect an end date"*.

I wonder when I should choose either of these options. I assume that the second option is for representing an Event in a Calendar. But if I don't need this, is the first option then the best?

**EDIT:**

If you plan use the "**collect an end date**" option you need read this:

How to use the Time ago view formatter when you have an end date collected in your date field?

Because you can have problems with the Views module and the **Time ago** view formatter.

# Answer
**Why having two fields if one will be enough to serve the purpose?**

Your question itself states that you need a "Start Date and End Date" so I think option 2 will be better, as it's simpler and could perfectly solve the problem you are facing. Also, the Date module is highly flexible, so displaying your dates in different formats will be easy enough.

On the other hand, only reason that comes to my mind for having 2 separate fields could be for re-usability, for example, if you wanted to reuse only one of your fields in another content type.
> 4 votes

---
Tags: nodes, datetime
---


# Question
Title: How to access and edit files from admin panel?
How i can acces my files without going to host control panel or by ftp. I mean if any module is for that to access and edit files from Admin panel.

# Answer
> 1 votes
Try elfinder File Manager module, which also allows inline text file editing, besides other file managing operations.

# Answer
> 0 votes
The full path or under sites/foobar/files? You should try IMCE. It has a browser-client. This is the link: https://www.drupal.org/project/imce

---
Tags: theming, files
---


# Question
Title: Programmatically show field in different regions depending on content
I'm creating an Omega sub theme & three regions ("Sidebar 1", "Content" & "Sidebar 2") inside of the "Content zone". "Sidebar 1" & "Content" are both set to always show, "Sidebar 2" however is set to only show if there's content inside of it.

I also have a field which contains links related to the page, this is output programmatically into all three regions but CSS hides all but one. This is done so it can be shown in the "Sidebar 1" region which stacks above the "Content" region on small screens but on larger screens it'll be hidden in the "Sidebar 1" region & shown in the "Sidebar 2" region instead, on the right hand side. If "Sidebar 2" doesn't exist it'll then be shown in "Content."

"Sidebar 1" pretty much only contains a menu, only on some pages though, which is again programmatically output. The reason being that I want to label / title of the menu to be set to the name of the currently active page and it was the best way I could see of doing it.

I've almost got it all working as I have a class set on the content zone div which states how many regions are inside of it (2 means no "Sidebar 2", 3 means it's there) & the first sidebar now adds a class stating if it's empty or not.

I've attempted to add a class to the "Sidebar 2" region by using drupal\_get\_region\_content("sidebar\_1") to detect if the "Sidebar 1" region is empty of not and add a class to the "Sidebar 2" region based on this will CSS selectors will use. Problem is no mater what I try or what region I try to output drupal\_get\_region\_content always returns NULL.

**The basics of what I'm trying to do** I'll try and write here what I'm wanting in a more concise manor, above I've also included how I'm trying to do it.

I have some pages with three regions in the content zone, I want to output a field in all three regions so they can be shown & hidden at different screen sizes with CSS.

The left sidebar might have a menu in which is added programatically. If it does not have this then the second sidebar doesn't need to the field I'm outputting programmatically will just be shown in the first sidebar & main content area.

I realise this is very long, appreciate anyone who's read it and any help you can offer.

# Answer
> "I have some pages with three regions in the content zone, I want to output a field in all three regions so they can be shown & hidden at different screen sizes with CSS..."

If this is the case, you could solve this entirely in CSS, by using media queries to show / hide areas -or your field -depending on the browser size. And you don't even need to have the same field in all the three regions.

However, **if what you want is to show / hide columns inside your content depending on a field value**, you might be looking for the Display Suite module, which allows you to easily create different layouts and *view modes*. For example, you could:

1. Create one view mode with 2 columns and another one with 3 columns.
2. Add the fields you want to display in each one of those view modes.
3. If you want to switch the view mode, depending on whether a field has a value or not, you could use hook\_entity\_view\_mode\_alter() like this:

```
function YOUR_MODULE_entity_view_mode_alter(&$view_mode, $context) {
  // If viewing a node in the two_columns view mode...
  if ($context['entity_type'] == 'node' && $view_mode == 'two_columns') {

    // If your field 'something' has a value, change the view mode to 'three_columns'.
    if (!empty($context['entity']->field_something)) {
      $view_mode = 'three_columns';
    }
  }
}

```

Or you could also use the Contextal View Mode module to change the view mode for a node based off of a context.
> 0 votes

---
Tags: 7, entities, theming
---


# Question
Title: User module functions undefined in custom module
I am attempting to use the user\_password() and user\_save() functions from user.module in my custom module file, but I only receive the following:

> Fatal error: Call to undefined function user\_save() C:\xampp\htdocs\drupal-7.38\sites\all\modules\\(modulename)\\(modulename).module on line 1037

I get a similar error if I comment out all of my code, leaving the module file as

```
<?php
user_save();

```

As far as I know, if the only problem was the lack of parameters, it chould be an entirely different error, not 'Call to undefined function'.

The function in which I'm trying to use user\_password() and user\_save() is as follows:

```
function create_user_by_id($id){
    $password = user_password(8);
    $info = soap_info($id);
    $fields = array(
        'name' => $id,
        'mail' => $info['mail'],
        'pass' => $password,
        'status' => 1,
        'init' => 'email address',
        'roles' => array(
            DRUPAL_AUTHENTICATED_ROLE => 'cas authenticated user'
        )
    );
    $account = user_save('', $fields);
    drupal_mail(
        'user',
        'register_no_approval_required',
        $info['mail'],
        NULL,
        array('account' => $account),
        variable_get('site_mail', 'noreply@example.com'));
}

```

# Answer
> 1 votes
So you are just calling a function without telling drupal how to access that function , you can tell drupal about where to find this function using this code :

```
 module_load_include('module', 'user', 'user.module');

```

---
Tags: users
---


# Question
Title: Migrate module showing 0 processed on production server
We intend to run regular migrates to update content and the initial migrate was on my local machine. Now that its up on production I changed the connection strings to the database and its showing 0 processed. This is the same database structure except one is local and the other is on production.

How can I get migrate module to recognize the production database with these nodes already processed? I would just reimport them but the problem is that there are other nodes that reference these already and it will mess up a lot of structure.

# Answer
> 0 votes
I guess I didn't take as much time to look into this and then had a light bulb moment. Migrate actually creates a table in the database of the one it is importing from (probably skimmed over this in the docs). So I need to do a sync of those tables from my local to production.

---
Tags: migrations
---


title: Diff of module version releases

text:
# Question
Title: Diff of module version releases
I'm trying to debug an error I'm encountering in the latest version of the Custom Formatters module and I'm encountering a common problem I have in debugging. There's no easy way to do a project-wide diff of project from release to release. I'd like to easily diff https://www.drupal.org/project/custom\_formatters 7.x-2.4 with 7.x-2.3. I can use software locally to do that, but github has spoiled me I guess. Am I missing a hidden function of drupal.org that shows diffs between releases?

# Answer
> 2 votes
You can clone down the project via

`git clone --branch 7.x-2.x http://git.drupal.org/project/custom_formatters.git`

When in the directory do a `git diff 7.x-2.4..7.x-2.3` and review the output.

If you don't want to scroll through your terminal, try `git diff 7.x-2.4..7.x-2.3 > version-change.diff` and pop the output into a diff viewer.

I wish cgit had this built it, but the diff viewer in it only supports per commit (as far as I know)

---
Tags: 7, debugging
---


# Question
Title: How to use user_load() for user on $_GET[] request in Drupal way?
I'm trying to get UID of users on $\_GET\[\] request, following is my module code:

**my\_module.module**

```
function hover_card_init() {
  $module_path = drupal_get_path('module', 'hover_card');
  drupal_add_js($module_path . '/javascripts/hover_card.js');
  drupal_add_js(array('hover_card' => array('module_path' => $module_path)), array('type' => 'setting', 'scope' => JS_DEFAULT));
}

function hover_card_menu() {
  $items['hover-card'] = array(
    'title' => 'Hover Card',
    'page callback' => 'hover_card',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function hover_card() {
  $id = $_GET['id']; // Get UID using JS, not a Drupal way!
  $user_fields = user_load($id);

  if (isset($user_fields->name) && !empty($user_fields->name)) {
    $name = $user_fields->name;
  }

  $array = array(
    'name' => $name,
  );

  return theme('hover_card_template', array('details' => $array));
}

```

**my\_module.js**

```
(function ($) {
  Drupal.behaviors.hover_card = {
    attach: function (context, settings) {
      var module_path = Drupal.settings.hover_card.module_path;
      var hoverUserDetails = '<div class="hover-details"></div>';
      $("a.username").hovercard({
        detailsHTML: hoverUserDetails,
        width: 250,
        onHoverIn: function () {
          var user_id = $(this).find("a").attr("href").split("/");
          var hover_details = $(".hover-details");
          $.ajax({
            url: Drupal.settings.basePath + "hover-card",
            type: 'GET',
            data: {
              id: user_id[3] // What should I do here? As this is not a clean and Drupal way :-(
            },
            beforeSend: function () {
              hover_details.empty();
              hover_details.prepend('Loading...');
            },
            success: function (data) {
              hover_details.html(data);
            },
            complete: function () {
              $('.loading-text').remove();
            }
          });
        }
      });
    }
  };
})(jQuery);

```

# Answer
> 1 votes
As said in the comment for the question, you should use placeholders in your menu definition.

```
function hover_card_menu() {
  $items['hover-card/%user'] = array(
    'title' => 'Hover Card',
    'page callback' => 'hover_card',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

Then you can pass the user ID for the currently logged-in user to the JavaScript code, instead of passed the module path, which is irrelevant.

```
function hover_card_init() {
  $module_path = drupal_get_path('module', 'hover_card');
  drupal_add_js($module_path . '/javascripts/hover_card.js');
  drupal_add_js(array('hover_card' => array('user_id' => $GLOBALS['user']->uid)), array('type' => 'setting', 'scope' => JS_DEFAULT));
}

```

The JavaScript code doesn't need to know the module path, since it will make an AJAX call to hover-card/%user which is not related to the module path in any way.

---
Tags: hooks, users, entities
---


# Question
Title: Generate a view with parent - child taxonomy terms
Is there any way that I can create a view of parent-child taxonomy terms that would look alot like this? I was thinking I could use the parent relationship and then group terms and print in a grid but there is no options for parents to be a group field.

http://www.amazon.com/gp/site-directory/ref=nav\_shopall\_btn

# Answer
I figured the answer. There is a relationship select box that appears on existing fields. I had to add twice the name field, make one of them use the parent relationship and exclude it from display and then use this as a grouping variable for the grid.
> 1 votes

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


# Question
Title: Update field data added in user form using a hook?
I've added three fields in user form.

1. User code
2. User name
3. User ID.

I want to add this field data into the database. My question is, in which hook, i should write the logic of manipulating and saving data.

# Answer
Hook implementation depends on ***when*** you want to manipulate the user account data.

If you need to update existing users with new data you need your own custom function that makes user of `user_load()` (to load a user object) & `user_save()` (to save your manipulated user object with new data).
> 0 votes

---
Tags: forms, users
---


# Question
Title: Drupal gives me a blank page after moving from localhost to server
I am new to Drupal . I moved my project from local host to server but it does not display either an database error or a page not found error. Everything works better in local. Please help me .

# Answer
With the limited amount of details provided it is really hard to guess what might be causing it. So here are some things you may want to check:

* look in your webserver logs if any error is shown there.
* make sure you granted the appropriate file permissions.
* not enough PHP memory.

If you add more details to the question (like which OS, which webserver, etc) we might provide more answers also ...
> 1 votes

---
Tags: 7
---


# Question
Title: How to get only field value in View template
How can I access/print the raw value of a date field? (or any field for that matter). I am working in a View template and I typically use `$fields['field_myfield']->content`. But that gives me the HTML not just the value.

My template.php file:

```
 function mytheme_preprocess_views_view_fields(&$variables)
{
    $view = $variables['view'];
    if($view->name == "news_main_list")
    {
          $variables['news_date'] = $variables['fields']['field_news_date_text']->content;
          $variables['news_type'] = $variables['fields']['field_news_type']->content;
          $variables['theme_hook_suggestions'][]='views_view_fields__news_main_list__block_1';
     }
 }

```

My views-view-fields--news-main-list--block-1.tpl.php file:

```
  <?php if (!empty($field->separator)): ?>
<?php print $field->separator; ?>

```

```
  <?php print $field->wrapper_prefix; ?>
<?php print $field->label_html; ?>

<p class="newsTitle"><?php print $fields['title']->content; ?></p>
<p class="dateByLine">
    <?php print $news_date; ?> | <?php print $news_type; ?>
    <?php if ($news_type == "event") : ?>
        <?php print 'hello'; ?>
    <?php endif; ?>
</p>

  <?php print $field->wrapper_suffix; ?>

```

# Answer
> 1 votes
You must specify which one of Views template files you are working on, If it is `views-view-fields.tpl.php` then `$fields` variable is availabe but if it is not `views-view-fields.tpl.php` then `$view` object is available. use `kpr($variable)` to get the `$variable` available properties.

You can also use `hook_preprocess_views_view_fields(&$var)` to set the values of fields in `$var` array then retrieve them in fields template file

---

**UPDATE:**

First define the following function in your `template.php` file

```
    function THEME_preprocess_views_view_fields(&$variables)
    {
        $view = $variables['view'];
        if($view->name == "THE_VIEW_NAME")
        {
              $variables['my_field'] =strip_tags( $variables['fields']['field_myfield']->content);
              $variables['title'] =strip_tags( $variables['fields']['title']->content);
              $variables['theme_hook_suggestions'][]='views_view_fields__SOMETHING';
         }
     }

```

By this function the `$my_field` and `$title` variables are available in the `views-view-fields--SOMETHING.tpl.php` file. You have to create `views-view-fields--SOMETHING.tpl.php` file in your theme directory and use above variables in it. `views-view-fields--SOMETHING.tpl.php` file is created to theme every output (record or row of columns) of your View. Make sure you are using `-` instead of `_` when creating `views-view-fields--SOMETHING.tpl.php` file.

`$view` variable is a variable that contains every detail of the current View. you can use `kpr($view)` to see its results.

# Answer
> 0 votes
if you want, you can use variable $variables. In file template, use code

```
dpm($variables)

```

and see that.

# Answer
> 0 votes
If you want the raw value, and you're in a Views Row template (usually somehow overriding `views-view-fields.tpl.php`) you can use the $row object to get the associated fields.

In this case, you can try `$row->field_field_myfield[0]['raw']['value'];`

---
Tags: 7, views, theming
---


title: Storing taxonomy terms count in DB

text:
# Question
Title: Storing taxonomy terms count in DB
In drupal 6 , Term Node Count were the module which was developed to store number of nodes containing each taxonomy term in DB , but it is not developed for Drupal 7 . Now my question is : "Is there any module like Term Node Count in Drupal 7 ? if not what solution do you present for this problem "

**Note** : In a project with thousands of taxonomy term I want to know which terms are used most and on the fly calculation will become too time consuming.

# Answer
> 1 votes
You should be able to do this with Views, I am pretty sure that is why the D7 port did not happen for Term Node Count (see: https://www.drupal.org/node/603868). A view can be cached so it will essentially store the value as that module did but it will update more frequently (or less if you want to set the cache up like that) and give more flexibility to where you can display the information. You can setup a view pretty easily for this:

This is just one way to get the information but the view will really depend on your use case for what you need the count for:

In Fields: add Taxonomy term: Name In Relationships, add a Taxonomy term: Content with term Add a contextual filter for Taxonomy term: Name Choose 'Display a summary' Choose 'Display Record count with link'.

Views is a very flexible module and chances are you are probably already using it, it will work for most all needs. You can also do this yourself in code pretty easily by doing the count and storing it statically then writing a update function that will update the term count every once and a while but it will cut down on flexibility but I tend to go for code if it makes sense.

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


# Question
Title: How to track what has (or hasn't) been "featurized" in the UI?
On a sufficiently large or complex site that uses Features to export or manage configuration, it seems easy to encounter a scenario where an administrative user can inadvertently change a variable that has been "featurized" and end up having that variable reverted when features get reverted at the next code update.

The person making the change needs to remember (and to have access) to either check the Feature UI or grep the features code. I'm curious how other big sites might be handling this problem. Is there any trick to maybe highlight variables that have been featurized when they get exposed in the UI?

# Answer
Try using the configuration module along with Drush. It writes the configurations into files which you can manage using GIT.

You run `drush config-export –all` on your dev and push your code with the config using GIT. Then you pull the changes on your prod server and run `drush config-sync`. It takes the config from the text files and puts them into the database making the changes live on the site.

Here is a nice article which explains this - https://shanetully.com/2014/04/drupal-and-the-holy-grail-of-workflows/
> 0 votes

# Answer
Checkout Features Builder (I work with the guy who builds this but I'm not basing this answer on that it is really a good module and used it before that).

> Stop clicking together your Features
>
> Save valuable time (and sanity) by bypassing the process of picking and choosing which components go into which Features. Features Builder is a module that analyzes the build of your Drupal site and automatically builds Feature modules to capture the site's configuration.
> 0 votes

---
Tags: features, configuration
---


# Question
Title: Prevent Redis Cache from clearing ALL keys
We are using the Redis module and Redis Database as cache with the following setup:

```
$conf['redis_client_interface'] = 'PhpRedis';
$conf['redis_client_host']      = 'redis.internal';
$conf['lock_inc']               = 'sites/all/modules/contrib/redis/redis.lock.inc';
$conf['cache_backends'][]       = 'sites/all/modules/contrib/redis/redis.autoload.inc';
$conf['cache_default_class']    = 'Redis_Cache';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

```

Also we have our custom module that writes some keys to the database as well.

The problem is that periodically entire redis cache is cleared out ( flushed ) together with our custom keys...

How do we prevent that ?

Can Redis Cache just handle its own keys ?

# Answer
> 1 votes
You can set your default Drupal key up (in settings.php) then have your custom keys set to not expire or last longer.

```
$conf['cache_prefix'] = array('default' => 'your-redis-key');

```

See Redis config file for documentation on how to setup max memory and such: https://raw.githubusercontent.com/antirez/redis/2.8/redis.conf

By doing this you would be setting up the policies that Redis will use to clear the cache out and what to clear. It has to clear eventually or it will become unstable, it's just cache after all :) I wouldn't be depending on it to stay that's for sure.

---
Tags: 7, caching, database
---


# Question
Title: Why is the CSS rule that I applied via the CSS injector module not active on my mobile device?
I have a panel row with two regions and I wish to re-order the display for mobiles. Below is what I wish to accomplish:

And I thought it would be as simple as the below css rule :

```
@media screen and (max-width:480px)
{
   .pane-2
    {
    display:block;
    }
}

```

But nothing happened with the above rules.

I am using the CSS Injector module to apply the above css.

Can anybody help me with this one?

# Answer
> 1 votes
# Clear cache or CSS aggregation bug

Comment #1 in issue # 1588822 contains some interesting hints that might help to answer your question:

* to see the changes, you must clear the cache. Since your question doesn't mention anything like that, make sure you did cear the cache.
* bugs in CSS aggregation can be problematic with specific CSS constructs. If you trigger one of those, it can result in CSS being omitted from the aggregation CSS file.

# CSS rule overwritten by another module

And the rules provided by this module might be overwritten by another module, as briefly mentioned in the last paragraph of the module's readme.txt ...

# CSS edits via external editor

CSS edits via external text editor not displaying (which only applies to the 7.x-2.x version, not to 7.x-1.x) might be what's causing the issue.

---
Tags: panels, theming
---


# Question
Title: pass argument as a wildcard to node/add/Article/560012
Case :

I do have a Article-share content type , it does contain a node reference to type "Article" , now this is my scenario :

* user selects a node of type Article
* he redirects to node/add/Article share
* now in this form I want the selected coupon shows up in the form automatically so the user wont need to fill this field again

Some more deails:

* I have a content type called "Article-Share".
* This type has a reference field to Node type "Article".
* I want my content creation form for type "Article Share" to use wildcards to automatically fill "Article Link".

Any suggestions how I can do so?

# Answer
> 0 votes
I have solve this problem by jquery.

```
jQuery(document).ready(function(){
  var urlVar =  window.location.pathname.split('/');
  if(urlVar[4]=='coupon-share' && urlVar[5]!=''){
    jQuery("#edit-field-user-coupon-link-und").val(urlVar[5]);
  }
});

```

# Answer
> 0 votes
You will need a module for that but it's easy :

the scenario is this : on screen 1 , you've got a form which contains a select list , when user submits this form , will redirects to a content creation form , the important thing is that the coupon id must be passed to it .

so the solution :

you will have a submission function for your first screen form

```
function first_screen_form_submit($form, &$form_state) {
  //enter some codes here to get nid of selected coupon
  //.
  //.
  $form_state['redirect'] = 'node/add/coupon-share/'. $nid;
  drupal_redirect_form($form_state);//this will redirects you to form and passes the nid
}

```

now you must alter the node creation form :

```
//Implement hook_form_BASE_FORM_ID_alter()
function YourModuleName_form_node_form_alter(){
  if(isset($form['type']) && isset($form['#node'])) {
    $type = $form['#node']->type;
    switch($type) :
        case 'coupon-share':
          $passedNid = arg(3);
          $passedNode = node_load($passedNid);
          //now you have the coupon node available here and can fill your field with it
          //.
          //.
          breake;
  }
}

```

# Answer
> 0 votes
This sounds very much like you want the Entityreference prepopulate module.

"Allow prepopulating any Entity reference field via URL"

From the README.txt:

```
Usage
=====
In order to pre-populate an entity reference field you have to supply the
parameter in the URL.

The structure is
node/add/article?[field_ref]=[id]

Where [field_ref] is the name of the entity reference field and [id] is
the id of the entity being referenced.

Examples:
node/add/article?field_foo=1
node/add/page?field_bar=1,2,3

```

---
Tags: 7, hooks, nodes, organic-groups
---


# Question
Title: Update hook - is it possible to generate success or failure message on operation success?
I would like to be clear on how to indicate success (or failure) messages in update hooks, when a step completes successfully (not using &sandbox).

I vaguely remember seing a post on this (probably here) but all the examples I searched for do not show any messages in the update hook.

# Answer
In Drupal 7, `hook_update_N()` doesn't need to return anything to make Drupal understand the update was successful; it needs to throw an exception in case of failure, which is what the methods of `DatabaseSchema`, such as `DatabaseSchema::addField()`, already do. (Those methods are the ones behind functions like `db_add_field()`.)

See any of the update hooks used by Drupal core as example. (I removed the code comments just to make the code shorter.)

```
function user_update_7010() {
  db_change_field('users', 'signature_format', 'signature_format', array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => FALSE,
    'description' => 'The {filter_format}.format of the signature.',
  ));

  db_update('users')
    ->fields(array('signature_format' => NULL))
    ->condition('signature', '')
    ->condition('signature_format', 0)
    ->execute();

  $existing_formats = db_query("SELECT format FROM {filter_format}")->fetchCol();
  $default_format = variable_get('filter_default_format', 1);
  db_update('users')
    ->fields(array('signature_format' => $default_format))
    ->isNotNull('signature_format')
    ->condition('signature_format', $existing_formats, 'NOT IN')
    ->execute();
}

```

```
function node_update_7012() {
  if (variable_get('update_d6', FALSE)) {
    db_update('field_config')
      ->fields(array('translatable' => 0))
      ->condition('field_name', 'body')
      ->execute();

    foreach (array('field_data_body', 'field_revision_body') as $table) {
      db_update($table)
        ->fields(array('language' => LANGUAGE_NONE))
        ->execute();
    }

    node_type_cache_reset();
  }
}

```

The only reason for `hook_update_N()` to return a string is changing the message seen in the update page.

```
// user_update_7002
if ($sandbox['user_from'] == $sandbox['user_count']) {
  if ($sandbox['user_not_migrated'] > 0) {
    variable_set('empty_timezone_message', 1);
    drupal_set_message(format_string('Some user time zones have been emptied and need to be set to the correct values. Use the new <a href="@config-url">time zone options</a> to choose whether to remind users at login to set the correct time zone.', array('@config-url' => url('admin/config/regional/settings'))), 'warning');
  }
  return t('Migrated user time zones');
}

```

### Reference
> 1 votes

---
Tags: hooks
---


# Question
Title: Use print_pdf in the background on node save?
As the Print module's creation of a PDF can be quite slow (and use a lot of memory/CPU), is it possible to save a PDF into the `public://` files area each time a node is saved?

Has anyone done this? Presumably you could call a save-PDF function on `hook_node_presave` but I'm not sure what the next step is. Call a print-PDF function with a file path? Where is that print-PDF function and how would you call it?

# Answer
> 0 votes
The function used from that module to output PDF is `print_pdf_generate_html()`, which gets a filename as last parameter.

To understand what to pass as first argument, see `print_pdf_generate_path()`, which is the function calling `print_pdf_generate_html()`. In particular, see the following code.

```
$print = print_controller($path, $cid, PRINT_PDF_FORMAT);
if ($print === FALSE) {
  return;
}

```

---
Tags: 7, nodes, files
---


title: How to create custom rule event

text:
# Question
Title: How to create custom rule event
I'm working on integration of my D7 module with Rules. I have custom SQL table with 2 columns `node_id` and `status`. `Status` may have values 0, 1, 2, 3. How can I create event with `hook_rules_event_info` to react on status change? I.e. status changed from `0` to `1` -\> send email to node owner.

# Answer
> 0 votes
If this is a formal drupal node you can use node update event , then check if the node-\>status is changed or not (you have 2 versions of node in this event one referring to unchanged and second refers to changed noge)

---
Tags: rules
---


# Question
Title: How to rearrange user register form and still pass validation
I've implemented a hook\_form\_alter to change order of fields on user registration form. i've moved mail and username fields inside a fieldset. on submit, drupal is returning an error of undefined mail and account index.

How should i handle this? do i create a submit function that defines `$form['mail'] = $form['fieldset']['mail']`?

Here's my code:

```
/**
 * Change the elements from registration form
 *
 * @return outputted form
 * @author
 **/

function userreg_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == 'user_register_form'){

        if (current_path() == 'supplier/register'){
            unset($form['profile_main']);

            //move the whole form inside suppliers tab
            $supinfo = $form['account'];
            unset($form['account']);

            $form['profile_supplier']['account'] = $supinfo;

            //add our custom form_validate form to handle what we just changed?

            array_unshift($form['#submit'], 'userreg_form_submit');

        }
    }
}

function userreg_form_submit($form_id, &$form_state){

    $form_state['values']['mail'] = $form_state['profile_supplier']['mail'];

}

```

The error i'm getting is:

> Notice: Undefined index: mail in user\_account\_form\_validate() (line 1264 of /var/www/funa/d/modules/user/user.module).
>
> Notice: Undefined index: account in user\_account\_form\_validate() (line 1265 of /var/www/funa/d/modules/user/user.module).
>
> Recoverable fatal error: Argument 2 passed to drupal\_array\_set\_nested\_value() must be of the type array, null given, called in /var/www/funa/d/includes/form.inc on line 2602 and defined in drupal\_array\_set\_nested\_value() (line 6695 of /var/www/funa/d/includes/common.inc).

# Answer
I would try defining the name of the field manually like so. This should overwrite the default naming of the variable in the values/input array in the `$form_state`.

```
$form['profile_supplier']['account']['#name'] = 'account';

```
> 0 votes

---
Tags: forms
---


title: Print specific field of a specific node

text:
# Question
Title: Print specific field of a specific node
I have the content type of "Front Page Section" where there are the fields "body" and "field\_home\_section\_photo".

On the home page (page--front.tpl.php) I would like to be able to print the body and image fields separately for particular nodes with their formatting in place:

Print Node 42 Body Print Node 42 Image Print Node 43 Body Print Node 43 Image Print Node 44 Body Print Node 45 Image

# Answer
> 0 votes
You can do this by `hook_preprocess_node(&$vars)` function. By this function you can check the Node ID then if it is some custom IDs, fetch the appropriate data and assign them in `$vars` array.

In the aggregate we have

```
function THEME_preprocess_node(&$vars){
    if(drupal_is_front_page() == true){
         if($vars['node']->nid == 44){
             $newNode = node_load(45);
             $wrapper = entity_metadata_wrapper('node',$newNode);
             $image = $wrapper->field_home_section_photo->value();
 //here use kpr($vars) to get the correct syntax of  field_home_section_photo in $vars
// suppose it is $var['fields']['field_home_section_photo']->value
              $var['fields']['field_home_section_photo']->value = $image;
           }
      }
}

```

don't forget to install entity module.

# Answer
> -1 votes
If you're not familiar with the module layer of drupal I would suggest using the views module to build a view page of all the nodes of type "Front Page Section" and use this as the front page. https://www.drupal.org/project/views

---
Tags: theming
---


# Question
Title: Disable 3rdparty hook from custom module once
Im using the `menu_trail_by_path` which does a pretty good job for most of my URL's, however in a custom module I'm setting the breadcrumbs directly (`drupal_set_breadcrumb` in a page callback). These crumbs get messed up due the `menu_trail_by_path` module (sort of overwritten I guess =/)

This happens because `menu_trail_by_path` sets the crumbs using `hook_page_delivery_callback_alter` which is called after the page callback apparently.

I would like to keep my custom crumbs in the page callback as it has all the required (dynamic) data available.

Hero we go.. how on earth can I disable the `page_delivery_callback_alter` hook from the `menu_trail_by_path` module... once? I.e. for the current runtime /request only.

Thanks!

Roland Franssen

# Answer
> 3 votes
You could implement `hook_module_implements_alter()` to avoid a hook implemented by a module is invoked. The problem is that Drupal saves in cache the list of modules implementing a hook, but you can change the list of hooks implemented by modules back to the original one.

```
function mymodule_implements_alter(&$implementations, $hook) {
  if ($your_condition && ($hook == 'page_delivery_callback_alter')) {
    $old_implementations = &drupal_static(__FUNCTION__, array());
    if (empty($old_implementations)) {
      $old_implementations = array_merge(array(), $implementations);
      unset($implementations['menu_trail_by_path']);
    }
  }
}

function mymodule_exit() {
  $old_implementations = &drupal_static('mymodule_implements_alter', array());
  $implementations = &drupal_static('module_implements');

  if (!empty($old_implementations)) {
    $implementations['page_deliver_callback_alter'] = $old_implementations;
  }
}

```

This code works only in the case `hook_exit()` is invoked, which is normally done in `drupal_page_footer()`.

You should be sure `mymodule_implements_alter()` is executed after the implementations made from other modules, in order to preserve the changes done from other modules.

---
Tags: 7, hooks
---


title: Posting drupal content to tumblr

text:
# Question
Title: Posting drupal content to tumblr
I am trying to post article content type to my tumblr account (want to post all articles created by different user roles) . I have tried tumblr\_connect but its not working i have also installed tumblr api module and registered a application and added the keys.

But i am stuck there i dont how to configure to post only the article content type and link it to my tumblr blog.

# Answer
You will have to do this in code. Use hook\_node\_insert() in a custom module and filter by content type. You can then invoke the tumblr API and send the node data across. See tumblr.lib.php for API usage.
> 1 votes

---
Tags: nodes
---


title: How to auto generate biblioographies

text:
# Question
Title: How to auto generate biblioographies
I currently have a content type called book, where the book has fields: author name, book title, ISBN , publication date, ect.

I'd like to automatically generate a bibliography entry for each book so that users can copy and paste it easily. Is there a module that can do this? I know of the biblio module, but to the best of my knowledge you must directly input the information.

So is there a way to automatically generate a bibliography citation entry for a given book based off of the book's given fields?

# Answer
You need to look into views https://drupal.org/project/views and you can display your content anyway that you want to display it. There is a small learning curve but displaying content type fields is one of the easiest forms of a view to setup. There are tons of examples setup and disabled by default from many modules so chances are you already have views code somewhere in your site even if you don't have the actual module yet :) Look at the project page under Resources heading to find documentation and tutorials plus there are millions online with quick Google searches.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to adjust price in Drupal Commerce based on quantity and attributes?
I wonder how I can adjust the price in Drupal Commerce depending on quantity and attributes.

I found *Commerce Price Table* and *Commerce Pricelist* for **quantity**, and *Commerce Pricing Attributes* for **attributes**. Not sure which one is more matchable for that.

Any suggestions?

# Answer
> 1 votes
# Attributes

Consider using the Commerce Pricing Attributes module. Here is an excerpt from its project page:

> ... provides some enhancements to the Commerce Product Option and Commerce Product Attributes handling by applying pricing rules to custom product attributes.
>
> Features:
>
> * Dynamic price calculation based on selected operators.
> * Cart combination based on product attributes.
> * Support for multi currency.
> * Multilingual attributes.
> * Different attributes and settings per product.
> * Price adjustments either per item or per order.
> * Rules integration.
> * Easy UI for editing and reordering attributes.

This module depends on Commerce Product Option and Commerce Product Attributes.

Refer to the video about this module for a great introduction about it.

# Quantity

From your question it's not realy clear to me what exactly you mean the quantity part of it.

Which is also why I'm not convinced (yet) that you should use the modules Commerce Price Table or Commerce Pricelist.

However, you should probably consider the Rules module, using some custom Rules, something like so:

* Events = Calculate Sell Price of Product.
* Actions = calculate the price, and set the price to the calculated value.

Not sure (yet) ifff you'd need some extra 'Conditions' added to this.

Refer to Drupal commerce and rules: changing the product price dynamically for an example of dynamically changing product prices.

---
Tags: 7, commerce
---


title: How to get each db result value count

text:
# Question
Title: How to get each db result value count
How to get values count in db\_select My query is:

```
$last_item = '2015-07-19';
$query = db_select('field_data_appointment_date','ap');
$query->join('field_data_appointment_slot','aps','aps.entity_id = ap.entity_id');
$query->fields('aps',array('appointment_slot_value '));
$query->condition('ap.appointment_date_value', '%' . db_like($last_item) . '%', 'LIKE');
$result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);
dsm($result);

```

and my result is:

```
... (Array, 4 elements)
0 (Array, 1 element)
appointment_slot_value (String, 11 characters ) 10.00-11.00
1 (Array, 1 element)
appointment_slot_value (String, 11 characters ) 10.00-11.00
2 (Array, 1 element)
appointment_slot_value (String, 11 characters ) 10.00-11.00
3 (Array, 1 element)
appointment_slot_value (String, 11 characters ) 11.00-12.00

```

I need result like count of

```
:10.00-11.00 is 3
:11.00-12:00 is 1

```

Anyone help me out

# Answer
Not fully understanding the output you really want to achieve, but here's examples on how to count the results coming from the database

get count with db\_select

OR

rowCount

Let me know if any of those work for you.
> 0 votes

---
Tags: database
---


# Question
Title: populate drop down from results using ajax
I am having a problem trying to get ajax functioning properly, everytime I do a call i get

```
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /system/ajax
StatusText: Internal Server Error
ResponseText:

```

What am i trying to do is have the drop down fill with the results of a function from api. The function works perfectly it gets the results when needed however the problem is with the ajax I even try to print out hello world and still got the 500 error.

this is the code I currently have, any advice is appreciated.

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

    $form['vehicle_info'] = array(
        '#type' => ('fieldset'),
        '#title' => t('Vehicle Information'),
    );

    $form['autoinfo']['vehicle_year'] = array(
        '#type' => 'select',
        '#title' => t('Vehicle Year'),
        '#options' => auto_title_year_api(),
        '#ajax' => array(
            'callback' => 'auto_title_make_api_callback',
            'wrapper' => 'api_make'
        ),
    );

    $form['autoinfo']['wrapper'] = array(
        '#prefix' => '<div id="api_make">',
        '#suffix' => '</div>',
    );

    $options = array('- Select Make -');
    if(isset($form_state['values']['vehicle_year'])){
        $options = auto_title_make_api();
    }

    $form['autoinfo']['wrapper']['make_description'] = array(
        '#title' => t('City'),
        '#type' => 'select',
        '#options' => auto_title_make_api(),
  );

    if(isset($form_state['values'])){
        $form['page_output'] = array(
        '#markup' => autotitledb_submit($form, $form_state)
        );
    }
    return $form;
}

function auto_title_make_api_callback($form, $form_state) {
  return $form['autoinfo']['wrapper'];
}

function auto_title_make_api(){
$url_make = 'https://test.api.800loanmart.com/Loanmartservice.svc/soapssl'; // SOAP 1.1
$post_str_make = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetVehicleMakes xmlns="http://tempuri.org/">
<customerId>73c858f0-791c-454e-b4d5-5634bf13621d</customerId>
<authenticationId>3074940f-7efe-447c-a7ff-3c152acdf8c4</authenticationId>
<year>2000</year>
</GetVehicleMakes>
</s:Body>
</s:Envelope>';

    $headers_make = array(
        'Content-type: text/xml; charset="utf-8"',                      // For SOAP 1.1 - JHW Jan 26, 2013
        "Accept: text/xml",
        "Cache-Control: no-cache",
        "Pragma: no-cache",
        "SOAPAction: \"http://tempuri.org/ILoanmartService/GetVehicleMakes\"",
        "Content-length: ".strlen($post_str_make)       // Amount of data in bytes to be posted
    );

      $options_make = array(
          CURLOPT_RETURNTRANSFER => true,         // return web page / XML result
          CURLOPT_HEADER         => 0,          // 1/0 return/don't return headers 0 for production or 1 for debug
          CURLOPT_HTTPHEADER     => $headers_make,          // post headers
          CURLOPT_FOLLOWLOCATION => true,         // follow redirects
          CURLOPT_ENCODING       => "",           // handle all encodings

          // Browser/User Agent String
          CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],

          CURLOPT_AUTOREFERER    => true,         // set referer on redirect
          CURLOPT_CONNECTTIMEOUT => 120,          // timeout on connect
          CURLOPT_TIMEOUT        => 120,          // timeout on response
          CURLOPT_MAXREDIRS      => 10,           // stop after 10 redirects
          CURLOPT_POST           => 1,            // We are sending post data needs to be = '1'
          CURLOPT_POSTFIELDS     => $post_str_make,     // this is the XML post data
          CURLOPT_PORT           => 443,                    // SSL Port, probably unnesecery

          CURLOPT_SSL_VERIFYHOST => false,        // Don't verify ssl on either side
          CURLOPT_SSL_VERIFYPEER => false,        // dito, don't verify ssl on either side

          CURLOPT_VERBOSE        => 1,            // Set to 1 for debug
        );

    $soap_do_make = curl_init($url_make);
    curl_setopt_array($soap_do_make, $options_make);
    $result_make = curl_exec($soap_do_make);

$sls_make = simplexml_load_string($result_make);
$sls_make->registerXPathNamespace('a', 'http://schemas.datacontract.org/2004/07/LM.API');
$sls_list_make = $sls_make->xpath('//a:MakeDescription');
foreach($sls_list_make as $sls_list_make_child){

$sls_list_make_child_result[] = sprintf("%s", $sls_list_make_child);}
dpr($sls_list_make_child_result);
$sls_list_make_child_results = array_combine($sls_list_make_child_result, $sls_list_make_child_result);

        // Close cURL
        curl_close($soap_do_make);

 return $sls_list_make_child_results;
}
function auto_title_year_api(){
$url_year = 'https://test.api.800loanmart.com/Loanmartservice.svc/soapssl'; // SOAP 1.1
$post_str_year = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetVehicleYears xmlns="http://tempuri.org/">
<customerId>73c858f0-791c-454e-b4d5-5634bf13621d</customerId>
<authenticationId>3074940f-7efe-447c-a7ff-3c152acdf8c4</authenticationId>
</GetVehicleYears>
</s:Body>
</s:Envelope>';

    $headers_year = array(
        'Content-type: text/xml; charset="utf-8"',                      // For SOAP 1.1 - JHW Jan 26, 2013
        "Accept: text/xml",
        "Cache-Control: no-cache",
        "Pragma: no-cache",
        "SOAPAction: \"http://tempuri.org/ILoanmartService/GetVehicleYears\"",
        "Content-length: ".strlen($post_str_year)       // Amount of data in bytes to be posted
    );

      $options_year = array(
          CURLOPT_RETURNTRANSFER => true,         // return web page / XML result
          CURLOPT_HEADER         => 0,          // 1/0 return/don't return headers 0 for production or 1 for debug
          CURLOPT_HTTPHEADER     => $headers_year,          // post headers
          CURLOPT_FOLLOWLOCATION => true,         // follow redirects
          CURLOPT_ENCODING       => "",           // handle all encodings

          // Browser/User Agent String
          CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],

          CURLOPT_AUTOREFERER    => true,         // set referer on redirect
          CURLOPT_CONNECTTIMEOUT => 120,          // timeout on connect
          CURLOPT_TIMEOUT        => 120,          // timeout on response
          CURLOPT_MAXREDIRS      => 10,           // stop after 10 redirects
          CURLOPT_POST           => 1,            // We are sending post data needs to be = '1'
          CURLOPT_POSTFIELDS     => $post_str_year,     // this is the XML post data
          CURLOPT_PORT           => 443,                    // SSL Port, probably unnesecery

          CURLOPT_SSL_VERIFYHOST => false,        // Don't verify ssl on either side
          CURLOPT_SSL_VERIFYPEER => false,        // dito, don't verify ssl on either side

          CURLOPT_VERBOSE        => 1,            // Set to 1 for debug
        );

    $soap_do_year = curl_init($url_year);
    curl_setopt_array($soap_do_year, $options_year);
    $result_year = curl_exec($soap_do_year);

$sls_year = simplexml_load_string($result_year);
$sls_year->registerXPathNamespace('a', 'http://schemas.datacontract.org/2004/07/LM.API');
$sls_list_year = $sls_year->xpath('//a:Year');
foreach($sls_list_year as $sls_list_year_child)
{$sls_list_year_child_result[] = sprintf("%s", $sls_list_year_child);}

$sls_list_year_child_results = array_combine($sls_list_year_child_result, $sls_list_year_child_result);

        // Close cURL
        curl_close($soap_do_year);

 return $sls_list_year_child_results;
}

```

Edit #1

```
The errors I am gettings are
Notice: Undefined index: #options in form_select_options() (line 2661 of /home/loansdotorg/public_html/includes/form.inc).

And

Warning: Invalid argument supplied for foreach() in form_select_options() (line 2668 of /home/loansdotorg/public_html/includes/form.inc).

```

Edit #2 I think I have this working although I will need to test it out more.

# Answer
> 1 votes
If you look at function "form\_select\_options()" it also sets the selected item so set `'#default' => 0` for your dropdown form variable and you wont see see that warning anymore!

```
$form['autoinfo']['vehicle_year'] = array(
        '#type' => 'select',
        '#title' => t('Vehicle Year'),
        '#options' => auto_title_year_api(),
        '#default' => 0, //this was missing and hence the warning,
        '#ajax' => array(
            'callback' => 'auto_title_make_api_callback',
            'wrapper' => 'api_make'
        ),
    );

```

# Answer
> 0 votes
I'd suggest using devel module and dd() that return value just before the return to ensure it is correctly structured. with devel enabled a drupal\_debug.txt file will be created on server in /tmp

# Answer
> -1 votes
When I call a web service from php I do something like this:

```
  $client = new SoapClient("Your URL .svc?WSDL");
  $result = $client->MethodName(array('param' => 'value'));
  $result_object = $result->MethodNameResult;

```

Then you don't need to make the whole soap body and envelope. If you need to pass credentials in the header you can use:

```
$client = new SoapClient("some.wsdl", array('login'          => "some_name",
                                            'password'       => "some_password"));

```

---
Tags: forms, ajax
---


# Question
Title: How to add a user/login Link to the Maintenance Mode page?
I have my site in Maintenance Mode. I know I can get to my login page by going to http://example.com/login .

My client wants a login link on the Maintenance Mode page (when in this mode). Before I say "no this is not possible", I am wondering if this is possible. I could add this to the Maintenance template page right? I already have a custom Maintenance Mode page.

EDIT: Where the http://adaptivethemes.com/how-to-theme-the-user-login-page-in-maintenance-mode solution works, its not what I want. All I want is a link to the user login page displayed on the Maintenance Page.

I did try this: I added html to the maintenance php template: `<div><a href="/user/login" >Login</a></div>`

HOWEVER this only show a link that was NOT clickable. Also how would I get to the User login page if I am testing this on a test server, but the domain will be different than on the test server. Change the domain once on the production server?

# Answer
> 1 votes
Yes, you should be able to. You can create a maintenance page template similar to any other in Drupal, "maintenance-page.tpl.php". However, to get that to work you probably have to make some changes to your template.php file.

More info can be found here: http://adaptivethemes.com/how-to-theme-the-user-login-page-in-maintenance-mode although I believe that example is from Drupal 6, but the idea should be fairly similar for Drupal 7 as well.

# Answer
> 0 votes
Using the `maintenance-page.tpl.php` file is indeed a vaid approach for this. However if you use that approach, there are **two maintenance page** files that you should create. You can duplicate your theme's page.tpl.php twice and name them:

* `maintenance-page.tpl.php`: This file controls the page that is displayed when the site is in "maintenance mode" but ***the database connection and database are still functioning correctly***.
* `maintenance-page--offline.tpl.php`: This file controls the page that is displayed ***when Drupal cannot access the database (for whatever reason)***.

For more details on this, and related changes in `settings.php`, refer to the community documentation about Theming the Drupal maintenance page.

---
Tags: theming, users, maintenance-mode
---


# Question
Title: How can I combine a product attribute with a subset of another one in Drupal Commerce?
Assume I have 2 product attributes (using the Drupal Commerce module):

1. **Background color** (white, black, green, blue, yellow).
2. **Surface** (glossy or matte).

And assume that surface "glossy" can be only selected in combination with background color "white" or "black".

How should I configure this conbination of attributes?

# Answer
> 2 votes
# Required steps

### Step 1

Create 2 taxonomies:

1. Background color, with terms white, black, green, blue, yellow
2. Surface, with terms glossy or matte.

### Step 2

For each prod type, add field "Background color", which is a field "term referenace" (and refer to the Background color taxonomy).

Attentionn: make sure to check the option "attribute field settings" (enables this field to function as an attribute field on the add-to-cart-form).

Then add a similar term reference field "Surface".

### Step 3

Use `store / products / add product` to add individual products, with a specific SKU, and for which you pick the right values for each of both taxonomies.

So for "Matte surface", you should create 5 individual products (one for each background color). But for "Glossy surface", you only create 2 individual products (1 with a white background color, and 1 with a black background color)

# Video tutorials

For a more detailed video tutorial of the steps described above, refer to Drupal Commerce - Pruduct Attributes (16:13). Before doing so, you may want to first view these related videos:

By only reviewing/studying these 3 videos (total time = about 37 mins), you'll have a very good foundation to get started with the fundamentals of Drupal Commerce.

# Commerce Backoffice

Managing products (and orders) can be confusing. However, the Commerce Backoffice module helps with that. For more details about that module, refer to my answer to the question about Correct way for Attributes in Commerce

---
Tags: 7, commerce, database
---


# Question
Title: Allow only the users with the access code to browse the website
I am building my site on Drupal 7.

I want to restrict the usage of my website only to certain people who I have sent the access code to. I don't want to put my website into maintenance mode because I want those users to fully use my site (including registration form etc.).

So how can I build a page with a simple form where users will enter the access code and then get allowed to enter the website? And also whenever somebody types in another URL in the website without actually entering the access code first, they must be redirected to the security page to enter the code; then they will be allowed to proceed to that URL they wanted to go to.

I would prefer to be able to remember their sessions and if the user has a session on the website (such that they have entered the code before) they shouldn't be sent to the security page the second time (until their session time ends maybe?).

How can I achieve this?

# Answer
> 0 votes
* create a page, and include the User Login as a block on that page. Theme as desired. You can also set this as a Front page in the system settings if you like.
* alternatively, create a customised user login, whereby the password is populated as part of a custom submit function of the form. Then you would use a *Code* as the user name, and the password would be automatically assigned. The question is too broad to detail how this would be accomplished. Look into the forms API and building forms with customised submit functionality.
* get LoginToboggan. It has a setting to redirect users to a specified page on access denied
* in permission, for Anonymous Role, uncheck ALL items. This will essentially disallow anonymous user to do anything, or view any content, which should then be redirected to the login page by logintoboggan

Keep in mind that this method is prone to major security breaches by bots. They WILL randomly guess the code and gain access to the site, which is why two fields are required in standard practice (email/user, password)

**EDIT FOR OP**

**I solved it by a custom module. I cant answer my own question due do low reputation so accepting yours as an answer and writing a comment. I created a block, which contains a custom form. This form redirects to home page if the access code is correct and also sets TRUE on $\_SESSION\['access\_code'\]. And then I created a page and embedded the block In a custom Rule, I redirect user to the access page if $\_SESSION\['access\_code'\] is not TRUE and if the user is anonymous whatever the URL it is. So user always redirected to that page, unless they have entered the code before, or a logged in user.**

# Answer
> 0 votes
You can try a module called Shield

https://www.drupal.org/project/shield

PHP Authentication shield. It creates a simple shield for the site with Apache authentication. It hides the sites, if the user does not know a simple username/password. It handles Drupal as a "walled garden".

I don't know if it will 'remember the session' but I believe it can help with the other part of you request

# Answer
> 0 votes
Below is the answer (solution) that Shamil.F came up with ...

* This question can be solved by a custom module.
* I created a block, which contains a custom form.
* This form redirects to home page if the access code is correct and also sets TRUE on $\_SESSION\['access\_code'\].
* Then I created a page and embedded the block in a custom Rule: I redirect user to the access page if $\_SESSION\['access\_code'\] is not TRUE and if the user is anonymous whatever the URL it is.
* So user is always redirected to that page, unless they have entered the code before, or a logged in user.

PS: The comment like "*I cant answer my own question due do low reputation so accepting yours as an answer and writing a comment.*" seems a bit bizarre to me. Which is why I moved it (with some reformatting) to a separated answer.

I don't "expect" any upvotes for doing so, since I mostly posted this extra answer to have it posted as such (an an extra answer). At the risk that the OPer is now going to "change" the accepted answer to this answer ... And even at the risk of this answer being downvoted and/or deleted.

Oh well, so be it, I just wanted to help "clean up" the (pseudo-accepted) answer ... For any other user ever looking at this question, and answer(s).

---
Tags: 7, users
---


# Question
Title: How to hook into Drupal 6 search process?
I need to modify the search results drupal generates to include selected content from some other D6 sister sites. `hook_search` seemed like the obvious choice, but when I implement it, it's never invoked with the keywords I'm searching for:

```
function nmc_xsearch_search( $op = 'search', $keys = NULL ) {

    switch ($op) {

        case 'name':
            return t('Content');
            return $form;

        case 'search':
            dsm( "Operation: $op | Keys: $keys" );
                return $results;
    }
}

```

When I walk through this code in the debugger, my function nmc\_xsearch\_search() is hit twice. The first time $op = 'name' and $keys = null. The second time $op = 'name' and $keys = '1'.

When I put a breakpoint on `node_search` it is invoked four times - all before my nmc\_xsearch\_search() is hit. The last time node\_search is hit the provided parameters are: $op = 'search' and $keys = 'my search keywords'.

Basically I want my function to get the same invocation that `node_search` is getting so that I can access the keywords and modify the results array returned by hook\_search. Any ideas?

# Answer
If you look at `search_menu()`, you will notice the following code.

```
  foreach (module_implements('search') as $name) {
    $items['search/' . $name . '/%menu_tail'] = array(
      'title callback' => 'module_invoke',
      'title arguments' => array($name, 'search', 'name', TRUE),
      'page callback' => 'search_view',
      'page arguments' => array($name),
      'access callback' => '_search_menu',
      'access arguments' => array($name),
      'type' => MENU_LOCAL_TASK,
      'parent' => 'search',
      'file' => 'search.pages.inc',
    );
  }

```

Every module implementing `hook_search()` gets a menu tab. So, your module will be asked to search only when the users select its tab.
> 0 votes

---
Tags: 6, hooks, search
---