# Question
Title: How do I add JavaScript to the administrative area?
I'd like to add some Javascript into Drupal's admin area (content creation to be specific) and was wondering what's the best approach to do it: I'm using the admin theme Rubik. Shall I just add the JS as part of the Rubik theme? Should I create a sub-theme? But its just one file...

# Answer
> 6 votes
@kiamlaluno explain answer very good way

Using a module, you can follow two methods:

Implementing hook\_init() Implementing hook\_form\_alter() The first method would allow you to add the extra JavaScript (or CSS) files to any administration pages, while the second method would allow you to add those files only to pages containing forms.

```
function mymodule_init() {
  if (arg(0) == 'admin') {
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_js($path . '/mymodule.js');
    drupal_add_css($path . '/mymodule.css');
  }
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (arg(0) == 'admin') {
    $path = drupal_get_path('module', 'mymodule');
    $form['#attached']['css'][] = $path . '/mymodule.css';
    $form['#attached']['js'][] = $path . '/mymodule.js';
  }
}

```

Replace "mymodule" with the short name of your module; replace "mymodule.js" and "mymodule.css" with the actual names of the JavaScript and CSS files.

more detials

# Answer
> 4 votes
If your script is adding functionality, a module might be an even better place (we usually keep a "backend\_helper" module around for that purpose).

To add your script to every admin page, use:

```
/**
 * Implements hook_page_build().
 */
function mymodule_page_build(&$page) {
  // Alternatively we could check for the current theme.
  if(path_is_admin(current_path())) {
    $page['mymodule']['#attached'] = array(
      // ...
    );
  }
}

```

If you only plan to attach your scripts to particular forms, use hook\_form\_FORM\_ID\_alter(). For node add forms, this would be:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form['#node'];

  // Case 1: Only attach on "Add" forms.
  if(empty($node->nid)) {
    // ...
  }

  // Case 2: Limit to certain content types.
  // This can also be achieved by using the "my_content_type_node_form" form ID.
  if($node->type === 'my_content_type') {
    // ...
  }

  // Both conditions can of course be combined. Finally attach your script as described above.
  // You can also reference your theme, if this is where your script is located.
  $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/path/to/script.js';
}

```

Note: Do **not** use `hook_form_alter()`, as it will affect *all* forms. In most cases using the form specific hook is the preferred method.

# Answer
> 2 votes
```
function custum_form_alter_init() {
  if (arg(o) == 'admin') {
    drupal_add_js(drupal_get_path('module', 'custum_form_alter') .   '/custum_form_alter.js');
  }
}

```

and add custum\_form\_alter.js file in your module file

---
Tags: 7, javascript
---


title: One Content Type - 2 Different Displays

text:
# Question
Title: One Content Type - 2 Different Displays
I have a content type that I want to have certain fields show up for different users. For instance, for admin, I'd like the users to see all of the fields available, however, for non admins, I'd like to have one certain fields displayed. Is this possible?

# Answer
Field visibility & access can be controlled with the Field Permissions module.
> 1 votes

# Answer
Yes Field Permission is best choice. If you don't want to go with **Field Permission** module then below is another option. function hook\_form\_alter(&$form, &$form\_state, $form\_id) {

```
if($form_id == 'form_id') {
  global $user;

 //  print_r($user->roles);
 // Check to see if $user has does not have the administrator role.

  if (!in_array('anonymous user', array_values($user->roles))) {
    $form['field_your_field']['#access'] = FALSE;
      }

}

```

}
> 0 votes

# Answer
You may make two templates for that, one for admin user and second for non-admin user. In your custom templates you can show up fields according to your own will. For more details about template suggestion check drupal docs.
> 0 votes

---
Tags: users, display-suite, nodes, entities
---


# Question
Title: 401 Unauthorized : Missing required argument node
I am trying to Create Services to Create Node Type Discussion in a Group using Services Module, but getting the error : 401 Unauthorized : Missing required argument node

In the Header I have given:

> Content-type:application/json
>
> x-csrf-token:token value
>
> session-name:session name value

In the Body I have given :

```
{
"og_group_ref": {"und": [{"target_id": "3897"}]},

"title": "Title of discussion",

"field_description": {"und": [{"value": "test description"}]},

"type": "discussion",

}

```

Can anyone please tell me why I am getting this error ?

# Answer
> 0 votes
You put comma on last parameter `"type": "discussion",` that doesn't required at the end. javascript, jquery, json doesn't allow comma at end of array. It returns invalid argument.

# Answer
> 0 votes
Try wrapping your data like so:

```
{
  node: {
    type: 'discussion',
    /* ... */
  }
}

```

---
Tags: nodes, organic-groups, services, 8
---


title: Commerce controller hook_entity_delete

text:
# Question
Title: Commerce controller hook_entity_delete
The DrupalCommerceEntityController should invoke hook\_entity\_delete before the records in the database are deleted.

As seen in node\_delete\_multiple.

# Answer
> 0 votes
These comments should be filed as a code task in the Drupal Commerce issue queue: https://www.drupal.org/project/issues/commerce

---
Tags: commerce
---


# Question
Title: Filtering referenced nodes where logged in user is a member
I am trying to set up a view of referenced nodes (entity reference field) of the current viewed (group)node. So when a node is viewed i like to filter all the nodes that point to the current node.

Using the node id from url in contextual filter gives no problems. So far so good.

However i like to only display those referenced nodes where the current logged in user is a member of.

Is this possible using views?

# Answer
Thanks for pointing me the right direction. The next setup is my solution: "1 Add a Contextual filter on "OG membership: Group ID".

2 When the filter is not available Provide default value "The OG groups of the logged in user ". Leave the concatenator as "+".

3 Under More check "Allow multiple values"

4 Add a second contectual filter choose: content:name of the entity reference field

5 Config this filter with provide default value "Current OG group from context"

6 Under More check "Allow multiple values"

7 Add a relationshiop :OG membership from node group

8 Under the contextual filter:"OG membership: Group ID" add the relationship mentioned under 7

Looks like this is working
> 0 votes

# Answer
Ok Organic Groups. I got a long way with the following recipe. Unfortunately I could not set up an identical environment to yours.

1 Add a Contextual filter on "OG membership: Group ID".

2 When the filter is not available Provide default value "The OG groups of the logged in user ". Leave the concatenator as "+".

3 Under More check "Allow multiple values"
> 1 votes

# Answer
i edit the text before and working for me

Thanks for pointing me the right direction. The next setup is my solution: "1 Add a Contextual filter on "OG membership: Group ID".

2 When the filter is not available Provide default value "The OG groups of the logged in user ". Leave the concatenator as "+".

3 Under More check "Allow multiple values"

i omitted this step

5 Config this filter with provide default value "Current OG group from context"

6 Under More check "Allow multiple values"

7 Add a relationshiop :OG membership from node group

8 Under the contextual filter:"OG membership: Group ID" add the relationship mentioned under 7

Looks like this is working
> 0 votes

---
Tags: views, organic-groups, entities
---


# Question
Title: How to create a separate web page menu to be used only on one of my web pages?
My site has a main menu displayed at the top of each page. But one of my pages is about a Parade we host, and it has a lot of content.

I would like to create a menu just on the Parade web page. Every option I have looked at has edited the main site menu.

But how do I create a separate menu just to be displayed on my specific pages?

# Answer
> 3 votes
Add a new menu to the site.

Go to Structure \> Menus \> Add Menu

Once you have added a menu, and the links, this menu will now be available as a block.

Go to Structure \> Blocks and assign the new menu to a region.

under that block settings, you can define which URL you would like the block to display on. Set that to the URL of your page, and you're good to go.

# Answer
> 2 votes
Would the Menu Block module help here? You could use the standard menu system to create a custom menu and then expose some or all of that menu as a block that could be added to new or existing region in your layout.

# Answer
> 1 votes
# Step 1: Create the Parade menu

Navigate to `admin/structure/menu/add` in your site and add a new (custom) menu you want. Add at least the "Title" of the menu (like *Parade menu*), save it, and it will show up in `admin/structure/menu` also. From there you can start to add menu items (which will be the "Parade related menu items" you are looking for).

# Step 2: Make the menu visible

Head over to `admin/structure/block` to indicate in which region of your theme you want that newly added menu (*Parade menu*) to be shown.

Tune the "block visibility settings" so that this block is ONLY shown on your "Parade Web page".

# Step 3: Clear the cache

And don't forget to clear the cache (since you're changing things that are cache sensitive ...). I think "menu" cache should be sufficient, but to be sure I usually just clear all caches ...

---
Tags: navigation, blocks
---


# Question
Title: Display one image of commerce product in product display view
I have created a view which display indexed nodes (product displays) in teaser mode. The commerce product entity has a field called `field_images` which contain several images.

In teaser display mode of the commerce product, I choose to display Images. On the views, for each commerce product, all images are displayed. I'd like only the first to be displayed. Unfortunately, I can't set a delta in the teaser display mode form. I could have set the delta to 0.

I will seems reasonable to me, but I can't find an easy way to fix it. How can I achieve this ?

# Answer
> 0 votes
I used the Image Delta Formatter module : https://www.drupal.org/project/image\_delta\_formatter and set the delta to 0 in the product commerce display teaser

---
Tags: commerce
---


# Question
Title: Webform adding custom component or modify radio buttons
I need to make a webform that will display the radio buttons like this jsfiddle, where the label is above the radio button. Do I need to make a new webform component to achieve this or can I just modify the default to add the div and change orientation?

# Answer
> 0 votes
You should be able to do this with CSS alone.

---
Tags: 7, webforms
---


title: Adding JavaScript to Slideshow?

text:
# Question
Title: Adding JavaScript to Slideshow?
I asked a question a few days ago about getting the height of images to adjust in Slideshow along with the width. Unfortunately, I received no responses.

So, I went about writing some JavaScript that adjusts images in a page the way I would like the images in Slideshow to be adjusted. The code works fine on regular Drupal pages, but does not work for the images in Slideshow.

Does anyone know how to get the JavaScript to work for the images in the Slideshow? I should state that I am brand new to coding and JavaScript, so there may be some issues with the code below, but it does work.

Here is the JavaScript code:

```
function myFunction() {
  var x = document.getElementsByClassName("slide");

  for (i = 0; i < x.length; i++) {
    var viewHeight = window.innerHeight;
    var viewWidth = window.innerWidth;
    var viewAspect = viewWidth / viewHeight;

    var imageHeight = x[i].height;
    var imageWidth = x[i].width;
    var imageAspect = imageWidth / imageHeight;

    if (imageAspect < viewAspect) {
        x[i].style.height = viewHeight + "px";
    }
    else {
        x[i].style.width = viewWidth + "px";
    }
  }
}

window.onload = function() {
  myFunction();
};

window.onresize = function() {
  myFunction();
};

```

# Answer
I ended up creating a regular view, not a slideshow. Then I used a variation on the code above to reshape the images. And I used CSS on the mini pager to turn it into the buttons that one would find in a typical slideshow. It turned out exactly how I wanted it. Although it took a lot of time and aggravation, I learned a bit more about about Drupal, JavaScript, and CSS. Plus, I can reuse the code again.

If anyone is interested, my final JavaScript code is below; there were a few minor problems with the code above that caused it to act wonky in certain resizing situations.

```
    function myFunction() {
      var x = document.getElementsByClassName("slide");

      for (i = 0; i < x.length; i++) {
        var viewHeight = window.innerHeight;
        var viewWidth = window.innerWidth;
        var viewAspect = viewWidth / viewHeight;

        var imageHeight = x[i].height;
        var imageWidth = x[i].width;
        var imageAspect = imageWidth / imageHeight;

        if (imageAspect < viewAspect) {
          x[i].style.height = viewHeight + "px";
          x[i].style.width = "auto";
          x[i].style.marginTop = - viewHeight/ 2 + "px";
          x[i].style.marginLeft = - x[i].width / 2 + "px";
        }
        else {
          x[i].style.width = viewWidth + "px";
          x[i].style.height = "auto";
          x[i].style.marginTop = - x[i].height / 2 + "px";
          x[i].style.marginLeft = - viewWidth / 2 + "px";
        }
      }
    }

    window.onload = function() {
      myFunction();
    };

    window.onresize = function() {
        myFunction();
    };

```
> 1 votes

---
Tags: javascript, views
---


# Question
Title: Creating a fake JavaScript exposed filter in Drupal 7 Views module
In this website I'm building there's a page with a Views list of people, divided into categories. I've exposed a category filter and a name filter to visitors.

Since the list isn't long, I would like to show all the items on page load and use the exposed filters as "fake" filters. Those will not actually make a request to the database, but call a JavaScript function that will go through the list and hide the unwanted items using CSS.

I can create my own filters, but then the category filter will not auto update when a new category is created. I've seen that I can use `MYTHEME_preprocess_views_exposed_form` hook to change it to how I want, but then the page will still download and run `auto-submit.js`, which is the CTools JS file that Views module uses for auto submitting. I can remove it with `MYTHEME_js_alter`, but it seems like a lot of effort - and mostly wasted computational time slowing the page load - for a simple task.

Does anyone know a better way to accomplish this? Am I just overreacting over a few lines of code?

Thanks guys, hope everything is clear.

EDIT:

About 5 seconds after posting I've realized that I could use `auto-submit.js` with the JavaScript too. So all I need to do is remove the action of the form and add `onSubmit` that'll point to my script.

# Answer
Here is the solution I used:

I created a new module named "My Views' Client Side Filters".

In the module's `.module` file I added:

```
<?php

function my_views_client_side_filters_form_views_exposed_form_alter(&$form, &$form_state, $form_id)
{
    $form['#attributes']['onsubmit'] = 'return exposedFilterOnSubmit();';
    drupal_add_js('sites/all/themes/MY_THEME/js/MY_JS_FILE.js');
}

```

Which resulted in the HTML:

```
<form onsubmit="return exposedFilterOnSubmit();" action="MY FORM DESTINATION" method="get">

```

And `sites/all/themes/MY_THEME/js/MY_JS_FILE.js`:

```
function isEmpty(str) {
    return (str.length === 0 || !str.trim());
}
var departmentAllShown = true;
var nameAllShown = true;
(function ($) {
    function reloadNames(name) {
        $('.views-row').each(function() {
            if($(this).find('.doctors_view_row_title').text().toLowerCase().indexOf(name.toLowerCase()) >= 0)
                $(this).css('display','block');
            else
                $(this).css('display','none');
        });
        nameAllShown = false;
    }
    jQuery.extend({
        exposedFilterHider: function()
        {
            //Handle url (JavaScript only now enabled)
            if(!isEmpty(window.location.search))
                location = "MY_SITE_LOCATION/FORM_PAGE";

            var department = $('#edit-field-department-value')[0].value;
            var departmentIndex = $('#edit-field-department-value')[0].selectedIndex;
            var name = $('#edit-title')[0].value;

            var nameIsEmpty = isEmpty(name);

            if (departmentIndex != 0)
            {
                $('.item-list').each(function() {
                    if ($(this).children().first().text() === department)
                    {
                        $(this).css('display','block');
                        if (!nameIsEmpty)
                            reloadNames(name);
                        else
                            if (!nameAllShown)
                            {
                                $('.views-row').css('display','block');
                                nameAllShown = true;
                            }
                    }
                    else
                        $(this).css('display','none');
                });
                departmentAllShown = false;
            }
            else
            {
                //Enable all categories if not already
                if (!departmentAllShown)
                {
                    $('.item-list').css('display','block');
                    departmentAllShown = true;
                }

                if (!nameIsEmpty)
                    reloadNames(name);
                else //Enable all names if not already
                    if (!nameAllShown)
                    {
                        $('.views-row').css('display','block');
                        nameAllShown = true;
                    }
            }
        }
    });
})(jQuery);

function exposedFilterOnSubmit()
{
    jQuery.exposedFilterHider();
    return false;
}

```

Sorry I don't explain any further, I'm kind of stressed in time. If someone asks a specific question I promise to answer.

Hope this helps anyone!

BTW, although the code is a bit long it works spectacularly and runs swiftly.

Remember to change the classes! You might need to change things a bit since my layout may not be the same as yours.

**My classes:**

`.views-row` \- Entire "person" row (The name container is somewhere inside and there are a few of those in every category)

`.doctors_view_row_title` \- Name container

`.item-list` \- The category container

Good luck guys!
> 1 votes

---
Tags: hooks, views
---


# Question
Title: Server connect time significantly increased over the time
I run my web site on D7 with enabled `Cache pages for anonymous users` option `Cache blocks`is off. It works pretty fast for non registered users but I started to observe significant difference for registered users (they can create content and do other things) over 2 months. Server connect time has grown. What can be a reason for that and how can I fix it?

# Answer
You can use block cashing for users you can check this link for more details https://www.drupal.org/node/326504 Check your MySQL server memory.
> 0 votes

---
Tags: performance
---


# Question
Title: Views and how to get calendar taxonomy legend
In the below image example, the person has a taxonomy legend (lower right hand corner):

How did this person get the legend? From his blog:

> After \[adding taxonomy term fields\] let's hop back to our Views settings for the calendar view. Go to "Format" and Calendar Items Settings. **Here we have an awesome legend feature built right in**.

Um, no we don't. So how come he has a taxonomy legend feature (i.e. vocabulary legend types) in his Views and I don't? See below from his blog:

All I see in mine is the below:

Notice that my term field pull-down is mysteriously blank. Something whacky is going on!

# Answer
To see an option in the term field as above (e.g. field\_event\_type) make sure you add the Taxonomy field to your view and select Create a label in the **Configure Field** options. The label you create will then appear in the term field. If you do this with multiple term fields that are added to the view you can use the drop down to select.

Not sure at this stage regarding the Legend option however.
> 2 votes

# Answer
You have to set the label first of the term field.
> 1 votes

# Answer
Include the Vocabulary as a views field. The field wont't show in most calendar views anyways, but you can hide it from display.
> 0 votes

# Answer
This puzzled me for a few days .. indeed, you need to add the field from the ContentType; the field where you select the term.
> 0 votes

# Answer
I know that it's been a while, but it is still a valid question. I solved this very issue as follows:

1. I installed Views Field View
2. I created a view for the taxonomy terms that I am interested in
3. I selected the title and `Taxonomy term: term ID` as fields to show. Only that the latter is excluded from presentation, and output rewritten as `[tid]`

in the (fullcalendar) target view, I added a footer: `global: views field view` and chose the view created in the first place.

And voilà, that did the trick for me.

HIH
> 0 votes

---
Tags: 7, views, datetime
---


# Question
Title: How to add edit link within add to cart form in ubercart drupal 7?
I need to add ***edit*** link within **add to cart** form in ubercart in Drupal 7. I am using `hook_form_uc_cart_view_form_alter()` hook but not getting how to add ***edit*** link within this hook.

# Answer
> 0 votes
This is probably confusing due to UC's reliance on TAPIr to render the cart items. Anyway, you can modify data inside in the `$form['items']` array to change the output of those elements. For example, if you wanted to add an edit link underneath the product description:

```
function MYMODULE_form_uc_cart_view_form_alter(&$form, &$form_state) {
  foreach($form['items'] as $key => $value) {
    //Check a TAPIr row for a product associated with an editable nid
    if(is_int($key) && isset($value['nid']['#value']) && isset($value['desc'])) {
      if(node_access('update', $value['#entity'], $user)) {
        $form['items'][$key]['desc']['#markup'] .= l('(EDIT)', 'node/'.$value['nid']['#value'].'/edit');
      }
    }
  }

```

There might be a cleaner way to do this, but I haven't thought about TAPIr in a while.

---
Tags: ubercart
---


title: How to prevent empty token from showing

text:
# Question
Title: How to prevent empty token from showing
I want to capture a value from the url and display it in a piece of content, if available. In my node body I enter text like:

`The sid is "[current-page:query:sid]".`

If I then view that node at http://example.org/node/123?sid=foo the content shows as:

> The sid is "foo".

Excellent, all working great. Here's the problem: if I visit the page without the ?sid argument in the url (just going to /node/123), then the content displays literally as:

> The sid is "\[current-page:query:sid\]".

I would prefer the token to just be blank in that case. How can I get it to output

> The sid is "".

# Answer
> 2 votes
The reason for what you experiencing is the default behavior of `token_replace()` to leave tokens untouched if no replacement value was provided.

In your case, the *Token Filter* module would have to provide the option `'clear' => true` when calling `token_replace()`.

You may want to try to apply the patch in this issue to the token\_filter module.

---
Tags: tokens
---


# Question
Title: how to update price from front end in ubercart product in drupal 7?
I have a site in *drupal 7*, and I am the admin of site. I am using **ubercart** in my site for products. I have lot of products in my site with attributes and options. My products options are price based..

For example: I have one jewellery $100 with siver $23 and gold $43. Silver and gold are comming from option.

I want to update **options price from front end where product are displaying without going from edit product from backend**.

# Answer
This functionality isn't built into Ubercart. In order to do something like this, you're going to have to implement your own custom form to manipulate the options data, or, better yet, invoke `uc_object_options_form` (the options form display on **node/$nid/edit/options**) with `drupal_get_form()`.
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: How to (ab)use image effects to serve API generated images?
I made code to add a custom effect using `hook_image_effect_info()` that does not alter the image for real. I'd like to serve an image from my own API instead, that has calls like *myapi.com/img2123?w=25&h=88&watermark=true*. I don't think that the code for a placeholder effect is relevant is it?

I'd like to use this because that way if I add an **Image field** to a content type I can choose a banner for example on every '*Article*' **content type**.also I need to pass the parameter returned by the **dimensions callback** (set in the **form callback** of `hook_image_effect_info()`) to the GET request as an URL parameter.

I was thinking: could I use some node altering hook to change the uri that is parsed somewhere else in the program?

If you need some additional info, just ask. Thanks in advance.

# Answer
> 1 votes
The only way to abuse image styles in the way you described would be to issue a redirect when your image effect callback gets invoked. This is inefficient and will only work if no derivative has been created yet.

A better way to dynamically replace image paths would be via hook\_preprocess\_image() (see theme\_image() for available variables):

```
/**
 * Implements hook_preprocess_HOOK().
 */
function mymodule_preprocess_image(&$vars) {
  if($vars['path'] === 'arbitrary/condition') {
    $vars['path'] = url('http://my.api/', array('query' => array(
      'width' => $vars['width'],
      'height' => $vars['height'],
    )));
  }
}

```

# Answer
> 1 votes
If you are getting the image from another server/site you don't need an image field. If the link isn't going to change, you can store it in a text field and build a link like this

```
your_module_node_view($node, $view_mode, $langcode) {
    $url = $node->field_cool_image[LANGUAGE_NONE][0]['value'];
    //redefine field_cool_image to display your image
    $node['content']['field_cool_image'][0] = array(
        '#markup' = '<img src="' . $url . '" alt="my cool image" />'
    );

}

```

otherwise build the link when the node view is built.

```
your_module_node_view($node, $view_mode, $langcode){
    //whatever method you use to build a url
    $url = my_build_url($node);
    $node->['content']['my_cool_img'][0] = array(
        '#markup' = '<img src="' . $url . '" alt="my cool image" />'
    );
}

```

---
Tags: 7, media
---


# Question
Title: How to display content for specific user
I created a content type Report. One of the fields name is MyUser and field type is EntityReference. For this field, widget type is SelectList and Target type is User.

I added two contents: Content1 and Content2. I selected UserA for the MyUser field in Content1 and I selected UserB for the MyUser field in content 2.

Now, I created a page view to select the content for the logged in user. If userA logged in, he should see only content1 and if userB logged in, he should see only content2. I thought I needed to add a filter criteria/relationship in view.

How to add the filter criteria/relationship to meet the above requirements?

# Answer
> 2 votes
Add an explicit relationship to the user, and mark it as required. After that you will be able to add a new filter criterion to your view: `User: Current`.

# Answer
> 0 votes
I'm not sure to understand your problem but for what i've understand you could resolve using Content access module it permit you to associate a specific content type to a role ( user group )

Hope to help you

---
Tags: views
---


title: nice menu mobile gesture

text:
# Question
Title: nice menu mobile gesture
i've developed a project using Nice Menus module, but on mobile can't use well with submenus. So i thought to use JS injector to listen swipe on screen and make menu visible. i wrote this code

```
$(document).ready(function(){$("#second-column").on("swipe",function(){
      if($(window).width()<=900)
        $("#nice-menu-1>li>ul").css("display: block; visibility: visible;");
  });
});

```

but chrome console said `$ is not a function` so i search and replace `$` with `jQuery`, now i've no moar message but it doesn't work.

Thanks in advance for help

# Answer
> 1 votes
I think this is a syntax issue. Try using

```
jQuery(function($) {
    //Your Code
});

```

# Answer
> 1 votes
I'm taking a stab at this and guessing you are using D7, refer to the page I link below for D6/D8 versions of the behavior code below.

The correct way to use JS in Drupal is to wrap your code in a Drupal behavior.

```
(function ($) {
   Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      $('input.myCustomBehavior', context).once('myCustomBehavior', function () {
        // Apply the myCustomBehaviour effect to the elements only once.
      });
    }
  };
})(jQuery);

```

You can read more about that here: https://www.drupal.org/node/304258

Now that being said, technically swapping out for jQuery should have worked also but you should at least get some errors if the code is ran. Maybe swapping over to a behavior will let it continue through and finish running.

# Answer
> 0 votes
**If statement in jQuery example:**

```
if (n < 2) {
        $("body").css("background", "green");
    }

```

**I noticed your if statement is missing curly brackets `{ }` so try**

```
(function ($) {

  $(document).ready(function() {
     $("#second-column").on("swipe",function(){
           if($(window).width()<=900) {
           $("#nice-menu-1>li>ul").css("display: block; visibility: visible;");
           }
        });
    });

})(jQuery);

```

# Answer
> 0 votes
I discover what was the problem it's jQuery.
Drupal core run 1.4 but to use mobile gesture i need 1.7. After i've update to it my mobile menu works but all website functionality will broke because js is incompactible.
Now, i've search a lot and the best result i've found is this discussion so i've install jQuery multi but nothing change my site is broke. In particular i've a big problem, when i try to open a page it will not opened but the URL change and the page is printed at the bottom to the previous. So i need to refresh manually to get my page

Could someone adress me to the right way?

---
Tags: javascript, navigation
---


# Question
Title: Breadcrumbs stopped going to third level
I'm still learning Drupal, so have a basic understanding, and have been assigned to fix our breadcrumbs. Apparently it used to go to the 3rd level on this page (https://ccom.unh.edu/theme/auvs), but it no longer does, only to the 2nd level. It should say Home\>Research\>AUVs, but it only says Home\>Research.

The Crumbs module wasn't installed. I've been looking through our modules to try to figure out what is doing the breadcrumbs, but I don't see anything. If I install the Crumbs module I can't even find instructions on how to implement it. Can someone give me some guidance here please? Thanks!

# Answer
You can search for `theme_breadcrumb()`, they may develop it with this function ( search in template.php )
> 0 votes

# Answer
Your breadcrumb is likely dependant on the actual menu structure. As such it is quite possible that the menu structure itself has changed, especially if untrained editors don't respect certain conventions when making changes.
Thanks to archive.org we can take a look at past versions of your site:

You will notice that the breadcrumb only changes between 2014 and 2015, now displaying the "Research" item twice.

To narrow down the origin of the problem there are a few approaches:

1. Inspect the menu structure to see if there even exists a third level (assuming the breadcrumb is actually derived from it).
2. Inspect the remaining archive.org snapshots that lie in between the ones listed above for 2014 and 2015, until you find the closest two that differ.
3. If the code is versioned, inspect commits that fall into that time range.
4. If there are database backups, set up a local installation that uses an older version of the DB contents.
> 0 votes

---
Tags: breadcrumbs
---


# Question
Title: How to add custom field to image area where Alt and Title fields are showing?
I am trying add new field to image widget using hook\_field\_widget\_form\_alter

Bellow is the code:

```
function MYMODULE_field_widget_form_alter(&$element, &$form_state, &$context) {
     $element[0]['custom'] = array(
     '#type' => 'textfield',
     '#title' => 'Custom Field',
     '#default_value' => FALSE,
    );
}

```

But it add a new field to first image always. I'm expecting the custom field with each image as Alt & Title fields are showing for each image.

If I remove the \[0\] index like:

```
      $element['custom']

```

or

```
    $element[]['custom']

```

it show an error, and show the field bellow image field not with Alt & Title field.

```
Notice: Undefined index: #file in theme_file_widget_multiple() (line 861 of C:\xampp\htdocs\drupal39\modules\file\file.field.inc).

```

I also try with \[#process\]\[\] way:

```
function MYMODULE_field_widget_form_alter(&$element, &$form_state, &$context) {
if (isset($element['#field_name']) && $element['#field_name'] == 'field_gallery_image') {
      foreach (element_children($element) as $key => $child) {
          $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
      }
    }
}

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
$element['custom'] = array(
    '#title' => t('Custom Field'),
    '#type' => 'textfield',
    '#default_value' => isset($item['custom']) ? $item['custom'] : '',
    '#weight' => 1,
);
return $element;
}

```

This way the Custom field is adding to all images but create one EXTRA custom field bellow the Image field.

# Answer
I put element in IF condition in MYMODULE\_image\_field\_widget\_process and it works fine. What it does is, it checks for ALT attribute if it is ENABLED so it will then add the CUSTOM field, you can instead add the CUSTOM field visibility option in image setting page and check for that.

```
function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
   if ($element['alt']['#access']) { // IF condition added here
      $element['custom'] = array(
        '#title' => t('Custom Field'),
        '#type' => 'textfield',
        '#default_value' => isset($item['custom']) ? $item['custom'] : '',
        '#weight' => 1,
      );
   }
   return $element;
}

```
> 0 votes

---
Tags: entities, media
---


# Question
Title: How to create a vocabulary and populate it with terms using features
I'd like to create a feature that creates a vocabulary and populates it with taxonomy terms.

Creating a vocabulary is easy with features and it can be done using UI (I only need to select the desired existing vocabulary and add it as dependency and a file features.taxonomy will be created)

However, there's no way to export terms to a feature, so I created a feature\_name.install file and added the following function on it:

```
/**
 * Implements hook_install().
 */
function feature_name_install() {
  // Populates 'Vocabulary name' vocabulary with taxonomy terms.
  $vocabulary = taxonomy_vocabulary_machine_name_load('vocabulary_machine_name');
  $terms = array();

  $terms[] = t('Term 1');
  $terms[] = t('Term 2');
  $terms[] = t('Term 3');

  foreach($terms as $name) {
    $term = new stdClass();
    $term->vid = $vocabulary->vid;
    $term->name = $name;
    taxonomy_term_save($term);
  }
}

```

The problem with this code is that when installing the feature it is loaded before creating the vocabulary so tries to add terms to a vocabulary that does not exist yet and produces an error.

I have tried using hook\_post\_features\_enable\_feature but I didn't succeeded (I may be using a wrong syntaxis, see code below).

```
/**
 * Implements hook_post_features_enable_feature($component).
 */
function feature_name_post_features_enable_feature($component) {
  $component = 'feature_name';
  // Populates 'Vocabulary name' vocabulary with taxonomy terms.
  $vocabulary = taxonomy_vocabulary_machine_name_load('vocabulary_machine_name');
  $terms = array();

  $terms[] = t('Term 1');
  $terms[] = t('Term 2');
  $terms[] = t('Term 3');

  foreach($terms as $name) {
    $term = new stdClass();
    $term->vid = $vocabulary->vid;
    $term->name = $name;
    taxonomy_term_save($term);
  }
}

```

Can anyone tell me how to solve this?

# Answer
The problem with exporting content like taxonomy terms is keeping the taxonomy id intact when migrating it from site to site which is exactly what the features extension module UUID Features solves by using the UUID api:

> The UUID Features Integration module provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. What's that you say? You thought features was only for configuration? This module is meant to be used in the cases where certain pieces of content straddle the line between pure content and configuration.
> 1 votes

# Answer
Looks like your problem has to do with $component. The vocabulary isn't complete until $component == 'taxonomy' - you should do an if on this before trying to create terms.
> 1 votes

# Answer
Adding a vocabulary programmatically is just as easy as adding terms. You could use the same hook\_install() function you've built for your term, and insert the vocabulary first.

```
function feature_name_install() {
  $vocab = new stdClass();
  $vocab->name = "My vocabulary name";
  $vocab->machine_name = "my_vocabulary_name";
  taxonomy_vocabulary_save($vocab);

  // Note, you could also attempt to load the vocabulary by machine name first,
  // which would allow you to take action if a vocabulary using your name
  // already exists (either delete it, or error out, or...)

  $vid = $vocab->vid;  // $vocab object now has the vocabulary ID

  // ...continue as you were in peace

```
> 1 votes

# Answer
Unfortunately the vocabulary provided by the feature won't be available using that hook, you'll have to use hook\_post\_features\_rebuild() instead.
> 0 votes

---
Tags: taxonomy-terms, features
---


# Question
Title: how to theme nodes in views results if logged in user equals node author
I have a D7 site with search\_api module, I'd like to change border color of nodes in views results if logged in user equals node author, in plain English, make easy to logged in users identify its own content in views results.

# Answer
> 0 votes
You'll need to check this in a preprocess hook. You can load the global $user object and have views report the node author. In the preprocess hook you can check $user-\>uid against $node-\>uid and set a variable so you know in your tpl.php file which css class to set in your wrapper.

# Answer
> 0 votes
You can check the author condition in **theme\_preprocess\_search\_api\_page\_result** function. You can add a class to the result where the current user is the node author.

```
function theme_preprocess_search_api_page_result(&$variables) {
  global $user;
  if ($variables['item']->author == $user->uid) {
    $variables['classes_array'][] = 'node-author';
  }
}

```

I'm not sure of the 'if condition', you can print the **$variables** to confirm it.

```
.node-author {
  border: 1px solid black;
}

```

To add border, you can add the above css to your style.css or the css file you wish to add.

Hope this helps!

---
Tags: views, theming
---


# Question
Title: View of organic groups name list with no activity
I'm running a Drupal 7 site, and I want to create a list view of group names with no activity within last 60 days. For example if user have not created any content with in those groups.

Currently groups (OG) hold different content-types/nodes i.e news, galleries, wikis, and discussions.

Can someone please help me achieve this?

# Answer
I suggest you to create a custom table with group id and access timestamp. Whenever you are adding a new content to OG, update the table with group id and current timestamp. Then list inactive groups (by calculating current time from your timestamp saved in table), using theme\_table function.
> 0 votes

---
Tags: 7, views, organic-groups
---


title: Add classes to menu item based on url

text:
# Question
Title: Add classes to menu item based on url
For various reasons, I can not use the Drupal 7 menu system and have to hardcode a special menu. I am trying to add an active class basing on the URL. I was looking at this page and trying the following.

```
        <ul class="nav navbar-nav">
            <li><span class="icon-search"></span><a href="/search" title="" class="<?php if ( ($path == $_GET['q'] || ($path == '/search') ) ) : print ('active');endif;?>">Search</a></li>
            <li><span class="icon-sports"><a href="/sports" title="">sports</a></li>
            <li><span class="icon-news"><a href="/news/" title="">news</a></li>
            <li><span class="icon-ent"><a href="/entertainment" title="">entertainment</a></li>
        </ul>

```

# Answer
> 1 votes
You can read URL with out base path using $\_GET\['q'\] ..

```
<?php if ( $_GET['q'] == "search" ) : print ('active'); endif; ?>

```

OR

You can use current\_path API function which does the same...

# Answer
> 1 votes
**Update**, here is the working formula. Thanks Anil for pointing me in correct direction. I got this off this comment

```
$path = current_path();
$path_alias = drupal_get_path_alias(current_path());
<?php if ( $path_alias == "search" ) : print ('active'); endif;  ?>

```

# Answer
> 0 votes
this code is an exemple on how to add it to a div parent ( )

```
function yourtheme_preprocess_html(&$vars) {
 /*
  *
  * add contextual classes for each main menu sections for styling     purposes  *
  */
 $url_components = explode('/', request_uri());
 if ('en'===$url_components[1])
    $vars['classes_array'][] = 'menu-en-section-'.$url_components[2];
 else
    vars['classes_array'][] = 'menu-section-'.$url_components[2];
 };

```

---
Tags: routes, theming
---


# Question
Title: How to format a date submission value of a webform?
I need to format a birthday submission value to the short format (01.01.2015) defined under admin/config/regional/date-time on a webform.

This Token is working but it uses the long format (Fr, 01/01/2015):

```
[submission:values:bday]

```

I tried the following token variations :

```
[submission:values:bday:short]
[submission:values:bday:custom:short]
[submission:values:bday:custom:d.m.Y]
[submission:values:bday:date:short]

```

But none of them submits my desired output. Any Ideas?

# Answer
> 3 votes
I finally found a answer myself. Instead of changing the date format tokens you can set the date format globally for webforms under admin/config/content/webform.

# Answer
> 0 votes
You could change it server side with a datetimeformatter or client side. Also if you'd like these kind of things often, you can take a look at moment.js

---
Tags: webforms, tokens
---


# Question
Title: How to display one of the fields once in drupal views?
I have created a gallery view using nid as contextual filter, all images have the same album title. I need to output the album title field once. How can this be done?

I'm using views 3.

# Answer
> 2 votes
For example you can group the rows of the view by the title (Format: Unformated list - Settings)

# Answer
> 4 votes
Select settings in **Format** field,and select the title under Group field selectlist.

---
Tags: views, entities
---


# Question
Title: Method of initiating a text trim at a matching string?
Using Drupal 7, I'm creating nodes by email using Feeds and Mailhandler. The body of the email is mapped to the body of the node. I'd like to trim the text to eliminate boilerplate language from the email so that it's not in the body of the node. I can't initiate the trim on a character or word count, because that will vary with each email. Is there a module, or a method in either Rules or Feed Tamper, by which I can initiate a trim when encountering a particular text string? If not, is there another method (like rewriting the string) that would achieve this? Thanks!

# Answer
I'm answering my own question... To eliminate a text string in an imported node, I used the Feeds Tamper "find replace regex" plugin on the node's body.The regex to find was:

> /(?=FirstWord )(.\*)(?\<=LastWord\[.\])/s

Where FirstWord was the first word of the string to be eliminated, and LastWord\[.\] represented the last word of the string followed by a period. If you don't want to include punctuation, eliminate the \[.\] completely.

The trailing "s" indicates "single line mode," which makes the dot (before the asterisk) match all characters, including line breaks.

Of course, the replacement value was empty.
> 0 votes

---
Tags: rules, feeds
---


# Question
Title: Stop Drupal from redirecting to "Reset Password" on user account activation
I have a Drupal dev site where users register, then get sent an email with a link that they need to click in order to verify the account. The issue is that link directs them to a page with the title being "Reset Password" (but it doesn't actually enforce a password change). How do I change the page that the user is directed to when activating their account? It shouldn't be enforcing this.

I am also using the https://drupal.org/project/logintoboggan module to improve the registration process, and perhaps this is causing the issue? I am using the "Set a password" option on the plugin to force users to create a password when creating an account, so therefore the registration process should not be enforcing the user to then reset their password.

# Answer
Go to: admin/config/people/accounts

Edit: Welcome (no approval required) Email

Replace "\[user:one-time-login-url\]" with "\[user:validate-url\]"

https://www.drupal.org/node/1412778
> 2 votes

---
Tags: users, authentication-authorization
---


# Question
Title: What is the best way to make some content only available to authenticated users?
I'm currently trying out Drupal 8, but I'm wondering what is the best way to make some content (content types and some specific nodes) only available to authenticated users?

I'm using 2 content types, private and public, with both using the same taxonomy, but I would like one type to be published public and one private.

# Answer
> 2 votes
You can use the combination of ACL and Content access modules to achieve this. ACL + Content access give you better control over access to content: You can make certain types accessible to certain roles, or even specific nodes accessible to specific users.

Now here comes the tricky part:

Both the Acl and Content Access modules have no D8 release yet and have patches in their issue queues, which convert them to D8. For some reason the maintainers have not created D8 branches yet, but I'm using the patched versions of both the modules on my company site - they work perfectly.

ACL patch can be found here.

Content access patch can be found here.

# Answer
> 0 votes
Use the Content Access Drupal module, it allows per content type and per node access rights.

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

---
Tags: nodes, users, 8
---


# Question
Title: Generate google search result for my website like that of flipkart
I have my website which i can search in google and it comes up. But if i see flipkart search result on google, it is structured very well. Is there any module to do that in drupal?

# Answer
> 1 votes
I believe this technique is call Rich Snippets and this might be a cool module for you: https://www.drupal.org/project/schemaorg

---
Tags: search
---


title: Receive a file with Drupal 7

text:
# Question
Title: Receive a file with Drupal 7
I have a java application that will send a CSV file to a Drupal 7 site through using POST method.

how i receive file on drupal side by using custom module

I need to parse the file to add data into a custom table.

# Answer
I will try again:

you can `var_dump($_POST);` to get all posted variables on the site and know the array index in which your application POST's
> 1 votes

---
Tags: 7, files, services
---


# Question
Title: Does the SendGrid Integration module also require additional libraries?
I'm trying to use SendGrid for email delivery. I have an account on sendgrid.com, and have generated API credentials.

When I try to use the service I always get a 404 BAD username and password error:

> Email sending failed with 404/Bad Request. Bad username / password

Does the SendGrid Integration module also require additional libraries?

What can cause this problem?

# Answer
> 1 votes
Following this detailed tutorial it says you shouldn't. You might want to check if you added a trailing space to the end of your username or password?

The HTTP response 400 in combination with it's text should make it clear this is a configuration error, not an missing library error. Then it would probably show PHP dependancy errors.

---
Tags: emails
---


# Question
Title: Preview image after uploading using Form API
I uploaded an image file using the `managed_file` Form API type, but after uploading the image it does not appear as a thumbnail beside the field. What is rendered is the file name of the image with a link to the image and a small icon.

How do I show the thumbnail of the image after uploading it (like the image preview from the core Image field)?

Also how can I show a default image beside it (if it has a default value)?

This is my code:

```
$form['logo'] = array(
      '#title' => t('Logo'),
      '#type' => 'managed_file',
      '#required' => TRUE,
      '#default_value' => variable_get('logo', ''),
      '#upload_location' => 'public://',
      '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(0.3*1024*1024),
  )

```

# Answer
> 4 votes
I have resolved the issue with a simple fix. You can add a theme to the form element "tbs\_thumb\_upload" and in the theme file hand the element as mentioned in the theme file code.

```
 // THIS IS THE FILE FIELD
 $form['logo'] = array(
  '#type' => 'managed_file',
  '#title' => t('Logo'),
  '#description' => t('Allowed extensions: gif png jpg jpeg'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    // Pass the maximum file size in bytes
    'file_validate_size' => array(1 * 1024 * 1024),
  ),
  '#theme' => 'tbs_thumb_upload',
  '#upload_location' => 'public://society/',
  '#attributes' => array('default_image_path' => TBS_IMAGE_DEFAULT_SOCIETY)
  );

 // THIS IS THE THEME FILE : THEME : tbs_thumb_upload : Theme file code
 if (!empty($form['#file'])) {
   $uri = $form['#file']->uri;
   $desc = FALSE;
 }else {
   $uri = $form['#attributes']['default_image_path'];
   $desc = TRUE;
 }

 // Render form element
 print drupal_render_children($form);

```

# Answer
> 10 votes
Define the theme in the field, and simulate the code structure to preview the image that you just upload. My solution is as follows,

```
$form['abc_field']['abc_filename'] = array(
        '#type' => 'managed_file',
        '#title' => t('abc image'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(1 * 1024 * 1024),
        ),
        '#theme' => 'abc_thumb_upload',
        '#upload_location' => 'public://abc/'
    );

```

In your hook\_theme(),

```
return array(
    'abc_thumb_upload' => array(
        'render element' => 'element',
        'file'           => 'abc.module',
));

```

In your theme\_abc\_thumb\_upload(),

```
function theme_abc_thumb_upload($variables) {

    $element = $variables['element'];

    if (isset($element['#file']->uri)) {
        $output = '<div id="edit-logo-ajax-wrapper"><div class="form-item form-type-managed-file form-item-logo"><span class="file">';
        $output .= '<img height="50px" src="' . file_create_url($element['#file']->uri) . '" />';
        $output .= '</span><input type="submit" id="edit-' . $element['#name'] . '-remove-button" name="' . $element['#name'] . '_remove_button" value="Remove" class="form-submit ajax-processed">';
        $output .= '<input type="hidden" name="' . $element['#name'] . '[fid]" value="' . $element['#file']->fid . '">';

        return $output;
    }
}

```

# Answer
> 4 votes
about dimension check this validation file\_validate\_image\_resolution:

```
$form['logo'] = array(
      '#title' => t('Logo'),
      '#type' => 'managed_file',
      '#required' => TRUE,
      '#default_value' => variable_get('logo', ''),
      '#upload_location' => 'public://',
      '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(0.3*1024*1024),
            'file_validate_image_resolution'=>array('100x100'),
  )

```

# Answer
> 3 votes
Hacking up the HTML for a remove button does not work for me. The page refreshes without removing the image. Instead I copied from the core image field's `theme_image_widget` callback found in `docroot/modules/image/image.field.inc`.

```
/**
* Implements theme_mymodule_thumb_upload theme callback.
*/
function theme_mymodule_thumb_upload($variables) {
  $element = $variables['element'];
  $output = '';
  $output .= '<div class="image-widget form-managed-file clearfix">';

  // My uploaded element didn't have a preview array item, so this didn't work
  //if (isset($element['preview'])) {
  //  $output .= '<div class="image-preview">';
  //  $output .= drupal_render($element['preview']);
  //  $output .= '</div>';
  //}

  // If image is uploaded show its thumbnail to the output HTML
  if ($element['fid']['#value'] != 0) {
    $output .= '<div class="image-preview">';

    // Even though I was uploading to public:// the $element uri was pointing to temporary://system, so the path to the preview image was a 404
    //$output .= theme('image_style', array('style_name' => 'thumbnail', 'path' => file_load($element['fid']['#value'])->uri, 'getsize' => FALSE));

    $output .= theme('image_style', array('style_name' => 'thumbnail', 'path' => 'public://'.$element['#file']->filename, 'getsize' => FALSE));
    $output .= '</div>';
  }

  $output .= '<div class="image-widget-data">';

  if ($element['fid']['#value'] != 0) {
    $element['filename']['#markup'] .= ' <span class="file-size">(' . format_size($element['#file']->filesize) . ')</span> ';
  }

  // The remove button is already taken care of by rendering the rest of the form. No need to hack up some HTML!
  $output .= drupal_render_children($element);

  $output .= '</div>';
  $output .= '</div>';

  return $output;
}

```

Use this theme function to render the element:

```
/**
* Implements hook_theme().
*/
function mymodule_theme() {
  return array(
    'mymodule_thumb_upload' => array(
      'render element' => 'element',
    )
  );
}

```

Form element definition:

```
$form['upload_image'] = array(
  '#type' => 'managed_file',
  '#default_value' => $value,
  '#title' => t('Image'),
  '#description' => t('Upload an image'),
  '#upload_location' => 'public://',
  '#theme' => 'mymodule_thumb_upload',
  '#upload_validators' => array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('jpg jpeg gif png'),
    'file_validate_image_resolution' => array('600x400','300x200'),
  ),
);

```

# Answer
> 2 votes
Add another form element to contain the markup for your image preview. In the below code, $v contains the form values of interest. Your specific case may pull them from a node, from form state or somewhere else. It is a file object cast to an array.

```
// If there is a file id saved
if (!empty($v['fid'])) {
  // If there is no file path, a new file is uploaded
  // save it and try to fetch an image preview
  if (empty($v['uri'])) {
    $file = file_load($v['fid']);
    // Change status to permanent so the image remains on the filesystem.
    $file->status = FILE_STATUS_PERMANENT;
    $file->title  = $v['title'];
    // Save.
    file_save($file);
    global $user;
    file_usage_add($file, 'node', 'node', $user->uid);
    $v = (array)$file;
  }
  $form['photos']['items'][$i]['preview']['#markup'] = theme(
    'image_style',
    array(
      'style_name' => 'form_image_preview',
      'path' => file_build_uri(file_uri_target($v['uri']))
    )
  );
}

```

Note that I set the file status to permanent and re-save. This is for the images that are uploaded to be previewed correctly. Image styles can't be generated for images in temp storage, so you have to flag them as perm. Depending upon your use case and workflow, you may have to address "orphaned" images.

My form structure ($form\['photos'\]\['items'\]\[$i\]) is for a multi-entry image field. I have a theme template that gathers them up and puts them in drupal\_add\_tabledrag. Your form array structure will likely differ.

---
Tags: 7, forms, files
---


# Question
Title: SQL query to display a particular content type?
I want to create a view which displays a list of a particular content type. I only have access to the database and I need to figure out the list of content type through view; therefore, I am thinking to write SQL for it. Is it possible to do?

I am using Drupal 6.

# Answer
> 1 votes
# List all content types

To build a list of all your content types in a Drupal 6 site, use an SQL query like so:

```
SELECT * FROM `node_type`

```

The values in the `type` column in the results you get, corresponds to the machine name for each of the content types you have in your site.

# List all nodes of a particular content type

Here is an SQL query to display a list of nodes of content type `story` in a Drupal 6 site:

```
SELECT *  FROM `node` WHERE `type` = 'story'

```

Change `story` to the machine name of your particular content type (= any of the values in the `type` column from the first SQL above).

---
Tags: 6, database
---


# Question
Title: How to override an existing theme without subtheming it?
Does anyone know how to overload/override an existing theme with one's own .css and .tpl.php file, without subtheming it?

# Answer
> 0 votes
You can call for your css

```
<?php
function mytheme_preprocess_html(&$variables) {
  drupal_add_css('http://fonts.googleapis.com/css?family=News+Cycle', array('type' => 'external'));
}
?>

```

and for your tpl file

```
<?php
/**
 * Implements hook_theme_registry_alter().
 */
function my_module_theme_registry_alter(&$theme_registry) {
    // Defined path to the current module.
    $module_path = drupal_get_path('module', 'my_module');
    // Find all .tpl.php files in this module's folder recursively.
    $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
    // Iterate through all found template file objects.
    foreach ($template_file_objects as $key => $template_file_object) {
        // If the template has not already been overridden by a theme.
        if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
            // Alter the theme path and template elements.
            $theme_registry[$key]['theme path'] = $module_path;
            $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
            $theme_registry[$key]['type'] = 'module';
        }
    }
}
?>

```

# Answer
> 0 votes
It is possible, by simply editing the .info file in the folder of that theme, and edit/overwrite the relevant tpl.php files in the theme-folder, **however I wouldn't recommend overwriting a core/existing theme**. When the Drupal Core or the theme is updated, you lose your modifications, because your files are being overwritten by updating.

The other way is implementing hooks like user2754599 said.

---
Tags: theming
---


title: Registration Wizard

text:
# Question
Title: Registration Wizard
I 'm looking for help creating a registration wizard.

Currently I am using the Field Group and Multistep modules (which allows me to create some sort of wizard on the registration page).

But my problem is that the Register form (let's say "Step 1 of 4") needs to contain fields from both `user_register_form` and the `Profile2` form.

E.g.:

```
"Step 1 of 4"

First Name -> Profile2 field

Last Name  -> Profile2 field

Email      -> Account field

Job        -> Profile2 field

```

Any ideas of how I can do this?

# Answer
> 0 votes
Try using the Multi-Step Registration module instead. It allows to create multi-step (wizard) user account registration forms. Each step of the wizard can be configured to, optionally, expose one ore more Profile2 types.

I think both the fields from Profile2 and User Register can be used in this case.

---
Tags: 7, users
---


title: Drupal forum posts with images dilema

text:
# Question
Title: Drupal forum posts with images dilema
I want to use Drupal to make a forum where users can post either as text or upload images. This can be achieved with the Comment Upload module.

However if you attach an image and try to post without any text, you get an error message saying *'Comment field is required.'*.

Are there any solutions to this? Is it possible to remove the validation causing this issue?

# Answer
Seems like 'Comment Field is required' when clicking the Attach is similar (identical?) to the issue you encountered.

That issue has status *Closed (fixed)*, and also contains a patch for it.
> 0 votes

---
Tags: 6, nodes
---


# Question
Title: How to NOT change the path/uri after applying a style?
I'm working on a module. It uses an API to serve images. One of it's features is calling for a custom resolution image by GET request. So for example

myapi.com/img4324342?w=22&h=55.

I'm currently abusing the style function from the Image module.

I call hook\_preprocess\_image() and if it detects my effect (my custom style that has my custom effect) it has to return a modified path. But the path get's malformed when I apply a style. I just want to have the original URI so I can use the information inside to construct a REST call. How to prevent that the URI changes after style a.k.a. how to return the original URI as Path?

**Background:**

It's a brand portal and I'm an intern making the drupal plugin. The company I work for doesn't want the images to be served from the Drupal hosting, only provided by the API. But they ALSO want that adding a different banner for example to every article is still done the same way you normally do: by adding a image style and adding it as a field to the content type

The $vars variabele from `hook_preprocess_image()` in json looks like this:

```
{
 "path":"?itok=D1zdawxe",
 "alt":null,
 "style_name":"thumbnail",
 "width":null,
 "height":null,
 "title":null,
 "attributes":[],
 "theme_hook_original":"image",
 "theme_hook_suggestions":[]
}

```

after applying any effect.

This means that when I don't apply any effect my Path (my Uri) is `myscheme://img23423423432` and when I do apply ANY effect it get's malformed to random gibberish like `?itok=D1zdawxe`

# Answer
> 0 votes
I've found a kinda nasty solution:

```
hook_preprocess_image_style(&$variables) {
    $variables['uri'] = $variables['path'];
}

hook_preprocess_image(&$vars) {
    if(array_key_exists('uri', $vars)) {
        $vars['path'] = $vars['uri'];
    }

    if(!isset($vars['style_name'])){
        return FALSE;
    }

    $image_styles = image_styles();

    foreach ($image_styles as $image_style_key => $image_style) {
        if ($vars['style_name'] == $image_style_key) {
            foreach ($image_style['effects'] as $effect_key => $effect) {
                if ($effect['name'] == 'myEffect') {
                    $vars['path'] = generateAPIURL($vars['path'], $effect['data']); //get baseURL from path and URL parameters from data
                    break;
                 }
            }
        }
    }
    return FALSE;
}

```

---
Tags: 7, media
---


# Question
Title: Workflow assign user to handle node in given state
I am using `Workflow` module to implement moderation policy in one of my project. It is working fine. But I want is when a user changes workflow state of user, he must be able to select a given user also from given user group, who will be responsible to manage the node in that state.

So, ideally it would be drop-down of user, form where admin can select user to whom the the node be assigned.

I searched a lot, but didn't find any solution yet. Is there any way to achieve this.

-- Many thanks for your time.

# Answer
I am developing a module that address that very issue and some other things. Besides it is on sandbox yet, it is fully usable (I am using it on production).

> Workflow Hide Fields is an addon to the Workflow module.

You can clone it:

```
git clone --branch 7.x-1.x git://git.drupal.org/sandbox/fpap/2575131.git

```

And can visit the module page.
> 0 votes

---
Tags: 7, users, workflows
---


# Question
Title: How can I encrypt the login process without using SSL?
My webhost doesn't allow SSL certificates for my webhosting product since it is a shared IP server. (I would have to upgrade the product and pay a lot more money, which I don't want to at the moment) I don't really need all of the website encrypted, I only want to give the password (and username) submission on login a bit more protection. Is there a module that just does some asymmetric encryption on the password on submission, e.g. with JavaScript?

Note: I know about the possibility of Man-in-the-Middle attacks with this setup.

# Answer
So far, the only way that I've found to encrypt user login without SSL is the Encrypt Submissions Module (https://www.drupal.org/project/encrypt\_submissions)

It uses the jCryption library (http://www.jcryption.org/) to encrypt the username and password that drupal offers up in clear text otherwise. Fairly straightforward to set up. The only server requirement is bcmath php module which most servers have anyway.

I use Encrypt Submissions whenever I can't use SSL, not as a replacement. You may want to consider switching hosts if they don't allow SSL certs, they sound pretty backwards.
> 0 votes

---
Tags: users
---


title: print script on specific node id

text:
# Question
Title: print script on specific node id
I want to print out a script from facebook on a specific node page in my html.tpl.php file. What is the best way of doing this? looking for nid? I need some kind of a if statement...

thanks

# Answer
> 1 votes
a hacky solution in html.tpl.php could be like this:

```
$node = node_load(arg(1));
echo $node->nid;

```

You'll want to check for the existence of $node and such to avoid errors.

You could also create your own node template: node--123.tpl.php

You could also use the HOOK\_preprocess\_page() function to check for the node ID.

---
Tags: nodes, social-network
---


title: What is the "u=" and "i=" class in CSS?

text:
# Question
Title: What is the "u=" and "i=" class in CSS?
I am trying to modify the CSS in a Drupal 7 theme from being statically coded to one which is generated by views. The person before me, wrote the slideshow directly into the page--front.tpl.php file and this makes it next to impossible for users to change the slideshow without getting a Drupal developer involved.

In the "static" page, there are some tags which, due to my ignorance, I don't know how to deal with. For exampe:

```
<div id="yourid" class="yourclass" u="slides" ...>

```

I know what the "id" is and I know what the "class" is, but I have no idea what the "u=" references. I have also seen:

```
<div id="yourid" class="yourclass" i="icons" ...>

```

Can someone tell me the terminology associated with this tag so I can research it? Typing in `"<div u="` in Google is bringing up tons of unrelated results

# Answer
Those attributes ("u" and "i") are not standard attributes. They seems from this JOSS slider or another slider.

Examine your Drupal modules and the View your want to modify to know which slider are you using. Then check the documentation for that slider.
> 1 votes

---
Tags: 7, theming
---


title: page_cache_maximum_age wrongly set

text:
# Question
Title: page_cache_maximum_age wrongly set
In our production server, we wrongly set **page\_cache\_maximum\_age** a long value,

```
$conf['page_cache_maximum_age'] = 12960000;

```

Now viewers are complaining they are seeing old contents in there homepage.

I am able to see new contents with a force reload (CTRL + F5).

Is there any way to force the client side to refresh the pages in this stage?

We have our architecture **Drupal+Nginx+Varnish** and **CloudFlare** on top of it.

# Answer
Either you don't need, or you can't:

If this was translated to HTTP header, and browser "knows" not to ask for the page again, nothing you would try to do about it will have any effect, because browser simply won't contact your server anyway, so it will not download any remedy you might try.

If it affected only server-side systems, tuning it down and clearing caches should be enough already, and server shouldn't send "304 Not Modified" to your clients.

Hard to tell which case is it without knowing your caching setup, but I'm afraid "fix it and wait" is the only way either way.

Unless, for some reason, you can identify uncached JS file included on affected pages. This would be a bug, so I don't expect it to happen, but if, it might be a bug you could use - ask for it on Stack Overflow, then, as this is much less Drupal-related.

If your front page isn't cached that way, you can alter all affected links. It will not help people having issues with bookmarked pages, but it will direct regular users to current content.
> 1 votes

# Answer
You might want to flush the entire cache for now with

```
varnishadm "ban req.url ~ /"

```

found this at https://www.varnish-cache.org/forum/topic/696 OR

```
 set req.hash_always_miss = true;

```

What you are looking for is to `miss` as stated on https://www.varnish-software.com/book/3/VCL\_functions.html and the easiest way is to force the requested cache to not be present

simpeler explaination:
> 0 votes

---
Tags: caching
---


# Question
Title: How to use Rules to populate reference product after creating a Commerce product?
After a Commerce product is created I need to create a new product display node and reference the product in a field.

This is my first time using Rules. I can create a new product display node but I cant figure out how to populate the 'referenced product' field.

# Answer
Despite the limited information in your question, you should be able to create such rule (using the Rules module) like so:

* Use a Rules **Event** that is related to "When Commerce product is created" (something similar to "After saving content"?).
* Add a Rules **Condition** to make your `referenced product` field become available to use in a Rules **Action**. This condition can be either of those alternatives:

+ "Entity has field".
    + "Content is of type".
* Add Rules **Action** "Set a data value" for your `referenced product` field.
> 0 votes

---
Tags: 7, commerce, rules
---


title: Approach to custom advanced search box

text:
# Question
Title: Approach to custom advanced search box
I have a custom search form, made with Drupal Form API. It uses ajax, autocomplete, and some other properties defined in the built `$form`.

I use the data sent from the form to feed a `views_embed_view` call, and in the **View** I have defined some contextual filters, for each and every of the input boxes.

The problem is that **Contextual filters** do not apparently support the operator `LIKE` for several word or partial word matches, so the search is very restricted. Even putting Search field instead of Content field does not solve the problem completely.

If I use **Exposed filters** instead of Contextual filters, I don't know how to modify the input boxes to get all the functionality I already have. Maybe with `hook_form_alter`, but even so I do not know what to do with the sent data (it needs further PHP processing, this is why it was so convenient with Contextual filters).

I also found this piece of code I had already used (but forgotten), but I don't find the solution elegant (even if it works - it is taken from a different Drupal Answers question and adapted. It modifies the Contextual filter query and includes the LIKE operator):

```
function mymodule_views_query_alter(&$view, &$query) {
if( $view->name == "products_list" ){
    foreach($query->where as $key => $val) {
        $field = $val['conditions'][0]['field'];
        $operator = $val['conditions'][0]['operator'];
        $value = $val['conditions'][0]['value'];
        if(( $field == 'field_data_field_field_rf_producto.field_field_producto_value' || $field == "field_data_field_descripcion_producto.field_descripcion_producto_value") && $operator == '=') {
            $query->where[$key]['conditions'][0]['operator'] = 'LIKE';
            $query->where[$key]['conditions'][0]['value'] = '%' . $value . '%';
        } // if
    } // foreach
  } // if
} // function

```

# Answer
> 1 votes
You can programmatically change the filter configuration before executing the view:

```
$view_name    = 'my_view_name';
$display_name = 'my_display_name';
$handler_name = 'title';
$terms        = array('foo', 'bar');

$view = views_get_view($view_name);
$view->set_display($display_name);

$handler = $view->display_handler->get_handler('filter', $handler_name);
$handler->value = implode(' ', $terms);

$output = $view->preview();

```

This will work even without exposing the filter.

# Answer
> 0 votes
I would like to share my piece of code for implementing the idea proposed by user ciss, which has not been straightforward but more than a nightmare - my fault, and possible it can be solved much more easily.

First, I write, in the template, function `template_preprocess_page` :

```
$view = views_get_view($view_name);
$output = $view->preview();

```

Now, and here lies the nightmare, in order to make each Filter defined in the View not to block the list of results, I had to write the following:

```
function hook_views_pre_view  ( &$view, &$display_id, &$args) {
  if($view->name == "SEARCH_ADVANCED_VIEW"){

    $terms = array('2001');
    $terms2 = array('sport', 'shoe', 'orange');

    $view->set_display("block");

    $array_filters = $view->display_handler->get_option('filters');

    /* if I want to delete filter product_value
       and only keep filter `title` */

    unset($array_filters['field_product_value']);

    $view->display_handler->override_option('filters', $array_filters);

    $handler_name = 'title'; ;
    $handler = $view->display_handler->get_handler('filter', $handler_name);
    $handler->value = implode(' ', $terms);

  } // if
} // function

```

---
Tags: 7, forms, search, input-formats
---


# Question
Title: Overriding "/user" page with Feature (Drupal 7)
I am trying to learn about creating a reasonable workflow between a development site and a production site and I have decided to use the Features module to help accomplish this task.

Standard "/user" page allows me to click "forgot my password" or "create new account", but I want more options and I'd like to override that page with feature module. I am not sure is this a good approach, but with this feature I will have ability for users to create accounts, login to the website, and manage their account profile.

I have added dependencies and Strongarm variables, but I don't know how to make it use "/user" path.

Thanks, Michael

# Answer
> 0 votes
Features is the way to move configuration data between different environments, or at least the most typical. But in your case you need to move *functionality*, not simple configuration (as what you want to achieve can't be done just modifying configuration).

Features takes some Drupal objects as Views, permissions, roles, content types, panels and so on an put them into code that can be later imported to another Drupal instance. This is considered *configuration* because even when this kind of objects add functionality to the site you have added it *configuring* some modules.

So, if you can manage to achieve your desired functionality (I suppose using Panels and others modules) you may *export* that configuration using Features. And I say *may* because not all configuration can be exported this way (most yes).

In your case probably you'll need a custom module that menu\_alters the `/user` URL and uses a custom page callback that adds what you need. But what you need is too broad to explain in an answer here.

---
Tags: 7, users, features
---


# Question
Title: Passing the actual path in File Save Data
I have the following line in my script, but it fails to save the file in site/default/files folder. Is it possible I can replace `public://feedproducts.xml` with an actual absolute path to the files directory?

```
$file = file_save_data($sxe->asXML(),"public://feedproducts.xml",FILE_EXISTS_REPLACE);

```

This script runs from the command line, and is inside a sub-directory inside the root. It also loads Drupal Bootstrap.

# Answer
The issue was that the script was running from a subdirectory. Calling `chdir(DRUPAL_ROOT)` before `file_save_data()` fixed it.
> 2 votes

# Answer
No. Read the docs on `file_save_data()`, it needs a valid URI. otherwise it will not work.

If `file_save_data()` is returning false with the above code, you're better off investigating why. It's likely a permission or some other problem preventing file I/O on that directory.
> 1 votes

# Answer
All systems have a file stream wrapper, as far as I know, so try:

```
$uri = 'file:///absolute/path/to/file.ext';
file_save_data($sxe->asXml, $uri, FILE_EXISTS_REPLACE);

```
> 1 votes

---
Tags: feeds, files
---


# Question
Title: Adding fields, account registrations and editing profile
By default Drupal has a profile system in place that stores user name, password and email.

Profile2 extends this to allow specific roles upon account creation as well as more options for adding fields.

The problem is there are now two sections for adding fields, two tabs for editing account info, and no way to separate account editing into unique sections, or combine everything onto one edit page.

How can I have fields be on specific edit forms separated by how I feel they should be categorized.

**Example:** On user page there is an *edit* tab in user menu. when clicked there is a sub menu that has inks to specific edit forms: 1. edit profile 2. security info (password, phone number) 3. photos and media 4. Address 5. personal info 6. social networks

Why I asked the question: I sat down to add fields to the users pages, such as first name, last name and zip code and was very confuse where I should create these fields and which edit form they should live, the profile2 edit form or the core edit form.

# Answer
This is part of Profile2's interface design; different profile types (created in admin/structure/profiles) are presented as separate submenus on the user edit page.

If you want to work with the constraints of its interface, you can create profile type for each group of fields that you feel should be edited separately. If you feel like a field should be part of the main user edit page, you can add it to the core user entity (admin/config/people/accounts/fields).

As far as combining profile2 forms into the user edit form, Profile2 does allow you to embed profiles into the registration form (via its *Show on all user account registration forms.* option) but not the edit form. For that, there is the Account Profile module.

> Profile2 by default creates an additional tab for each new profile assigned to a user. Alternatively the submodule "Profile2 pages" provides a separated pages for viewing and editing profiles.
> 0 votes

---
Tags: users
---


# Question
Title: How to add and remove tabs from/to My Account page
I have created a role **Customers**. I added **UserA** to the role. When I logged in as UserA, I see **My Account** link in the Header region. After I click **My Account**, I see three tabs : Views, Edit, Checklists. How to remove Edit and Checklists tabs from the **My Account** page?

I created a page view. The path for the page view is xxx.com/payments. How can I add a new tab (Payment) next to **Views** tab on the **My Account** page? When UserA clicks the **Payment** tab, the page view xxx.com/payments displays right under all the tabs.

# Answer
For your first question answer remove the from page.tpl.php or you can alter it by hook\_menu\_alter. Use type MENU\_NORMAL\_ITEM.

For you view you need to create one hook\_menu\_alter and add type as MENU\_LOCAL\_TASK.
> 0 votes

---
Tags: views
---


# Question
Title: Creating a view of content that is filtered by the email of the current user
How can you create a view of content in a specific node type where there is an email address that will correspond with the email address of currently logged in user's email address? The content is not owned by user. This view will be used to assign relations to the user and other content with rules.

# Answer
Here is the approach to provide a relationship between **content** and **logged in user**:

1. Create a ***user*** view.
2. Add a contextual filter on **User: E-mail**.
3. Add a relationship on **User: Content authored**.

Now you can do rest of you functionality.
> 1 votes

# Answer
Since the content is not authored by the user, I needed to create a relation from the user to the content. The content has a matching email. I was able to achieve a list of content filtered by a user's email through Rules, VBO, and passing the email address as contextual argument. Then rules can apply the relation to the content.
> 0 votes

---
Tags: views, users, emails, input-formats
---


# Question
Title: I want to display the all true/false questions in same page using quiz module. Is it possible?
I have installed drupal 7 quiz module in my project.I want to display the all true/false questions in same page. Is it possible?

# Answer
> 1 votes
Try using Quiz Progress module .. It offers nice User Experience to track status of questions and navigation..

Project page says

> Quiz 6.x has the limitation of displaying only one question at a time. This makes it hard to navigate from one question to other especially when you have a skipped question in the beginning and you have your current question at the closure of quiz.
>
> The "Quiz Progress" module tries to overcome this problem, it provides a block that prints the list questions in the quiz referenced by title or number (with tooltip) depends on the widget configured in module settings, highlighting their status skipped, answered or unanswered as a link.

Here is the final output using above module which lists all questions...

If you are looking for Solution from Quiz Module itself take a look at this issue in Quiz Module.. Seems like #106 works in above issue..

# Answer
> 0 votes
Add content to "Quiz Page" content type. For example "All true/false questions" --\> Go to "Manage QUestions"--\> Add the newly created "Quiz Page" question--\>Simply drag and drop "True/False QUestions underneath the newly added question "QUiz Page"

---
Tags: 7
---


# Question
Title: How do I provide a "delete" link for comments?
For example, if I am posting a comment, how can I delete it?
How delete links should be given?

# Answer
> 3 votes
On Drupal 6, users with the permission of administer comments and create comments are able to delete comments. The code that adds the delete link for comments is contained in comment\_links().

```
  if (node_comment_mode($comment->nid) == COMMENT_NODE_READ_WRITE) {
    if (user_access('administer comments') && user_access('post comments')) {
      $links['comment_delete'] = array(
        'title' => t('delete'),
        'href' => "comment/delete/$comment->cid",
      );
      $links['comment_edit'] = array(
        'title' => t('edit'),
        'href' => "comment/edit/$comment->cid",
      );
      $links['comment_reply'] = array(
        'title' => t('reply'),
        'href' => "comment/reply/$comment->nid/$comment->cid",
      );
    }

```

Similar code is present in Drupal 7 and higher.

Third-party modules allows other users to delete comments.

* Comment Delete allows the comment authors to delete the comment they created. The module is for Drupal 6.
* User tweaks, a module I maintain, allows the comment's authors to delete their own comments; it also allows users to delete any comment, or any comment associated with nodes of specific content types. In both the cases, the user needs an additional permission, but not the permission to administer comments. The module is for Drupal 7.

# Answer
> 1 votes
I found a module Comment Delete that will help to **allow comment authors to delete there own comments**.

It is available for version 6

# Answer
> 0 votes
For allowing users to delete their own comments in D7, here are a few threads with discussion and example code:

---
Tags: comments
---


# Question
Title: Ability to create forms for each node in Drupal 7
I am creating articles in which I want to ask, on each article, that whether the it was helpful to read or not.

The user would have two option boxes:-

© Yes

© No

One of these will be selected and the form should be submitted through JQuery. It should be recorded with each node so that we would also know how many total users found this helpful too?

Any idea how would I achieve that?

I wish it could be achieved through Flags or Rating but I haven't been able to do so.

Thanks a lot

# Answer
This is pretty much the use case of the Rate module. By using a *custom widget*, you can present arbitrary label/value options for the user to select (e.g. Yes = +1 / No = -1).

The only difference is that they're presented as hyperlinks instead of radio selects. With some front-end customization, you probably could change that as well.
> 0 votes

# Answer
Shawn is correct.

However if you're absolutely *set* on using form components and you don't want to mess with the front-end as suggested, you could try using Webform AJAX to add a form to your page that is submitted via AJAX (which is what I think you meant by "submitted through jQuery"?).

You can then use jQuery to click the submit button when they've made a choice. Even hide the submit button with CSS, it should still work.
> 0 votes

---
Tags: flags, rating, entities
---


# Question
Title: Search api solr deleted terms showing up in facet
Why would taxonomy terms that I have previously deleted show up in my facet? I'm using search api solr. There is no term named "23"; it is a tid, but tid 23 is not in the database yet my facet shows 29 items as being tagged with it. I have flushed cache, run cron, rebuilt index, all multiple times, and don't know what else to do.

# Answer
Filter by that facet and check the nodes that display, they probably still reference the deleted term (see issue: Database records not deleted for Term Reference Fields after Term is Deleted)

To get rid of it, edit the nodes and remove the term reference, either manually or programatically depending on the volume. *Then* reindex your content.
> 2 votes

---
Tags: cron, search
---


# Question
Title: How to set user search and filter preference on account registration
I'm bulding a dating site, and I want users to have default search and filtering capabilities.

The field in question is gender.

I want users to be able to choose default search parameter to male or female. So when they access the view, it will only show them males or females, depending on their choice at registration and user account profile settings.

I'm pretty sure core functionality can do something like that, but I can't figure out what kind of settings to use...

I'm attaching the image to demonstrate what I am trying to acheive with an example from another website, the fields "I am a man" \>\> "I want to find a woman"

# Answer
> 0 votes
You need to use views global filter to achieve this functionality. What you set in profile2 field you will be get it globally in views too. In view you need to add only filter for that value.

Another way you can add relationship of user profile and add in contextual filer of logged in user value of interest in gender field.

---
Tags: entities, users
---


title: create module that load index.php

text:
# Question
Title: create module that load index.php
I have a php code written in `index.php` that contain a form with method post.

It also read from an external database and fill a table. To load this form I created a `.module` file with 2 functions `_menu` and `_block`, but I am not able to load the form `(index.php)` I need to load the form and to open it in the main content of the drupal page i used :

```
header("location
drupal_goto(
$external_link

```

but nothing is going right and it open in new blank page not in the main content like i want.

please it is urgent any help

# Answer
> 4 votes
**The Drupal way**

In Drupal we create similar form like this:

**Create a custom module**

* Create a file sites/all/modules/own/form\_test/**form\_test.info** with this in it:

name = form\_test description = form\_test core = 7.x package = Own
* Create a file sites/all/modules/own/form\_test/**form\_test.module**

(start it with `<?php` tag, but don't add ending ?\> tag)

**Write these functions** in your module:

```
function form_test_menu() {
  $items['formtest'] = array(
    'title' => 'Form Test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_test_form'),
    'access callback' => TRUE,
    );
  return $items;
}

```

**An explanation**

**form\_test\_menu** creates a menu item in your navigation menu so we can have a place where to show our custom form. You can think that menu address referring to a page yoursite/**formtest**.

**title**

Title of the page.

**page callback**

Calls a function drupal\_get\_form which returns a render array for drupal\_render().

**page arguments**

Here we pass our custom render array (which form\_test\_form returns) as an argument for drupal\_get\_form.

**access callback**

We define it TRUE so that everyone can access this page.

(**Rendering** means turning a structured array into HTML.)

```
function form_test_form($form,&$form_submit) {
  $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
  );
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
    );
  return $form;
}

```

**An explanation**

So we use **render arrays** to describe a form in drupal.

When you use a function to return a render array for drupal\_get\_form, there are two default parameters that are in use:

**$form** Holds the form array items we define inside the function when this function is **called again**.

**&$form\_submit** This parameter holds various data items like the **values** you pass when you submit the form.

(Ampersand **&** means that this is a **reference to a variable**, so if we change this variable in this function, changes will show in the parent function too.)

Form items are **added as arrays** to the $form variable. Hash **(#)** sign refers to an attribute of the item.

**Enable the module** in admin/modules

**Flush the caches**

Form can be seen in **yoursite/formtest**, but it doesn't do anything yet.

OR more links are :

Drupal 7 - How to Make a Simple Module with a Form and Menu Link

Ten Step-by-Step Code Samples for Learning Form API

---
Tags: redirection
---


# Question
Title: Add a jQuery hover effect to images in a View
I would like to add a jQuery hover effect to a view of thumbnail images (the content type consists of an image field). The effect that I would like to add can be seen here:

> Code: http://www.freshdesignweb.com/responsive-portfolio-gallery-with-jquery-tutorial.html Example: http://elegantthemes.com/preview/Evolution/

It consists of an overlay that appears when the user hovers on an image. I would like the overlay to have links to the image itself (so the user can comment) and to open a larger version of the image in a lightbox.

I just cannot find an easy tutorial to add this. Anyone with good suggestions? Or with some time to show me the steps to implementing such an effect?

Thanks!

# Answer
> 1 votes
I would do it with adding a custom theme to that view How to apply theme to a view drupal 7 to make the views output to match with your tutorials HTML structure and add `.js` files as recommended.

When it goes advanced you can try creating a views style plugin so that you can add this jQuery effect directly from your views page.

see

How to create a Views style plugin for Drupal?

How to properly implement hook\_views\_plugins?

# Answer
> 0 votes
Code per Views Display

> **Features**
>
> * Add custom CSS or JS code to each display.
> * Serve code either as inline or from file.
>
> **Use Cases**
>
> CPV is useful in cases where:
>
> * you want to allow views admins to theme a particular display without granting them access to theme files;
> * you want to apply CSS and JS code to a display across all themes;
> * you want to apply CSS and JS code to a display without modifying an existing theme or creating a sub-theme.

---
Tags: 7, views, media, javascript
---


title: Custom User Fields Not Displaying

text:
# Question
Title: Custom User Fields Not Displaying
I've created a couple custom fields for Users in Drupal 7 via Config \> Account Settings \> Manage Fields. Mainly a user's real name, company and a welcome message.

I'd like this info to be displayed when the user views their account page (site.com/user/username) but the fields will not display except to my admin account. The fields are set to visible in the display settings and the users are assigned the appropriate permissions to view profiles and other content.

I've tried enabling Profile2 and using it as well but the problem still persists. Any ideas what's going on here? It's driving my crazy!

# Answer
Ok, the problem was one of the custom fields. I had added an Organic Groups reference so I could relate that user to a particular group or groups at the time of registration. But for some reason this field's presence was causing the others to not render. This opens up an entirely different issue and will make me rethink how I implement this groups relationship.
> 0 votes

# Answer
There is a check box on field edit page of user account which enable "Display on user registration form.". This one might work for you.
> 4 votes

# Answer
Just go into the *admin settings(or configuration)*, *OG permissions overview* and check the permission for each custom field.

The *OG permissions overview* can also be reached by: /admin/config/group/permissions

reference: https://www.drupal.org/node/1871428
> 2 votes

---
Tags: 7, users
---


# Question
Title: Views sort criteria setup by number of fields
I am using views with exposed so visitors can search on items that are published by other users.

Content type that views is showing has 50 fields (+ 3 taxonomy fields with around 200 terms). Only 7 fields are mandatory. Rest are there to better describe the item. Rarely someone uses all fields but most are using half.

Reward for using as many fields+terms as possible per content would result in higher position in view sort criteria.

**Example:** Users A and B have 2 nodes each.

A1 = 7 fields used

A2 = 12 fields used

B1 = 8 fields used

B2 = 10 fields used

Views results: A1, B1, B10, A12

Is there a way to do this with views ?

# Answer
It should be something like this. (It is not the exact code, but it will help you.)

```
function findNodesByUser($userID) {
$result = $query
  ->entityCondition('entity_type', 'node')
  ->propertyCondition('status', 1)
  ->propertyCondition('type', $type) //Where $type is the type of node
  ->propertyCondition('uid', $userID)
  ->execute();
}

function createArray() {
    customArray = array();
    $users = entity_load('user');

    foreach ($users as $user) {
        $user_nodes = findNodesByUser($user);
        foreach($user_nodes as $user_node) {
            customArray[$user . $user_node] = count(field_get_items('node', $entity, $field_name));
        }
    }
}

```
> 0 votes

---
Tags: views
---