title: Panel Node Page File Selector Variant

text:
# Question
Title: Panel Node Page File Selector Variant
Hello im back using Panels and im hoping it will help with something that ive ran into with the new Media fields etc.

I want to create a Node Page variant that will overide node page if there is a video file linked via the Media Youtube Multimedia asset Media file selector file. If there is an image in the Media field then show a differant variant. I think its to do with File types.

Sorry if im a little out my termenology its just D7 hs so many new things to get my head around.

So a panels node page based on variants of what type of file is added to the Media field.

thanks

# Answer
Fields are usually available as selector rules, so the solution to your problem: find out in which field the content is stored and use a empty/ not empty selection rule for your variant.

variants are selected by order, so the first variant that matches is selected. You could implement two panel variants, one with selection rule for empty, one for not empty, or use only one with selection rule and order the other on underneath that one.
> 0 votes

---
Tags: panels
---


title: Post AJAX JSON with session id

text:
# Question
Title: Post AJAX JSON with session id
Using Drupal Services I am able to log in but each time I post a node it posts as anonymous. I get the session id and session name upon login but can´t pass it along with a POST no matter what i try.

I have tried including it in the json string, as a header and within the URL - without any result. I'm testing using the Chrome Postman as REST client.

What am I doing wrong?

Thank you for any help!

```
var session_id = $('#session_id').text();
$.ajax({
  type: "POST",
  url: 'http://www.website.com/active_services/node?sessid='+session_id,
  data: JSON.stringify(noden),
  headers : {
    "Authorization" : session_id,
    "sessid" : session_id,
    "sessionid" : session_id,
  },
  beforeSend: function (req){
    req.setRequestHeader("Authorization",session_id);
    req.setRequestHeader("sessid",session_id);
    req.setRequestHeader("sessionid",session_id);
    req.setRequestHeader("Content-Type", "application/json");
  },
  dataType: 'json',
  contentType: 'application/json',
  success: function(data){
    console.log(data);
 }

```

# Answer
I am using POSTMAN to test my REST calls to server.

When i try http://mysite.com/api/endpoint/users/login.json

with parametes

1. Content-Type - application/json
2. username - A valid username on site
3. password - users password

I get a json looks like this

```
{
    "sessid": "6nRaPdlYfV4mDt0cgUHfGwNmWJZNvUfKM618DYY4unc",
    "session_name": "SESS4356595e5cb4b5df8f18058cfbd8d13a",
    "user": {
        "uid": "144",

```

From that i suspect you should pass `sessid` and `session_name` to get it work.

Try it and let me know whether its working if not we find some other solution which works :)
> 1 votes

---
Tags: nodes, ajax, services, 8, sessions
---


# Question
Title: how to create template file for single page in drupal 7
i have created "about us" page in drupal 7 admin interface of basic page type. I want to apply a specific layout for this "about us" page only.

But after goggling, i found solution of applying specific theme to specific content type like

page--content\_type.tpl.php.

i dont want to apply layout for all pages in that content type, but only for this specific page "about us". If this can be done by overriding like this "page--node--nodeid.tpl.php", then where to find the nodeid for this page.

# Answer
use "page--node--nodeid.tpl.php" template. you can find the nodeid for this page when editing.

edit "about us" page, you will got url like this `http://www.example.com/node/1/edit`

digit "1" in the url is node-id.
> 8 votes

---
Tags: 7, theming
---


# Question
Title: Getting an element of a CCK field to use and modify in hook_form after_build
I have a partially working solution for using `hook_form after_build` on a CCK field. The field has various elements (it's created with a custom module but I don't want to modify that so I've created a small overrides module to do some trivial form alter stuff.) I've been at this a good part of the day and finally had some luck adding some simple text to the field so I am know I'm getting close.

In the main module, the CCK field has various elements. Once such element is:

```
$element['week_night'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Week Night'),
    '#default_value' => isset( $element['#value']['week_night'] ) ? $element['#value']['week_night'] : NULL,
    '#attributes'    => array( 'class' => 'rate-widget-rate-field' )
  );

```

I am targeting the field itself in my overrides module as such:

```
<?php
function rates_override_form_alter(&$form, $form_state, $form_id) {
  //drupal_set_message($form_id);
  //dsm($form);
  if($form_id == 'ldisilink_property_node_form'){
    $form['#after_build'][] = '_rates_override_after_build';
  }
}

function _rates_override_after_build($form, &$form_state) {
  // This works so we know we are good to this point:
  $form['field_rates']['#prefix'] = 'do stuff';
  // Now we want to change the label on week_night but it's not working.
   $week_night = $element['week_night'];
   $form['field_rates'][$week_night]['#title'] = 'My new label title';
  return $form;
}

```

What I am trying to do is alter the label for the element `week_night`. Using `dsm($form)` I've tried various combinations of:

```
   $week_night = $element['week_night'];
   $form['field_rates'][$week_night]['#title'] = 'My new label title';

```

... but it's not working yet, but I think I'm close.

# Answer
> 0 votes
You are on the right track. You want to set the **#title** attribute of the form element whose label you want to change, which can all be done at the hook\_form\_alter() time.

In order to change the label of the 'week\_night' form element, try something like this:

```
function rates_override_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'ldisilink_property_node_form') {
    $form['field_rates']['week_night']['#title'] = t('My new label');
}

```

This is assuming the 'week\_night' form element is nested within 'field\_rates' fieldset. If that is not the case, use:

```
$form['week_night']['#title'] = t('My new label');

```

instead.

---
Tags: 6, hooks, forms
---


title: View search by multiple values, how?

text:
# Question
Title: View search by multiple values, how?
Now I have built a search view and expose one parameter for user to filter search results.

The parameter is input via a textfield, i.e.:

```
 +------------------+
 | car              | [search]
 +------------------+

```

Is it possible to modify the above search view by:

* change the textfield to textarea
* such that user can input multiple values (one at each row)
* the filter will match *any* of the values entered
* and present results

i.e.:

```
 +------------------+
 | car              | [search]
 | magazine         |
 | 2012             |
 |                  |
 |                  |
 |                  |
 +------------------+

```

# Answer
If you are trying to search through a view's node title field, node body field, or some other string field specifically, you may be able to customize the filter how you would like:

1. Add filter **Node: Title** or **Node: Body**
2. Set the Operator to **Contains any word**
3. Click **Expose**
4. Click **Update**

This will display a filter to the user that can filter the view by the corresponding field values that contain any of the entered words, separated by spaces. This does not format the textfield into a textarea, but works functionally as you had asked.
> 0 votes

---
Tags: views, 6, search
---


# Question
Title: Views: adding "new" image when published date < 1 month
In a table view of nodes i want to add a tiny "New" image only when a node is published \< 1 month ago. Is there a way to achieve this without using PHP? If not, is there an easy way and what PHP should i insert? I was hoping for a little module to get the job done, but haven't found anything.

Thanx, Cas

# Answer
> 2 votes
If the list is always going to be in date order, then it can be done without PHP by using a View with an attachment. See this answer for an explanation of how to do that.

If the list is not sorted in date order, PHP may be the way to go. (Though I'd be delighted to be contradicted.) You'll need the Views PHP module installed.

* Add the `Content: Post date` to your list of fields. If you don't want it displayed set the 'Exclude from display' check box. Displayed or not, it's needed.
* Add a 'Global: PHP' field to your list of fields. In the **Value code** box, insert the following snippet:

```
$interval = time()-  $data->node_created;
$days = round($interval/(60*60*24));
return $days < 30 ? $days : 0;

```

This snippet grabs the value of the `Post date` field from the database query that the view has executed. It then works out the number of seconds difference between the post date and the current time. It converts the seconds into days. If the post is less than 30 days old it returns the number of days as a field value, otherwise it returns 0. (It could just return 0 or 1, but returning the value could be useful in some cases.)

* In the No Results Behaviour section check the boxes for 'Count the number 0 as empty', 'Hide if empty' and 'Hide rewriting if empty'. This means when the PHP returns zero, nothing will be displayed.
* In the Rewrite Results section, insert whatever output you want when the node is less than 30 days old. In the question you talk about an image, so maybe put in something such as `<img src="your image">`.

**Additional Notes**

If you want to use different date fields etc. you can work out what to put in the PHP by switching on the display of the SQL query in preview. (See the Views settings tab from the main Views page.)

If you want a bit more control over your output, you can use the **Output code** box. For example the following code will put a red 'new!' label against new fields. When doing this you don't want to also have Rewrite Results set.

```
<?php if ($value) echo '<p style="color:red">new!</p>' ?>

```

This code checks to see if the result of the earlier PHP code is TRUE (and not zero is TRUE). If it is is displays the red 'new!'

---
Tags: views
---


title: Field Slideshow module in blocks

text:
# Question
Title: Field Slideshow module in blocks
Im trying to create a slide show banner for my home page in Drupal 7. I do not have enough skill to make my own or to edit the PHP, template files or JS.

So far the easiest module I have found to work with is "field slideshow" but I can only work out how to use this in content.

Does anyone know a way to enable this for use in blocks or a way to make a custom content type move to a different place than that of the main content block?

Thanks for your help!

# Answer
All modules will need to be have some tradeoff between a simple solution, and a powerful tool. Field slideshow is a relatively simple solution, while Views slideshow is a vastly more powerful tool. Utilizing the power of Views, you have far better control of your slideshow, one example being, that you can easily create blocks.
> 1 votes

# Answer
I didn't test the Field Slideshow but to find a Slider Module, there is an interesting doc at Comparison of Rotator / Slider modules.

I tested another module so I share what I found : To have a slide show on my frontpage (D7) I used the Views Nivo Slider. With it you can create a View that will display content in a Slide Show. Then you can display the view in a block or in a Content Pane for the Panel Module.. see the Views Nivo Slider project for more details. This module is in a dev version so there is some issues :

Hope this can be usefull even if I didn't know how to configure Field SlideShow
> 0 votes

# Answer
using CCKBlocks you can get your field slide show or any other field as block, which can than be placed through block management page but you may need to hide the field from manage display to avoid duplication.

you can create a node with your field slideshow and than set that as a front page.
> 0 votes

---
Tags: entities, blocks, media, javascript
---


title: Array argument to rules action

text:
# Question
Title: Array argument to rules action
I am building a Rules action that needs to take an array argument, that I would populate using a PHP script on the action UI.

Let's say the action is called TranslateMessage, with arg1 = text, arg2 = array

How to declare arg2 so that it shows up as a text area with PHP input in the Rules UI, and send the array (that I create in the PHP area) as an argument to the action function?

# Answer
you might want to serialize that array or json decode it, than it can easily be passed as a string.
> 1 votes

---
Tags: rules
---


# Question
Title: How to format Start + End Dates without using PHP
I have a content type with a start date, and an option for an end date. When this field is displayed in a view, I would like to see

```
1 May 2012
2-3 May 2012

```

(etc...)

At the moment, I can only adjust the format to display

```
2 May 2012 - 3 May 2012

```

I've also learnt that even though an end date may not be provided, it defaults to the start date, so I can't use any rewrite rules in Views module to get around this.

Is there anyway to adjust the Date format when using a start and end date?

# Answer
You can coax *something* out of Views without PHP (see *Partial Solution* below) but not, I think, quite what you want. A module or - against your team policy Views PHP - may be required.

## Discussion

Part of why some of the usual Views workarounds won't solve this problem is the edge cases. If we knew that ranges of dates would always be within the very same month, then this could be done in Views without PHP using the approach outlined below. But that seems unlikely! You need to consider what you want to do when you get cases such as 31 May 2013 to 2 Jun 2013 or 28 Dec 2012 to 4 Jan 2013. What do you want displayed? If you want '31 May - 2 Jun 2013' and '28 Dec 2012 - 4 Jan 2013' respectively, but in non month-crossing cases '2 - 3 May 2012', then some code is going to need to be involved somewhere.

## Partial Solution

A partial solution *can* be massaged out of Views. It will avoid repeating the year but not the month. So you get, e.g. '2 May to 3 May 2012', '28 Dec to 4 Jan 2013', '31 May to 2 Jun 2013' from it. Just possibly this might be close enough for some use cases.

The strategy is to add the date field twice (excluding it from display) and apply different formats / configurations. You can then use `Global: Custom text` fields to join the results together.

1. Create two date formatters. One to give '12 Mar' when given 12th March 2012 (`j M`) and one to give '2012' when give 12th March 2012 (`Y`).
2. Add the date field (and exclude from display). Set it to show both the START and END dates using the '12 Mar' format. When both START and END are present this will yield '3 Mar to 6 Mar' etc. When only START is present, it will yield '3 Mar'. **Recommendation** use the 'Administrative title' in the 'More' section to document this, e.g. 'Date or range without year'. This helps at the final step.
3. Add the date field (and exclude from display). Set it to show just the END date. Use the '2013' format. When an END date isn't present, Views will fall back to using the start date. **Recommendation** use the 'Administrative title' in the 'More' section to document this, e.g. 'Year'. This helps at the final step.
4. Add a `Global: Custom text` field and use 'Replacement Patterns' to output the 'Date or range without year' followed by the 'Year'. (Easy if you've documented with the 'Administrative title' - trial and error if not.)

**Note:** If you want to detect the absence of an end date at step (3), Views will do this if you make use of the No Results area. It only defaults to the Start Date if the No Results area is not used. That gives some, albeit, limited scope to vary formatting depending on the presence of absence of an end date.
> 1 votes

---
Tags: views, datetime
---


# Question
Title: How does the internal entity cache work?
The internal entity cache is interfering with display modes on my site. I have a view that is displaying a node with a custom display mode, 'slideshow'. When I look at the view from a page that displays the entity in a different display mode along side the slideshow block, the node is rendered as that mode and not slideshow, but the other nodes in the block display using 'slideshow'.

hacking core, and rewriting node.module:

`node_load_multiple($nids = array(), $conditions = array(), $reset = FALSE)`

to

`node_load_multiple($nids = array(), $conditions = array(), $reset = TRUE)`

resolves the issue. Under performance, caching is on for anonymous users. This is occurring while logged in. I've tried entitycache in the past, but it is not installed. Drush cc all does nothing. I'm open to any ideas that may help.

Here is the offending part of a backtrace that I managed to pull up:

It looks like somewhere in theme.inc the wrong template is being chosen:

```
10 (Array, 4 elements) file (String, 52 characters )
/home/mysite/git/mysite/includes/them...
/home/mysite/git/mysite/includes/theme.inc line (Integer) 1185
function (String, 21 characters ) theme_render_template | (Callback)
theme_render_template();
args (Array, 2 elements)
0 (String, 70 characters ) sites/all/themes/mysite/templates/ds/ds-...
  sites/all/themes/mysite/templates/ds/ds-1col--node-post.tpl.php
1 (Array, 86 elements)

```

It only affects the node being rendered currently, which isn't a post and shouldn't be using that template when it shows up in the slideshow block. I've grepped around for theme\_hook\_suggestions but haven't found any.

**---EDIT---** I've tracked it down to this code in views:

```
 function pre_render($values) {
    $nids = array();
    foreach ($values as $row) {
      $nids[] = $row->{$this->field_alias};
    }
    $this->nodes = node_load_multiple($nids);
  }

  function render($row) {
    if (isset($this->nodes[$row->{$this->field_alias}])) {
      $node = $this->nodes[$row->{$this->field_alias}];
      $node->view = $this->view;
      $build = node_view($node, $this->options['view_mode']);

      return drupal_render($build);
    }

```

For what ever reason, node\_load\_multiple is returning the current node being viewed with the type set to 'post', instead of the correct content type. Why would there be malformed nodes in the site's internal cache?

# Answer
> 2 votes
node\_load\_multiple() is using entity\_load() and should not interfere with the rendering of your node because it only handles the loading from database, not rendering.

The node controller is the DefaultEntityController which implements a static cache, which (as of code) does not respect conditions used by loading. This might interfere. Are you using special conditions here? how does the $conditions array look like?

Are you using views to render that specific page? then it could be problem with contextual arguments and caching see: How to get Views caching working with contextual filters?

---
Tags: 7, caching, display-suite
---


title: Taxonomy list in views

text:
# Question
Title: Taxonomy list in views
```
 -Term 1
   --Term 1 Sub 1
   --Term 1 Sub 2
     -- Term 1 Sub 2 Sub 1
     -- Term 1 Sub 2 Sub 2
 -Term 2
 --------------------
 -------------

```

This is my Taxonomy structure. I need to build a taxonomy list in views.

http://mydom.com/gallery/term-1 // this will list the next level of taxonomy. http://mydom.com/gallery/term-1/term-1-sub-1 // this will list the next sub level

etc like that. Can you please suggest one good way for doing this

# Answer
Install and activate the Views Tree module.

Add a new 'Taxonomy Terms' view. (Choose the vocabulary or 'All').

Add a relationship to Taxonomy Term:Parent Term. Do NOT set this relationship as required.

Add two fields for Taxonomy Term:Term ID. The first label as Main Term ID, and exclude from display. This one does not use the relationship. The second label as Pareent Term ID and exclude from display. This one Does use the relationship.

Add any other fields you wish to include (Name, Description etc) and style as you wish.

Change the view format from Unformatted List to Tree (Adjacency model), and under settings, set the Main field to Main Term ID and the Parent field to Parent Term ID.

Create a page display, give it a path, and save the view. Go to the path and look at your taxonomy tree. (The tree styling sometimes does not display in the live preview, particularly if you use Seven as an admin theme.)
> 6 votes

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


# Question
Title: How do I edit the format of things published to the front page?
How do I change the way info is published to the front page?

For example, it gives me a title, 1 paragraph of body, date, tags and a read more button. I need to set it so that it also gives me a particular image field from a custom content type on top of the body content.

Where do I make this correction? I don't see it anywhere in views and I don't want to redesign my front-page around a different block / new view.

# Answer
> 1 votes
It also possible with Views, if you set the Style (listed in the Basic Settings section) to Fields. You can then choose whatever Fields you like to be displayed.

Like you already mention yourself, it is possible with Display Suite. If you choose to work with Display Suite, you can select a Display Suite build mode in the Style option of a View.

---
Tags: views, media, nodes
---


# Question
Title: Nodes they have reference to the nodes of current user
I use node reference and want to display with views to the user only the nodes they have reference to its nodes :

A\*\<----B

^----C

E\**\<-----D

\*: node created by the current user.

\**: node created by an other user.

The views for current user will only show : B,C.

# Answer
> 0 votes
This can be done by using a view Relationship.

* In **Relationships**, add the content field that you are using as a node reference. This should be something like: Content: Reference (field\_parent\_node).
* When editing the new relationship, make sure **Require this relationship** is checked.
* In **Fields**, Add the corresponding fields that you want in your view. When selecting node fields, like **Node: Title**, be sure to set the **Relationship** to be the name of your relationship. In my example, this would be **Reference**.
* In **Filters**, add filter **User: Current**.
* When editing this filter, set the **Relationship** to be the name of your relationship (example: **Reference**) and set the **Is the logged in user** to be **Yes**.

I tested this briefly and it worked for creating a view that only lists the node references authored by the currently logged in user.

# Answer
> 0 votes
I assume you already have the view. In it under 'Advanced' add a contextual filter on Content:Author:UID. When you configure the filter select 'Provide default value' under 'When the filter value is NOT available' and set the Type to 'User ID from currently logged in user'. This will limit the display to nodes the current user created.

EDIT:

Misunderstood. If you are trying to create a list if nodes which reference the current node (eg, view displayed as a block when the page is displayed) the method is the same. Create a view of the nodes, and a Contextual filter on the Node Reference field. The default value type should then be set to 'Content ID from URL'. This will limit the list to those nodes which refer to the current node.

---
Tags: views, nodes
---


title: Multiple forms/pages in one hook_menu()

text:
# Question
Title: Multiple forms/pages in one hook_menu()
Within `hook_menu()`, I added multiple (form/page)s.

```
function mymodule_hook(){
  $form[...]=aray(...);
  // ...
  return $form;
}

function other_hook_form(){
  $form[...] = aray(...);
  // ...
 return $form;
}

function mymodule_menu() {
  $items['section/form1'] = array(
    'title' => 'form1',
    'page callback' => 'mymodule_form',
     'access arguments' => array('arg1 arg2'),
     'type' => MENU_CALLBACK, );

  $items['section/form2'] = array(
    'title' => 'form2',
    'page callback' => 'other_hook_form',
     'access arguments' => array('arg1 arg2'),
     'type' => MENU_CALLBACK, );

  return $items;
}

```

With the first Item I don't have a problem because it calls `mymodule_hook()`, but the second one renders the markup without `<form>` tag. So no submit/validation hooks are fired.

# Answer
> 1 votes
You should use `drupal_get_form` as your page callback and pass the id of your form to that. This will ensure the form is processed by Drupal.

For reference, take a look at how the aggregator module declares its form callbacks in aggregator\_menu().

Example:

```
$items['myurl'] = array(
  'title' => 'Page title',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('my_form_id'),
  'access arguments' => array('my_permission'),
);

```

---
Tags: forms, routes
---


# Question
Title: Accessible Checkboxes Using Drupal's Form API
Im trying to get a set of checkboxes produced via Drupal's form api to pass the WCAG AA accessibility standards, the problem i am facing is with regard to labels and for attributes.

For example i am returning the following form definition via a hook\_block\_view(), i cant use drupal\_get\_form as normal as i dont want a form element wrapping the output which means i lose some of the processing that drupal\_get\_form does which is why i have to add in form\_process\_checkboxes and am missing some other functionality that gives the individual checkboxes their ID's(which is then used as the for attribute)

```
$form['tests_taken'] = array(
  '#type' => 'checkboxes',
  '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
  '#title' => t('What standardized tests did you take?'),
   '#attributes' => array(
     'name' => 'example-checkboxes[]'
   )
);

$form['tests_taken'] = form_process_checkboxes($form['tests_taken']);

dsm($form);

return $form;

```

This produces the following markup.

```
<div class="form-checkboxes"><div class="form-item form-type-checkbox">
    <input name="example-checkboxes[]" type="checkbox" value="SAT" class="form-checkbox">
<label class="option">SAT </label>
</div>
<div class="form-item form-type-checkbox">
    <input name="example-checkboxes[]" type="checkbox" value="ACT" class="form-checkbox">
<label class="option">ACT </label>
</div>
</div>

```

I need the markup to either have labels with 'for' attributes pointing to the input elements or wrap the input elements with the label tag.

Heres thebest ive managed to come up with so far which doenst seem very satisfying

```
$form['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    '#attributes' => array(
      'name' => 'example-checkboxes[]'
    )
  );

  $form['tests_taken'] = form_process_checkboxes($form['tests_taken']);

  foreach (element_children($form['tests_taken']) as $key) {
       $form['tests_taken'][$key]['#id'] = drupal_html_id('edit-' . $form['tests_taken'][$key]['#attributes']['name'] . '_' . $key);

  }

  dsm($form);
  return $form;

```

Which now produces this markup

```
<div class="form-checkboxes"><div class="form-item form-type-checkbox">
<input name="example-checkboxes[]" type="checkbox" id="edit-example-checkboxes-sat" value="SAT" class="form-checkbox">
<label class="option" for="edit-example-checkboxes-sat">SAT </label>
</div>
<div class="form-item form-type-checkbox">
<input name="example-checkboxes[]" type="checkbox" id="edit-example-checkboxes-act" value="ACT" class="form-checkbox">
<label class="option" for="edit-example-checkboxes-act">ACT </label>
</div>
</div>

```

Anyone know of a cleaner way of doing this?

# Answer
Try changing your code to the following, no need for the call to form\_process\_checkboxes.

```
function my_module_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'myform':
    $block['content'] = drupal_get_form('mymodule_form');
    break;
  }
  return $block;
}

function mymodule_form() {

  $form = array();
  $form['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    '#attributes' => array(
      'name' => 'example-checkboxes[]'
    )
  );

  dsm($form);

  return $form;

```

}
> 1 votes

# Answer
I believe this is documented in Drupal's Form API Reference.

> Format a set of checkboxes. #options is an associative array, where the key is the #return\_value of the checkbox and the value is displayed.

You should be able to set the labels corresponding to each checkbox in the **#options** array. The array can be of the format:

```
array(
  'submitted_value1' => t('Label 1'),
  'submitted_value2' => t('Label 2'),
);

```
> 0 votes

# Answer
You could use `hook_theme_registry_alter` to override the theme function `theme_form_element_label`:

```
function mymodule_theme_registry_alter(&$theme_registry) {

    $theme_registry['form_element_label']['theme path'] = drupal_get_path('module', 'mymodule');
    $theme_registry['form_element_label']['function'] = 'mymodule_form_element_label';

}

```

Then just copy the implementation of `theme_form_element_label` from `/include/form.inc` and add a `for` element to the attributes:

```
function mymodule_form_element_label($variables) {

    $element = $variables['element'];
    // This is also used in the installer, pre-database setup.
    $t = get_t();

    // If title and required marker are both empty, output no label.
    if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
        return '';
    }

    // If the element is required, a required marker is appended to the label.
    $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

    $title = filter_xss_admin($element['#title']);

    $attributes = array();
    // ADD A FOR ATTRIBUTE TO THE LABEL AND SET IT TO THE ELEMENT ID
    $attributes['for'] = $element['#id'];
    // Style the label as class option to display inline with the element.
    if ($element['#title_display'] == 'after') {
        $attributes['class'] = 'option';
    }
    // Show label only to screen readers to avoid disruption in visual flows.
    elseif ($element['#title_display'] == 'invisible') {
        $attributes['class'] = 'element-invisible';
    }

    if (!empty($element['#id'])) {
        $attributes['for'] = $element['#id'];
    }

    // The leading whitespace helps visually separate fields from inline labels.
    return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";

}

```

This would add a `for` attribute to EVERY form element that has a label. If you only wanted to add it to checkboxes then you could add a check to the value of `$element['#type']` e.g:

```
if($element['#type'] == 'checkboxes') {
    $attributes['for'] = $element['#id'];
}

```
> 0 votes

---
Tags: forms
---


# Question
Title: Content creation screen: Add another field conditionally
I'm trying to figure out how to do the following in D7: I have a list field in a custom content type. The list contains 8 items. When creating content of this content type, the user can only select one item from this list. **But** there are two items from this list that I would like to have their own sub-lists. How would I have Drupal conditionally show another list if one of these items were selected? (This is all happening on the content creation screen).

**Update** This is not a duplicate of the question you have referenced because this is regarding Drupal 7 content creation. The "Conditional Fields" module was built for Drupal 6 and is not fit for production, as per the module page, in Drupal 7 pages. I am looking for a stable, maintainable solution for a production website.

# Answer
You may want to take a look at the Hierarchical Select module. It provides this kind of functionality for vocabularies.
> 2 votes

---
Tags: 7, entities
---


title: How to rewrite image url in nodes?

text:
# Question
Title: How to rewrite image url in nodes?
I need to rewrite all image urls inside certain node types into custom-defined urls. For example, this image:

```
<img src="/sites/default/files/u22/pretty.jpg" width="678" height="1024" alt="pretty.jpg" />

```

need to be rewritten to:

```
<img src="http://files.mysite.com/sites/default/files/u22/pretty.jpg" width="678" height="1024" alt="pretty.jpg" />

```

And I need to do that for all of the user-generated images. Obviously, the goal is to be able to off-load all images to a secondary file server. How can I do that?

Thanks

# Answer
> 3 votes
Take a look at the cdn module. It provides mapping methods for that kind of use.

# Answer
> 3 votes
ok if you're looking at drupal 6 look into custom\_url\_rewrite\_outbound(). For D7, you can use hook\_url\_outbound\_alter().

Some example code I have sitting around in a module that takes media resources of a Drupal site and points the generated urls to another server to serve media content, we used Nginx. Keep in mind that if you're just sending back to same server on another port .... you're just feeding yourself more traffic -- which isn't as helpful as a true CDN.

```
 /*
 *
 * A mechanism in Drupal to rewrite outbound urls to point to another domain.
 * This can be used to serve static content from a dedicated server, aka a CDN.
 *
 * Taken 100% from the following url. I am not smart enough to pull off this
 * magic :).
 *
 * http://drupal4hu.com/node/260
 *
 * In the below code $conf['dew_cdn_domain'] is a custom value in
 * settings.php that points to like "http://yourotherserver.com" to serve
 * media files.
 */

/**
 * Implementation of hook_file_url_alter()
 *
 * This inspects and transforms file urls to our remote CDN host.
 */
function dew_cdn_file_url_alter(&$uri) {
  global $conf;
  static $drupal_static_fast;
  // A drupal_static_reset() would clear this and then we need to rerun variable_get.
  if (!isset($drupal_static_fast['dew_cdn_domain'])) {
    $drupal_static_fast['dew_cdn_domain'] = &drupal_static(__FUNCTION__);
    $drupal_static_fast['dew_cdn_domain'] = $conf['dew_cdn_domain'];
  }
  $cdn_domain = &$drupal_static_fast['dew_cdn_domain'];
  if ($cdn_domain && strpos($uri, ':') === FALSE) {
    $uri = $cdn_domain . $uri;
  }
}

/**
 * Implementation of hook_stream_wrappers_alter()
 */
function dew_cdn_stream_wrappers_alter(&$wrappers) {
  $wrappers['public']['class'] = 'DrupalCDNPublicStreamWrapper';
}

/**
 * Any files that would go the public stream public:// get rewritten to another
 * base domain.
 */
class DrupalCDNPublicStreamWrapper extends DrupalPublicStreamWrapper {
  function getExternalUrl() {
    global $conf;
    $path = str_replace('\\', '/', $this->getTarget());
    return $conf['dew_cdn_domain'] . self::getDirectoryPath() . '/' . drupal_encode_path($path);
  }
}

```

---
Tags: uri
---


title: Media selector returns value ZERO

text:
# Question
Title: Media selector returns value ZERO
I have a custom form for with media selector from media module. The form field is as below.

```
$form['image'] = array(
      '#title' => t('Image'),
      '#type' => 'media',
      '#description' => t('The uploaded image will be displayed on the page unless it is marked as "removed".'),
      '#default_value' => array('fid' => $current_image),
      '#media_options' => array(
        'global' => array(
          'types' => array(
            'image' => 'image',
          ),
          'enabledPlugins' => array(
            'upload' => 'upload',
            'media_default--media_browser_1' => 'media_default--media_browser_1',
          ),
          'schemes' => array(
            'public' => 'public',
          ),
          'file_directory' => 'subpage_banner',
          'file_extensions' => 'png gif jpg jpeg',
          'max_filesize' => '1 MB',
          'uri_scheme' => 'public',
        ),
      ),
  );

```

When I select an image and post the form, I get the field value as an empty array. below is the print shot of my $form\_state variable.

```
Array
(
    [identity] => 9
    [path] => contact
    [image] => Array
        (
            [fid] => 0
        )

    [fid] => 0
    [language] => en
    [removed] => 0
    [submit] => Save
    [form_build_id] => form-zFkFCgBCHtesrAYOQrQXC3Ug_sMBg68dwgWwRE-Y2Ls
    [form_token] => i_aIpfgcwSz-7d_H0U48C5SUOkWlVAkBTz1M8yokXtg
    [form_id] => sitegeneral_settings_banner_sub_update_form
    [op] => Save
)

```

How do I get the selected image's fid?

# Answer
Added the following code

```
'#tree' => TRUE,

```

working charm!!

added after:

```
'#title' => t('Image'),
'#type' => 'media',
'#description' => t('...'),

```
> 1 votes

---
Tags: forms, media
---


title: How to add an error notice with jquery?

text:
# Question
Title: How to add an error notice with jquery?
Been trying to add a custom error notice with jquery, but so far the div looks funky

```
jQuery('h1').prepend('<div class=\"error\">Start</div>');

```

Any tips how to get this to work? As I understand Drupal uses the error div.

# Answer
Drupal uses `messages` as the 'base' class for messages so this should work:

```
jQuery('h1').prepend('<div class="messages error">Start</div>');

```

Note that you shouldn't escape double quotes inside a string unless the string is actually wrapped in double quotes.
> 1 votes

---
Tags: javascript, status-messages
---


title: How to link Profile2 fields in Views?

text:
# Question
Title: How to link Profile2 fields in Views?
Using Views in Drupal 7, I have listed certain fields of profiles (eg. Name, Job) and then link each field to the relevant profile. Now I am wondering how to link the fields to the relevant profile. I appreciate your hints.

# Answer
I assume you add Views for User listing:

1. add "User: uid" field;
2. exclude from showing;
3. move to the top of field list (rearrange);
4. Click on field, that you want to link with user profile.
5. Expand: Rewrite results
6. Check: Output this field as a link R
7. In the bottom, find "Replacement patterns", user uid pattertn: \[uid\]
8. Place it on "Link path" next text: user/\[uid\]
9. Check that link appear.
> 3 votes

# Answer
1. Create a content view page the path must be user/%
2. Go to Contextual filters and add Content: Author uid
3. Configure Contextual filters and add Content: Author uid by doing the following
4. In the Content: Author uid under (When the filter value is NOT in the URL) select Show "Page not found"
5. In the Content: Author uid under (When the filter value IS in the URL or a default is provided) select Override title and in the field put user/%1
6. In the Content: Author uid under (When the filter value IS in the URL or a default is provided) select (Specify validation criteria) and choose for Validator the option user
7. In the Content: Author uid under (When the filter value IS in the URL or a default is provided) go to (Type of user filter value to allow) and select only allow numeric UIDs
8. In the Content: Author uid under (When the filter value IS in the URL or a default is provided) go to (Action to take if filter value does not validate) and select Show "Page not found" and click apply.

Now go to relationships and add Content: Author (author) User: Profile make sure Content: Author is above (author) User: Profile otherwise you may get errors. Now that you have add the relationships you should be able to access all the user and profile fields including any other fields in views. This will allow you to customize that crappy default main profile page.
> 0 votes

---
Tags: views, users
---


# Question
Title: Make flippy pager appear in full content view
I love the simplicity of the Flippy pager, and it works exactly as advertised until I display the node it's supposed to appear on in a view. Basically, I want the latest node of a specific content type to appear as the front page. Okay, I can use a view with the full content style and number of results set to 1. That works, but the pager (generated by Flippy) is missing. This is a webcomic site, so it is critical that the pager appear. Is there any way to make the pager appear exactly as it does if I navigate to the actual node?

# Answer
I found an answer to this. I am also going to post the answer to drupal.org. I modified flippy.module using the following changes:

```
--- flippy.module.orig  2013-03-10 13:14:53.000000000 -0500
+++ flippy.module       2013-03-10 13:19:09.000000000 -0500
@@ -233,6 +233,8 @@
   // for getting node type
   if ($node = menu_get_object()) {
     $vars['node'] = $node;
+  } else {
+    $vars['node'] = node_load($vars['list']['current']['nid']);
   }

   $label_type = variable_get('flippy_label_type_' . $vars['node']->type, NULL);
@@ -315,7 +317,8 @@
   if (!is_object($node)) {
     return FALSE;
   }
-  return node_is_page($node) && variable_get('flippy_'. $node->type, NULL);
+  //return node_is_page($node) && variable_get('flippy_'. $node->type, NULL);
+  return variable_get('flippy_'. $node->type, NULL);
  }

 /**

```

Notes: This should be an option selectable in the module UI. Probably not everyone wants the pager in a view. Also, I'm not sure why `menu_get_object()` is really needed at all, since the current node is already available in `$vars['list']['current']['nid']`.
> 1 votes

---
Tags: 7, paging
---


title: Field in View linked to another View

text:
# Question
Title: Field in View linked to another View
I created View "Places" consisting of 3 fields (image,date and title) filtered by content type.

This is to create a page showing thumbnails.

I created another view "Gallery" showing images and I need this View to be linked to the corresponding thumbnail image.

Any idea how i can achieve this? Thanks to everyone...

# Answer
**Solution 1**

You could try making the **path** for each display some kind of hierarchy and using **Menu tab** as the menu Page settings in order to display both views next to each other in the primary tabs of a page.

**Example paths**

```
mypath/view1 // Display 1
mypath/view2 // Display 2

```

**Solution 2**

Add a header or footer to the view in **Basic settings** and include the link to the other view.

More info on Drupal Menu system.
> 0 votes

# Answer
If the question is how can I make it so that clicking on any of the images in the *Places* View take the user to the *Gallery* view, then this is just a matter of applying Rewrite Results in the configuration for the image view. Check the 'Output this field as a link' box and then put in the fixed path to the gallery. If you want to pass a parameter to the gallery then this is possible by using the replacement patterns available in Rewrite Results.

If this answer is way off base, you might need to fill out your question a little.
> 0 votes

---
Tags: views
---


title: Create Context Based on Field File Type

text:
# Question
Title: Create Context Based on Field File Type
I want a means of triggering a different Context depending on the type of file used in a field on a given content type.

I have been struggling with trying to achieve this for a few days/weeks now after recently moving from D6 to D7. After trying it with Panels I've moved onto Context Module and Context Entity Field. I'm hoping I can finally get this sorted so all help appreciated thanks.

I don't know if it's my lack of D7 experience that's causing this. Basically, I'm working with one content type. It has a Multimedia asset field. I allow uploading, adding images and youtube media via url in this field. I was wanting to create a new page context if the field contains youtube video field. If it has an image then let's do another context etc. Only one of these filetypes are allowed per node.

Context Entity Field seems to only work if the Multimedia asset field has something, or not. I was wanting to use context on file type.

Is this possible or am I really missing some simple D7 point that wasn't there in D6?

Thanks

Note that I am using Media Module for this Multimedia asset field.

# Answer
> 1 votes
Can I suggest a slightly different strategy? If you have the Rules modules installed - or are willing to install it - then can use a Rules condition to apply the specific test you want. If it passes that test, you can get Rules to set a field on your node that Context *can* respond to.

So, for example, you could have a Term reference on your content type that has three vocabulary items 'YouTube', 'Image', 'Empty'. Rules can set this field whenever the node is saved. And Context is able to respond differently depending on the Taxonomy Term that is present.

A downside is the user gets to see the Term reference field when entering data, but since it's changed to the right value on save anyway, this may not be a big deal. You can tell the user to ignore this on the form and hide it away, e.g. in a closed fieldset. Or if you are a Display Suite user, you can easily hide using configuration.

I've tested whether Rules can pick up the media type and can confirm it does so quite cheerfully. To start the process, add a new rule and choose **React on event** with the type 'Before saving content'. Supposing you have a field on your content type with the machine name `field_media`, then you will need to use a **Data comparison** condition that checked `[node:field-media:file:mime]` to see if it is equal to `video/youtube` or `image\png` etc. You may need to do a bit of fishing to get out all the relevant mime types. You'll then need to create an appropriate action when the condition is true. You'll probably want several rules bundled together in a Rule set.

A single condition will look a bit like this:

If you've not used Rules before, it can be a bit fiddly to set up the first couple of times, but well worth it. Knowing that it can detect the condition that is of interest to you, means that this is a solution that you can make work.

---
Tags: 7
---


# Question
Title: How to show a field in views only when a checkbox is ticked?
I want the user to be able to choose whether to show a description or not for each node in the view. Adding the filter only works on the entire object, I just want to show/hide one field. How can I achieve this?

# Answer
> 12 votes
You can do this with Views out of the box. No need for Views PHP here.

1. Add your boolean field in Views. (This assumes the default boolean set up, i.e. 0 for not checked and 1 for checked.)
2. Use the **Key** formatter - this isn't obvious, but I couldn't get it to work without this.
3. Select **REWRITE RESULTS** and put the description you want in there. This can include tokens so you can grab material from other fields in the node if that's what you need.
4. On **NO RESULTS BEHAVIOR** check all the boxes (Count the number 0 as empty, Hide if empty, Hide rewriting if empty)

# Answer
> 0 votes
You should be able to accomplish this with th Views PHP module.

Set up your view with the checkbox and description fields included but not visible. Then include a Global:PHP field, and under the field configuration put something like:

```
<?php
echo ($row->checkbox) ? $row->description : '';
?>

```

in the Display box.

---
Tags: entities, views
---


# Question
Title: How to make multiple fields with taxonomy terms?
Like so: select-taxonomy-term - price - raiting

Like this picture:

# Answer
> 0 votes
Try field\_collection. Add one to your form, allowing multiple responses for the field. Then add term reference, price, and rating fields to the field collection.

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


title: Verification mail goes to Spam Folder

text:
# Question
Title: Verification mail goes to Spam Folder
If the user register, the confirmation mail goes to spam folder. After doing some R&D, I enabled "Use two e-mail fields on registration form \> Set password" and tested; it goes to inbox from the web server. But as i badly need to show the demo to my supervisor from my local server instead of live, using "Acquia Dev Desktop", it goes to the spam folder. How can I prevent the message from going to the spam filter?

# Answer
You should use the SMTP Authentication Support module: http://drupal.org/project/smtp for sending email messages. You can go there: https://stackoverflow.com/questions/8939238/gmail-smtp-configuration-for-drupal-7 to see how they can use the SMTP Authentication Support module with Google Account.
> 4 votes

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


# Question
Title: How to make base path available in views 3 Drupal 7?
Without use of Views PHP module, I need to use `base_path` for a link. Although using views\_php module, we can add it inside php code but is there any way without using this module OR we'll have to write code to create something like handler. Currently available fields in my module are following:

```
 Content: Add comment link
Display the standard add comment link used on regular nodes, which will only display if the viewing user has access to add a comment.
 Content: All taxonomy terms
Display all taxonomy terms associated with a node from specified vocabularies.
 Content: Author uid
The user authoring the content. If you need more fields than the uid add the content: author relationship
 Content: Body
Appears in: node:page, node:article, node:event_calendar.
 Content: Comment count
The number of comments a node has.
 Content: Comment status
Whether comments are enabled or disabled on the node.
 Content: Delete link
Provide a simple link to delete the content.
 Content: Edit link
Provide a simple link to edit the content.
 Content: Event Date
Appears in: node:event_calendar.
 Content: Event Status
Appears in: node:event_calendar.
 Content: Has new content
Show a marker if the content is new or updated.
 Content: Image
Appears in: node:article.
 Content: Last comment author
The name of the author of the last posted comment.
 Content: Last comment time
Date and time of when the last comment was posted.
 Content: Last comment uid
The User ID of the author of the last comment of a node.
 Content: Link
Provide a simple link to the content.
 Content: New comments
The number of new comments on the node.
 Content: Nid
The node ID.
 Content: Path
The aliased path to this content.
 Content: Post date
The date the content was posted.
 Content: Promoted to front page
Whether or not the content is promoted to the front page.
 Content: Published
Whether or not the content is published.
 Content: Sticky
Whether or not the content is sticky.
 Content: Title
The content title.
 Content: Type
The content type (for example, "blog entry", "forum post", "story", etc).
 Content: Updated date
The date the content was last updated.
 Content: Updated/commented date
The most recent of last comment posted or node updated time.
 Content revision: Delete link
Provide a simple link to delete the content revision.
 Content revision: Link
Provide a simple link to the revision.
 Content revision: Log message
The log message entered when the revision was created.
 Content revision: Revert link
Provide a simple link to revert to the revision.
 Content revision: Title
The content title.
 Content revision: Updated date
The date the node was last updated.
 Content revision: Vid
The revision ID of the content revision.
 File Usage: Entity ID
The ID of the entity that is related to the file.
 File Usage: Entity type
The type of entity that is related to the file.
 File Usage: Module
The module managing this file relationship.
 File Usage: Use count
The number of times the file is used by this entity.
 FullCalendar: Google Calendar
Display events from a Google Calendar.
 Global: Contextual Links
Display fields in a contextual links menu.
 Global: Custom text
Provide custom text or link.
 Global: Math expression
Evaluates a mathematical expression and displays it.
 Global: View result counter
Displays the actual position of the view result
 Scheduler: Publish countdown
Time until the article will be automatically published
 Scheduler: Publish on
Date/time on which the article will be automatically published
 Scheduler: Unpublish countdown
Time until the article will be automatically unpublished
 Scheduler: Unpublish on
Date/time on which the article will be automatically unpublished
 Search: Score
The score of the search item. This will not be used if the search filter is not also present.

```

# Answer
> 1 votes
There is something in the view core. If youre planning to output some field with base path, follow the steps to get an absolute path.

1. Click on the Field
2. Scroll down to **REWRITE RESULTS**
3. Check **Output this field as a link** checkbox
4. Check **Use absolute path** checkbox

*If you're looking this for just a link Views PHP is a good choice.*

If youre not happy with this method take a look at How to create a custom Views handler

---
Tags: views
---


# Question
Title: how do I load a single page in a sub theme?
I am creating a page in a Drupal website of mine so that I can use it for a custom iframe in a Facebook app. The reason for this is that Facebook uses 520 instead of 960, and I was wondering if there is a way to create a separate sub theme that would be used for a single page on my Drupal site.

# Answer
Take a look at the ThemeKey module. From the project page:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.
> 1 votes

# Answer
Why an entire new theme? You can have body classes or page templates based on node id or content type. I would use the nid to have a different page template with different markup or you can have something like:

```
.node-56 #container{width:520px}

```

or

```
.node-type #container{width:520px}

```

Look at: http://drupal.org/node/1089656 for template suggestions
> 1 votes

# Answer
There is a global variable $custom\_theme. Set it in a module or template.php:

```
function masqtheme_init() {
  // url is facebook url, or referrer ...
  // if (strpos($_GET['q'], 'facebook') !== 0)
   global $custom_theme;
   $custom_theme = 'mycouncil';
  }
}

```

drupal api theme

This works in drupal-6 and drupal-7. In drupal-7 if playing with global variables has bad side-effects or feels dirty use:

```
hook_custom_theme()

```

instead. This returns the name of the theme for a specific page call. Mobile sites without mobileswitch are another case where we have used this.

Printing facebook canvas is a similar problem to displaying in a modal or print version of the site. The same result can be achieved by using a specific template e.g. page--facebook--news.tpl.php. Implement hook\_theme() and hook\_node\_view(). You copy the existing page.tpl.php and remove the 'furniture' that you don't want.
> 0 votes

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


# Question
Title: How do I programmatically close a simple_dialog window
I'm in D7

I open a simple dialog window with the simple dialog module, and i want to close the dialog programmatically.

I've tried this

```
// not working !
jQuery('#simple-dialog-container').dialog('close');

```

and this

```
jQuery(document).find('div.ui-dialog').remove();
jQuery(document).find('div.ui-widget-overlay').remove();
//This seems to work because the window disappears, but I can not open it again.

```

The X icon on the top-right do this proprely, but i can't catch the action

Thank you for help

# Answer
> 1 votes
try this code using jquery,

```
jQuery('#simple-dialog-container').trigger('click');

```

change id/class to anchor.

# Answer
> 0 votes
Thanks monymirza, it works !

```
jQuery('.ui-icon-closethick').trigger('click');
//or
//jQuery('.ui-icon-closethick').click();

```

---
Tags: 7, javascript
---


# Question
Title: How to show fields of referenced entity when referencing entity is being loaded?
I have 2 content types, the first one has an Entity reference fields that references nodes of the second type.

I want to build a view (block) that shows some fields of the second (referenced) node when the visitor loads the node id of the first (referencing) entity.

For some reason I think this may be done really straight forward, but I'm not getting it to work.

A similar question was self-responded for the user who made it, but I dont seem to understand the screenshot he posted. How to use Entity Reference and Views

Another question seems to be answered but It looks to me like it lacks some information, as following that 3 points I cant get my block-view to work. Puilling Information From Referenced Entities to Display/Use In A Custom Content Type?

Any ideas?

# Answer
> 0 votes
Even though the answer by @serpiente just works, that just wasnt the approach I wanted to take: I didnt want to get into theming to solve this.

Finally, I solved the issue using an existing EVA field and changing the query of the view totally (querying content of the referencing type and showing the EVA field in the block, which renders the referenced entity in the desired form, currently resume form).

# Answer
> 2 votes
Depending on where you want to create the block/ show the information the way to retrieve the data from the referencing node may vary. Here's a simple example for rendering from within a `node.tpl.php`:

```
$referenced_node=node_load($node->reference_field['und'][0]['target_id']);
print drupal_render(field_view_field('node', $referenced_node, 'field_something', 'displayname'));

```

This solution makes use of standard Drupal rendering methods/ display suite rendering for your referenced node. Change `displayname` to the proper display you want to use for rendering, you might want to add a custom one with different settings.

---
Tags: views, entities
---


title: Drupal7 Delete Page

text:
# Question
Title: Drupal7 Delete Page
In Drupal on all pages there is a tab to view or edit node. Is there a module or configuration option through which we can add delete option there.

# Answer
I don't know of a module that does that (it's probably too minor an action to warrant its own stand alone module), but you can add the following lines to an existing custom module or create a new one:

```
function MYMODULE_menu_alter(&$items) {
  $items['node/%node/delete']['context'] = MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE;
}

```

That will hoist the delete link out of the inline actions and make it available as a tab on node pages for users with the appropriate permissions.
> 3 votes

---
Tags: 7, nodes, forms
---


title: Weather information

text:
# Question
Title: Weather information
I have different cities pages on my website need to display there weather conditions. For example if some one goes to Capetown page its weather can be shown in the block. Please suggest if there is some website through which we can import feeds or any module.

# Answer
Paste the below code inside the block . i suggest to take the Capetown name or its latitude and longitude from google code and pass it to the $weather\_poin variable in code.

```
<?php

        $weather_poin = 'Your city name or cordinates from google (latitude and longitude)';

    $doc = new DOMDocument();
    $doc->load('http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query='.$weather_poin);
    /*for */
    $display_lacations = $doc->getElementsByTagName( "display_location" );
    foreach( $display_lacations as $display_lacation )
    {
    $full_adds = $display_lacation->getElementsByTagName( "full" );
    $full_add = $full_adds->item(0)->nodeValue;

    $con_coded = $display_lacation->getElementsByTagName( "country_iso3166" );
    $con_code = $con_coded->item(0)->nodeValue;

    $latituded = $display_lacation->getElementsByTagName( "latitude" );
    $latitude = $latituded->item(0)->nodeValue;

    $longituded = $display_lacation->getElementsByTagName( "longitude" );
    $longitude = $longituded->item(0)->nodeValue;

    $elevations = $display_lacation->getElementsByTagName( "elevation" );
    $elevation = $elevations->item(0)->nodeValue;

    $displ_1 = "<b>Location</b> -- <b>$full_add $con_code $state_na </b><br></br>";
    }

    $observation_times = $doc->getElementsByTagName( "observation_time" );
    $observation_time = $observation_times->item(0)->nodeValue;

    $observation_time_rfc822s = $doc->getElementsByTagName( "observation_time_rfc822" );
    $observation_time_rfc822 = $observation_time_rfc822s->item(0)->nodeValue;

    $local_times = $doc->getElementsByTagName( "local_time" );
    $local_time = $local_times->item(0)->nodeValue;

    $weathers = $doc->getElementsByTagName( "weather" );
    $weather = $weathers->item(0)->nodeValue;

    $temperature_strings = $doc->getElementsByTagName( "temperature_string" );
    $temperature_string = $temperature_strings->item(0)->nodeValue;

    $Fahrenheits = $doc->getElementsByTagName( "temp_f" );
    $Fahrenheit = $Fahrenheits->item(0)->nodeValue;

    $Celsiuss = $doc->getElementsByTagName( "temp_c" );
    $Celsius = $Celsiuss->item(0)->nodeValue;

    $relative_humiditys = $doc->getElementsByTagName( "relative_humidity" );
    $relative_humidity = $relative_humiditys->item(0)->nodeValue;

    $wind_strings = $doc->getElementsByTagName( "wind_string" );
    $wind_string = $wind_strings->item(0)->nodeValue;

    $wind_dirs = $doc->getElementsByTagName( "wind_dir" );
    $wind_dir = $wind_dirs->item(0)->nodeValue;

    //$displ_2 = '<b>Fahrenheit - </b> $Fahrenheit.°F <br></br><b>Celsius</b> - </b> $Celsius.°C <br></br><b>Relative humidity</b> -</b> $relative_humidity<br></br><b>Wind string</b> -</b> $wind_string <br></br><b>Wind Direction</b> -</b> $wind_dir<br>';
    $displ_2 = "<b>Fahrenheit - </b> ".$Fahrenheit.".°F <br></br><b>Celsius</b> - </b> ".$Celsius.".°C <br></br><b>Relative humidity</b> -</b>".$relative_humidity."<br></br><b>Wind string</b> -</b> ".$wind_string." <br></br><b>Wind Direction</b> -</b> ".$wind_dir."<br>";

    $iconss = $doc->getElementsByTagName( "icons" );
    foreach( $iconss as $iconst )
    {
    $icon_sets = $iconst->getElementsByTagName( "icon_set" );
    foreach( $icon_sets as $icon_setr )
    {
    $icon_urls = $icon_setr->getElementsByTagName( "icon_url" );
    $icon_url = $icon_urls->item(0)->nodeValue;
    }
    }
    $displ_3 = $icon_url;
    $WeaThValue.= "<br>";
    $imgURL = $displ_3;
    $result.= "<br>";
    $WeaThValue.= $displ_1;
    $WeaThValue.= $displ_2;
    print '<img src="'.$imgURL.'" border="0">'."".$WeaThValue;
    //print $WeaThValue;

```

?\>
> 1 votes

# Answer
I guess Google must be down where you are (obviously you would have searched at *least* for "Drupal Weather" before you posted this question, which is the search term I used), so in the meantime...

Weather module

> This module uses METAR (METeorological Aerodrome Report) data to display current weather conditions from anywhere in the world.
> 1 votes

---
Tags: 7, services
---


title: How to get first submenu item path?

text:
# Question
Title: How to get first submenu item path?
I need to create a link to first submenu item from specific menu. The link will be placed in custom block.

To be more precise, I have a menu with following structure:

```
parent-menu
 item-1
 item-2
 item-3
 ..

```

I need that after clicking "parent-menu" user would end up in item-1 page. Also, there will be several links in some blocks, linking to "parent-menu" - they need to open 'item-1' item too.

My current approach is to create 'parent-menu' page template override which finds top child item from 'parent-menu'. That page will be linked from content and main menu. Problem is that I need a way to find first menu sub item from code.

UPDATE:

Ended up on using query:

```
$link_path = db_select('menu_links', 'n')
->fields('n', array('link_path'))
->condition('n.plid', '269', '=')
->orderBy('weight', 'ASC')
->range(0, 1)
->execute()
->fetchField();

```

Is there any alternative way to do this, without querying database?

# Answer
I found this module Menu Firstchild maybe it will do what you want it to do.
> 1 votes

# Answer
You can use the ctools page manager to do a redirect. ( Page manager is basically a GUI for hook\_menu\_alter(); ) If you aren't familiar with it, the quickest way to learn it is to watch Johan Falk's screencast series at Nodeone.se

Using page manager, you can easily redirect one page to another.

Sub-menu Tree is another module you may want to try out. It will make a page for the parent menu item that lists all of the child items.
> 0 votes

# Answer
I have added this piece of code at the bottom of my tepmlate file (before closing body), it takes the name and target of the parent link and then injects it as the first item in the sub-menu. It will work with morst browsers, what was good enough for my client.

```
<script type="text/javascript">
(function ($) {
  $(document).ready(function() { // Re-create the first child in a menu to mimic the main link
    var me = $(".menu li .menu li.first");
    var parent = me.parent().parent();
    me.before('<li class="'+parent.attr('class')+'"><a href="'+parent.find('a').attr('href')+'" class="'+parent.find('a').attr('class')+'">'+parent.find('a').html()+'</a></li>');
  });
}) (jQuery);
 </script>

```
> 0 votes

# Answer
You can use menu\_tree() and menu\_link() menu\_tree creates the `<ul>` wrapping while menu\_link creates the menu list items `<li>`

Inside menu\_link() you can find $submenu, this contains an array with the submenu. This function return this `<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";`

Cheking the variable $element you can find the all the things for the list item i.e. Title, link etc...

So, if you want to do this for all the link in the first level:

```
if ($variables['element']['#original_link']['depth'] == 1)

```

or you can find the objects that say "has a sub menu and it's expanded"

Then you can rewrite your $output giving the item name with the first submenu item link.

I hope it's clear.
> 0 votes

---
Tags: 7
---


title: handle the submit button

text:
# Question
Title: handle the submit button
Hello guys i am trying to add data to one of my tables... when the submit button is pressed. I have the following script:

```
function review_m_admin_settings_form($node){
    $form = array();

    $form['overview'] = array(
        '#markup' => t('This interface allow adminss to manage general content types and vote them up!'),
    );
    $form['select'] = array(
        '#type' => 'select',
        '#title' => 'Choose a content type!',
        '#options' => node_get_types('names'),
    );
    $form['mark'] = array(
        '#type' => 'textfield',
        '#title' => 'Give a mark to the content type(1 to 10)!',
        '#size' => 60,
        '#maxlength' => 2,
    );
    $form['text'] = array(
        '#type' => 'textarea',
        '#title' => 'leave a feedback!',
        '#cols' => 60,
        '#resizable' => FALSE,
        '#rows' => 5,
    );
    $form['created'] = array(
        '#type' => 'textfield',
        '#title' => 'Enter the date!',
        '#size' => 60,
        '#maxlength' => 10,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Send review'),
        '#weight' => 10,
    );
    $form['action'] = $url;
    return $form;
}

```

this is my form.... i called the function with the \_submit at the end .. **but it doesn't work!**

```
    function review_m_admin_settings_form_submit($form, &$form_state){
    if(!isset($node->text)){
        $node->text = '';
        }
        if(!isset($node->created)){
            $node->created = '';
        }
        db_query(
            'INSERT INTO {review_m} (rid, nid, uid, mark, text, created)'
            . "VALUES (%d, %d, %d, '%s', '%s')",
            $node->rid,
            $node->nid,
            $node->uid,
            $node->mark,
            $node->text,
            $node->created
        );
}

```

**Help!**

# Answer
> 1 votes
You're trying to assign a value to an object property without declaring the object. Try this:

```
function review_m_admin_settings_form_submit($form, &$form_state){
    $node = new stdClass();

```

There's actually not any need to check if $node-\>text isset either because we know we haven't set it already.

You also need to pull your form values from the `$form_state` variable. For example:

```
$node->text = $form_state['values']['text']

```

---
Tags: forms
---


title: using the hook_nodeapi in the view mode

text:
# Question
Title: using the hook_nodeapi in the view mode
I am trying to add a form when I view my node; for that I am using the following code.

```
function review_m_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL){
    switch($op){
        case view:

```

In this case I would like to call `drupal_get_form()`.

I would like to add the following code.

```
function review_m_form($node) {
    $form = array();
    $form['mark'] = array(
        '#type' => 'textfield',
        '#title' => 'Give a mark to the content type(1 to 10)!',
        '#size' => 60,
        '#maxlength' => 2,
    );
    $form['text'] = array(
        '#type' => 'textarea',
        '#title' => 'leave a feedback!',
        '#cols' => 60,
        '#resizable' => FALSE,
        '#rows' => 5,
    );
    $form['created'] = array(
        '#type' => 'textfield',
        '#title' => 'Enter the date!',
        '#size' => 60,
        '#maxlength' => 10,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Send review'),
        '#weight' => 10,
    );
    return $form;
}

```

How can I pass this in the view case, so that it works good for me?

I am trying something like the following code.

```
case view:
            $node->content['form'] = array(
                drupal_get_form('review_m_form'),
              );

```

# Answer
> 0 votes
You're missing the first required variable in the signature of your form declaration so things will never work quite as you're expecting.

The function signature should be:

```
function review_m_form(&$form_state, $node) {

```

Then you would attach it to your node content like so, remembering to pass the node as a parameter:

```
$node->content['form'] = drupal_get_form('review_m_form', $node);

```

---
Tags: forms
---


# Question
Title: how to check non existent field added later using entityfieldquery?
I added a required field in a Job type node later. So existing nodes don't have that particular field value. I want to include all such field values. But how can I do it?

Here is query sample:

```
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', array('central_government_vacancy','psu_vacancy','state_government_vacancy'))
    ->propertyCondition('status', 1)
    -> fieldCondition('field__expired_processed', 'value', 'NULL', '=')  //I'm looking for this field
    ->fieldCondition('field_last_date_of_application', 'value', $date, '<=');

```

In the above code I want to find nodes having uninitialized field values : field\_expired\_processed.

!=, or using NULL to compare does not seem to work.

# Answer
> 2 votes
If you look on the fieldCondition documentation page you will see the following warning:

> Note that entities with empty field values will be excluded from the EntityFieldQuery results when using this method.

Checking whether a field exists or not has been added to entityFieldQuery in Drupal 8, but unfortunately won't be backported to Drupal 7.

This means you must use standard SelectQuery in order to achieve this. You must join the table which contains your data, and check whether the fiels IS NULL. It would be something like:

```
$q = db_select('node', 'n');
$q->condition('n.type', 'central_government_vacancy', '=')
->addJoin('LEFT', 'field_data_field_expired_processed', 'f')
->isNull('f.value');
$r = $q->execute();

```

---
Tags: 7, database, entities
---


title: User one time login and password reset

text:
# Question
Title: User one time login and password reset
I want to implement a functionality such that: The user registers on site and is sent an email (validation). Then he is taken to a page where hes is able to click on login form.

This was done using drupal's basic functionality. I had to change the message that was coming upon clicking onetime login page.(/user/reset/#hash)

I did it using hook\_form\_alter.

But it seems, that the text has been changed for the forgot my password link also.

Is there some way? May be I might have to create a separate page for the forgot password?

Thanks in advance

# Answer
Try to do the form\_alter, only if url has a #hash

```
if (preg_match('#^user/reset/(.+)#', $_GET['q'], $matches)) {
  //here for new user
}

```
> 1 votes

---
Tags: users
---


title: Memory requirement of Ubercart?

text:
# Question
Title: Memory requirement of Ubercart?
I am setting up a shopping cart for a client and will host the new site on a separate VPS. What is the typical memory required to run a Ubercart site? We are targeting a few thousand users, around a hundred products, and under ten concurrent users.

# Answer
Drupal 7 requires a minimum of 32MB (see - http://drupal.org/requirements/php) however in reality it will require much more, simple sites with a few contributed modules should be around 96MB.

Personally I'd recommend 128MB minimum and then tweak as required.

You can use the Devel module to output the pages memory usage to help you.
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: How to reset values of elements in multi-step form
I'm building quite a complicated and large custom form. Below I've made a simple example form to demonstrate my case:

```
function mymodule_form($form, &$form_state) {
  $form['step1']['element1'] = array(
    '#type' => 'select',
    '#title' => 'Element 1',
    '#options' => array('All' => '- Any -', 'option1' => 'Option 1', 'option2' => 'Option 2'),
  );

  $form['step1']['element2'] = array(
    '#type' => 'select',
    '#title' => 'Element 2',
    '#options' => array('All' => '- Any -', 'option1' => 'Option 1', 'option2' => 'Option 2'),
  );

  $form['step1']['addfilter'] = array(
    '#type' => 'submit',
    '#value' => 'Add filter',
    '#name' => 'addfilter',
    '#ajax' => array(
      'callback' => 'mymodule_form_callback',
      'wrapper' => 'results-div',
    ),
  );

  $form['step2'] = array(
    '#type' => 'fieldset',
    '#title' => t('Results'),
    '#prefix' => '<div id="results-div">',
    '#suffix' => '</div>',
  );

  // Ajax values process
  if(isset($form_state['values'])) {
    foreach($form_state['values'] as $key => $value) {
      if($value != 'All') {
        $form['step2']['step2-'.$key] = array(
          '#type' => 'button',
          '#value' => 'remove ' . $key,
          '#name' => 'step2-'.$key,
          '#ajax' => array(
            'callback' => 'mymodule_form_remove_callback',
            'wrapper' => 'results-div',
          ),
        );
      }
    }
  }
}

function mymodule_form_callback($form, &$form_state) {
  return $form['step2'];
}

function mymodule_form_remove_callback($form, &$form_state) {
  // What to do here???
}

```

Basically what should happen is:

1. Select a value from the step1 elements
2. Click Add Filter button
3. The form function runs again, and this time it creates ajax'd "remove" buttons under step2.
4. When you press the remove button, the corresponding form element in step1 should get its value reset to `'All'` and the corresponding step2 button needs to get removed.

I'm getting stuck at step 4, I'm not sure how to reset a submitted multi-step form's values.

# Answer
I was able to make this happen. I'm not sure if the way I'd done it is way too hacky/improper use of FAPI. But it works. What I did was:

1. On the remove button, I added a rel attribute with the name of the item to reset, as suggested by @enzipher
2. On the same form function, I checked for `$form_state['triggering_element']` and see if its value is remove and has rel attribute. If so, then I do form\_set\_value and reset the item's value in $form\_state. Because form\_set\_value only changes form\_state and not the $form, I also immediately set #value of the $form elements to the reset value.
3. On the callback function I built an array of ajax commands to both replace the target form element, as well as replace #results-div so that the button gets removed.
> 0 votes

# Answer
As I understand it, you don't need the ajax callback for the remove button. You should be able to do that with just using jQuery, and a `rel` attribute to hold the ID. Consider the following:

Add a class for the jQuery script and a `rel` attribute that holds the Step 1 element count id to the remove button.

```
$form['step2']['step2-'.$key] = array(
  '#type' => 'button',
  '#value' => 'remove ' . $key,
  '#name' => 'step2-'.$key,
  '#attributes' => array('rel' => 1, 'class' => 'remove-button'),
);

```

jQuery script to remove the "remove" button and reset the the Step 1 form element.

```
$('.remove-button').click(function(e) {
  var id = $(this).attr('rel');
  $('#element'+ id +').val('All');
  $(this).closest('.button-wrapper-class').remove();
  e.preventDefault();
});

```

This is (most likely) non-working example code, but I think you'll understand my point.
> 0 votes

---
Tags: 7, forms, ajax
---


# Question
Title: hook_block_view_MODULE_DELTA_alter gets fired twice
I'm trying to change the content of a block when a specific node is displayed. The code works fine. BUT the hook custom\_block\_view\_block\_1\_alter gets called twice. that is GOT MY NODE is displayed twice. How come?

```
<?php
/**
* Implementation of custom hook_node_load
*/

$count=0;
function custom_node_load($nodes,$types){
  foreach($nodes as $key =>$node){
    if($node->type=="person"){
      drupal_set_message("Person Node loaded");
      $customised_value="WAHAHAHAHAHAHAHAHAHAHAHA";
      $node->customised = $customised_value;
      variable_set('my_person_node',$node);
      drupal_set_message("WAHAHA");
    }
  }
}

/**
* Implementation of hook_block_view_MODULE_DELTA_alter
*/
function custom_block_view_block_1_alter(&$data, $block) {
  global $count;
  if($block->delta=="1"){
    ++ $count;
    $block->title="HERHE";
    $my_nodes=variable_get('my_person_node');
    dpm($block);
    $data['subject']="HEHE";
    $data['content']="<strong>".$my_nodes->customised."</strong>";
    drupal_set_message("GOT MY NODE".$count);
  }
}

```

# Answer
I faced a similar issue recently and the problem was the team had created both a module and a theme with the same name so Drupal was executing the same hook twice (once for the module and once for the theme). Renaming the theme solved the problem.
> 1 votes

---
Tags: hooks
---


title: Find item position in the pager

text:
# Question
Title: Find item position in the pager
I was wondering how I am able to find the position of an item in a views pager?

I have nodes listed using views (with pager, 20 every page), and I'd like to find out for example where in the pager one node is?

# Answer
EDIT (2015-04-05): Updated the snippet to work with newer version of Views.

Us too had to find the page number of a views result on which a certain node appears, so we can redirect visitors to this page.

By loading a view for a specific display and executing it's query manually, we retrieve an array with all node ids which we can search for a specific node id. When we have got the position of the node id, we divide it by the amount of items per page to get the page number the node is on.

I understand that loading all node ids at once in an array probably should not be done on large amounts of records, but for this exercise it's okay.

```
/**
 * Custom function to get the page number of a views result a node appears on.
 * Based on Drupal's views_get_view_result().
 */
function yourmodulename_views_get_item_page_nr($nid, $name, $display_id = NULL) {
  $args = func_get_args();
  array_shift($args); // remove $nid
  array_shift($args); // remove $name

  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (is_object($view)) {
    if (is_array($args)) {
      $view->set_arguments($args);
    }

    if (is_string($display_id)) {
      $view->set_display($display_id);
    }
    else {
      $view->init_display();
    }

    // Set the limit to 0 to retrieve all node ID's.
    $view->set_items_per_page(0);

    $view->pre_execute();
    $view->build();

    // Get the views query.
    $query = $view->build_info['query'];

    // Get the return assoc array with return objects, keyed by nids.
    $nids = $query->execute()->fetchAllAssoc('nid');

    // Get position of nid in nids array.
    $index = array_search($nid, array_keys($nids));

    // Get amount of items per page.
    $items_per_page = $view->display[$view->current_display]->handler->get_option('items_per_page'); // As seen at http://api.drupal.org/api/views/includes%21view.inc/function/view%3A%3Aexecute/7.

    // Calculate page number.
    $page_nr = $index === null ? 0 : intval($index / $items_per_page);

    return $page_nr;
  }
  else {
    return 0;
  }
}

```
> 2 votes

# Answer
If you want to look at the css, it will tell you that in that each "item" is a row, and each are surrounded with a div that has classes like:

```
<div class="views-row views-row-## ... ">

```

and the views-row-## is the item number in that pager.

You can also use the `Global: View result counter` as a field, but that gives you the position in ALL of the results, not the page in question, but a quick manipulation of that and the page number in question will give you the result, too. You might be able to use ctools' `Global: Math expression` to do that for you if it isn't already there for you (you didn't say what versions/modules you are running.)

If you want to dig into the guts of the view in a template, you could also get this information from `$view->result`.
> 1 votes

# Answer
Your problem is that you don't need that. I mean knowing the precise position of a node in a views query, makes you search on the entire record set, which would result in a huge performance issue.

The good question is : why do you need that ? There is 100% another, more accurate solution to your functional problem.
> 0 votes

# Answer
How to get that depends on what you will be using for. If you will be using for calculation under the hud. You could get it using simple php:

```
$position = $absolute_position % $pager_limit;

```

$absolute\_position is position of node in not paged the whole list if Drupal does not give you that by default at worst case scenario you could run a simple foreatch loop which would check for the node\`s title or id to match.

If you will use it for theming Javacript can do the trick. Would personally use use jQuery library to make easier for my self. A simple script could find desired element by it\`s tags and then change it accordingly.
> -2 votes

---
Tags: views, paging
---


title: unwanted cache_page flush for no reason

text:
# Question
Title: unwanted cache_page flush for no reason
On my drupal 6 site, from time to time, for no obvious reason, all caches gets cleared. Native caching is enabled (normal caching mode, minimum lifetime 1 day). Cron is not setup to run automaticaly. No rules are created regarding flushing of cache. In meantime I do not do any website manipulation like editing content, editing taxonomy or installing new modules. What I can see in recent log entries is that users keep logging in and out, users make orders (ubercart 6) and several not found errors probably caused by bots.
What can trigger such automatic/unwanted cache clearing, what logs should I check or how to fix that? Thank you.

# Answer
you could place a `watchdog('cache_clear_backtrace', print_r(debug_backtrace(),1);` in that `cache_clear_all()` function to see from the log why/ where that happens.
> 0 votes

---
Tags: 6, caching
---


# Question
Title: How to make the help text of a content type field collapsible?
I have built my Drupal 7 tennisclub-site so that a few users can maintain the content in it.

Most of these few are irregular users, that only come to maintain their part of the content a couple of times a year. For these people it is important that they are led through the steps of lets say... creating a calendar item, using the field-helptext. So there is a helptext for the title, a helptext for the date(s) and a helptext for the body of the content type "calendar-item".

While very usefull to the infrequent user, these helptexts are quickly becomming annoying to regular users. How do I make the helptexts collapsible and how do I set it's default state? Which modules do I need for this to work?

Thanks in advance,

Tijs

# Answer
Each form element in your input/edit form will be in a div with a unique id, and will have a child division with the 'description' class which contains the help text.

If you know which div's you wish to collapse, it can be done with javascript, following the model for Collapsible Blocks.
> 1 votes

---
Tags: entities, nodes
---


title: how can I change the admin url?

text:
# Question
Title: how can I change the admin url?
Is it possible to have the administration pages on a different place than /admin?

so something like: www.mysite.com/someotheradminlocation

I don't want the admin location to be guessable by hackers.

# Answer
> 2 votes
This should be very easy. It's under Site building \> URL aliases \> Add alias (admin/build/path/add) You can add a new URL alias there.

So if you can't find it you might need to install the pathauto module

**solution 2**

If you are using Drupal 6, you can get the same feature by using the following code in your settings.php file.

```
function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
    if (preg_match('|^admin(?![^/])(.*)|', $path, $matches)) {
        $path = 'backend'. $matches[1];
    }
}

function custom_url_rewrite_inbound(&$result, $path, $path_language) {
    if (preg_match('|^backend(?![^/])(.*)|', $path, $matches)) {
        $result = 'admin'. $matches[1];
    }
    if (preg_match('|^admin(?![^/])(.*)|', $path, $matches)) {
        $result = '404'. $matches[1];
    }
}

```

# Answer
> 3 votes
There is a module to do what monymirza suggested - http://drupal.org/project/rename\_admin\_paths

> The purpose of this module is to secure drupal backend by overriding admin path.

---
Tags: 6, security, uri
---


# Question
Title: How to make form buttons call only javascript?
I'm experimenting with JavaScript and Drupal forms. Currently I'm trying to make a button in the administration form of a module that will use JavaScript to append options to a select list. The problem I'm running into is that when I click the button, my JavaScript gets called but the whole form refresh. I've looked at the Forms API reference thinking there was some kind of attribute I can set on the button to stop it from but found nothing. Is there any way I can stop the button from refreshing the page or is this a dead end?

```
$form['#attached']['js'] = array(
  drupal_get_path('module', 'test').'/js/test.js',
);

$form['list'] = array(
  '#type' => 'select',
  '#options' => array(),
  '#attributes' => array(
    'name' => 'sellist',
  ),
  '#size' => 4,
);

$form['add_button'] = array(
  '#type' => 'button',
  '#value' => 'Add',
  '#attributes' => array(
    'onclick' => "add_to_list(this.form.sellist, 'Append' + this.form.sellist.length);",
  ),
);

//JavaScript
function add_to_list(list, text) {
  try {
    list.add(new Option(text, list.length), null) //add new option to end of "sample"
  }
  catch(e) {
    list.add(new Option(text, list.length));
  }
}

```

My final code:

```
<?php
function jstest_menu() {
  $items['admin/config/content/jstest'] = array(
    'title' => 'JavaScript Test',
      'description' => 'Configuration for Administration Test',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('_jstest_form'),
      'access arguments' => array('access administration pages'),
      'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function _jstest_form($form, &$form_state) {
  $form['list'] = array(
    '#type' => 'select',
    '#options' => array(),
    '#size' => 4,
  );

  $form['text'] = array(
    '#type' => 'textfield',
  );

  $form['add_button'] = array (
    '#type' => 'button',
    '#value' => t("Add"),
    '#after_build' => array('_jstest_after_build'),
  );
  return $form;
}

function _jstest_after_build($form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'jstest').'/js/jstest.js');
  return $form;
}

JavaScript
(function ($) {
  Drupal.behaviors.snmpModule = {
    attach: function (context, settings) {
      $('#edit-add-button', context).click(function () {
        var list = document.getElementById('edit-list');
        var text = document.getElementById('edit-text');

        if (text.value != '')
        {
          try {
            list.add(new Option(text.value, list.length), null);
          }
          catch(e) {
            list.add(new Option(text.value, list.length));
          }

          text.value = '';
        }

        return false;
      });
      $('#edit-list', context).click(function () {
        var list = document.getElementById('edit-list');

        if (list.selectedIndex != -1)
          list.remove(list.selectedIndex);

        return false;
      });
    }
  };
}(jQuery));

```

# Answer
> 3 votes
The most easy way to accomplish this is just return false in your javascript code:

```
function add_to_list(list, text) {
  try {
    list.add(new Option(text, list.length), null);
    return false;
  } catch(e) {
    list.add(new Option(text, list.length));
    return false;
  }
}

```

or a better way is using behaviors:

```
Drupal.behaviors.some_action = function(context) {
  $('#id-button:not(.button-processed)',context)
  .addClass('button-processed').each(function() {

    //whatever you want here
    return false;
  });
}

```

# Answer
> 7 votes
the form button definition below works for me, the #after\_build is useful for loading in javascript that can attach the click handler.

```
$form['add_button'] = array (
  '#type' => 'button',
  '#attributes' => array('onclick' => 'return (false);'),
  '#value' => t("Add"),
);

$form['#after_build'] = array('[module_name]_after_build');

```

Then my javascript that is loaded in a separate file by the after build function, looks something like:

```
Drupal.behaviors.[module_name] = function(context) {
  $('#edit-add-button').click(function() {
   ...Do something here
  });
};

```

# Answer
> 3 votes
You can just add the `return false` statement after your function call, inside the attribute line of the button form element:

```
'#attributes' => array(
   'onclick' => "add_to_list(this.form.sellist, 'Append' + this.form.sellist.length); return false",
),

```

# Answer
> 0 votes
Ideally, have a read into Drupal's own AJAX (or AHAH) form abilities. Really basic intro here http://drupal.org/node/752056

Otherwise, I'm surprised it is refreshing the page as it is just a 'button' not a submit or anything.

Does it need the javascript to return false, like on an link does to stop it jumping back to the top of the page?

---
Tags: 7, forms, javascript
---


# Question
Title: How to access the published field in my PHP code?
I am defining a datatype called slider

```
$nodes = node_load_multiple(array(), array('type' => 'slider'));
foreach($nodes as $slider):

```

and trying to iterate through each of them. I want to access the field which says if the content is publised or not. I tried this -

```
$slider->$status == 1

```

But this is not working. Does anyone have a solution this problem?

Thanks

# Answer
> 1 votes
It is

```
$slider->status == 1

```

instead of

```
$slider->$status == 1

```

# Answer
> 0 votes
Try EntityFieldQuery to get al `nid`s

```
 $query = new EntityFieldQuery();
 $result = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'mycontenttype')
    ->execute();
 $nodes = node_load_multiple(array_keys($result['node']));
 foreach($nodes as $node){
  if($node->status == 1)
  drupal_set_message('node '.$node->title.' is Active');
 }

```

---
Tags: 7
---


# Question
Title: Multiple local Drupal sites for development on WAMPServer?
I'm still very new to Drupal. I'm hoping to create multiple site instances via my local WAMPServer WAMP stack. I have one. I realize that Acquia makes this very simple via their DAMP stack, but have heard that it can be very painful upgrading and/or transferring these to a server due to the non-standard paths that Acquia uses for some of its files (some of its modules specifically). So I'm wondering how I can emulate what DAMP does, albeit without their Dev installer app. I've searched here and googled, but can't seem to find anything...

# Answer
> 1 votes
This question is a bit off-topic. What you need to do is to setup Apache with name-based virtual host support. Of course you could place your sites in sub-directories, but you would be much happier with virtual hosts, i.e. one local 'domain' and www root per site.

---
Tags: installation, distributions
---


# Question
Title: How to display multiple fields in one line in drupal
First of all I'm new to Drupal. I want to add 3 form fields inline as shown in the image. So I want to know what is the best method of doing it.

# Answer
As mentioned in the comments, you need to use CSS to achieve this. Drupal makes it really easy by wrapping the elements nicely with divs and relevant classes. For example, if you are creating a new issue in Drupal.org, the form provides http://drupal.org/project/issues/linkedin?categories=All this kind of structure.

Using an inspector tool, you can find the target divs and apply a CSS in this way to your theme:

```
.views-exposed-form .views-exposed-widget {
    float: left;
    padding: 0.5em 1em 0 0;
}

```

Thats it. Don't forget to clear your cache to see the changes!
> 1 votes

---
Tags: 7, entities, hooks
---


# Question
Title: How to make a table sortable by CCK field
An odd question: I have a custom column added to the default admin/content page that shows the value of a CCK field "field\_foo". I'm trying to sort the table by this field. (I can't use Views for this unfortunately). This is what I have for the header:

```
$header = array(
  'title' => array('data' => t('Title'), 'field' => 'n.title'),
  'foo' => array('data' => t('Foo'), 'field' => 'n.field_foo', 'sort' => 'desc');
)
$query = db_select('node', 'n')
   ->extend('PagerDefault')
   ->extend('TableSort');
node_build_filter_query($query);

```

I also tried the name of the field as declared in the $rows, ie...

```
'foo' => array('data' => t('Foo'), 'field' => 'n.foo', 'sort' => 'desc');

```

This results in a link at the top of the Foo column head, but when I try to click on the link to sort Asc or Desc it doesn't really work and the Foo values aren't ordered in the requested order. If anyone has any suggestions I'd really appreciate it. Thanks!

# Answer
> 0 votes
Try out Tablesorter moulde and add js function to your js file

```
$("Table").tablesorter();

```

---
Tags: 7, entities
---


title: How to get user by uid in views_php?

text:
# Question
Title: How to get user by uid in views_php?
i am using the views\_php module and i need to get the user by his uid to read out some properties to build a filter. (It is not the currently logged-in user!). Is there some drupal function like this ?

```
$myuser = drupal_get_user_by_uid(uid);

```

# Answer
> 4 votes
The answer is :

```
$user=user_load($uid);
$username=$user->name;

```

# Answer
> 1 votes
Yes there is

user\_load

> Loads a user object.

user\_load\_multiple

> Load multiple users based on certain conditions.

---
Tags: views
---


title: How to setup year increment?

text:
# Question
Title: How to setup year increment?
I use Date module in D7, and I create new field "decade" (field type is Date). Also in the settings, I add a custom input format 'Y' (only years). There is increment for time (+/-30 minutes), but I need increments for years (+/- 10 year). In node add form I need selectbox with values like:

1700
1710
1720
1730
....
now
How can I do that?

# Answer
> -1 votes
You shouldn't use a date format for your field

I advice you to use CCK module (7.x-2.x-dev)

> some miscellaneous helpers to do things that core will not do, like maintain the PHP code snippets some fields may have been using to define allowed values (partially working)

With this module, you define these kind of allowed values from a php code

---
Tags: 7, datetime
---


# Question
Title: common header and footer for all pages in drupal7
i use different layouts for different pages for a large website, which share common header and footer. how can i create common header and footer templates and link the templates to these pages.

# Answer
The most common is to structure your header and footer using the core block system. Another solution would be to place the structure in the `page.tpl.php`. If you have a lot of `page.tpl.php` files and still want to use templates, then it might be better to place the header and footer in the `html.tpl.php` template.

Personally I would recommend using the blocks system.
> 4 votes

# Answer
Way to do this, creating region--header.tpl.php and region--footer.tpl.php, which contains the html structure for header and footer region. Make sure tat base template file region.tpl.php file is included.

For dynamic header and footer, use blocks. And for static header and footer section, write html code in the header and footer template files. And for semi-dynamic portion, combination of both can be used.

However there should be a block atleast in the header and footer region to take effect.
> 1 votes

---
Tags: theming
---