title: How to add users under a specific role

text:
# Question
Title: How to add users under a specific role
We have 4 type of users -

```
Admin   -  can view and manage all other users
Parent  -  Can view and manage students but own child
Teacher -  Can view and manage students assigned to him
Student -  Can view and manage own profile & details

```

So it's clear that everything is around students can be accessed by 3 other roles as per rules.

I am trying with different role and users modules but not getting exactly how to setup this structure in drupal.

I am sure there is definitely a way to do this because it's a general requirement and drupal has a way to implement this. But I am newbie and trying from couple of hrs but not able to set this.

Anyone please guide me on this or share any link where I can get exact information regarding this.

Thanks is Advance

# Answer
> 1 votes
I assume you use something like Entity reference to add children to parents and to teachers.

I don't think that default Drupal supports this kind of user permissions. As I couldn't find any modules for this functionality, you probably need to do some coding.

The easiest approach would be altering the `user/%uid/edit` menu item with a custom access callback in a custom module. This ensures users can only access the user edit pages matching your criteria:

```
function MYMODULE_menu_alter(&$items) {
 if (isset($items['user/%user/edit'])) {
   $items['user/%user/edit']['access callback'] = '_mymodule_user_edit_access';
  }
}

function _mymodule_user_edit_access($account) {
  global $user;

  // May edit own profile
  if ($account->uid == $user->uid) {
    return TRUE;
  }

  // Check if $user has permissions to edit $account
}

```

The access callback should check if the $user has role Teacher or Parent and if it is referencing to the $account-\>uid.

Edit:

I just realize you also need to manage profile view rights, this could be done with the same hook, on path `user/%user`.

---
Tags: users
---


# Question
Title: instant upload after select file in a file or image field (quit upload button)
In the normal fashion you have to select the file you want to upload in a file field or image field and then click "upload" button.

this is not very "user friendly"

How to upload the image or file just after the user selects it in the window without the necessity of click "upload" button.

# Answer
> 2 votes
You can also use Drag & Drop Upload

Here you just browse the file.

select the file and it will be automatically upload.

# Answer
> 1 votes
You can use Autoupload module

> AutoUpload is a user interface (UI) enhancement that initiates automatic upload of files minimizing the number of clicks required by a user.
>
> Currently, users must select files, then press the "Upload" button. We found users often don't realize a button press is necessary and mistakenly think their image is uploaded when it's not.
>
> This module removes the extra button press and hides the "Upload" button via JavaScript for a quicker, automatic file upload. When JavaScript is not enabled, it falls back to the "Upload" button.

or you can check this post.

---
Tags: 7, files, media
---


# Question
Title: How to change the draggable icon of new theme
I am using draggable table in my new theme. Every thing is working properly but

I want to show this icon like in Bartik theme for every draggable rows:-

Currently it is showing as

How to change this?

# Answer
> 2 votes
I suspect it's similar to a problem I had with draggable table rows in a zen subtheme: the icon was just a bit mis-placed. Using Firebug or similar tools you can see what's going on – on my site it looked like this:

Using firebug I could see the reason for this:

The icon was mis-placed. So I suppose you probably don't have to *change the draggable icon* itself, but you'll have to *adjust the position* of the icon.

The css responsible for the position should look like this:

```
a.tabledrag-handle .handle {
background: url("../../misc/draggable.png") no-repeat scroll 6px 9px rgba(0, 0, 0, 0);
height: 13px;
margin: -0.4em 0.5em;
padding: 0.42em 0.5em;
width: 13px;
}

```

and you should find it in this system css file: /modules/system/system.base.css

Instead of changing it in that system css file you should however override the settings in your theme's css file. You probably don't have to change much – just have to play around with the settings for margin and padding according to your theme… Hope this helps somehow?

---
Tags: 7, forms
---


# Question
Title: jquery script on view not working when filtering with (ajax on) 'better_exposed_filters' module
i have a script for dealing with node images hover

```
(function ($) {
    $(function(){

    $('.node-photos-teaser').mouseenter(function() {
        $(this).addClass('photos-hover');
    }).mouseleave(function() {
        $(this).removeClass('photos-hover');
    });

});
})(jQuery);

```

when clicking on a node filter set by 'better\_exposed\_filters' using ajax, the POST drupal/views/ajax?field\_tags\_tid\_1=4 is loaded and filter out nodes fine but the JQuery behaviour is working nomore.

Ajax breaks jquery

Any help?

# Answer
Thanks to Clive answer i have solved out the problem embedding to my theme script file :

```
 Drupal.behaviors.betterExposedFilters = {
    attach: function(context) {  }}

```

now having:

```
 (function ($) {
Drupal.behaviors.betterExposedFilters = {
        attach: function(context) {

    $('.node-photos-teaser').mouseenter(function() {
        $(this).addClass('photos-hover');
    }).mouseleave(function() {
        $(this).removeClass('photos-hover');
    });

        }}
})(jQuery);

```

renders compatible the JQuery from my theme with ajax from betterExposedFilter module
> 1 votes

---
Tags: ajax, javascript, views
---


title: ajax reload causes jquery issues

text:
# Question
Title: ajax reload causes jquery issues
i jquery applied to a exposed filter to force the look of a drop down with checkboxes which works fine until the ajax reloads the content and cause the slideToggle to open and close immediately. i switched it to just css height and the box wont open after ajax reload. Anyone have any ideas or options that might work after ajax reload. just css option

```
boxes1.css({"display" : "none", "background": "#f2f2f2", "border" : "1px solid #ccc", "padding":"5px", "margin-top" : "25px","position":"absolute","overflow" : "hidden"});
    title.live("click",function(){
        if(boxes1.is(":hidden")){
            boxes1.css({"height" : "300", "display" : "block"});
        }
        else {
            boxes1.css({"display" : "none"});
        }
    });

```

slideToggle option

```
boxes1.css({"display" : "none", "background": "#f2f2f2", "border" : "1px solid #ccc", "padding":"5px", "margin-top" : "25px","position":"absolute","overflow" : "hidden"});
    title.live("click",function(){
            boxes1.slideToggle('slow');
    });

```

# Answer
this might have to do with behaviours

see jquery script on view not working when filtering with (ajax on) 'better\_exposed\_filters' module
> 1 votes

# Answer
I just ran into the similar issue and was able to resolve :) I came across this post while searching. I realize it's been a bit since your post, and this is not the entire answer to your puzzle, but...

In my case, it was a field that updating via ajax and showing briefly. I ended up enclosing the field in a div and setting the div to {display:none}. In your example, the jQuery should then act upon the div $('#yourdivid').find('.myclass').

Don't know if it will work for you, but if you're still stuck, it may point you in the right direction!

KMT
> 0 votes

---
Tags: ajax, javascript, views
---


# Question
Title: Trying to render an array of items with the drupal_add_html_head function
I have a `preprocess_html` function that gets an array of google fonts and adds them as an html class. I have it partially working but if say I have three fonts, only the last one gets into `<html class="">` element. Here is what I have so far:

```
if ($families) {
   foreach ($families as $fontString) {
   $fontclass = preg_replace('/[^\d\w]+/', '-', strtolower($fontString));

   $element = array(
     '#tag' => 'html',
     '#attributes' => array(
     'class' => $fontclass,
    ),
   );
   drupal_add_html_head($element, 'google_fonts');
  }
}

```

In the example above, I have these fonts in my site:

* Montserrat
* Actor
* Pathway Gothic One

... but only the last one renders in my html class as:

```
<html class="pathway-gothic-one-regular">

```

If I do a dsm within my function:

```
dsm(drupal_get_html_head());

```

I see all three fonts print out in separate boxes as

```
<html class="actor-regular" />
<html class="montserrat-regular" />
<html class="pathway-gothic-one-regular" />

```

so I think I am not getting something right here.

Note, if I change my code to a body class array, it works as expected. e.g.

```
   if ($families) {
          foreach ($families as $fontString) {
            $vars['classes_array'][] = preg_replace('/[^\d\w]+/', '-', strtolower($fontString));
          }
        }

```

yields:

```
<body class="actor-regular montserrat-regular pathway-gothic-one-regular">

```

From a build standpoint, I'd like to keep these classes one level higher than body so that's why I'd like them to be in `<html class="">`.

# Answer
```
if ($families) {
    $element = array(
        '#tag' => 'html',
    );
    foreach ($families as $fontString) {
        $fontclass = preg_replace('/[^\d\w]+/', '-', strtolower($fontString));
        $element['#attributes'][class'][] = $fontclass;
    }
    drupal_add_html_head($element, 'google_fonts');
}

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How to add padding/margin for sidebar-right in Adaptive Theme?
I am trying to make something with Adaptive Theme, but I can't find how to set a padding or margin to Right Sidebar...

I am using only `content -- right sidebar` layout, and if I wish to add some padding for Right Sidebar - it just disappears and falls down to bottom of page.....

Also, the problem started when I wanted to remove any Margin for a Content area, which was set to 10 px; but - when I removed margin for Content, it disappeared from Sidebar; and if I try to add margin/padding to Sidebar only, It just fall to bottom of page, probably resembling the tablet layout...

# Answer
> 1 votes
What Geoff said is basically true, but there is a way to change the margins and the paddings without messing up your basic page layout.

The way to do it is the following:

* Take a look at the structure of the HTML in the sidebar region. There should be a div that has a class .region-sidebar-second or .region-sidebar-first. If you try to change the padding/margin of this div, your structure will be messed up.
* You can, however, change the margin and padding of the div with the region-inner class by using a selector like ".region-sidebar-first .region-inner" or ".region-sidebar-second .region-inner".
* You can even go deeper if you want to change the margin/padding of a specific block and not the whole region's by using something like ".region-sidebar-second #blockID" as your css selector.

---
Tags: theming
---


# Question
Title: Adaptive Theme: give the option to user to switch between fluid and fixed layout in specific nodes
I would like to give the option to my users to switch between fluid and fixed layout when viewing nodes of a specific type. There is an option in the adaptive theme where you set the maximum width. Is there a way for me to bypass this and give a button to my users that will allow them to switch between fluid and fixed layout?

# Answer
Assuming that you did not heavily modify the base structure of Adaptive Theme, you can explore using a custom solution to do this.

For example you can add a button like this in a block's contents (using the Raw HTML input format):

```
<button id="toggle-width">Toggle Width</button>

```

then a new class in your CSS to override the max-width property in .container (this is where the max-width is set in Adaptive Theme):

```
.page-full-width { max-width: none !important; }

```

and then add some jQuery to your button:

```
$( "button#toggle-width" ).click(function() {
  $( "#page" ).toggleClass( "page-full-width" );
});

```
> 0 votes

---
Tags: 7, theming
---


title: Form in template without <form> tags

text:
# Question
Title: Form in template without <form> tags
My forms dont seem to have tags wrapping them in my templates. What am I doing wrong here?

I have a template whith some calls to theme() inside it. Two of these are forms with their own template. This template is called from a block\_view().

my modules block function:

```
$form = drupal_get_form('stappenoverzicht_appointment_form');
  $reset = drupal_get_form('stappenoverzicht_reset_form');

  $block['content'] = theme('overzicht', array('status' => $status, 'links' =>$links, 'form' => $form, 'reset' => $reset));

```

my modules theme function:

```
$return['overzicht'] = array(
'variables' => array('status' => array(), 'links' => array(), 'form' => null,
 'reset'      => null),
'template' => 'templates/dashboard--stappen-overzicht',
    'render element' => 'form',

```

);

```
$return['appointment'] = array(
        'arguments' => array('form' => NULL),
        'render element' => 'form',
        'template' => 'templates/form--appointment',
    );
$return['reset'] = array(
    'arguments' => array('form' => null),
    'render element' => 'form',
    'template' => 'templates/form--reset',
);
return $return;

```

base tpl:

```
<div class="appointment-container">
   <?php print theme('appointment', array('form' => $form));?>
</div>
<div class="reset-button-container">
   <?php print theme('reset', array('form' => $reset));?>
</div>

```

form--reset:

```
<div class="reset-submit-btn">
       <?php print drupal_render($form['submit']);?>
</div>
  <i><?php print drupal_render($form['description']);?></i>
<?php
print drupal_render_children($form);
?>

```

I came across this Render form in template answere here, but I want to manipulate the wrapping html as shown in the reset template.

# Answer
your module should be like this:

```
function yourmodule_menu()
{
    $items = array();
    $items['path/to/form'] = array(
        'title' => 'Page Title',
        'description' => 'Page Description',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('yourmodule_form_function'),
        'type' => MENU_NORMAL_ITEM,
    );
}

function yourmodule_form_function()
{
   //build form api here as array
   //return array
}

```

Hope this helps you!
> 1 votes

# Answer
Just create a form

```
<?php
    function testform(&$form,$form_state){
    $form['description'] = array(
        '#type' => 'textfield',
        '#title' => t('Description'),
        '#default_value' => '',

      );
    return $form;

    }
    ?>

```

Now in menu you can use theme function

```
<?php
theme('test',array('myform'=>render(drupal_get_form('testform'))));
?>

```

And in your template file form can be used this way

```
<?php
print $myform;
?>

```

Hope it will work for you.
> 0 votes

---
Tags: forms, theming
---


title: Adding a block to markup

text:
# Question
Title: Adding a block to markup
I have created several content types and using views I have created blocks that take the uid as an argument and displays content that that author has created. So far so good.

What I want to do now is create a module that displays all these blocks in a given area,

I have the HTML ready and I can create a page that passes the markup back to drupal and display that, what I would like to do is populate those areas with the given block.

so for example. If I have a page called:

www.example.com/displayMyContent/58 (where 58 is the user ID)

the HTMl of the page would be online these lines:

```
<?php
$uid = args(2);
$markup = "
<div id="myVideoBlock"> ". drupal_call_to_render_block("MyVideosBlock", $uid). "</div>";

?>

```

what would be the function to insert the given block into the given section and how would I pass the $uid to the block so that only the authors content would be displayed?

Also there are reasons why i am not using the blcok functions in admin mainly because there will be other blocks added on the page and I need control of where the blocks will be placed

# Answer
> 0 votes
I think you may be able to do this by using the global $user variable.

1. 1 create the hooks block\_info and block\_view
2. create hook\_theme()
3. define a theme to be able to pass variables to template.
4. create the template

in your block\_view do something along the lines of this:

```
switch($delta){
    case 'myvideoblock':
            global $user;
            $view = views_get_view('YOURVIEW');
            $view->set_display('YOURDISPLAY');
            $view->set_arguments($user->uid);
            $result = $view->execute;
            $your_variable = $result->result;
            $block['content'] = theme('videoblock', array('your_variable' => $your_variable));
}

```

You should poke around in the $result-\>result object to get to your content though.

Hope this helps

---
Tags: blocks
---


title: Customize search block in frontpage

text:
# Question
Title: Customize search block in frontpage
I am using Zen3 theme , i created a subtheme ,i want have a big search box in front page , for doing this , i created a front page template `page--front.tpl.php`. also i added a custom css to my search-box by this code in `template.php`

```
function myrtheme_form_search_block_form_alter(&$form, &$form_state) {
    $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-icon.png');
    $form['actions']['submit']['#attributes']['class'][] = 'search-icon';
    $form['search_block_form']['#attributes']['class'][] = 'search-box';
    }

```

my problem is how can add css class only to the frontpage in `page--front.tpl.php`.

# Answer
I suggest you use `drupal_is_front_page()` to check it is on front page or not. You can achieve it using code similar to the following.

```
function myrtheme_form_search_block_form_alter(&$form, &$form_state) {
  $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-icon.png');
  if (drupal_is_front_page()) {
    $form['actions']['submit']['#attributes']['class'][] = 'fpage-search-icon';
    $form['search_block_form']['#attributes']['class'][] = 'fpage-search-box';
  }
  else {
    $form['actions']['submit']['#attributes']['class'][] = 'other-page-search-icon';
    $form['search_block_form']['#attributes']['class'][] = 'other-page-search-box';
  }
}

```
> 1 votes

---
Tags: 7
---


# Question
Title: trigger event before content is parsed after ajax
I want to ajaxify my site. Everything, that is usally parsed as "Page Content" sould be opened in a lightbox. So the idea is to ajaxify every link and let #lightbox be filled with the result.

but before ajax parses the request-result, I want some javascript to be done. So I want an event to be triggered after the ajax respond, and want to parse the result by myself.

any suggestions?

~~**EDIT:**~~

~~I could store the content in an hidden div#object, and use an `ajax_command_invoke('body','trigger',array('myevent'))` to trigger a function attached to `myevent`. Does this make sense? than I just dont know how to implement this to all links.~~

# Answer
> 1 votes
Are you using AJAX API? All the Ajax commands have the same return, for example

```
array(
    'command' => 'insert',
    'method' => 'html',
    'selector' => $selector,
    'data' => $html,
    'settings' => $settings,
);

```

And if you open the file misc/ajax.js, you will find insert() function in Drupal.ajax.prototype.commands. I think now you got the idea right? You just need to define a new ajax command by extending standard library, for example

```
Drupal.ajax.prototype.commands.lightbox = function (ajax, response, status) {
    // Do something with response.
};

```

And on server side, you just need to return

```
array(
    'command' => 'lightbox',
);

```

You can put more options in the command like what core does.

---
Tags: 7, ajax
---


# Question
Title: How to make a custom block listen to context module?
I've been creating my own module that consist an array of blocks. I plan to print them using context as oppose programatically as I already have the module on use (no need to reinvent the wheel). However, whenever I use context to display a block on a region, it always display it on the highest part of html body tag. e.g.

```
<body>
  block content rendered here...

```

as oppose to my custom region,

```
<div class="l-info-bar">
  I want my block content rendered here...

```

I cleared the cache several times. Made sure that the context is set to display the block on info bar region.

Here's my code for reference.

```
    function custom_module_block_info() {
      $blocks = array();
      $blocks['my_block_top_navigation'] = array(
        'info' => t('Top Bar Navigation Menu'),
        'cache' => DRUPAL_CACHE_GLOBAL,
      );
      $blocks['my_block_avatar'] = array(
        'info' => t('Avatar'),
        'cache' => DRUPAL_CACHE_GLOBAL,
      );

      return $blocks;
    }
    /**
    * Implements hook_block_view().
    */
    function custom_module_block_view($delta = '') {
      $block = array();
      switch ($delta) {
        case 'my_block_top_navigation':
          $block['subject'] = '';
          $block['content'] = _custom_module_block_top_navigation_content();
          break;
        case 'my_block_avatar':
          $block['subject'] = '';
          $block['content'] = _custom_module_block_avatar_content();
          break;
      }
      return $block;
    }

function _custom_module_block_top_navigation_content() {
    lots of code here...
}

function _custom_module_block_avatar_content() {

   lots of code here...
}

```

I'm guessing you have to prep your block so context can actually place it to certain region?

**Update1:** I forgot to mentioned that normal blocks works on context and normal block display (only my custom block doesn't work on normal way and context—which is why I though problem lies in my coding—not context module). I also tried printing the block through code and works perfectly but I don't want extra code I don't need because I have context on use.

**Update 2:** I also replaced the block content with print t('TEST') and still printing above body through normal means and context. Works well printing using code.

# Answer
> 0 votes
Firstly, You can try putting a regular block at a regular region created by drupal core in context. That should work.

Then compare the different results you got for your custom block and custom region. Try putting your custom block at regular region, or putting regular block at your custom region.

Also, You may need to double check the 'custom region' you mentioned at question does exist at page.tpl.php. I.e the code does print the 'custom region' in page template, like

```
<?php print render($page['your_custom_reagion']); ?>

```

# Answer
> 0 votes
Ok it seems the problem is that when creating a custom block through code, YOU MUST "RETURN" the variable, not just print or echo them—or else it won't print on the right region.

e.g.

```
function _custom_module_block_top_navigation_content() {

$test1 = t('test1');

return $test1;

}

```

NOT

```
function _custom_nixket_block_top_navigation_content() {

print t('test1');

}

```

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


# Question
Title: Alternative link to download modules from drupal.org
I am unable to download these modules for Drupal 7. It shows the "Not Found" error.

1. https://www.drupal.org/project/search\_api\_solr
2. https://www.drupal.org/project/fuzzysearch

Is there an alternative link to download these modules?

# Answer
> 2 votes
Click on the version control tab on the module page and it will give you instructions to download it via Git.

To get up and running with Git look at Installing Git.

---
Tags: community-official-site
---


# Question
Title: How can I hide a nodereference url link for users who have already created a node
I am working on a job listing site and wants users to be able to apply for jobs on the site. I created 2 content types "Job posting" and "Job Application".

I used the nodereference\_url module to add an apply now link on the job posting node that directs the user to the "job Application" form. This works fine but i would like to make each user to be able to apply for a particular job only once.

Is there a way i can achieve this with my current setup? Is there a different way to go about this that will give me the desired result?

Thank you for the help

# Answer
One solution that comes to mind includes using the nodereference\_url\_create\_link function that is included in the Node Reference URL Widget module. From the documentation of the specific function:

```
/**
 * Helper function for themers to easily create a link.
 *
 * This function should be used in custom themes, rather than making manual
 * links because it first checks a user's access before showing the link. If
 * the user does not have access to create the node then an empty string will
 * be returned.
 *
 * @param $node
 *   The node object that will be referenced.
 * @param $field_name
 *   The name of the Node Reference field.
 * @param $type_name
 *   The name of node type that contains the Node Reference field.
 * @param $attributes
 *   Optional. An array of additional attributes to add to the link.
 */

```

You can use this in the node.tpl.php file for the Job Posting content type (which should be along the lines of node--job\_posting.tpl.php if you're in D7 or node-job\_posting.tpl.php for D6). The outline of the process should be as described below:

* Hide the field at the top of your template file (you will render it later on if the user did not apply for the specific job).
* Check if the user has already created an application node that references to the current posting.

The first step can be easily implemented by writing something along the lines of:

```
hide($content['YOUR_FIELD_NAME']);

```

at the top of your template file. Use a `dpm($content);` first to make sure that you are hiding the right field.

The second step is a bit trickier. The most elegant way that comes to mind is to use the Corresponding Node References module so that when you create a reference from the application to the posting, a corresponding reference from the posting to the application is also created (this can also be useful if you want to show all the applications that were created for a specific posting in the posting's page).

After you have "linked" the posting and the application with CNR, all you need to do is check if the author of the other postings is the logged in user. Specifically, you can use the node reference array in the `$node` object to get the referencing applications with node\_load\_multiple and then with a `foreach` loop compare each `$node->uid` against the uid of the logged in user.

There is a blog post in Drutácora that describes a similar process and includes relevant code snippets (it's not in English but you should get the basic idea from the code).
> 0 votes

---
Tags: nodes
---


# Question
Title: How to create Drupal 7 clean pager links?
In my last project my client aksed me to do clean pagers in his website. However drupal 7 handles pagination using **?page=1** but I need **page/1** insted of that. Do someone have experience of creating clean pager links using pager alter and .htaccess. I see lot's of modules but they are not working properly. I tried with clean pagination, smart paging modules but they did not work properly, Then I tried to do it by custom way through htaccess file and altering pager link, but can't get success.

**http://someexample.com/hello-node/?page=1 to http://someexample.com/hello-node/page/1**

Any help will be appreciated.

# Answer
> 3 votes
Hi please check the following link Clean Pagination, Hope this will help you.

> Clean Pagination is a very simple module that allows you to enable clean URL pagination for specified pages. The way Drupal typically works, if you had a view with the URL 'my-view', subsequent pages would normally use a query to pass the page number, as in 'my-view?page=2'. When Clean Pagination is being used for a page, it will create a url like 'my-view/2'.

# Answer
> 0 votes
I've had similar problems, and found it very frustrating - sometimes it's because you haven't enabled the rewrite module in Apache. Open a terminal window and do sudo a2enmod rewrite.

If that doesn't work, you might need to look at your virtual hosts file, which if you're using an ubuntu server will be in /etc/apache2/sites-available. If there are any lines in the file that read AllowOverride, make sure you set them to "all". Your file should look something like:

```
<VirtualHost *:80>
    ServerAdmin you@example.com
    ServerAlias your.url

    DocumentRoot /path/to/files
    <Directory />
            Options FollowSymLinks
            AllowOverride All
    </Directory>
    <Directory /path/to/files>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>

```

Then do service apache2 reload.

# Answer
> 0 votes
For what it's worth, another thing I spotted when I was fighting with the clean URLs was that, depending on how you copy your files, dot files don't always get copied. So on occasion I've been working with a local Drupal site and I've not copied the original .htacess file to my local environment. That'll normally mess up clean URLs for you, no matter your virtual hosts file or anything else.

---
Tags: paging, theming
---


# Question
Title: How are node and node_revision tables related?
I've noticed that the following does not work to unpublish nodes:

```
db_update('node')
  ->fields(array('status' => 0))
  ->condition('nid', $array_of_nids, 'IN')
  ->execute();

```

But it does if you follow up with the same update on the `node_revision` table. (But perhaps I should only be updating the status of the current revision (vid)?)

I found this confusing because the nodes in question do not use revisioning yet it seems that the revision table holds more authoritative data than the main node table (so if so, what's the point of `node` table?)

Can anyone explain how `node` and `node_revision` are related and therefore how to do a bulk update such as this 'properly'? (I'd prefer to avoid a costly loop of `node_load`, `node_save` if poss.) I'd like to understand the Drupal Way here.

(I have read node revisions which covers D6, but that did not give me the understanding I was after.)

# Answer
> 5 votes
The `node` table holds the basic information about the node, the `nid` is the primary key on this table and contains the `vid` field which is a foreign key to the `node_revision` table. The `node_revision` table holds each revision of the node, the `vid` is the primary key on this table and contains the `nid` field which is a foreign key to `node` table.

You may think that this information is identical, but it's not. The `node` table only contains one record relating to a node and also stores the current `vid` whereas the `node_revision` table contains the revision data. Just because you're not using revisions it doesn't mean that this process isn't being used.

Also keep in mind that all `field` tables have 2 versions, `field_data_[field_name]` and `field_revision_[field_name]`, the data tables contain the current revision and the revisions table contain the revision data.

To get an understanding of how practical revisioning works try looking at Revisioning, a more complex and powerful solution can be achieved using Workbench

# Answer
> 0 votes
Node revision handles the edits in the node time to time so if you want to unpublish any node just try unpublishing the node by node\_load();

```
<?php
$node = node_load($nid);
$node->status=0;
node_save($node);
?>

```

It will update the status in all the tables automatically.

If you don't want to use default methods.

Its the best way to update any node, hoewever if you want to update any node data using query then you need to update it in both the tables(node and node\_revision)

Also revision is to keep backup of old data and create a new edited copy. Drupal will pick the data from the latest revision( not the older one) because there can be multiple revision created with each edit. If it is disabled there will be only one revision entry same as the node table

It can be seen in the top right bar in the node edit area when any of its revision is created.

Revisions can be controlled by admin/structure/types/manage/\[content type name\] against Publishing options tab to make it enabled/disabled by default

And later it node/edit area it has a separate tab to enable/disable it

---
Tags: 7, nodes
---


# Question
Title: How to add custom login logout links in Bootstrap theme?
I am new to drupal, but I had a requirement, my current site using bootstrap theme. Previously there was no login and logout buttons on header. Today I got html login and logout strip from desinger. For this I have created a new block and selected bootstrap region as Navigation. Now this custom header perfectly sits at the top of the page. with static Myaccout, Logout , contactus which are sent by desinger.

```
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
     </div>
    <div class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Navigator</a></li>
        <li><a href="#">Contact Us</a></li>

          </ul>
          <ul class="nav navbar-nav navbar-right">
<li> <a href="#">My Account </a></li>
 <li> <a href="#">Log Out </a></li>
 </ul>
        </li>
      </ul>
    </div><!--/.nav-collapse -->
  </div>
</div>

```

But my question how to make that header dynamic like when user with out login need to show Login , and after login need to show myaccount and logout. Above code is the static html bootstrap header sent by desinger. Please suggest me how to do this?

# Answer
> 2 votes
It can be done this way

```
<ul class="nav navbar-nav navbar-right">
<?php
global $user;
 if($user->uid):?>
<li> <a href="#">My Account </a></li>
<li> <a href="#">Log Out </a></li>
<?php else: ?>
<li> <a href="/user">Log in</a></li>
<?php endif; ?>
</ul>

```

Hope it will help

# Answer
> 0 votes
Edit the code between your ul class="nav navbar-nav navbar-right"\> to make it look like this:

```
<?php if(global $user):?>
<li> <a href="#">My Account </a></li>
<li> <a href="#">Log Out </a></li>
<?php else: ?>
<li> <a href="/user">Log in</a></li>
<?php endif; ?>

```

---
Tags: 7, navigation
---


# Question
Title: Alternative Top Menu bar for logged in users only via their Role
I want to have an alternative top menu bar for certain Roles when they are logged in. For example, 'Teachers' have one top menu bar, 'Students' have another type.

For now, I want to do this using Rules, is this a good approach or is there an easier way. Simple functionality is the key here so at this time I'm not looking to hack tpl.php files as I just want to get something working for demo purposes.

I'm using Bootstrap and happy to stay that way for the future.

Any suggestions & advice on the above, most welcome. Thanks in advance.

# Answer
> 2 votes
When you create a menu, a block should be created at the same time (https://drupal.org/taxonomy/term/32478). Go to Admin, Structures, Blocks and place one of those menus in the area you want it to appear - under Role restriction at the bottom of the block configuration, you can decide who has access to that specific menu. Repeat for each menu - this way, the menu appears in the same spot, but a different menu will appear for different roles.

# Answer
> 1 votes
Just navigate to **admin/structure/menus**

Create menu **Students** and **Teacher** and assign some menus into it.

These menus will automatically create two blocks on path **admin/structure/blocks** Create a region in info file **header\_menu** and render it in page.tpl.php

Now assign both these menus to the same region and restrict its display to roles by its display settings.

Hope it will help!

# Answer
> 0 votes
I found an alternative to my original question which I have resolved myself, for others, here is the answer to my problem.
What I wanted to do was only show a top-menu bar link to certain members and hidden to others. I resolved this by setting the "Selection Rules" of the page to: User: role: Logged in user has one of 'whatever role you want to allow to show' (i.e Teacher Role) and setting the criteria to 'Only one criteria must pass'. So if set to 'Teacher' when the teacher logs in the menu link shows for them, if the 'student' logs in (which has no permission to view the link) they do not see the said link. It must be stated that link to the page you wish to use, must be in your Menu Links (under the Structure) in my case, the 'Main Menu' links structure.

Maybe there are other ways to do this, but for now a simple result works for what I need for now and I'll probably replace it with some CSS structure, but it works. Try it yourself.

---
Tags: routes, rules
---


# Question
Title: Use One Content type's field as a reference in another content type's view?
I have following requirements :

Add and List of Book Add and List of Quiz related to book.

I have created content type for Book with field name : book\_id,book\_name,price etc..,here book\_id will be unique in every time.

Also created content type for quiz with field name : quiz\_name,my\_book\_id etc..

Now in view of quiz i have to show field quiz\_name with book\_name. How can it will be possible to map this field?

I refered too much like entity reference, node reference module etc but didnt get any solution.

# Answer
My solutions is

**1.** In your Quiz content type remove book\_id field , add another field with (each name you want here I named it my\_book\_id ) select type `node reference` for it.

then in views, create a views of content type quiz, create a relation on my\_book\_id then you can add book title .

**2.** Another way is using php views field create a views with content type quiz, select quiz desire field, then add my\_book\_id field ,exlude it from dispaly then create php field , in value use something like this

```
<?
 $node=node_load($data->mybookid); // this is not precise way, you should put nid in node_load(nid);
 print $node->title;
?>

```
> 1 votes

---
Tags: views, entities, nodes
---


# Question
Title: Using Bootstrap with a Zen subtheme in Drupal 7
I was wondering if anyone could provide me with some advice on implementing bootstrap in D7 with the a Zen subtheme.

I'm really only using it for the responsive div sizing at the moment - I've got a 3 column layout on my homepage that uses col-sm-4 so that it stacks the columns when you're looking at it on a phone-width browser. I've done quite a lot of customization in my Zen subtheme, so I don't really want to install an entirely new theme (the Drupal bootstrap theme, or Zenstrap, for example).

I've tried a couple of approaches to this. First time around, I just copied the bootstrap css file into my theme's css directory, then included it in the normalize.css file, at the top. This worked pretty well, but it occurred to me that if I wanted to use any of the JavaScript features I wouldn't be able to.

Second time around I tried using the Drupal Bootstrap library module. This is also pretty good, and includes the css and js files on all the site pages.

However, I note that it overrides quite a lot of my existing styles. For example, I've got a number of linked headings on the homepage. I don't really want them to use the link style, but whatever I do in the normalize.css stylesheet, I can't stop my homepage picking up the Bootstrap styles. I guess maybe the theme stylesheet loads before the bootstrap stylesheet.

So I'd like some advice, please. Which of the two approaches is the better way to use Bootstrap? Is there another way that is better than either of those approaches? Is using Bootstrap even the best way to make my site responsive?

Thanks very much.

# Answer
In `your_theme.info` do the following:

```
stylesheets[all][] = bootstrap.css
stylesheets[all][] = yourstyles.css

```

This should load both Bootstrap first and your own CSS files afterwards.
> 5 votes

---
Tags: theming
---


# Question
Title: Views display product attributes with prices
How do I create something like this with Views ? This is my version in the making:

this is my view set-up:

# Answer
> 0 votes
You need to group your fields by the title. Specifically:

click on the settings button of the table format in your view and then select to group by the field that is the same in the 2 entries:

EDIT:

You can now hide your title field since it will appear in the group name:

and your final view (that you can theme according to your needs) will look like this:

---
Tags: views, commerce
---


# Question
Title: Assign existing field to new content type programmatically
I'm developing a module that create a several new content types:

```
function create_new_content_type($type, $name){
    $t = get_t();

    $new_node = array(
        'type' => $type,
        'name' => $name,
        'base' => 'node_content',
        'custom' => TRUE,
        //'description' => 'This is an example node type with a few fields.',
    );
    $content_type = node_type_set_defaults($new_node);
    node_add_body_field($content_type);

    // Check if we create content type or update.
    $status = node_type_save($content_type);

    // Replacement rule for the messages.
    $t_args = array('%name' => $content_type->name);

    if ($status == SAVED_NEW) { // create case
        watchdog('node', 'Added content type %name.', $t_args, WATCHDOG_NOTICE, l($t('view'), 'admin/structure/types'));
        return true;
    }

    return false;
}

```

after that creates a new fields for that type (for example):

```
function createTextField($name, $label, $bundle, $required=FALSE){
    // Create the field base.
    $field = array(
        'field_name' => $name,
        'type' => 'text',
    );
    field_create_field($field);

    // Create the field instance on the bundle.
    $instance = array(
        'field_name' => $name,
        'entity_type' => 'node',
        'label' => $label,
        'bundle' => $bundle,
        // If you don't set the "required" property then the field wont be required by default.
        'required' => $required,
        'widget' => array(
            'type' => 'textfield',
        ),
    );
    field_create_instance($instance);

}

```

Lets assume I have already existed field with name `field_my_custom` how can I attach it to my new created content type? (if I understand right in the method above I only create new fields).

# Answer
> 1 votes
You would need to call again the `field_create_instance()` function passing a new array.

```
 $instance = array(
    'field_name' => 'field_my_custom', // ** This already exists, or check with field_info_field()
    'entity_type' => 'node',
    'label' => 'a label', // change this of course
    'bundle' => $new_created_content_type, // this too
    'widget' => array(), // if you're not sure about your widget settings, take a glimpse at an existing field instance using debug(field_info_instance(...));
);
field_create_instance($instance);

```

More links to read and better understand the above functions:

https://api.drupal.org/api/drupal/modules%21field%21field.info.inc/function/field\_info\_field/7 https://api.drupal.org/api/drupal/modules%21field%21field.info.inc/function/field\_info\_instance/7 https://api.drupal.org/api/drupal/modules%21field%21field.crud.inc/function/field\_create\_instance/7

Also, take a look at the Examples for Developers module, node example and field example.

# Answer
> 1 votes
No creating a new instance means you are attaching that field to a content type. Here $bundle is the machine name of the content type

# Answer
> 0 votes
```
<?php

function new_menu(){
    $items = array();

 $items['field_create'] = array(
        'page callback' => 'field_create',
        'type' => MENU_CALLBACK,
        'access callback' => TRUE,
      );

return $items;

}

function field_create() {

/*print_r(field_info_field($myField_name));
exit;*/

$contenttypes = node_type_get_types();

foreach($contenttypes as $type)
{

     $myField_name = "new_".$type->type."_value9";

    if(!field_info_field($myField_name))
    {

    /*print_r($type);
    exit;*/

    $field = array(
        'field_name'    => $myField_name,
        'type'          => 'image',
    );
    field_create_field($field);

    $field_instance = array(
        'field_name'    => $myField_name,
        'entity_type'   => 'node',
        'bundle'        => 'Basic Page',
        'label'         => t('Select an image'),
        'description'   => t(''),
        'widget'        => array(
            'type'      => 'image_image',
            'weight'    => 10,
        ),
        'formatter'     => array(
            'label'     => t('label'),
            'format'    => 'image'
        ),
        'settings'      => array(
            'file_directory'        => 'gallery',
            'max_filesize'          => '4M',
            'preview_image_style'   => 'thumbnail',
            'title_field'           => TRUE,
            'alt_field'             => FALSE,
        )
    );
    field_create_instance($field_instance);

}
 }
 drupal_set_message("Field created successfully!");

}

```

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


title: How to submit a custom form in drupal 7

text:
# Question
Title: How to submit a custom form in drupal 7
I am new to drupal, but i have a requirement with form submission .For this i have created a static block . In that block some input types are there like dropdown menu, checkboxes radio button etc. When user clicks on preview button i am able to fetch the data into bootstrap modal dialogue box.So in that modal dialogue form, submit button is there.But when i try to submit the values from modal dialogue box those values are not posted. Those values sent to url.

```
For this i am using normal $_POST method.

```

I have placed this code in the block section like regualr php .

```
if(isset($_POST['sendtorfq'])
{
  print_r($_POST);
}

<form name="rfq_form id="rfq_form method="post">
  <input type="submit" class="btn btn-primary" name="sendtorfq" value="SendData">
</form>

```

But it takes form method as GET. and when i place the mouse on the submit button it shows the url of that page like /process?name=somename&email=someemail.Every time when i submit the form values are posted to url . But not to post method. Please suggest me where i was wrong?

# Answer
I think you should work with Drupal forms api

But here you are missing some quotes in your html so it could be the issue your form is not working

```
--<form name="rfq_form id="rfq_form method="post">
  --<input type="submit" class="btn btn-primary" name="sendtorfq" value="SendData">
--</form>

TO

++<form name="rfq_form" id="rfq_form" method="post">
  ++<input type="submit" class="btn btn-primary" name="sendtorfq" value="SendData">
++</form>

```

Firebug your html in browser you will see it is breaking. Now it should work.
> 1 votes

# Answer
I would strongly recommend the Entityform module. Going with this module, would allow you to take advantage of the countless contributed modules that add fields via field ui. Like the most useful for you would be the Rules and Views modules.

Rules would be used to create custom conditional actions when your form is submitted and Views would allow you to create custom displays using form submissions.
> 1 votes

# Answer
I completely disagree with this method you did, you can achieve it by more better and clear solution,like using great `webform` module, by the way I suggest you add `action` property to your form, also register a callback menu to receive and process your data.
> 0 votes

# Answer
Get yourself familiar with Drupal Form API if you want tight control on custom form. Or like what zhilevan has suggested, (which I totally agree—no need to reinvent the wheel) use Webform module. 421,374 sites and over 2 million downloads! Can't go wrong with security and guaranteed peer reviewed by a lot of people for awesomeness.

**Some relevant reads:**
> 0 votes

---
Tags: forms
---


title: Using block as sub-menu

text:
# Question
Title: Using block as sub-menu
Is there any module to put blocks under menu items? I will use it to create mega menu. I mean something to generate this code:

```
<ul class="menu">
  <li>
    <a href="...">Item</a>
    <div class="sub-menu">
     <div class="block">...</div>
    </div>
  </li>
</ul>

```

# Answer
best one out there from my experience would be: http://www.drupal.org/project/tb\_megamenu --- it should take you no longer than 15 minutes to figure out how it works. you'll still need to do some css width adjustments to get it working with your own layout.
> 0 votes

# Answer
I think menu\_block is what you want.

Another suggestion is use php filter in block content and try something like

```
<?php
 $menu = menu_navigation_links('menu-your-custom-menu-name');
 print theme('links__menu_your_custom_menu_name', array('links' => $menu));
?>

```
> 0 votes

# Answer
I think TB mega menu or Menu block is the answer for your question. It provides you better control on menus.

Hope it is what you need.
> 0 votes

---
Tags: 7, routes, blocks
---


# Question
Title: Views OOP approach - Let Views extend from Meta/Parent View
Hej.

On my Drupal Site I have several slider, all of them have the most in common but could differ in some way.

I'd like to have a View as Meta/Parent View so that if something is changed it will be changed in the Child Views as well. But every Child View could have their own attributes or adaptions.

I know there is the Display Section in the View but if I add a View or Display and change something, it effects every view even the Master Display.

Is there something like a View OOP approach in Drupal?

# Answer
> 1 votes
When you change something on any of the different displays (other than master), there should be combobox at the top that says "for" which defaults to "All Displays" meaning that the change will apply to all displays. But you can select "This Block" or "This Page" so that the change only happens to that particular display.

Also, if you go into views settings "admin/structure/views/settings" you can set "Always show the master display" which I usually do.

---
Tags: views
---


# Question
Title: How to execute Drupal form without waiting? Ajax? Jquery?
I am trying to code one of my first Drupal modules and hitting this problem.

I have a simple form in a custom module, that checks value of field\_status and depending on if it is "down" or "up" executes one of two bash scripts "startup" or "shutdown" respectively. Here is the code:

```
function status_form_submit($form, &$form_state) {
   $node = menu_get_object();
   $status_code = $node->field_status_code[LANGUAGE_NONE][0]['value'];
if ($status_code=="down") {
   $string = shell_exec('ssh startup);
   $node->field_status_code[LANGUAGE_NONE][0]['value'] = "up";
   node_save($node);
} else {
   $string = shell_exec('ssh shutdown);
   $node->field_status_code[LANGUAGE_NONE][0]['value'] = "down";
   node_save($node);
}

drupal_set_message($string);
return $form;
}

```

The submission button:

```
function status_form($form, &$form_state) {
$form['status'] = array('#markup' => block_content());
    $node = menu_get_object();
    $status = $node->field_status[LANGUAGE_NONE][0]['value'];
    if ($status=="down") {
    $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Start up'),
    );
    } else {
    $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Shut down'),
  );

}

```

The bash scripts have to take from 3 to 5 minutes, during which I'd like to entertain a user, but don't know how to "release" the browser window to do something else - ideally to start showing some improvised status bar because I know in PHP it is not possible to know the status of the process until it is really finished and sent back to user browser.

I tried to add `'#ajax' => array( 'callback' => 'status_form_submit'),` like so:

```
 $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Shut down'),
    '#ajax' => array( 'callback' => 'status_form_submit'),

```

however unfortunately it failed to execute the form.

Could anyone help me to properly apply ajax or jquery or direct me to another way of to get this done? Thanks for attention!

**Edit:**

With the modification suggested by 2pha, my Ajax button starts working but giving this error in a popup window:

```
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /system/ajax
StatusText: Service unavailable (with message)
ResponseText: #0  entity_extract_ids(node, stdClass Object ([field_status_code] => Array ([und] => Array ([0] => Array ([value] => down))))) called at [/home/dev/public_html/modules/field/field.attach.inc:191]
#1  _field_invoke(presave, node, stdClass Object ([field_status_code] => Array ([und] => Array ([0] => Array ([value] => down))))) called at [/home/dev/public_html/modules/field/field.attach.inc:914]
#2  field_attach_presave(node, stdClass Object ([field_status_code] => Array ([und] => Array ([0] => Array ([value] => down))))) called at [/home/dev/public_html/modules/node/node.module:1085]
#3  node_save(stdClass Object ([field_status_code] => Array ([und] => Array ([0] => Array ([value] => down))))) called at [/home/dev/public_html/sites/all/modules/custom/server/server.module:171]
#4  status_form_submit(Array ([status] => Array ([#markup] => Your server is currentlyRunning,[#tree] => ,[#parents] => Array ([0] => status),[#array_parents] => Array ([0] => status),[#weight] => 0,[#processed] => ,[#required] => ,[#attributes] => Array (),[#title_display] => before,[#id] => edit-status,[#sorted] => 1,[#validated] => 1),[submit] => Array ([#type] => submit,[#value] => Shut down,[#default_value] => 1,[#ajax] => Array ([callback] => status_form_submit,[wrapper] => block-server-server-status,[event] => mousedown,[keypress] => 1,…

```

**Edit2**

After little bit modification my code looks like below, but it is till giving the same error above:

```
function status_form($form, &$form_state) {
$form['status'] = array('#markup' => block_content());

   $node = menu_get_object();

    $form['nid'] = array(
    '#type' => 'hidden',
    '#default_value' => $node->nid,
    );

   $status_code = $node->field_status_code[LANGUAGE_NONE][0]['value'];
   if ($status_code=="down") { $value="Start up"; } else { $value="Shut down"; }

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

     '#ajax' => array(
     'callback' => 'status_form_submit',
     'wrapper' => 'block-server-server-status',
     ),

    );

$form['uptime'] = array('#markup' => block_uptime());
  return $form;
}

```

**Edit3**

```
<div id="block-server-server-status" class="block block-server">

    <h2>Server Status</h2>

  <div class="content">
    <form action="/server/141044310074320-1-1-22091820210112" method="post" id="status-form" accept-charset="UTF-8"><div><p>Your server is currently</p><p class="status virt">Running</p><input type="hidden" name="nid" value="1">
<input type="submit" id="edit-submit" name="op" value="Shut down" class="form-submit ajax-processed"><p>3 days, 19 hours, 44:05 minutes (330245 seconds) uptime</p><input type="hidden" name="form_build_id" value="form-29nkoOYINz8YhIWyfp9mALYxMKUZVKbkks6s6J3wGQM">
<input type="hidden" name="form_token" value="Fz1c4yAkg0YwhMxzhs3X3a3aBwuEoE3t0JM1uhT3yd4">
<input type="hidden" name="form_id" value="status_form">
</div></form>  </div>
</div>

```

# Answer
> 1 votes
Basically, you need to set the 'wrapper' for your returned element.
This is what it says under the '#ajax\['wrapper'\]' part of the form api.
"This property is required for using AJAX requests in on a form element."

eg.

```
 $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Shut down'),
    '#ajax' => array(
      'callback' => 'status_form_submit',
      'wrapper' => 'status-form-wrapper',
    ),

```

Which corresponds to the div wrapped around your form so javascript knows what dom element to replace with what is returned by your submit function.
So, if using the code above, you need to wrap your form with the id 'status-form-wrapper'.

```
function status_form($form, &$form_state) {
  $form['prefix'] = '<div id="status-form-wrapper">';
  $form['suffix'] = '</div>';
  $form['status'] = array('#markup' => block_content());
    $node = menu_get_object();
    $status = $node->field_status[LANGUAGE_NONE][0]['value'];
    if ($status=="down") {
      $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Start up'),
    );
    } else {
      $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Shut down'),
  );
}

```

NOTE: I am unsure if you can set 'prefix' and 'suffix' to the form element itself, if not, you will have to nest your form elements under the wrapper div.

**EDIT adding example of node id in hidden field.**

```
function status_form($form, &$form_state) {
  $form['status'] = array('#markup' => block_content());
  $node = menu_get_object();
  // ADDING THE HIDDEN FIELD HERE
  $form['nid'] = array(
    '#type' => 'hidden',
    '#default_value' => $node->nid,
  );
  $status = $node->field_status[LANGUAGE_NONE][0]['value'];

  if ($status=="down") {
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Start up'),
    );
  } else {
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Shut down'),
    );
  }
  return $form;
}

```

---
Tags: forms, ajax
---


title: Migration of data from old site to new

text:
# Question
Title: Migration of data from old site to new
I am working on data migration from old site to new site.

Which module i can use for data migration. I am stucked in the issue that fields are not same in the old site and new site. How can i map fields so data can be migrated from old site to new one.

**Issues that i am facing:-**

1) In old site there are lot of content types and new site there are few. Because fields are managed to merge in few content types.

2) Fields name are not same exactly same like the old site.

3) Few of the fields are converted into taxonomies.

4) Old site contain lot of data as well as images.

So is there any drupal module that i can use or i need to follow some other approach?

Please suggest me some solution.

# Answer
From experience the Migrate module can do all of this for you if you're willing to sit down and write some PHP code to define Mappings and the necessary individual migrations from/to whatever content you need.

See the project page for alot of introductory information and the `/examples` directory for sample beer data migrations.

**EDIT**

the Migrate module is a developer module which you must write PHP classes to define field mappings and source to destination content types. Example migration classes are discussed in the official documentation. There is also a Drupal 2 Drupal migration module that provides some UI to require less custom coding.

At this time I cannot provide additional tutorials/examples -- there are many available on google, eg:

not free: https://drupalize.me/videos/introduction-migrate-module-series?p=1271

free 45min talk from a DrupalCamp: http://vimeo.com/54448150
> 1 votes

---
Tags: nodes, taxonomy-terms, migrations
---


# Question
Title: Merge production site's content into staging through database tables
I am working on a major upgrade on my website which includes several new modules being installed, various theme changes, updates on existing modules and a few modules that were uninstalled.

All the changes have been made in the staging site but, in the meantime, content is continuously being added in the production site. Since the staging site was a mirror of the production site (at that time), I was thinking that since the configuration changes that I made are a lot, I could just merge the database tables that are related to content in the staging site and make it my new production site (after some testing that everything works OK of course).

Notice that I have already checked the Deploy and Node Export modules but the first one is still in Alpha and the second does not support exporting revisions (which is a critical issue for my site).

My question is: what are the database tables that I should export from the production site in order to transfer all the content (nodes, revisions, profile2 entities, files) from the live to the staging database?

Keep in mind that no structural changes related to entities have been made to either database, so they should be identical.

From a preliminary search, the tables that seem to be relevant are: field\_\* , node\_\* , taxonomy\_\* , url\_alias, profile, location\*.

Is there something that I' missing here (other tables that I should copy or possibly a better way to do what I'm after)?

# Answer
try the migrate or feeds modules. I recently used the migrate module with great success, though it does require you to write your own classes.
> 0 votes

---
Tags: 7, database
---


# Question
Title: Drupal 7 completely offline, avoid Boostrap via CDN
I need to move my Drupal site to completely offline environment. The bootstrap library takes the correct Bootstrap JS and CSS from sites/all/libraries, but there is a CDN call to download Bootstrap that screws up the bootstrap functions (ex: popup is undefined) in other JS.

So, I have all necessary JS files locally, they are correctly loaded but when I switch off internet, bootstrap functions are undefined.

As far as I see in Bootstrap module, there is no way to avoid this CDN call. I setup in boostrap module settings\[bootstrap\_cdn\] = 0 but it's still calling.

Would appreciate a lot any idea, its kind of urgent.

# Answer
> 0 votes
Try the Bootstrap Library module

---
Tags: 7, bootstrapping, cdn
---


title: Add custom fields to Ubercart orders

text:
# Question
Title: Add custom fields to Ubercart orders
I would like to add a few custom fields to Ubercart orders. These would be fields like "order assigned to" (which would allow an admin user to choose a user from the site's user list, or a simple text field where they can type a person's name). The fields would be updated via the order admin screen. Does anyone have any ideas on how this can be accomplished?

Thanks!

# Answer
You can add custom fields to Ubercart orders the same way you add custom fields to content types. They can be added by going to Store -\> Configuration -\> Orders -\> Manage Fields (admin/store/settings/orders/fields)

These fields would then be available on the order admin pages.

Hope that helps.
> 3 votes

---
Tags: 7, ubercart
---


# Question
Title: Display an image in menu generated from taxonomy terms
I am using Drupal 7 with Taxonomy and Taxonomy Field Menu to generate a menu based on taxonomy terms (Categories) - including node links (the terms themselves are not linked, just the nodes, in case this is important somehow). I am using this menu in Panels in two panes.

I need to display an image alongside the nodelinks (just one per taxonomy term) and this image needs to be easily replaceable from the backend. The menu is supposed to look like this:

```
- Home
- Taxonomy Term 1
    - Node
    - Node
    - Node
    [Image for Term 1]
- Taxonomy Term 2
    - Node
    - Node
    - Node
    [Image for Term 2]
- Taxonomy Term 3
    - Node
    - Node
    - Node
    [Image for Term 3]

```

The views module is not really an option, as I don't have enough time to work through and understand 30 chapters of "Taming the Beast". It may pay off in the long run, but there simply isn't enough time for views at the moment. Any alternative approaches are welcome.

# Answer
> 1 votes
Try the Taxonomy Image module

> The taxonomy\_image module allows site administrators to associate images with taxonomy terms. With the association created, an admin can then make a call to 'taxonomy\_image\_display()' from their theme or other PHP code to display the appropriate image.

---
Tags: 7, taxonomy-terms, routes, panels, theming
---


# Question
Title: Can I create two views with the same paths?
I have a path pattern that looks the same for two content types. For example, pattern http://my-site.com/x/y/z, for content type 'Article' and content type 'Property'. They follow the same pattern because they only differ in the actual content. The paths are composed of taxonomy items which are the same for the two content types.

So where x/y are the taxonomies called 'categories' and 'types' while z is the title of the content. And both content types follow the same taxonomy group. So only differs in the actual content. One uses generic 'Article' fields while other one uses many custom fields.

My view mostly is defined by the system path node/% but I need to separate them for 'Article' only types and 'Property' only contents. This works for 'Property'. 'Article' based contents are no longer shown by Drupal now.

I have looked into this and this but they somehow use panels and other one is based on blocks and permissions, which is not what I needed.

I can't seem to use panels because I cannot, for some reason, see my view in the contents that can be added. (Most probably because my Views path is node/%). I can only pull those views that does not follow this format.

Is there any other simple way to pull the two types of contents without having to resort to Panels and separating contents by different blocks? Because it is more readable using Views and much lighter and easier to just configure the parameters I think. U reduce a lot of overheads.

Any thoughts?

# Answer
> 2 votes
If I understand correctly, yes you can simply achieve that using views.

Go to your views and add an "*Attachment*" to the '*page*' view. Set *Filter Criteria* accordingly. You can also achieve that using *Views Block*.

# Answer
> 1 votes
Create one view to cater for both. Set the format to content, and choose a custom View Mode that you create in code or via Display Suite. Then for each of your types go to its manage display settings and select the fields you want to display for the custom view mode you created.

To create a custom view mode you can install a module such as Display Suite (install sub-modules ds, ds\_extra and ds\_ui as a minimum). Then navigate to admin/structure/ds/view\_modes/manage and define a new view mode for Node.

Afterwards navigate to the Manage Display tab of your first content type and select tab 'Custom Display Settings'. Your new view mode should be there. Activate it, and then optionally select a layout and re-arrange the fields in that view mode to your liking. If you install ds\_extras you can also select to completely rewrite the output on a per field basis.

Do that for the second content type as well, using the same View Mode you already created. It will have different fields, but will use the same view mode.

Lastly, in views select Content under FORMAT, and choose as view mode the custom view mode you just created.

You can now for even more control of your output also add a template\_preprocess\_node function to your theme's template.php and set a theme suggestion on it to target NODE\_TYPE\__VIEW\_MODE.

To create a view mode in code you can do the following in a custom module:

```
/**
* Implements hook_entity_info_alter().
*/
function MYMODULE_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['another_teaser'] = array(
    'label' => t('Another teaser'),
    'custom settings' => TRUE,
  );
}

```

See Drupal 7 custom node view modes and remember to clear the cache.

There are more light-weight modules out there that can create view modes for you, ie. Entity view modes. But with Display Suite you can completely override the field templates and do stuff like embed views within fields you make up etc.

---
Tags: 7, views
---


# Question
Title: allow users to continue the survey (webform) if closed by accident
I wonder if there is a way of let users continue with survey (webform) in case they close the browser or the tab. For example:

I have a very long webform survey, it has like 30 questions, if Users start answering the survey today I need to let them continue with it if they close it and reopen it tomorrow.

example the url ot my survey is "node/1"

so if user begins the survey and closes it, then tomorrow he must be able for login and go to "node/1" and continue with the survey, right now users have to start over if they close the tab.

any idea? suggestions?

Thank you

# Answer
It's simple. Go to your webform and add page break type wherever you want to split the form.

Then go to Form Settings and check Automatically save as draft between pages and when there are validation errors. or Show "Save draft" button.

If you want to go further, meaning if you want to save a draft when user closes the browser. check Use AJAX to auto save a draft
> 2 votes

---
Tags: 7, users, webforms
---


# Question
Title: Switching from Search API Database to Solr
i have a site which is already using **Search API database** and **Facets search** hosted on Acquia. The site main search (recipe search) is a view with exposed filters to display search and similar content etc. And the site is in 2 languages ( EN and Arabic )

I need to implement spellcheck (did you mean) in the site and this module is only available for Solr.

I have no experience with Solr search. My question is how easy it will be to switch to Solr? Will i have to create different VIEW etc?

I have done a lot of theming, i am afraid of doing that all work again.

What is your expert opinion.

thanks :)

# Answer
> 1 votes
You will need to switch search server for your search index. But I think your view can stay as configured now as it targets a index (which only will change server).

You will also need the module Search API Spellcheck. Then add the "Search: Spellcheck" field to the header of your view. This will output the message “Did you mean "something" in the header if a suggestion is returned by Solr.

You will find the setting for which server your index should use under your index.

---
Tags: search
---


# Question
Title: Is it possible to redirect after "pushing" a file to the user?
I've got a setup where a site generates internal analytics about site usage. Users are able to request a download of their personal analytics, and because this information is sensitive I do not create any files, I generate a CSV file in a variable and then "push" it to the user with this:

```
function _cex_download( $output, $filename )
{
  header("Pragma: public");
  header("Expires: 0");
  header("Cache-Control: private");
  header("Content-type: application/octet-stream");
  header("Content-Disposition: attachment; filename=$filename");
  header("Accept-Ranges: bytes");
  echo $output;
  exit;
}

```

This causes the user's browser to pop a "save file" dialog, and the user gets the file created on their end. This works fine, except the site's administrators are able to trigger 'destructive exports' - and in that situation I have a secondary confirmation form the admin needs to accept before the destructive export executes.

The problem is that this "push download" routine ends the Drupal page processing. There does not appear any way to redirect the admin to some page after that push download routine is called. Admins get a 'save file' dialog popped by their browser, but they remain on the confirmation form.

I tried going the multi-step form route, but after a day of dinking around with strange redirects, I backed out of that confusion. Started looking at ChaosTool's multi-step form logic too. But something tells me that the issue really is that this "push downloading" is a guided-process-killer.

Perhaps a jquery confirmation dialog that intercepts the initial 'Export' button click, do the confirmation entirely in javascript, forget out having a php/FAPI confirmation form, and when the user confirms in jquery I programmatically submit the Export I intercepted?

# Answer
There seem to be some tricks, no idea how well they work inside Drupal.

See for example http://www.willmaster.com/blog/automation/one-link-download-and-redirect.php
> 3 votes

# Answer
As far as I know, that is not possible. You can either send content (in your case a file), or redirect. Not both. This is a limitation of the HTTP protocol
> 4 votes

# Answer
I think your best bet might be to generate a token when the user submits the form, and then have the token store all the necessary information to generate the CSV file. Have the form redirect the user to the appropriate page, and use drupal\_set\_message() to provide a link that contains the token.

When the link is clicked, the CSV file can be generated and sent to the user at that time. Granted, it's more complicated than just generating it on form submit, but as Fuzzy76 says, you're up against a limitation of the HTTP protocol. Doing it this way might be simpler than trying to make a JavaScript-based solution.
> 3 votes

# Answer
This is how I Achieved it in Drupal via Jquery / JS My Answere here -\> I achieved it via JS, Fine my answer here -\> https://stackoverflow.com/questions/822707/php-generate-file-for-download-then-redirect/25843144#25843144
> 1 votes

---
Tags: 7, forms, redirection
---


# Question
Title: Commerce: retrieve coupon code used in order
Using the Commerce Coupon module, how can I retrieve any coupon codes used in a particular order, given the order id? It seems that the coupons used are not actually stored in the database (as far as I can see).

# Answer
> 1 votes
If you're using 1.x version, an entity reference field is attached to the commerce order field upon installation (see `function commerce_coupon_order_configuration()`). This creates the field table commerce\_coupon\_order\_reference.

To check coupons attached to an order, simply access the commerce\_coupon\_order\_reference field, like:

```
if (!empty($order->commerce_coupon_order_reference)) {
  // Traverse the coupons referenced by this order.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_coupon_order_reference as $coupon_wrapper) {
    dpm($coupon_wrapper->value());
  }
}

```

---
Tags: commerce
---


# Question
Title: How to integrate captcha to multi page webform
I have integrated a multi step form through the drupal webform modules. Need to add a captcha at the end of the form. I have used captcha module for it..but while enabling the module and assigning the form id from the backend it is adding the captcha to each step forms.

Can any one please help me how to add the captcha at the end of the form.

# Answer
One thing that may work is altering the form using HOOK\_form\_alter() and than modifying the form to show the captcha only on the last step something as below:

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Get the form id through dpm() or print_r().
  switch ($form_id) {
    // Add the form id as here.
    case 'webform_client_form_form-id':
      // Get the value of step number and the total number of steps in form.
      $page_num = $form['details']['page_num']['#value'];
      $page_count = $form['details']['page_count']['#value'];

      // Check if its not the last step and catcha present in form.
      if (($page_num != $page_count) && (!empty($form['captcha']))) {
        // Remove the captacha from the form.
        unset($form['captcha']);
      }
    break;
  }
}

```
> 1 votes

---
Tags: webforms, captcha
---


title: Retrieve value from an array

text:
# Question
Title: Retrieve value from an array
I have an array, that I want to retrieve the values from. When I test the array with a print\_r, it says that it has the right values. But when I want to show them in their right places, it says that it has no values.

```
function employees_items($nodeid, $language)
{
  $query  = db_query(//SOME QUERY);
  $rows   = array();

   foreach ($query as $row) {
    $rows[] = array(
        $row->nid,
        $row->title,
        $row->field_service_nummer_value,
        $row->field_support_email_value,
        $row->uri,
    );
}

    return $rows;

```

}

Here I want to retrieve the values...I want the value in $row-\>uri. The errormessage: Trying to get property of non-object i employees\_block\_view()

```
  function employees_block_view($delta = '')
 {
 if (array_key_exists($brandpage_id_page, $medarbejder_brandpages))
    {
     switch ($delta)
    {

        case 'employees':

        $employees = employees_items($brandpage_id_page, $lang_name);

        foreach ($employees as $row)
            {

              $block['content'] .= '<div class="img">';
              $block['content'] .= '<img style="width: auto; height: 100px;"    src="'.file_create_url($row->uri). '" alt="Vores support medarbejder" />';
   }
  return $block;
 }

```

# Answer
> -1 votes
Try `$row['uri']` instead. As 'uri' is merely the key and not another object.

In this line of code:

`$block['content'] .= '<img style="width: auto; height: 100px;" src="'.file_create_url($row->uri). '" alt="Vores support medarbejder" />';`

you refer to another object, the uri `($row->uri)`. Within the `$row` array, that you printed with `print_r`, there is the key 'uri'. To get the value of that key you should use `$row['uri']`.

---
Tags: theming
---


# Question
Title: Disable ordering in entity reference (user)
I have an **entity reference** of widget `type = autocomplete`. It's a collection of users where you can add multiple users.

Now I would like to **disable the ordering of the users**. So you can't order the users and the text `Show row heights` isn't show. Here you can see how it is now:

I tried to follow this tutorial but I'm stuck at the last step, he can't find the `element['#field_name'] = 'myfield'`.

This is what I have so far from the tutorial: (I'm using a custom module named other)

```
function other_theme_registry_alter(&$theme_registry) {
    if (isset($theme_registry['field_multiple_value_form'])) {
        $theme_registry['field_multiple_value_form']['type'] = 'module';
        $theme_registry['field_multiple_value_form']['theme path'] = drupal_get_path('module', 'other');
        $theme_registry['field_multiple_value_form']['function'] = 'other_theme_field_multiple_value_form';
    }
}

```

```
/**
 * Theme function override for multiple-value form widgets.
 *
 * @see theme_field_multiple_value_form()
 */
function other_theme_field_multiple_value_form($variables) {
  $element = $variables['element'];
  $output = '';

  // The first condition is the override.
  if (($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) && isset($element[0]['#nodrag'])) {
    die;
    $table_id = drupal_html_id($element['#field_name'] . '_values');
    $required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';

    $header = array(
      array(
        'data' => '<label>' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "</label>",
        'class' => array('field-label'),
      ),
    );
    $rows = array();

    // Sort items according to weight
    $items = array();
    foreach (element_children($element) as $key) {
      if ($key === 'add_more') {
        $add_more_button = &$element[$key];
      }
      else {
        $items[] = &$element[$key];
      }
    }
    usort($items, '_field_sort_items_value_helper');

    // Add the items as table rows.
    foreach ($items as $key => $item) {
      // We don't want the weight to render.
      unset($item['_weight']);
      $cells = array(
        drupal_render($item),
      );
      $rows[] = array(
        'data' => $cells,
      );
    }

    $output = '<div class="form-item">';
    $output .= theme('table', array(
      'header' => $header,
      'rows' => $rows,
      'attributes' => array(
        'id' => $table_id,
        'class' => array('field-multiple-table'),
      ),
    ));
    $output .= $element['#description'] ? '<div class="description">' . $element['#description'] . '</div>' : '';
    $output .= '<div class="clearfix">' . drupal_render($add_more_button) . '</div>';
    $output .= '</div>';
  }
  elseif ($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) {
    $table_id = drupal_html_id($element['#field_name'] . '_values');
    $order_class = $element['#field_name'] . '-delta-order';
    $required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';

    $header = array(
      array(
        'data' => '<label>' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "</label>",
        'colspan' => 2,
        'class' => array('field-label'),
      ),
      t('Order'),
    );
    $rows = array();

    // Sort items according to '_weight' (needed when the form comes back after
    // preview or failed validation).
    $items = array();
    foreach (element_children($element) as $key) {
      if ($key === 'add_more') {
        $add_more_button = &$element[$key];
      }
      else {
        $items[] = &$element[$key];
      }
    }
    usort($items, '_field_sort_items_value_helper');

    // Add the items as table rows.
    foreach ($items as $key => $item) {
      $item['_weight']['#attributes']['class'] = array($order_class);
      $delta_element = drupal_render($item['_weight']);
      $cells = array(
        array(
          'data' => '',
          'class' => array('field-multiple-drag'),
        ),
        drupal_render($item),
        array(
          'data' => $delta_element,
          'class' => array('delta-order'),
        ),
      );
      $rows[] = array(
        'data' => $cells,
        'class' => array('draggable'),
      );
    }

    $output = '<div class="form-item">';
    $output .= theme('table', array(
      'header' => $header,
      'rows' => $rows,
      'attributes' => array(
        'id' => $table_id,
        'class' => array('field-multiple-table'),
      ),
    ));
    $output .= $element['#description'] ? '<div class="description">' . $element['#description'] . '</div>' : '';
    $output .= '<div class="clearfix">' . drupal_render($add_more_button) . '</div>';
    $output .= '</div>';

    drupal_add_tabledrag($table_id, 'order', 'sibling', $order_class);
  }
  else {
    foreach (element_children($element) as $key) {
      $output .= drupal_render($element[$key]);
    }
  }

  return $output;
}

```

```
function other_field_widget_form_alter(&$element, &$form_state, $context) {
  if (isset($element['#field_name'])) {
    var_dump($element['#field_name']);
    switch ($element['#field_name']) {
      case 'field_co_authors': die;
        $element['#nodrag'] = TRUE;
      default:
        break;
    }
  }
}

```

As you can see I have a switch but the text is never equal to field\_co\_authors. The two fields that are an entity reference and can have multiple values don't show... .

Am I doing something wrong or is there another way to do this?

# Answer
`$element['#field_name']` doesn't seem to be set for entityreference fields, this worked for me:

```
function other_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['instance']['field_name'] == 'field_co_authors') {
    $element['#nodrag'] = TRUE;
  }
}

```

This is how I've modified the theme funciton:

```
function other_field_multiple_value_form($variables) {

  $element = $variables['element'];
  $output = '';

  if ($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) {
    $table_id = drupal_html_id($element['#field_name'] . '_values');
    $order_class = $element['#field_name'] . '-delta-order';
    $required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';

    $header = array(
      array(
        'data' => '<label>' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "</label>",
        'colspan' => 2,
        'class' => array('field-label'),
      ),
    );
    $rows = array();

    if (!isset($element[0]['#nodrag'])) {
      $header[] = t('Order');
    }

    // Sort items according to '_weight' (needed when the form comes back after
    // preview or failed validation)
    $items = array();
    foreach (element_children($element) as $key) {
      if ($key === 'add_more') {
        $add_more_button = &$element[$key];
      }
      else {
        $items[] = &$element[$key];
      }
    }
    usort($items, '_field_sort_items_value_helper');

    // Add the items as table rows.
    foreach ($items as $key => $item) {
      $item['_weight']['#attributes']['class'] = array($order_class);
      $delta_element = drupal_render($item['_weight']);
      $cells = array(
        array('data' => '', 'class' => array('field-multiple-drag')),
        drupal_render($item),
      );
      if (!isset($element[0]['#nodrag'])) {
        $cells[] = array('data' => $delta_element, 'class' => array('delta-order'));
      }
      $rows[] = array(
        'data' => $cells,
        'class' => array('draggable'),
      );
    }

    $output = '<div class="form-item">';
    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => $table_id, 'class' => array('field-multiple-table'))));
    $output .= $element['#description'] ? '<div class="description">' . $element['#description'] . '</div>' : '';
    $output .= '<div class="clearfix">' . drupal_render($add_more_button) . '</div>';
    $output .= '</div>';

    if (!isset($element[0]['#nodrag'])) {
      drupal_add_tabledrag($table_id, 'order', 'sibling', $order_class);
    }
  }
  else {
    foreach (element_children($element) as $key) {
      $output .= drupal_render($element[$key]);
    }
  }

  return $output;
}

```

UPDATE:

To change the "Add another item" text, I think you'll need to implement a form alter. Assuming the node type is page, this is how to do it:

```
function other_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  $language = $form['field_co_authors']['#language'];
  $form['field_co_authors'][$language]['add_more']['#value'] = t('Add another user');
}

```

or you can use the general hook\_form\_alter if you need this in multiple content types.

There is some discussion on drupal.org about adding the appropriate alter function to drupal core here: Add hook alter to override field\_multiple\_value\_form()
> 2 votes

# Answer
You could hide the drag handle and the "show row weights" text using css. Also, you could use `hook_form_alter()` where you can add your own validation function to reset the weight field to 0 (just in case someone changes the value using firebug / inspector)
> 0 votes

# Answer
I suggest you you can do it by jquery, simple and quick. add js that load only in this page by `drupal_add_js`

then worte

```
  $('.field-multiple-drag').remove();

```

in your coustom module in hook\_form\_alter

```
if($form_id=='your_form_name'){
drupal_add_js(drupal_get_path('module', 'yourmodule') . '/removesortable.js');
}

```

then in js file

```
//removesortable.js
(function($) {
    Drupal.behaviors.yourmodule = {
        attach: function(context) {
        $('.field-multiple-drag').remove();
    }
  }
})(jQuery);

```

and enjoy :)
> 0 votes

---
Tags: 7, forms, users, entities, ajax
---


# Question
Title: How to limit a user to one vote when using Rate module?
In Drupal 7, I have installed the Rate module for voting. But here, the user can change his vote anytime he wants.

If I want to restrict an user to vote for a particular node only once, what I have to do?

# Answer
> 0 votes
I don't remember this feature in Rate. I don't know the module well enough to know if you can set that user can vote only once per node, but you can just alter the render. You should probably go for a custom module and implements HOOK\_preprocess\_HOOK.

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MODULE_preprocess_rate_widget(&$vars) {
global $user;
// if user have voted
// then alter the render
// else nervermind
}

```

Hope that help.

---
Tags: 7, rating
---


# Question
Title: How to install certain modules only for specific site using Acquia Desktop
I am using Acquia Desktop for creating multisites. Problem is whenever I am installing a module it gets replicated in everyother site. What i need to know is that if i want to have a module only for specific site do i need to first manually create a modules folder inside the site folder such as practice.localhost\modules (where practice.localhost is the site name) folder as the modules directory is not created by default for any of the subsite folder.? Is my approach correct Moreover I have also heard that if we create modules for specific sites then we are going to find it difficult to export sites to FTP for making the site go online.?

# Answer
> 0 votes
> do i need to first manually create a modules folder inside the site folder such as practice.localhost\modules (where practice.localhost is the site name) folder as the modules directory is not created by default for any of the subsite folder.?

Yes, you need to create a specific modules folder for the specific site(s) you wish that module to be available for. If you want it available on, say, 10 out of 20 sites, you'll need a copy in each site's modules folder. You can remove the need for this by making it available in sites/default/modules, but obviously it will be available to all sites in the multisite.

> are going to find it difficult to export sites to FTP for making the site go online.?

Completely depends on your deployment process. You'll probably want to review that process before implementing this on your live servers, but whether or not it's 'difficult' depends on what you need to do.

---
Tags: acquia-dev-desktop
---


# Question
Title: Add block to form (before submit button)
I'm having problems placing a block in my form. This is what I have now:

I have a register form and a fb button **block**. I say the block must be visible **only when page is equal to user register page**.

But the problem is that I don't want to have the form and underneath the block. I would like to add the block before the submit button of my form. How can I do this?

# Answer
You can do something like this:

1. load the block content manually
2. control the order of fields withj `#weight` option

example:

```
function my_form()
{
  $block = block_load(MODULENAME, BLOCKDELTA);
  $block = _block_render_blocks(array($block));
  $block_build = _block_get_renderable_array($block);

  $form['FIELD_1'] = array(
    ...
    ...
    '#weight' => 1
  );

  $form['FIELD_2'] = array(
    ...
    ...
    '#weight' => 2
  );

  $form['FIELD_3'] = array(
    '#prefix' => '<div class="SOME_CLASS">',
    '#suffix' => '<div>',
    '#markup' => render($block_build),
    '#weight' => 3
  );

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

  return $form;
}

```

if those forms are from other modules you can alter them with hook\_form\_alter(&$form, &$form\_state, $form\_id) function.

example:

```
function MYMODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id) {
  // dpm($form_id);
  if ('user_register_form' == $form_id) {
    $form['actions']['#weight'] = 50;

    $block = block_load(MODULENAME, BLOCKDELTA);
    $block = _block_render_blocks(array($block));
    $block_build = _block_get_renderable_array($block);

    $form['fb_field'] = array(
      '#prefix' => '<div class="SOME_CLASS">',
      '#suffix' => '<div>',
      '#markup' => render($block_build),
      '#weight' => 49
    );
  }
}

```
> 1 votes

---
Tags: 7, forms, blocks
---


# Question
Title: Adding Paypal Express Checkout for multiple domains
I'm working with a multi-site setup (via Domain Access) and am having issues using Paypal Express Checkout on more than one domain.

What I have done so far:

* Add a new Payment Method Rule with:
    + Event = Select available payment methods for an order
    + Rule = an existing component with a Domain Comparison element
    + Action = Enable Payment Method : Paypal Express Checkout
* Edited the Action element to add in the updated Paypal payment settings (user, pass, Signature)
* Ensure Rule is active

This does not add the Paypal Checkout button to `/cart` like I expected.

For testing, I edited the component for the domain that does have it and used the new domain for the Domain Comparison. This *did* add the Paypal button to the second domain. The only differences between these rules:

* The component used in the rule has a different domain
* The payment settings (user, pass, signature)
* The original one has a status of *Overridden* whereas the new one has *Custom*

I appreciate any suggestions for troubleshooting the issue - let me know if you need more information!

Chris

# Answer
> 0 votes
This functionality is not currently in the Paypal EC module. Please see https://www.drupal.org/node/2130605 for more information.

Basically, the rule that is created by enabling the Paypal EC module is hard coded into the .module file, making it impossible to use more than one instance without patching the module.

---
Tags: commerce, payment-gateways
---


title: Password may contain illegal characters

text:
# Question
Title: Password may contain illegal characters
Is it possible to change an option or overwrite the password validation so that a user can add characters like `é` to their password?

# Answer
From the Login Toboggan config page:

> LoginToboggan automatically performs basic password validation for illegal characters. If you would additionally like to have a minimum password length requirement, select the length here, or set to 'None' for no password length validation.

If you check the logintoboggan\_validate\_pass you see:

```
  if (preg_match('/[\x{80}-\x{A0}'.          // Non-printable ISO-8859-1 + NBSP
                   '\x{A1}-\x{F7}'.          // Latin punctuations
                   '\x{AD}'.                 // Soft-hyphen
                   '\x{2000}-\x{200F}'.      // Various space characters
                   '\x{2028}-\x{202F}'.      // Bidirectional text overrides
                   '\x{205F}-\x{206F}'.      // Various text hinting characters
                   '\x{FEFF}'.               // Byte order mark
                   '\x{FF01}-\x{FF60}'.      // Full-width latin
                   '\x{FFF9}-\x{FFFD}]/u',   // Replacement characters
                   $pass)) {
    return t('The password contains an illegal character.');
  }

```

So your problem comes from Login Toboggan.

I think this automatic validation is only performed when user can set the password int he register process.
> 3 votes

---
Tags: 7, users, forms
---


# Question
Title: Drupal 7 - Anyway to make Facebook Picture take place of User Picture if not available
I am creating a view of users that displays a list of Users with Picture and Name. This drupal install allows facebook users to sign in and automatically have an account created. Their account is also added to this jCarousel view.

The problem I am facing is that when a user signs up from Facebook, but does not upload an image directly to drupal, their facebook picture does not show on the list. Anywhere else on the site, however, their facebook pictures shows with the profile.

On the views field, I have:

* *User:Picture*
* *User:Name*

**Is there anyway to have a logic in the view where I can request the Facebook Picture if User:Picture is not available?**

Thank you in advance,

# Answer
> 0 votes
You can use the Views PHP module and use PHP to create whatever logic you want for this image output.

> This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.
>
> This is the successor of Views Custom Field for both D6 and D7. The D6 version supports both Views 2 and Views 3.
>
> Note
>
> While this module allows you to directly use PHP inside views which may be useful for quick and easy solutions, it is highly advisable to use regular handlers and plugins when available (or even to create one yourself). Take note that filtering and sorting a view using PHP always has a considerable perfomance impact.

So in your view you can have:

* 3 fields, `user profile picture`, `facebook picture` and the `php field` used to display a picture.
* for the `user profile picture`, make it a default image display and `exclude` it from the output.
* for the `facebook picture` make it a default image display and `exclude` it from render output.
* in the `php field` you simply want to check if a file exists for `user profile picture` and then `drupal_render()` or return the profile or facebook picture Views will have already formatted for you using the other 2 fields.
* be sure the 2 image fields are higher up in the `field list` of the View than the PHP field, so the PHP field can make use of those values in code.

**EDIT**

An alternative that is slightly less magical and tied to Views is to use Display Suite and add a `Custom Field` in display suite for a `User`. This custom field does basically all the logic between the 2 fields and it's literally a pseudo-field for Users. Views can then use the `view_mode` for Users that you've provided by DS.

---
Tags: blocks, views, social-network
---


# Question
Title: how to create categorized webforms in drupal?
I want to create a multiple Forms in my site . so i am going with the webform module , i want webforms in such a categorized as display below ,

general inquiry Forms

1. general feedback
2. general inquiry
3. Training request

Product Inquiry Forms

1. Product 1 Inquiry
2. Product 2 Inquiry
3. Product 3 Inquiry
4. Product 4 Inquiry

Service
5. Service Request
6. service Feedback
7. online parts request

In this general inquiry Forms is like a category and genaral feedback and inquiry is webforms. so how can i create that for prodcut inquiry and service categorized multiple form.

and there are many fields are common in that different form , so if i have to create different fields for different form or can i use one field in a multiple time in different forms.

Thanks, vipul.

# Answer
> 1 votes
With Views, you can group the results by the value of a field, so create a field for your Forms and then group by that. You will have to get creative (custom templates) to get the numbering, if that's important to you.

As for sharing fields between Forms, I don't know of an easy way to do that.

---
Tags: webforms
---