# Question
Title: How to get images into a slideshow via json javascript with new itok
I have just updated to drupal 7.21, and I have massive errors with the new itok suff: Right now I use `json_encode(views_get_view_result('viewsitem'))`, and decode the result with JSON and JavaScript. My slideshow wants to have the normal path but returns things similar to "...sites/default/files/styles/large/public/field/image?itok=M-zTIVI1/mypic.JPG."

Normally, I get the images using the following code.

```
if (value.field_field_image) {
  var images = value.field_field_image
  // iterating over the images per nid
  for (var i = 0; i < images.length; i++) {
    slideshow_settings.this_slides += '<a class="rsImg" href="'
      + slideshow_settings.basepath + '/' + images[i].raw.filename
      + '"></a>';
  }

  pics = slideshow_settings.this_slides;
}

```

How can I fix this?

# Answer
Your root problem seems to be that you are using a side effect of `image_style_url()`.

When you don't pass in a valid image path, you used to get back the basepath of the image style. Now, with the token patch, it will include the token, and therefore not really be the basepath. From what I can gather, this is why a lot of modules broke.

The proper thing to do is to use the API to create the URL for you on the server side, instead of gluing together parts in JS.

This is something that I used on a recent project:

```
$images = array();
$styles = image_styles();

if (! empty($node->field_my_image[$node->language])) {
  foreach ($node->field_my_image[$node->language] as $image) {
    $fid = (int) $image['fid'];
    $uri = $image['uri'];
    $url = file_create_url($uri);

    $metadata = array(
      'alt' => empty($image['alt']) ? '' : $image['alt'],
      'width' => (int) $image['width'],
      'height' => (int) $image['height'],
    );

    $metadata['styles'] = array(
      'original' => $url,
    );

    foreach ($styles as $style => $unused) {
      $metadata['styles'][$style] = file_create_url(image_style_url($style, $uri));
    }
  }

  $images[$fid] = $metadata;
}

drupal_add_js(array('mymodule' => array('images' => $images)), 'setting');

```

This dumps all of my image fields into a JS array with all of their metadata, including all of the URLs for the image styles that I may need. My JS code can then use what it needs from this array without worrying about building paths up.
> 4 votes

# Answer
There is a recent (today) patch in this issue and if the thread is to be believed, itok's days may be numbered as 'too intrusive'. Personally, I have frozen any image-intensive sites at 7.19 until this issue is resolved. You might consider a rollback.
> 1 votes

# Answer
As a quick hack you could do something like...

```
for (var i = 0; i < images.length; i++) {
  var parts = slideshow_settings.basepath.split('?');
  var href = parts[0] + '/' + images[i].raw.filename + '?' + parts[1];

  slideshow_settings.this_slides += '<a class="rsImg" href="' + href + '"></a>';
}

```
> 1 votes

---
Tags: media, files
---


# Question
Title: Make custom form submit data to view filters
I have a custom-generated form on a page and it needs to submit data to a view on a different page. I'm currently trying to get this to work by passing the form #validate through a submit hook and then using `$form_state['redirect'] = 'customsearch/';` to catch the results. The view has several exposed filters and will ideally set themselves to the data received from the initial custom form page.

It doesn't look as though data is actually making it to the /customsearch/ landing page however. I have enabled the Views Expost module and am watching for POST variables from a PHP field in the landing page view.

The current code including form, validation and redirection can be found over here.

What is the proper 'Drupal' way of passing data from a form to a view with exposed filters? Should I be watching for GET or POST variables or will Drupal pass data with a different set of functions than the ones currently used?

# Answer
> 1 votes
Views exposed filters are using information supplied by the relevant GET parameters so this use case is actually very simple. You only need to build the correct url in your custom form submit handler from the received data and then redirect the user. A basic example to illustrate this:

```
function mymodule_custom_search_form($form, &$form_state) {
  $form['key1'] = array(
    '#title' => t('Key1'),
    '#type' => 'textfield',
  );
  $form['key2'] = array(
    '#title' => t('Key2'),
    '#type' => 'textfield',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );

  return $form;
}

function mymodule_custom_search_form_submit($form, &$form_state) {
  $options = array('absolute' => TRUE);
  $key1 = trim($form_state['values']['key1']);
  if ($key1) {
    $options['query']['key1'] = $key1;
  }
  $key2 = trim($form_state['values']['key2']);
  if ($key2) {
    $options['query']['key2'] = $key2;
  }
  $form_state['redirect'] = url('customsearch', $options);
}

```

If the user submits the form with "key1" value "one" and "key2" value "two" then they will be redirected to "customsearch?key1=one&key2=two". What you need to note is that the GET parameters "key1" and "key2" must match with what you've set in the relevant view: click on your filter criteria -\> "MORE" link at the bottom and then check/modify "Filter identifier".

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


# Question
Title: More Node Access Product (nap.module) Problems
I have a client who cannot launch his website because of continuing problems with the Node access product module.

After a customer makes a purchase, they are prompted to login. Upon attempting to login they receive a white screen with the following message -

> "Fatal error: Cannot use object of type stdClass as array in home/mysite/public\_html/sites/all/modules/nap/nap.module on line 824"

Have already looked everywhere for a solution. Any suggestions?

# Answer
> 0 votes
Try changing `$purchases['product_vid']` to `$purchases->product_vid` on line 824. Issue has been created on the project.

---
Tags: ubercart, users
---


# Question
Title: Help with wrapping character with CSS span using Jquery
I have this jfiddle working (http://jsfiddle.net/FJxcG/), but the same code does not work on my Drupal 7 website. I added the JS file to my theme .info file, and the JS is showing up in the source; it's just not displaying the end result on-screen.

The reason I need this is so that I can wrap a span class around all instances of the Trademark special character (™). That character is too large in the font I am using, and I'd like to use that css/jquery function to apply the span so I can give the TM a smaller font size without affecting the rest of the text around it. Some of the TM's are within menu links, so I can't simply hard-code the new span class.

Thanks!

# Answer
Two things I can think of that could possibly cause the problem:

1. Your code runs before the document is fully loaded. To fix it try wrapping the function call inside `$(document).ready`:

```
$(document).ready(function() {
  $('div').wrapInTag({
    words: ['™'],
    tag: '<span class="trademark">'
  });
});

```
2. The CSS style are being overridden. Quickfix would be to add `!important` at the end.

```
.trademark {
  font-size: 9px !important;
  vertical-align: top !important;
}

```
> 2 votes

---
Tags: 7, theming, javascript
---


# Question
Title: How much of Drupal 8 will rely on or be compatible with Symfony?
Now that Drupal 8 is being redeveloped with Symfony, and we are just about to go into the code freeze so that early adopters can start playing with it, what will it affect?

Will we be able to write modules and themes like writing bundles? Should we all start brushing up on or learning Twig?

# Answer
> 7 votes
Symfony, as in full stack Symfony, we aren't to be compatible with.

We are using Symfony components so many concepts used there will be useful.

---
Tags: 8, theming
---


# Question
Title: Which contributed modules are being moved into Drupal 8 core?
There were a significant number of D6 modules (or versions of) that were pulled into D7 core. I am wondering if there are any for D8?

# Answer
The short answer is that Drupal is developed by the community, so it depends on what YOU (anyone reading this answer) add to Drupal 8.

I always use the Add jQuery UI elements to core issue as an example of how this process works. A few people had an idea, they posted some code, it was reviewed and debated, then added to Drupal 7 core.

Core contributions are by no means exclusive, so be bold! Start contributing.
> 10 votes

# Answer
# Modules brought into core

## Entirely:

* Breakpoint
* CacheTags
* Content Translation
* Email (simple field, HTML5 validation only)
* Entity API
* Entity Reference
* Entity view modes
* File Entity
* Link (simple field, HTML5 validation only)
* Phone (simple field, HTML5 validation only)
* Picture
* Quick Edit
* Transliteration
* UUID
* Views
* RESTWS (Renamed to REST module)

## Partially:

* Admin Views (reworked)
* CKEditor
* CTools
* Date (all except recurring dates)
* Display Suite (view modes)
* Internationalization
* Migrate
* Views Bulk Operations (reworked)

## Removed

* Blog (moved to contrib)
* Dashboard (moved to contrib as Homebox)
* Open ID
* Overlay (fundamentally reworked to not provide an "overlay")
* PHP Filter (moved to contrib)
* Poll (moved to contrib)
* Profile (Use Profile2 now)
* Translation (replaced by Entity Translation)
* Trigger (use Rules now)
* Signature (functionality provided by User moved to contrib)
* XML-RPC (moved to contrib)

# Modules fundamentally changed by Drupal 8:

## Deprecated (you won't need these anymore)

* Admin
* Administration Language
* Bean
* Boxes
* Caption Filter
* Computed Field
* Ctools exportables
* Fallback Language Negotiation
* Field Hidden
* Fieldable Panels Panes
* Float Filter
* Hidden Field Widgets
* History
* IMCE
* Localization update
* Localized Drupal Distribution
* Menu Block
* Menu Trails
* Module Filter
* Node Reference
* Placeholder
* Profile2
* RSS permissions
* Services
* String overrides
* Strongarm
* Token
* Transliteration
* User Picture Field
* User Reference
* Vertical Tabs
* Wysiwyg * (the module and everything related to it)

## Reduced (these will have less work to do)

* Backup and Migrate
* Context
* Custom Breadcrumbs
* Features
* Feeds
* Menu Breadcrumb
* Service Links
* Rules
* Views * (every module related to views)
> 45 votes

# Answer
It's not modules which are pulled into core, it's functionality. Functionality that might have been provided by contributed modules (and the code that was added to core might have been influenced by those modules but not necessarly that actual code is reused. For example fields, which was inspired by CCK but was a complete rewrite from scratch). And then these contrib modules don't need to be ported to the next core version.

That said, there is no roadmap in Drupal core development. So it is impossible at this point to answer your actual question.

The only thing that now exists are a number of so called core initiatives. That is an area where people are working together under the "lead" of the initiative owner to improve Drupal in a specific area. One of those is HTML5 (which might mean that a number of HTML5 related modules might not be necessary in D8) another is Web Services and Context (which means that for example the Context module will be unecessary and maybe parts of Panels). But all that is just speculation at this point. Because even though these initiatives exist, it is not set in stone that anything they're working on will be commited.

That is basically the two main tasks that Dries Buytaert (and to a certain degree co-maintainers, initiative owners, ...) are doing. They're talking about how Drupal *could* evolve and what could be done. And then finally Dries decides if a patch is commited or not.

In between, everything depends on if there are people who are interested in something and want to implement/improve/fix some part of Drupal core.
> 6 votes

---
Tags: 8
---


# Question
Title: Changing blocks based on visitor's country
On a Drupal 6 site I am trying to display blocks on my site based on user's country.

1. To do this I had to install 'IP to Country' module
2. Updated IP to Country
3. Created a new block and added the following code into the block body to print the user's country code:

```
<?php
$co=module_invoke('ip2cc','get_country',$_SERVER['REMOTE_ADDR'];);
print($co->country_code);
?>

```
4. Then, under 'Show block on specific pages' selected 'Show if the following PHP code returns TRUE (PHP-mode, experts only).' and then added the below mentioned code, so that the block is displayed based on the country ID.

```
<?php $co->country_code == "IN" ?>

```

After doing all these the block is getting disabled for the ID mentioned, eg: If 'IN' is mentioned the block should only be displayed for Indian visitors, but the block is actually being disabled.

# Answer
> 1 votes
Your code seems to be right. You've mis-spelled the module name in the `module_invoke` function at #3 and misplaced the semicolon `;`

Try this:

```
<?php

$detectedcountry = module_invoke('ip2country','get_country',$_SERVER['REMOTE_ADDR']);
$us_canada = array(
  'US','CA'
);

//return true in block visibility when the country appears to be in detected country
if(in_array($detectedcountry,$us_canada)){
  return true;
}

?>

```

---
Tags: 6, blocks
---


# Question
Title: How to show payment form on node form preview in Drupal 7?
I have make a content type, I have make compulsory to preview node before saving, now what I need when user click on the preview button, he can review his information which he wrote in the form and then there should be payment form, if the payment is successful, node will be saved else not.

# Answer
Try out Pay-per-node module.

> It can be used as standalone module or as an e-commerce plug-in. In the second case paypernode can be integrated with Ubercart, providing a new "product feature" which will allow, upon product purchase, to create a number of nodes.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to ajax changing date field on _node_form?
On content type called Order have 2 fields - "Category name" (term reference) and "Date" (Date (Unix timestamp)). On node edit form I want to change date to other value (for test purpose it is "hard coded", see code below) on changing "Category name". Ajax fire on "Category name" and "Date" fieldset "fade" but date value still no change.

Code:

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'order_node_form') {
    // Date (Unix timestamp)
    $form['field_date']['#prefix'] = '<div id="field-date-replace">';
    $form['field_date']['#suffix'] = '</div>';

    // Taxonomy reference select list
    $form['field_category_name']['und']['#ajax'] = array(
      'callback' => 'category_name_callback',
      'wrapper' => 'field-date-replace',
      'method' => 'replace',
      'effect' => 'fade',
    );

    if (!empty($form_state['field_category_name']['und'][0]['tid'])) {
      $form['field_date']['und'][0]['#default_value']['value'] = strtotime('12/12/2013 00:00:00');
    }

    // Test - work if uncommented
    //$form['field_date']['und'][0]['#default_value']['value'] = strtotime('10/10/2013 00:00:00');
  }
}

function category_name_callback(&$form, &$form_state) {
  // don't work too
  //return $form['field_date'];

  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace("#field-date-replace", render($form['field_date'])),
    ),
  );
}

```

# Answer
I found a solution but not why, if someone knows and says I will mark as the correct answer. Phone type behaves similarly to the decision to date and it is the same.

First of all this was hard to debug. For this I add in ajax callback the line

```
ajax_command_prepend("#field-date-replace", theme_status_messages(dpm($form_state)), 'status'),

```

And now all code

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'order_node_form') {
    // Date (Unix timestamp)
    $form['field_date']['#prefix'] = '<div id="field-date-replace">';
    $form['field_date']['#suffix'] = '</div>';

    // simple text line input
    $form['field_some_text']['#prefix'] = '<div id="field-some-text-replace">';
    $form['field_some_text']['#suffix'] = '</div>';

    // Phone number module field
    $form['field_phone']['#prefix'] = '<div id="field-phone-replace">';
    $form['field_phone']['#suffix'] = '</div>';

    // Taxonomy reference select list
    $form['field_category_name']['und']['#ajax'] = array(
      'callback' => 'category_name_callback_func',
      'wrapper' => 'field-some-text-replace',
      'method' => 'replace',
      'effect' => 'fade',
    );

    if (!empty($form_state['values']['field_category_name']['und'][0]['tid'])) {
      $form['field_some_text']['und'][0]['value']['#value'] = 'after change';
    }
    else {
      $form['field_some_text']['und'][0]['value']['#value'] = 'before change';
    }

  }
}

/**
 * AJAX callback for 'field_category_name' form
 */
function category_name_callback_func($form, $form_state) {

  if (!empty($form_state['values']['field_category_name']['und'][0]['tid'])) {
    $form['field_phone']['und'][0]['number']['#value'] = '999999';
    $form['field_phone']['und'][0]['country_codes']['#value'] = 'gb';

    $form['field_date']['und'][0]['value']['date']['#value'] = '01/01/2014';
  }
  else {
    $form['field_phone']['und'][0]['number']['#value'] = '';
    $form['field_phone']['und'][0]['country_codes']['#value'] = '';
  }

  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace("#field-date-replace", render($form['field_date'])),
      ajax_command_replace("#field-some-text-replace", render($form['field_some_text'])),
      ajax_command_replace("#field-phone-replace", render($form['field_phone'])),

      // remove comment (//) on next line for debuging
      //ajax_command_prepend("#field-date-replace", theme_status_messages(dpm($form_state)), 'status'),
    ),
  );
}

```

The difference between all the examples I've seen, and this decision is that the values change is made in "ajax callback" but not in hook\_form\_alter.
> 2 votes

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


# Question
Title: How to remove results returned from Views UI
I am getting results as expected using Views UI. But I don't want to display a particular record from the output of Views UI. How to achieve this and will I require any hooks for this?

For example; My Views return result as 1,2,3,4. Now I don't want to show 1 in the result. I cannot change the query using `hook_views_query_alter` as 1 is being used in "where" clause.

# Answer
> 2 votes
An answer to this question very much turns on what record you want to exclude from the listing. But the typical route here is to use a Contextual Filter on your view.

A typical pattern is that you are displaying a View alongside a node, e.g. a view of items that are related to that node. In this case, you want to exclude the node itself. For this you create a contextual filter that provides a default value of the the current node when there is no filter value present in the URL. You then check the exclude box in the contextual filter configuration. (Detailed steps below.)

**Update** In comments, you give more detail about what you want to exclude. Or, put another way, what you want to include. In general terms, you want to include nodes that share ANY taxonomy terms with the current node. Specifically, if you have a Teacher content type and a Subject taxonomy, then your requirement is to show every teacher that shares ANY of the taxonomy terms (representing subjects taught) of the currently displayed teacher.

Contextual Filters can do this out of the box, although the configuration is not especially intuitive. The approach is to add a `Content: Has taxonomy term ID` contextual filter and then configure it so it pulls taxonomy terms out the current node. (Detailed steps below.)

# Stage one: Exclude current node

1. Add a contextual filter `Content: Nid` (under **ADVANCED** to the right of the Views configuration page).
2. Under **WHEN THE FILTER VALUE IS *NOT* IN URL** select 'Provide a default value' and choose 'Content ID from URL'. (This gets the node id.)
3. In the **MORE** section check the box 'Exclude'. (This says instead of filtering to show only the node, filter to show anything but the node. Of course, the normal non-contextual filters also apply.)

You can add more than one Contextual filter to build up more complex conditions. And, as noted above, you can write PHP for the Contextual filter.

# Stage two: Include all nodes that share ANY of the taxonomy terms of the current node

(aka, exclude any nodes that don't have any common taxonomy terms with the current node, but include everything else)

1. Add a contextual filter `Content: Has taxonomy term id`.
2. Under **WHEN THE FILTER VALUE IS *NOT* IN URL** select 'Provide a default value' and choose 'Taxonomy term ID from URL'. (This is a powerful option and what it does depends on the next configuration steps.)
3. **Uncheck** the 'Load default filter from term page' box.
4. **Check** the 'Load default filter from node page, that's good for related taxonomy blocks'
5. You will usually want to **check** the 'Limit terms by vocabulary' box and then select the relevant vocabulary, e.g. 'Subjects'. You might skip this step if you know you only have term reference field on kinds of nodes you are interested in. But it does not harm to check it even in these cases.
6. Under **Multiple-value handling** select the 'Filter to items that share any term' option.
7. Further down the configuration find the 'Reduce duplicates' check box and **check** it.
8. Open up the **MORE** fieldset at the bottom of the configuration and **check** 'Allow multiple values'

# Answer
> 0 votes
I created sample block that display 5 articles (titles).

One way of ommit first article is go to:

Pager -\> User pager and click on numers of element, than:

Specify offset to 1 to the job

# Answer
> 0 votes
If there is something specific about the record you don't want to return, you can filter your results so that it excludes that record. For example, if you're returning nodes and you don't want to return the node with NID = 1, then add an entry to Filter Criteria where Content:Nid "is not equal to" the value of 1.

---
Tags: 7, views, hooks
---


# Question
Title: How can I access values of multiple select list in a form?
I have a custom form in a custom module with multiple select:

```
$form['sponsors'] = array(
 '#type' => 'select',
 '#options' => $sponsors,
 '#multiple' => TRUE,
 '#size' => 20,
);

```

But I'm stumped how to access the submitted multiple values in the form\_submit function. I tried to get the values by looping through the key (one guess was `$form['values']['sponsors'][$key]`) but no luck... anyone can point me in right direction would be appreciated!

# Answer
> 0 votes
Submitted data goes into `$form_state['values']` (not `$form['values']`), and in the case of a multiple select/checkbox element you can filter out the selected items like this:

```
function MYMODULE_form_submit($form, &$form_state) {
  $selected = array_filter($form_state['values']['sponsors']);
}

```

As monymirza mentioned you're also missing the `#` symbol at the start of both the `size` and `multiple` keys. I imagine that error is just in your question, not in your actual code, or you'd expect to see more errors.

# Answer
> 1 votes
in case whether the user may select more than one item, `size` value be written like this way:

```
'#size' => $multiple ? min(12, count($options)) : 0,

```

this is how used in (taxonomy.module).

---
Tags: 7, forms
---


# Question
Title: How can I access a node's menu link and weight through EntityFieldQuery
In D7, I'm trying to set up a custom menu that is ordered by the weight of the node-\>path ("weight" field in table menu\_links). How can I access the node's path's weight value in my query so it can be ordered correctly? This is what I had but was shot down very quickly:

```
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_meeting', 'value', $meetid, '=')
    -> propertyOrderBy('weight','ASC')
    ->addMetaData('account', user_load(1)); // Run the query as user 1.
    $result = $query->execute();

```

# Answer
> 2 votes
I ended up using db\_query JOIN to get the info straight from the database:

```
$sql = "SELECT menu_links.link_path, menu_links.link_title, menu_links.weight, node.nid
        FROM menu_links
        JOIN node.nid
        ON menu_links.link_path LIKE CONCAT('node/', node.nid)
        ORDER BY menu_links.weight ASC";
$result = db_query($sql);

```

---
Tags: 7, database
---


# Question
Title: Reject e-mail address from specific domain in simplenews newsletters e-mails
i have a lot of spam users request account with mails on specific domain,i used the User restrictions module to make e-mails on that domains not allowed, but only to the registration .i want to know how can i do the same to the Simplenews module to reject e-mails from specific domains to register in the newsletter. thatnks

# Answer
> 0 votes
How are users registering their email addresses? For example, we use simplemail on http://goniseko.com in the footer. It's a signup block that anyone can use.

Is this where your spammers are signing up from?

In my opinion, this is super easy to fix, if you aren't afraid of creating a quick and dirty module that uses `hook_form_alter`.

In the module you would simply create a validation rule that if the form value submitted contained 'baddomainame.com' it would prevent the form from sending.

```
function mymodule_hook_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'my_simple_news_form_id'){
        $form[#validate][] = 'check_domain_callback_validate';
    }
}

function check_domain_callback_validate(&$form, &$form_state){
    if(&$form_state['values']['simple-news-email-value'] == 'baddomainame.com'){
        form_set_error('', 'BAD DOMAINNAME, BAD! YOU NO SIGN UP');
    }
}

```

of course all of that is pseudo code, but the structure should get you started. Here is a link to the forms API tutorial that will help if you are not very familiar with FAPI.

http://drupal.org/node/262422

---
Tags: users, emails, advertising
---


# Question
Title: Having a view spitting out a form - the UI way
Suppose I have a lot of entities that match users to some nodes and the entities have a field called "rating" which is/could be a Drupal list of four possible values ranging from interesting to uninteresting.

I want to have a view that spits out all entities related to the currently logged in user and let him choose his rating for each of them. When he comes back later, he should see his choices and be able to edit it. How to do that?

I know, that it's somehow possible by writing a module. Ideally, I don't want to do that but rather solve it completely with UI.

(I'm not fixed to the entity approach I described above. If you think it's a bad idea, I'll be happy to hear alternate suggestions.)

# Answer
> 2 votes
You can try using the editablefields module.

I personally find it better to write a custom views handler implementing the Views Form API, but you can try to see how far this takes you.

---
Tags: views, forms
---


title: Add Form frields to View

text:
# Question
Title: Add Form frields to View
I'd like to generate a view of Employee names, but I'd like to embed it inside a form as well as add checkboxes next to each Employee name. I tried to use `Rewrite the output of this field` but my `<input/>` tag is getting stripped out when being displayed.

How would you recommend I do this?

# Answer
I ended up using Views Bulk Operations to generate the page content and then I added some javascript and css to hide certain things and to also add some extra fields, etc.

It was a total hack, but it got me through on a time crunch.
> 1 votes

# Answer
Maybe you would have benefitted from the Editable Fields module (http://drupal.org/project/editablefields).

You can add the checkbox as a boolean field to the employee, I suppose, and then in the view choose "Editable" as Formatter. Works for more sophisticated stuff as Text fields etc. as well.
> 0 votes

---
Tags: 7, views, forms
---


title: delete/approve comment

text:
# Question
Title: delete/approve comment
How can the administrator delete an "impolite" comment and approve comments before publishing?

Globally speaking, what is the best management of the comments?

# Answer
You can set permissions for users - `Skip comment approval` in `admin/people/permissions/list#module-comment`(in drupal 7). After as admin you can manage your comments here - `admin/content/comment` you can approve comments, delete them or unpublish.
> 2 votes

---
Tags: 7, comments
---


# Question
Title: Setting field attribute as read only in hook_form_alter?
I'm trying to create a simple custom module to stop the Title of a specific node being edited.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'nodetitle_node_form') {
    unset($form['title']);
  }
}

```

Currently it just removes any reference to the Title from the edit pages. Does anyone know how I can set the Title field attribute read only?

# Answer
> 3 votes
You can use the #disabled attribute:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'nodetitle_node_form' && $form['nid']['#value']) {
    $form['title']['#disabled'] = TRUE;
  }
}

```

I made the assumption that you want this when editing nodes only (not when they are being added) which is what the `&& $form['nid']['#value']` part is for.

---
Tags: forms
---


title: Running JQuery code in Admin Overlay

text:
# Question
Title: Running JQuery code in Admin Overlay
I have an overlay module installed which allows my admin to open in an Overlay (Jquery Pop Up)

I want to run a specific JQuery code whenever admin page opens in an overlay. How can I do that?

# Answer
> 0 votes
Implement `hook_overlay_child_initialize()`

```
<?php

function YOURMODULE_overlay_child_initialize() {
  drupal_add_js(drupal_get_path('module', 'YOURMODULE') . '/YOURMODULE-overlay.js');
}

?>

```

and in file `YOURMODULE-overlay.js` add:

```
(function ($) {
  Drupal.behaviors.YOURMODULE = {
    attach: function (context, settings) {
      // Your jQuery code here
    }
  };
})(jQuery);

```

---
Tags: modal-dialogs, users
---


# Question
Title: Installed D7 with Minimal profile and root user do not have any role set to it. How to create a locked role for root?
Now I can create only simple role which can be easily edited and deleted. I need a role for root user (user ID 1) for some other modules that requires selecting a role.

Now installing minimal profile of Drupal my root user is roleless. Don't know how to call it.

In overall I need something that the root user would be undeletable/uneditable by any other admin who has power to edit users and permissions and roles.

# Answer
Navigate to `/admin/config/people/accounts#edit-admin-role` and select from the list which role should be treated as "Admin role".
> 2 votes

---
Tags: 7, users
---


# Question
Title: Webform many dropdownlist results saved under one unique field
I'm working with webform to collect information on car relliabilty level.

I've set one dropdownlist to allow user choosing a car brand. As a car brand is selected, only the coresponding dropdownlist, with car models, is showing up (done with Webform Conditional).

All is working fine, but I realize each model dropdownlist is saving data in its own field in the database.

I want to analyse results by car brand and car models. What would be the best way to proceed?

Saving all models in one fields, when data are submitted? Maybe with a hook
Merging all car models after data submission in one unique field?

My test: http://fiabilidad-coche.blg.lt/?q=node/10

Any help or hint would be greatly appreciated.

# Answer
Ok, I found a solution: I've used a presave hook. This hook is saving all values submitted by users in a hidden field called "model". A loop will be needed to read the 56 listboxes and save the only value the user have selected.

To do my test I've created a test webform, with only one listbox and one hidden field (this field created automatically my needed field "model" in my database). That speed up a little my tests:

First at all I've created a custom module with a "presave" hook In a new directory named "duplicated\_data", I have create two files:
data\_duplicate.info
data\_duplicate.module

In the info file I've declared my module

```
name = Data Duplicate
description = Duplication Data for Webform
core = 7.x
package = Webform
dependencies[] = webform

```

In the module file I've written my php code

```
<?php
function data_duplicate_webform_submission_presave($node, &$submission) {
  $component_id = 1; // dropdownlist cid = 1
  $mem = $submission->data[$component_id][0]; // retrieve the submitted value
  drupal_set_message('datos :'.$mem); // print the result
  $component_id = 2; // cid = 2
  $submission->data[$component_id][0] = $mem; // save the data in the hidden field
}
?>

```

Now I need to activate my custom module. Each time I make a choice in my dropdownlist/listbox and click on submit, the results will be saved in the database in both fields.

For my production webform , I need to create the loop in order to read all the 56 listbox values and save in my field "model" only the value from the selected listbox. It will be easy to catch it, because it will be the only one, different from NULL.

Hope it will be help somebody else!
> 2 votes

# Answer
Here I leave the final code:

```
<?php
function data_duplicate_webform_submission_presave($node, & $submission) {
  if($node->title == 'Encuesta') { // the hook will only work with this node
  for ($component_id = 2; $component_id < 58; $component_id++) { //loop into all my listboxes
  $mem = $submission->data[$component_id][0];
  if ($mem != NULL) { // save only data <> NULL => the user selected data.
  $submission->data[100][0] = $mem; // save the data in my field "model"
  drupal_set_message('Model : '.$mem); // optional, message with the value of the user selection.
  }
  }
  }
}
?>

```
> 0 votes

---
Tags: hooks, webforms
---


# Question
Title: How do I remove extra space in table field?
I'm using Views Module. I created a new ContentType with 3 custom fields: (text)Criteria, (decimal)Monthly, (decimal)Semester.

I created a table style view that retrieved the ContentType I created and dropped the values into a table. I'm actually using Javascript to grab the contents of each row generating a JSON array of objects with key-value-pairs for the content of the table, then I'm doing some fancy Javascript rendering. It's just a quick way to leverage Drupal's views and get the data where I want it exactly.

Anyway, when I grab the content of the Title row, `$(this).find('td.views-field-title a').text();`, it works fine, but when I try the exact same thing with the other 3 rows, I end up with a lot of space and `\n`. So my object ends up looking like:

```
[
 {'title':'Correct Title','criteria':'\n     Criteria Title    ','monthly':'\n     $70.00     '},
 {...},
 {...}
]

```

I can't figure out where the `\n` and extra space is coming from. It seems to be how the view formats the fields. How can I get rid of those?

Note: I do have the fields set to Plain Text in the configuration.

# Answer
I checked this in my site and this is indeed default behaviour of Views. The easiest way to fix this is by changing your code to:

```
$.trim($(this).find('td.views-field-title a').text());

```
> 0 votes

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


title: Image not showing in Drupal 7

text:
# Question
Title: Image not showing in Drupal 7
Site is hosted in fasthosts wherein `<IfModule>` is not supported so they advice me to edit `.htaccess` to something like this.

```
Comment,
Order allow,deny
</FilesMatch>
Options –Indexes
Options +FollowSymLinks
DirectoryIndex index.php
Enable expirations
ExpiresActive On
ExpiresDefault A1209600
ExpiresByType text/html A1

```

Sample:

```
#<FilesMatch
#"\.(engine|inc|info|install|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl|svn-base)$|^(code-style\.pl|Entries.*|Repository|Root|Ta
#g|Template|all-wcprops|entries|format)$">
# Order allow,deny
#</FilesMatch>

```

It solved my first issue, 500 error.

This time, another error is showing, images are not correctly showing and css. Instead of the path to be `site.com/drupal installation/` image of path, image address become `site.com/image of path`.

By the way, I am installing drupal in a sub folder. `site.com/dupalHere`

# Answer
> 0 votes
Add line

```
RewriteBase /dupalHere

```

to your `.htaccess` file.

---
Tags: uri
---


# Question
Title: Add div after each field of a certain name
I'm trying to display a div container after each field item with the name additional\_content of my page content type. Right now im trying to preprocess my field but i can't go down to the real field item i want to proprocess...

Is it better to override the template? And how would that work? i have a field called additional\_content integrated into my page content type. After this has been printed i want to add a div container to each of this items.

Any help with that?

# Answer
> 1 votes
Copy `modules/field/theme/field.tpl.php` file into `sites/all/themes/YOUR_THEME/templates`

Rename it to `field--additional_content--YOURCONTENTTYPENAME.tpl.php`
(or only `field--additional_content.tpl.php` if you want to change its template for all content types)

Edit its template like this:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
      <div class="your-additional-div"></div>
    <?php endforeach; ?>
  </div>
</div>

```

---
Tags: entities, theming
---


title: date information in another language

text:
# Question
Title: date information in another language
In order to display the date information in French, I have modified the node.tpl.php file as follows.

```
 print t('publié le !datetime',
      array('!datetime' => format_date($variables['node']->created, $type='medium', $format = 'D j F Y', $timezone = NULL, $langcode = 'fr'))
 );

```

The week day, and the month are still displayed in English!

# Answer
> 0 votes
Add this to your template.php file.

```
function THEMENAME_preprocess_node(&$variables) {
  $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
}

```

You might need to add this to your node.page.tpl file.

```
$variables['submitted'] = t('Submitted on !datetime', array('!datetime' => $variables['date']));

```

The source is this post.

---
Tags: nodes
---


# Question
Title: drush open_basedir restriction in effect on media temple
I'm using drush on mediatemple grid service. I think i've got setup drush correctly. At least to my knowledge. I've been able to use it; but with nagging errors/warnings each time.

And whenever i invoke drush i get these errors:

`The following restricted PHP modes have non-empty values: check your configuration settings in /usr/local/php-5.2.14/etc/php.ini or in your drush.ini file`

Anyone have any clues how to rectify this?

# Answer
> 0 votes
Setting an alias for drush allowed me to fix this issue:

> alias drush='/usr/bin/php5 -c /home/000000/etc/drush.ini ~/bin/drush/drush.php'

# Answer
> 1 votes
```
drush topic docs-ini-files

```

That command tells more about creating a drush.ini file. In it, you want to remove the listed restrictions (you didn't provide them).

# Answer
> 0 votes
Because making an alias for `drush.php` is not covered in `drush-5.x` Readme file. A better solution is to copy the server's default configuration `php.ini` file to `$HOME/.drush` or to `/etc/drush`.

Then, edit it to set `open_basedir` to no value and add any other custom configuration for crush.

Sample of drush specific `php.ini` file:

```
# Drush configuration
open_basedir=
safe_mode=
disable_functions=
disable_classes=
magic_quotes_gpc=

```

Hope this helps.

---
Tags: drush
---


# Question
Title: How do I remove a character from the replacement pattern?
In view I call the field *field\_store\_car\_model*

**settings of this field:**

formatter: link result URL is:`veyron-164`

So far as expected.

---

But I need this URL: `vehicles/veyron-164`. Because of this I have to rewrite the link.

I check rewrite result, format is plain text, I write in the field `vehicle/[field_store_car_model]`

**Result here:** `vehicles/veyron-16.4`.

Now I have this punctuation in the URL! where does the decimal point come from? From my vocab because view grabs the term BEFORE pathauto cleans it up.

So how can I **get rid of the decimal point**? I am sure there is some PHP but WHERE I have to put the PHP code?

Any ideas?

# Answer
> -1 votes
I'm not sure I completely understand your question. But I'm guessing this is what you're looking for.

* In Views, under FIELDS, click on the name of your field
* Click on REWRITE RESULTS
* Enable Output this field as a link
* In Link path, insert something like **vehicles/\[field\_store\_car\_model\]**, where \[field\_store\_car\_model\] is one of the available Replacement patterns.

Hope this helps.

---
Tags: views
---


title: Drupal web page logging

text:
# Question
Title: Drupal web page logging
I have a website built on drupal. I want to log (preferably db log) all the calls being made to a drupal page. The drupal page is called as shown here

`http://www.example.com/page-name?url=example2.com&redirect=example3.com&uid2=randomNumber`

I need to log all URL fields (url,redirect,uid2) alongwith timestamp and drupal user id.

Whats the best way to do it?

# Answer
> 2 votes
Create a custom module, for example:

`MODULENAME.install` file with `hook_schema()` implementation:

```
<?php

/**
 * Implements hook_schema()
 */
function MODULENAME_schema() {
  $schema['MODULENAME'] = array(
    'description' => 'Description of the table.',
    'fields' => array(
      'timestamp' => array(
        'description' => 'Timestamp of the rquest.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      // definitions for the rest of fields here
    ),
    'indexes' => array(
      // define indexes
    ),
    'primary key' => array('NAME_OF_PRIMARY_KEY_FIELD'),
  );
  return $schema;
}

?>

```

`MODULENAME.module` file with `hook_menu()` implementation:

```
/**
 * Implements hook_menu()
 */
function MODULENAME_menu() {
  $items['page-name'] = array(
    'title' => 'Example title',
    'access callback' => TRUE, // imply no restrictions
    'type' => MENU_CALLBACK,
    'page callback' => 'MODULENAME_pagename_view',
  );
  return $items;
}

function MODULENAME_pagename_view() {
  global $user;
  // insert into Drupal database
  db_insert('MODULENAME')
    ->fields(array(
      'timestamp' => REQUEST_TIME,
      'user_id' => $user->uid,
      'url' => $_GET['url'],
      'redirect' => $_GET['redirect'],
      'uid2' => $_GET['uid2'],
    ))
    ->execute();
}

?>

```

---
Tags: views
---


title: Calendar - current week

text:
# Question
Title: Calendar - current week
I am looking for a way to add a class to the week row indicating whether the week is the current week.

The week is rendered by `calendar-month-row.tpl.php` and the arguments are passed within `calendar_build_month()`.

What is the "Drupal way" of intercepting this procedure?

I of course do not want to hack the module to generate the desired output.

# Answer
> 0 votes
Copy template file
`sites/all/modules/calendar/theme/calendar-month-row.tpl.php`
to
`sites/all/themes/YOUR_THEME_NAME/templates` directory and edit it in this manner:

```
<?php
/**
 * @file
 * Template to display a row
 *
 * - $inner: The rendered string of the row's contents.
 */
$attrs = ($week > 0) ? 'week="' . $week . '"' : '';
$attrs .= ($iehint > 0) ? ' iehint="' . $iehint . '"' : '';
if ($week == date('W')) $class .= ' calendar-current-week';
$attrs .= ($class) ? ' class="' . $class . '"': '';
?>
<?php if ($attrs != ''):?>
<tr <?php print $attrs?>>
<?php else:?>
<tr>
<?php endif;?>
  <?php print $inner ?>
</tr>

```

Don't forget to clear page cache after this.

---
Tags: views, 6, datetime
---


# Question
Title: How do I programmatically generate a menu based on field values?
I'm working on a site where I want to have a menu that displays links based off of the content of a certain field.

For example, lets say it is `int field_apples`. I want to automatically generate a menu that will have links to lists of articles with each value of apples (or a range of apples such as ≤9 apples).

* Apples menu
    + 1 apple
    + 2 apples
    + 3 apples
    + 7 apples
    + 9 or more apples

Each link above will show a list of articles for that particular value of apples.

# Answer
This could be achieved by using taxonomy to define your terms and the Taxonomy Menu module to create the menu from these terms. Taxonomy is the preferred method for categorising content.
> 1 votes

# Answer
I haven't found anything that will programmatically build a list based on each value of a field. Instead I had to use views to build a report for each possible value of the field. I used a list of integers to keep the permutations manageable. This is far from ideal, but workable. It just means I have a lot more work to do to maintain it if I make any changes.
> 0 votes

---
Tags: entities, routes
---


# Question
Title: How does a Webform able to differentiate among radio buttons, check boxes and Lists
I am using **webform module** to build forms. Initially i created a simple form with few components like **text-field**, **text-area**, **radios**, **check boxes** , **Drop down list** and submitted it.

When i checked the database, I found that the module is storing type "**select**" for the components radio, check boxes and lists in table name "**webform\_component**". I want to know how can we **differentiate** them.

Please check the screenshot,

While creating the form i choose the following parameters

**Gender** ----\> **Radio**

**Range** ----\> **List**

**Hobbies**----\> **Checkbox**

But in the table it was shown as "**select**" for all the fields

Can anyone suggest the way to find out ?

# Answer
> 0 votes
the `webform_component` table also has an `extra` column you've cropped out.

It's SQL column help description is:

> Additional information unique to the display or processing of this component.

A `select` can simply be rendered many ways -- I believe the display settings for the "selectable options" used in rendering a radio, list or checkbox are in that column.

---
Tags: 7, webforms
---


title: Views sliding pager

text:
# Question
Title: Views sliding pager
I googled so much time but i couldn't find what i'm looking for.
My views i have a image slideshow and pager for it, i set the pager as field and selected image field(thumbnails).
i select a controller too in the bottom but what i need is when click on next or previous links the pager(Thumbnails) only must go (sliding) right or left according to the direction.
Description:

# Answer
> 1 votes
Use this module http://drupal.org/project/views\_galleriffic, it will match your requirement and use css for customization.

Hope it helps you!.

# Answer
> 0 votes
firs : Set the number of item in the pager or make it to display all item
Second : on the setting of slide show use the controller (prev, next) use this model is simple and useful for you Views Slideshow

---
Tags: 7, views
---


# Question
Title: How can I create bidirectional node references?
I want to have a node reference for a content type. I have two content types A and B. I want to reference content B from a field in content type A. In the same way I want to refer content type A from content type B. What I want is If I referenced content type B from content type A, Ta field should be added automatically to content type B with reference to content A.

Linking from A to B should make it linking from B to A too. Both should have updated fields for this.

How can I do this? Which module can I use for this?

# Answer
> 4 votes
There has been a lot of movement around this subject lately.

The state of the art module seems to be Entity Reference.

It may lack some functionality you're asking for, so cnr may be of help too.

# Answer
> 2 votes
Well, I found a solution that sort of works, the basic functionality works exactly like you describe, my problems with it are more around the edges (but I will put those in a separate question). The only way I found to do this using existing modules and no custom code is using the References Module This is a bit dated module, and hopefully in the future, Entity Reference will have the needed functionality, but it doesn't at the moment...

OK, so after you install the References Module, you need to install the Corresponding node references module and follow the exact instructions on the module page:

* To install enable the module at admin/build/modules
* Create node type A
* Create node type B
* Create a node reference field on node type A pointing to node B
* Create a node reference field on node type B pointing to node A
* Go to the settings page at **admin/config/system/corresponding\_node\_references**. Select to enable the corresponding referencing for these node types pointing to each other.
* Create some nodes and reference them to each other

From that moment on, once you reference it one way, the other way synchronizes by itself (using the newer Entity Reference module you have to do this manually).

Hope this helps.

# Answer
> 1 votes
The Relation module gives bidirectional references and more. It creates a node to describe the relationship which can itself can have fields. That lets you do things like describe how/why one node relates to another, for example, was the Person entity a director/actor/taxonomy term in the Movie entity it relates to?

# Answer
> 1 votes
Working with "entity reference" module which can be extended with (Entity)Reference Field Synchronization module (http://drupal.org/project/ref\_field) to synchronize two entities, fields next article/ previous article for example. When "next article" is set in article A, "previous article" is synchronized in article B. There is currently an error message when installing, but a patch is available here : http://drupal.org/node/1670356 and works just fine.

# Answer
> 0 votes
I think you can write your module and you need provide this hooks:

```
//create relation
function hook_node_insert($node) {
  switch($node->type):
    case 'A':
      update refereed node from type B
    break;
    case 'B':
      update refereed node from type A
    break;
  endswitch;
}
//update relation
hook_node_update()
//delete relation
hook_node_delete()

```
1. http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook\_node\_insert/7
2. http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook\_node\_update/7
3. http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook\_node\_delete/7

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


# Question
Title: Drupal 7 Draggable Views in different order when logged in
My site is : www.terrafirmasouth.co.uk I have draggable views set up for projects, I have a menu option called 'Sort Projects', certain users can access this to rearrange projects, if they have a role called 'publisher' . I have given the Publisher role access to 'Sort Draggable Views' in People/Permissions (but not for anonymous users). When they are logged in, they can rearrange projects under a Sort Projects menu item (path is 'sort-projects'), and the order seems fine, then when they log out the order just reverts back to what it was before the update. When they log back in again, the order to retained from the previous update. When I log in as administrator and do the same thing i.e. change order of a project, the order is fine , and when I log out.

Is there some other permission I need to set for anonymous users so they see they updated order? Also, on the Sort Projects screen, it doesnt show 'updated successfully or saved' in green at the top which I would normally expect, i dont get any message, other than the spinning circle at the top, then it finishes as normal. Any ideas?

# Answer
> 1 votes
This can be resolved by following this link:- http://drupal.org/node/616658

Scroll to the bottom, and follow instructions in the last Post whereby you install the Rule module, create a rule to clear cache on sorting a View, you may have a problem where the option to create custom PHP is not in the drop down list, if so, this is resolved by enabling the 'PHP Filter' module.

All tested and works perfectly ! :)

# Answer
> 0 votes
Draggable views doesn't suits you.

You have to create your own views handler to allow each user to have it's own elements order.

---
Tags: views
---


# Question
Title: Exposing a single field to users to create new nodes from a page
I am researching if Drupal is the right choice for my project and so far it seems like it fits, except for one issue. I want to give my users ability to create new nodes from a page, let's say it could be something like creating a Facebook status and would reside at /statuses.

Then these nodes could be visible to other users from the same /statuses page. I don't want my users to deal with publishing and path and all those other options that are available via general Create New Node form - I just want to expose one field that they can fill out on /statuses, hit Submit and then have Drupal do the rest.

Is Drupal suitable for such tasks and what would be the most Drupal way to do it?

I am fairly new to Drupal but have tons of experience with other CMSs and frameworks.

---

Edit

I am not looking to create specific feed Facebook/Twitter functionality - it was just an example. The functionality that I am going to create will include much more than that. Feeds were just an example - sorry if I gave the impression that it's what I want to make.

The question is what would be the most Drupal-way to expose a single form field that will allow users to create a new node from a page.

---

Edit

Here's a mockup of the form and page that I want to make. So what would be the best way to proceed?

# Answer
> 1 votes
So you want to create something like simplistic Twitter/Facebook wall? Check following modules:

## Microblog

> Users can publish microblog updates, follow and be followed by other users, and reply to other users' microblog updates.
>
> Module also provides "public timeline" page as well as followers and following pages, and a block of "recent microblog updates."

Drupal 6 & 7: https://drupal.org/project/microblog

## Statuses (Social Microblog)

> Provides status updates / microblogs like Facebook's Wall / News Feed, Twitter's Timeline, and Yammer's Feed. Users can update their own status or write messages to other users, nodes, Organic Groups, taxonomy terms, or other entity types. @mentions and #hashtags are supported, as well as comments on status updates, viewing conversations between users, the ability to "like"/"reply" to/RT a message, automatic updates without page refreshing, and integration with over 20 modules.

For Drupal 6: https://drupal.org/project/facebook\_status
For Drupal 7: https://drupal.org/project/statuses

# Answer
> 0 votes
You can create activity streams or Facebook-like statuses with the Message module. Check it out.

---
Tags: 7, forms
---


# Question
Title: How can I recognize when the user is editing or inserting something?
I have a form which adds some information. I used `hook_form()` for inserting and loading data. units/add calls the form to insert data and units/%unitid/edit calls the form to edit data. In `hook_form_submit()`, how can I recognize when the user is editing or inserting something? Should I use `$delta`, or is it no longer available in Drupal 7?

# Answer
Field `nid` is unset if node is created. Optionally, you can check if `arg(1) === 'add'`
> 1 votes

---
Tags: forms
---


# Question
Title: Node/add and node/edit do not display forms
I am logged in as an admistrator account and all relevant permissions are enabled for admistrators(some rights to delete a few types are disabled).

When I attempt to edit or create an event I get a page with a bread crumb, a title and no actual form or styling. I checked the html and the form isn't being sent and just not displayed either. I am using drupal 7.14 and this setup was working before moving it to another server.

# Answer
According to the person who resolved the issue memory\_limit on the server was the problem.
> 0 votes

---
Tags: nodes, theming
---


# Question
Title: How to create language object from language string (e.g. 'en')?
As in question, ofcourse I am asking about Drupal function for this job.

So I need function that get language string as param (e.g 'en','pl' etc) and returns me standard Drupal language object. Similar to global $language.

# Answer
> -1 votes
I would use the following code; with `mymodule_get_language_obj($name, FALSE)` you get a language object only if it has been enabled.

```
function mymodule_get_language_obj($name, $all = TRUE) {
  if ($all) {
    $languages = language_list();
  }
  else {
    $languages = language_list('enabled');
    $languages = $languages[1];
  }

  return isset($languages[$name]) ? $languages[$name] : NULL;
}

```

Notice that on Drupal 7.43 (and possibly, on previous Drupal 7 versions), `language_list()` returns an array of objects, contrary to what reported in a comment posted in the documentation page.

> When calling:
>
> ```
> <?php
>   $languages = language_list('enabled');
> ?>
>
> ```
>
> You can expect the return value to be:
>
> ```
> <?php
> $languages = array(
>     '1' =>
>         array(
>             'en' => array('language'=>'en', 'name'=>'English', ... ),
>             'fr' => array('language'=> 'fr', 'name' => 'Francais', ... ),
>         )
>     );
> ?>
>
> ```
>
> The index being 1 because it's the value of the 'enabled' column.

With Drupal 7.43, I obtained the following:

### *Locale* module not installed

* Output of `print_r(language_list('enabled'));`

```
    Array(
      [1] => Array(
        [en] => stdClass Object(
          [language] => en
          [name] => English
          [native] => English
          [direction] => 0
          [enabled] => 1
          [plurals] => 0
          [formula] =>
          [domain] =>
          [prefix] =>
          [weight] => 0
          [javascript] =>
        )
      )
    )

```
* Output of `print_r(language_list());`

```
    Array(
      [en] => stdClass Object(
        [language] => en
        [name] => English
        [native] => English
        [direction] => 0
        [enabled] => 1
        [plurals] => 0
        [formula] =>
        [domain] =>
        [prefix] =>
        [weight] => 0
        [javascript] =>
      )
    )

```

### *Locale* module installed, and *Esperanto* enabled as additional language

* Output of `print_r(language_list('enabled'));`

```
    Array(
      [1] => Array(
        [en] => stdClass Object(
          [language] => en
          [name] => English
          [native] => English
          [direction] => 0
          [enabled] => 1
          [plurals] => 0
          [formula] =>
          [domain] =>
          [prefix] =>
          [weight] => 0
          [javascript] =>
        )
        [eo] => stdClass Object(
          [language] => eo
          [name] => Esperanto
          [native] => Esperanto
          [direction] => 0
          [enabled] => 1
          [plurals] => 0
          [formula] =>
          [domain] =>
          [prefix] => eo
          [weight] => 0
          [javascript] =>
        )
      )
    )

```
* Output of `print_r(language_list());`

```
    Array(
      [en] => stdClass Object(
        [language] => en
        [name] => English
        [native] => English
        [direction] => 0
        [enabled] => 1
        [plurals] => 0
        [formula] =>
        [domain] =>
        [prefix] =>
        [weight] => 0
        [javascript] =>
      )
      [eo] => stdClass Object(
        [language] => eo
        [name] => Esperanto
        [native] => Esperanto
        [direction] => 0
        [enabled] => 1
        [plurals] => 0
        [formula] =>
        [domain] =>
        [prefix] => eo
        [weight] => 0
        [javascript] =>
      )
    )

```

The equivalent code for Drupal 8 would be the following one.

```
function mymodule_get_language_obj($name) {
  $languages = \Drupal::languageManager()->getLanguages();

  return isset($languages[$name]) ? $languages[$name] : NULL;
}

```

Note that Drupal 8 version of the code returns instances of the `Locale` class, not the `stdClass` class.

# Answer
> 9 votes
Use `language_list()` function:

```
<?php

function get_langugage_object($language) {
  $installed_languages = language_list();
  return $installed_languages[$language];
}

?>

```

---
Tags: 7, i18n-l10n
---


# Question
Title: Mapping a csv field to Meta Title and Meta Description using feeds and metatag
I have a csv of node data that I want to import into drupal. I'm using the `feeds` parse, and I can map the Page Title, Body, and other fields just fine. The issue I'm having is trying to map the CSV fields to the Meta Tag and Meta Description items (provided by the metatag module). Since metatag does **not** store it's information as a drupal field, I cannot map it with the feeds UI.

One possible solution I have considered is to use a metatag module that does use node fields to store meta data, but that would require a shift in the way our content editors handle things, and the installation of that seperate module on all of our maintained sites. I'd rather just use feeds with `metatag`

I'm a beginner when it comes to using the feeds api, and want to know if it is possible to write a custom mapping function that could populate metatag data for nodes from a feeds import.

# Answer
> 2 votes
You could create fields for the metadata, hide them in "Manage display" and map them to the Metatag module (add the field tokens as content), as I described in the answer to "How can to make required the fields keywords and description of the metatags module?".

Now in your CSV import you add the metadata to your manually created fields, and the Metatag module will fetch the content.

---
Tags: feeds, meta-tags
---


# Question
Title: Can you create a new block region using just a module?
I am writing a module that will, using javascript, create a slide down container at the top of the page. (modelled on the login here http://xenforo.com/community/).

Rather than hardcode the content in this slide-down region, I'd rather just create a new block region, and let the user put whatever blocks into it he/she sees fit.

The thing is, this sort of thing would normally be done with the theme, not with a module. Is it possible to define a new block region using a module, and if so, how?

# Answer
> 10 votes
hook\_system\_info\_alter is your friend.

```
<?php
/**
 * Implements hook_system_info_alter()
 * Adds a new "tray" region to the current theme
 */
function MODULE_system_info_alter(&$info, $file){
  global $theme;

  // If non-default theme configuration has been selected, set the custom theme.
  $custom_theme = isset ($theme) ? $theme : variable_get('theme_default', 'bartik');

  if ($file->name == $custom_theme){
    $info['regions'] = array_merge($info['regions'],  array('tray' => t('Tray')));
  }
}

```

# Answer
> 1 votes
Not possible. All regions are defined in `.info` file of theme and your theme templates must contain code which print content of region somewhere in a page.

# Answer
> 0 votes
There are 'blocks' and there are 'regions'. You can put blocks into regions. You don't need to know what regions someone has on a site in order to create a block, which is what I believe you're wanting to do.

In order to create a block, at a minimum you need to define what is listed in the drupal blocks listing, i.e. "My lovely block"; what happens to it if displayed, i.e. add my lovely javascript, output this html, etc. You can also add configuration options etc. depending on your particular requirements.

There are plenty of examples of block code throughout the core and contrib drupal modules so feel free to look up the code, also see:

http://drupal.org/project/examples http://api.drupal.org/api/drupal/modules!block!block.api.php/7

---
Tags: 7, blocks
---


title: How do I insert HTML onto every page?

text:
# Question
Title: How do I insert HTML onto every page?
I've got the following code in my module. I'm trying to get it to insert some HTML, ideally at the start of `<body>`, but it seems that my call in `hook_init()` isn't working - what would be the right hook to call this in? I'm hoping it will just render slidedown.tpl.php after `<body>`.

```
<?php
function slidedown_init() {
    drupal_add_js(drupal_get_path('module', 'slidedown') . '/slidedown.js');
    drupal_add_css(drupal_get_path('module', 'slidedown') . '/slidedown.css');
    slidedown_insert_html();
}

function slidedown_insert_html() {
    return theme('slidedown_template');
}

function slidedown_theme() {
    $themes = array (
        'slidedown_template' => array(
            'template' => 'slidedown', // your template file called slidedown.tpl.php
            'arguments' => array(),
        ),
    );
    return $themes;
}
?>

```

# Answer
> 4 votes
You probably want `hook_page_build()`:

```
function slidedown_page_build (&$page) {
  $path = drupal_get_path('module', 'slidedown');

  drupal_add_js($path . '/slidedown.js');
  drupal_add_css($path . '/slidedown.css');

  $page['page_top']['slidedown_template'] = array(
    '#weight' => -1000,
    '#markup' => theme('slidedown_template'),
  );
}

```

I can't remember if that hook is too late to add JS and CSS. You may need to put those in a `template_preprocess_html()`. That is a better choice that `hook_init()`.

# Answer
> 1 votes
The template page.tpl.php and its variants define what is placed within the \<body\>\</body\> tags.

It will probably be better to define a region in page.tpl.php and place it where you want. Then render your slideshow in this region.

For more information check out How the Drupal theme system works.

---
Tags: 7, theming, hooks
---


title: How to alias / rewrite path to theme?

text:
# Question
Title: How to alias / rewrite path to theme?
The paths to css/js/images in a theme look like /sites/mysite.org/theme/\*

Is there a way to rewrite those paths to – let's say – /mytheme/\* ?

# Answer
> 2 votes
URL mappings can be altered with two hooks: `hook_url_inbound_alter()` and `hook_url_outbound_alter()`.

`hook_url_inbound_alter()` is used for paths that Drupal is responding to. See `drupal_get_normal_path()`.

`hook_url_outbound_alter()` is used for paths constructed by `url()`.

Whether or not you can accomplish this will require some experimentation, as I don't know how the theme registry will complicate matters.

---
Tags: path-aliases
---


# Question
Title: how to map fields in feeds module with csv that has no headers?
Can feeds module still know how to map the fields correctly even if there are no headers in a .csv file. I am trying to migrate sample data from database which i exported to a .csv file through phpmyadmin. i am testing the feeds module if it can handle large file migrate.

if the answer is no, can i manually input the headers in the excel files? or it has to be exported again with headers?

# Answer
The Feeds module support CSV files without column headers. On admin/structure/feeds/foo\_importer/settings/FeedsCSVParser, you just need to select "No Headers". Then on admin/structure/feeds/foo\_importer/mapping, you use the column numbers for the source.

Be careful when entering the Name of source field. Your first column is named '0', the second '1' and so on.
> 4 votes

---
Tags: feeds
---


# Question
Title: Is it possible to render an Adsense Block as a custom field block in Drupal?
I'm trying to add an adsense banner inside my content and Drupal's Adsense regular module doesn't do that. It can only add Adsense in one of my regions but none within articles. Would that be possible using Display Suite?

# Answer
You can use Block Inject to create an arbitrary region in your node body. Then place the adsense block in that region. (Please be aware of this issue.)

On a page by page basis, you can also use Insert Block, but there are limitations.
> 0 votes

---
Tags: display-suite
---


# Question
Title: What am I doing wrong with accessing this array element?
```
  $form['cookie']['saved'] = array(
    '#type' => 'textfield',
    '#title' => 'How long?',
    '#required' => TRUE,
  );

```

But if I do:

```
  if ($form_state['values']['cookie']['saved'] == 'Dog the Bounty Hunter') {
    form_set_error('dog_error', t("That doesn't make any sense."));
  }

```

I get an error that the 'cookie' index doesn't exist.

# Answer
> 3 votes
Install the development module and do `dpm($form, 'the form');` and `dpm($form_state, 'my form state');` in your form alter function. I believe you'll see that `$form_state` is "flattened" to only the innermost values of your form array.

So, the `saved` array key exists, not `[cookie][saved]`.

*In general try to make use of this convention, or assumption by drupal.* Usually your FAPI form has fieldset(s) as outer keys (not passed into $form\_state at all, they only affect the appearence of the form) and input values as inner keys. So rename your 2nd key from `saved` to `cookie_saved`.

If you really (for some reason) want the `['cookie']['saved']` to be in `$form_state` just as-is -- perserving the hierarchy of information. You would want to set the `#tree` property of `cookie` in your FAPI array.

See these 2 resources of information:

Both are relevant for background information how FAPI usage and how its evolved to meet our needs as developers. Search for `#tree` and `#parents` within the linked documentation pages.

# Answer
> 0 votes
Array 'cookie' using only to group form items but to get value you need to use 'saved' key:

```
if ($form_state['values']['saved'] == 'Dog the Bounty Hunter') {
  form_set_error('dog_error', t("That doesn't make any sense."));
}

```

---
Tags: 7, forms
---


# Question
Title: Cannot import multiple nodes in feeds module using csv files
Im trying to import these files into nodes in my drupal 7 site

i used the no header and i mapped the columns into numbers (0,1,2. ..)

but i end up only getting only 1 node.

The alert says "created 1 node, updated 19 nodes" how come?

# Answer
You file shows 20 rows. From your description, I bet that the GUID has been the same for each import, and you have actually created one node 20 times. (Created once then updated 19 times.) You need to define a unique field in each record, with a corresponding unique field in your node (eg guid). Then feeds will map that field to determine which nodes to create (no nodes with matching unique field) or to update (node has a matching field).

Try using the Title field as unique instead of guid.
> 2 votes

---
Tags: feeds
---


# Question
Title: views display restricted number of results based on nid
Is it possible to create a view which would show only 3 rows. Based on curent node (nid) show result before current row and show one row after this row.

# Answer
> 0 votes
You can do this by using the `Node: Nid` filter.

1. Add the `Node: Nid` filter
2. Select **Operator** \> **equal to** \> **Is between** and then select the nid before your node as the **Min** and the nid after your node as the **Max**.

---
Tags: 7, views
---


title: Autocomplete results in a HTML listbox

text:
# Question
Title: Autocomplete results in a HTML listbox
I am using autocomplete from drupal so that users can be guided into finding what they are looking for. For an even better user experience it would be great if autocomplete is returning the results in a listbox. I just started to learn drupal programming (and loving it :) ) but I can't find anything on this particular question.

At this moment when I start typing in a textarea, drupal will show a selection of approx. matches in a pulldown list. How do I get those matches in a html listbox?

I am using the code below for autocompletion

```
/**
* autocomplete helper
* $string = string for search
*/
function _complete_autocomplete($string) {
  $matches = array();
  $result = db_select('notebooks', 'c')
    ->fields('c', array('product'))
    ->condition('product', '%' . db_like($string) . '%', 'LIKE')
->range(0, 10)
    ->execute();

  // save the query to matches
  foreach ($result as $row) {
    $matches[$row->product] = check_plain($row->product);
  }
  // Return the result to the form in json
  drupal_json_output($matches);
}

```

# Answer
Okay I got a bit working. But it only fills the select options after the textfield is losing focus. How can I make it so that while typing in the textfield, the select options is filled with data. Kinda similar as to autocomplete?

And another question, if i press enter I get an HTTP error . An Ajax HTTP request terminated abnormally. path: /?=system/ajax status : text responsetext: ready/state:4

Any ideas why this is happing?

```
<?php

function dropdown_menu(){

$items['test/drop'] = array(
'title' => 'Fill select options from db',
'page callback' => 'drupal_get_form',
'page arguments' => array('select_dropdown'),
'access callback' => TRUE,
'weight' => 4,
'type' => MENU_NORMAL_ITEM,
);

return $items;
}

function dropdown_submit($form, &$form_state) {
//dpm($form);
drupal_set_message('Submit handler was called.');
}

function select_dropdown($form, &$form_state) {

$form['searchfield'] = array(
        '#title' => t('Search database and fill select options'),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#maxlength' => 115,
        '#size' => 55,
        '#weight' => 0,
'#default_value' => 'look for it',
'#ajax' => array(
  'event' => 'change',
  'callback' => 'search_db',
  'wrapper' => 'dropdown-second-replace',
),
    );

  // Get the list of options to populate the first dropdown.
$options_first = _drop_get_first_dropdown_options();
$selected = isset($form_state['values']['searchfield']) ? $form_state['values']['searchfield'] : key($options_first);
$form['dropdown_second'] = array(
'#type' => 'select',
'#title' => 'Options filled from db',
'#prefix' => '<div id="dropdown-second-replace">',
'#suffix' => '</div>',
'#size'=>10,
'#options' => _drop_get_second_dropdown_options($selected),
'#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
);

//  $form['submit'] = array(
// '#value' => 'Submit',
//   '#type' => 'submit',
// '#submit' => array('dropdown_submit')
// );

  return $form;
}

function drop_dependent_dropdown_callback($form, $form_state) {
return $form['dropdown_second'];
}

function search_db($form, $form_state) {
return $form['dropdown_second'];
}

// normally pulling data from the database.
function _drop_get_first_dropdown_options() {
return drupal_map_assoc(array(t('empty')));
}

function _drop_get_second_dropdown_options($key = '') {
$matches = array();
$result = db_select('tabel', 'c')
->fields('c', array('product', 'xtra'))
->condition('product', '%' . db_like($key) . '%', 'LIKE')
// ->range(0, 10)
->execute();

// save the query to matches
foreach ($result as $row) {
$matches[$row->product] = check_plain($row->product) . ' xtra:' . ($row->xtra);
}
return($matches);

}

```
> 1 votes

---
Tags: ajax
---


# Question
Title: How can I stop js script from running on mobile?
I need some help with a Zen subtheme using responsive-sidebars.css I have some javascript that I only want to run if the screen is bigger than 480px. The javascript is:

```
(function ($) {
        jQuery(document).ready(function(){
         $('#selllink').trigger("click");
       });
    })

```

I am not sure how I would restrict this. Many Thanks Julie

# Answer
> 1 votes
You can deetect the screen size in Vanilla JS or jQuery. In jQuery you can use `height()` and `width()` to get screen size. So you can try this

```
jQuery(document).ready(function(){
  if($(window).width() > 480){
    $('#selllink').trigger("click");
  }
});

```

You could also use `resize()` to check for window resize event.

---
Tags: javascript, theming
---


title: Update field via url

text:
# Question
Title: Update field via url
Is it possible to modify a field on a node via a url string? For example, my node (1) has a field (field\_stage) which I'd like to update using the following url:

www.mysite.com/node/1?field\_stage=complete

I can't seem to find a lead on this. Any help is greatly appreciated.

# Answer
> 1 votes
There's the Prepopulate module

> The Prepopulate module allows fields in most forms to be pre-populated from the $\_REQUEST variable.
>
> For example, the following URL,
>
> *http://www.example.com/node/add/blog?edit\[title\]=this is the title*
>
> will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well.

It's only in dev for Drupal 7 but I've used it in a couple of projects and I haven't had any major problems. If it doesn't quite match your use case you could always take a look at the code, it shouldn't be that tricky to adapt for other purposes.

---
Tags: entities, uri
---


title: Field access for specific nodes

text:
# Question
Title: Field access for specific nodes
I have a node type called 'basic' with 10 nodes and a bunch of fields. However, I want to add a field that is specific to only one node. What is the best way to do that?

At the moment I've got a custom field and I'm hiding it using hook\_form\_alter() `['#access'] = FALSE` (and hiding visibility via the UI), so it's not editable or visible for the other 9 nodes, which works but I'm worried this isn't the best way performance wise. Aren't those field tables then being joined for every node call?

Using the Form API isn't an option because I want to take advantage of the field widgets (using unlimited values etc).

Any ideas?

# Answer
Dealing with such a limited number of nodes, my first reaction would be to clone the content type, say 'basic\_extra', and add the field to the clone. Just make sure to change the scope of any views including 'basic' to include both. It would eliminate a lot of work for only one node.
> 1 votes

---
Tags: entities
---


# Question
Title: How to embed a view into the teaser of a node?
On the main page, I have a view that lists 3 items (3 boxes). One of them is linking to the news section. Right now, it's only a plain node and only the teaser is displayed on the front page.

If it's possible, I want to include the top 3 news headlines within the teaser of this node. Basically this will be a view inside of a teaser that is also listed to the front page by a view.

I might succeed with this method but I want to avoid using PHP as a text format. Should I just create a module and insert the view into the teaser by code? Is there a more convenient way?

# Answer
You can install and activate the Field views module, and add the field type to your content type. Configure it for your view.

Then edit your content type, and under 'Manage Display' configure the field to be visible in your teaser.
> 2 votes

---
Tags: views, nodes
---


# Question
Title: Automatically fill in "City" field when "Postal code" is entered
I encountered a problem that has been discussed many times but for which no solution has been written down yet. This is about Drupal 7.

On my node add form, I have an "Address" field; a field collection item that consists of a "Postal code" field, a "City" field, and some other fields. All addresses will be German addresses and in Germany a 5-digit postal code *uniquely* determines a city, i.e. no two cities have the same postal code. I would like to manipulate the node add form such that when a postal code is entered, the city field is automatically filled in.

http://www.zippopotam.us offers an API that lets me achieve this as follows. (Note that on the node add form the postal code field's id is *edit-field-address-und-0-field-postal-code-und-0-value* and the city field's id is *edit-field-address-und-0-field-city-und-0-value*.)

1) I have added a custom module that contains the following code.

```
function custom_form_alter(&$form, &$form_state, $form_id) {
  $form['#after_build'][] = 'custom_afterbuildfunction';
}

function custom_afterbuildfunction($form_element, &$form_state) {
  drupal_add_js('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', 'external');
  drupal_add_js('sites/all/modules/custom/custom.js', 'file');

  return $form_element;
}

```

2) And then, in the module's directory, I add the custom.js file which contains the following code.

```
$(function() {
  // Disable City and State on Load
  $(document).ready( function() {
    $('#edit-field-address-und-0-field-city-und-0-value').attr('readonly','readonly');
  });

  // OnKeyDown Function
  $("#edit-field-address-und-0-field-postal-code-und-0-value").keyup(function() {
    var zip_in = $(this);
    var zip_box = $('#field-address-und-0-field-postal-code-add-more-wrapper');

    if (zip_in.val().length<5) {
      zip_box.removeClass('error success');
    }
    else if (zip_in.val().length>5) {
      zip_box.addClass('error').removeClass('success');
    }
else if ((zip_in.val().length == 5)) {
      // Make HTTP Request
      $.ajax({
        url: "http://api.zippopotam.us/de/" + zip_in.val(),
        cache: false,
        dataType: "json",
        type: "GET",
        data: "de/" + zip_in.val(),
        success: function(result, success) {
          // German Post Code Records Officially Map to only 1 Primary Location
          places = result['places'][0];
          $("#edit-field-address-und-0-field-city-und-0-value").val(places['place name']);
          zip_box.addClass('success').removeClass('error');
        },
        error: function(result, success) {
          zip_box.removeClass('success').addClass('error');
        }
      });
    }
  });
});

```

**However**, I would really like to independent of Zippopotamus. I have imported a table of all postal codes and corresponding cities into my database, called "zipcodes". It has a column called "zip" and a column called "city". This table comes with Location module. I would really like to get the city corresponding to the postal code from my *own* database via `db_query("select city from {zipcodes} where zip = :zip limit 1", array(":zip" => '$zip_in'))->fetchField();` and then fill it in to the "City" field.

**\***** *Edit* **\*******

I tried the following modified code, which unfortunately does not work.

1) In the custom module:

```
/**
 * Implementation of hook_menu()
 */

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

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

return $items;
}

/**
 * Implementation of hook_form_alter()
 */

function custom_form_alter(&$form, &$form_state, $form_id) {

if ($form_id == 'job_offer_node_form') {

    $form['#after_build'][] = 'custom_validate_and_populate';

}
}

/**
 * Implementation of #after_build custom function hook_validate_and_populate()
 */

function custom_validate_and_populate($form_element, &$form_state) {

drupal_add_js('sites/all/modules/custom/custom.js', 'file');
return $form_element;

}

/**
 * Implementation of hook_get_city()
 * This function ONLY introduces a new variable that carries the city name corresponding to the entered zip code.
 * replacement of Zippopotamus API;
 * does NOT yet populate any fields; this happens in the corresponding javascript file
 */

function custom_get_city() {
$zip = strtolower($_GET['zip_in']);
$city = db_query("select city from {zipcodes} where zip = :zip limit 1", array(":zip" => $zip))->fetchField();

}

```

2) In the javascript file:

```
$(function() {

        // Set city to 'readonly' on load.
        $(document).ready( function() {

            $('#edit-field-address-und-0-field-city-und-0-value').attr('readonly','readonly');

        });

        // keyup function
        $("#edit-field-address-und-0-field-postal-code-und-0-value").keyup(function() {
            var zip_in = $(this);
            var zip_box = $('#field-address-und-0-field-postal-code-add-more-wrapper');

            if ((zip_in.val().length == 5) )
            {

                // Make HTTP Request
                $.ajax({
                    url: "/get_city",
                    cache: false,
                    dataType: "json",
                    type: "GET",
                    data: "zip_in=" + zip_in.val(),
                    success: function(result, success) {
                        $("#edit-field-address-und-0-field-city-und-0-value").val('$city');
                        zip_box.addClass('success').removeClass('error');
                    },
                    error: function(result, success) {
                        zip_box.removeClass('success').addClass('error');
                    }
                });

            }
});
});

```

# Answer
> 3 votes
Perhaps something as follows? i did not try the code below it is based on something I am working on (see : http://drupal.org/node/1956690 ) .. I am trying to autofill options of a 'selectbox'. Which is working .. And since you are great with javascript :) How do I prevent prevent the 'enter key on a form' ? :) (see : http://drupal.org/node/370694 )

(edit: I tested the code below and it works. Type in the postalcode in the searchbox, hit tab-key and the CITY textfield will be filled with data from your dbase :) ). THe only issue that remains is that when the user hits the enter button, the form will be submitted. Hence my question, how do we prevent the enter key invoking the form-submit?

(edit 2: to prevent to submit the form when hitting return-key

```
$form['#attributes'] = array('onsubmit' => 'return false');

```

) the above will disable submit all together

scenario 2 (javascript):

```
  $('#edit-searchfield').keypress(function(event) {
   if (event.keyCode == '13') {
       event.preventDefault();
   }
});

```

### #

```
<?php

function autofill_menu(){

    $items['test/cities'] = array(
        'title' => 'autofill from db',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('autofill_cities'),
        'access callback' => TRUE,
        'weight' => 4,
        'type' => MENU_NORMAL_ITEM,
        );

    return $items;
    }

function autofill_cities($form, &$form_state) {

    $form['searchcity']['input'] = array(
        '#title' => t('Search database and fill select options'),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#maxlength' => 115,
        '#size' => 55,
        '#weight' => 0,
        '#default_value' => 'look for it',
         "#executes_submit_callback" => FALSE,
        '#ajax' => array(
            'event' => 'change',
            'callback' => '_get_select',
            'wrapper' => 'replace_textfield_div',
            ),
    );

    $form['city'] = array(
        '#type' => 'textfield',
        '#title' => 'City',
        '#size' => 15,
        // The prefix/suffix provide the div that we're replacing, named by
        // #ajax['wrapper'] above.
        '#prefix' => '<div id="replace_textfield_div">',
        '#suffix' => '</div>',
    );

    if (!empty($form_state['values']['input'])) {
        $test =  $form_state['values']['input'];
        // dpm($test);
        $getrow = _get_cities($form_state['values']['input']);
        $form['city']['#value'] = $getrow;
        }

  return $form;
}

function _get_select($form, $form_state) {
  // The form has already been submitted and updated. We can return the replaced
  // item as it is.
  return $form['city'];
}

function _get_cities($key) {

$query = db_select('zipcodes', 'ct')
        ->fields('ct')
        ->condition('zip', array($key)  , '=')
        ->execute()
        ->fetchAssoc();

return($query['Product']);

}

```

---
Tags: ajax, javascript, database, location
---


# Question
Title: get form state values of forms which added via ajax
the forms were added via ajax,but I just don't know how to get $values= $form\_state\['values'\]\['field\_name'\]; ,the result return nothing.Thanks in advance!

```
<?php

/**
 * hook_menu()
 */

function addstudent_menu(){
    $items= array();
    $items['user/%/add-students'] = array(
        'title'=>t('添加學生賬戶'),
        'page callback' =>'drupal_get_form',
        'page arguments' => array(addstudent_form),
        'access arguments' => array('create new users'),
        'type' => MENU_LOCAL_TASK,

    );

    return $items;

}

function addstudent_form($form,&$form_state){

    $dropdown_source = taxonomy_get_tree(3);
    if(!empty($dropdown_source)){
        $options = array('0'=> '--none--');

        foreach($dropdown_source as $item){ //we get all class term here
            $key = $item->tid;
            $value =$item->name;
            $options[$key] = $value;
        }
    }else {
        drupal_set_message(t('你还没有创建任何班级'),'error');
    }

    $form['addstudent_wrapper'] = array(
        '#title' => t('添加學生賬戶'),
        '#type' =>'fieldset',
        '#prefix'=>'<div id="fields_wrapper">',
        '#suffix'=> '</div>',

    );

    $form['addstudent_wrapper']['fields_head']['select_class'] = array(
        '#title'=> t('班级'),
        '#type' => 'select',
        '#options'=>$options
    );

    $form['addstudent_wrapper']['fields_head']['student_qty'] = array(
        '#title' => t('人數'),
        '#type'=> 'textfield',
        '#size'=> 10,

    );

    $form['addstudent_wrapper']['fields_head']['add'] = array(
        '#type' => 'submit',
        '#value'=> '確認',
        '#ajax' => array(
            'callback' => 'addstudent_get_callback',
            'wrapper' =>'fields_wrapper',

        ),
    );

    $form['addstudent_wrapper']['fields_wrapper']=array(
        '#tree' => TRUE,
    );

    return $form;

}

function addstudent_get_callback($form,&$form_state){
    $form_state['rebulid'] = TRUE;
    $i = $form_state['values']['student_qty'];
    return $form['addstudent_wrapper']['fields_wrapper'] = _addstudent_fields($i);

}

function  _addstudent_fields($i){
    for($a=0;$a<$i;$a++){

        $form[$a]['field_number'] = array(
            '#title' => '學號',
            '#markup'=>$a+1,
            '#tree' =>TRUE,
            '#type'=>'markup'

        );

        $form[$a]['field_name'] = array(
            '#title' => '姓名',
            '#type'=> 'textfield',
            '#tree' => TRUE,
            '#parents' => array('field_name', $i, 'field_name'),
            '#size'=> 10,
            '#default_value'=>''
        );
    }

    $form['addstudent_wrapper']['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Confirm',
        '#submit' => array('addstudent_form_submit'),
    );

    return $form;
}

function addstudent_form_submit($form,&$form_state){

    $values= $form_state['values']['field_name'];
    $a = array_values($values);
    foreach($a AS $b){
        foreach($b as $c){
            $r[] = $c;
        }
    }

    dsm($values);

}

```

# Answer
> 1 votes
Try `$values= $form_state['values'];`

and then dsm the values. You will get all field values of the form.

I think you should get the form values of ajax in `$form_state['values']['addstudent_wrapper']['fields_wrapper'][0]['field_name']` and so on.

# Answer
> 0 votes
Below an example taken from the drupal examples module; Hope it helps

```
function ajax_example_submit_driven_ajax($form, &$form_state) {
  $form['box'] = array(
    '#type' => 'markup',
    '#prefix' => '<div id="box">',
    '#suffix' => '</div>',
    '#markup' => '<h1>Initial markup for box</h1>',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'ajax_example_submit_driven_callback',
      'wrapper' => 'box',
    ),
    '#value' => t('Submit'),
  );

  return $form;
}

/**
 * Select the 'box' element, change the markup in it, and return it as a
 * renderable array.
 *
 * @return renderable array (the box element)
 */
function ajax_example_submit_driven_callback($form, $form_state) {
  // In most cases, it is recomended that you put this logic in form generation
  // rather than the callback. Submit driven forms are an exception, because
  // you may not want to return the form at all.
  $element = $form['box'];
  $element['#markup'] = "Clicked submit ({$form_state['values']['op']}): " . date('c');
  return $element;

```

---
Tags: forms, ajax
---


# Question
Title: Change notification to different languages
I have a multilingual website which has English and Chinese as the languages. I use the admin account but i have made a translator account for my chinese colleagues to make translations. Now if i make any changes to the pages in English how can they automatically get notified that they need to update the translation for that specific page. Is there any automatic way to do this ?

# Answer
> 1 votes
I believe, the module, you need is Subscriptions

The docs say:

> "This module enables users to subscribe to be notified of changes to nodes"

It is actively maintained and was started in 2003.

---
Tags: i18n-l10n, notifications
---


# Question
Title: Override Views Contextual Filter in View Exposed Form Validation
I'm using the `Content:Nid` contextual filter in my view (with exposed filters) and would like to dynamically set the value of this contextual filter from the exposed form validation callback. Is this possible?

# Answer
> 0 votes
I succeeded doing this by modifying `$form_state['view']->args[0]`, which is the first argument (contextual filter) for the view. In my case, this was the `Content: Nid` contextual filter.

# Answer
> 0 votes
Contextual filters work with arguments from the url so for example {drupal site}/search-nid/% where search-nid is the url of your page and % is the value you wish to submit to the contextual filter.

An exposed filter tends to take it's values from the query string E.G. {drupal site}/search-nid?field\_nid=% (Again search-nid is the page url and % is the value of the nid)

If you are trying to do what I think you are, (Filter results to a specific nid using a URL to "autofill" the filter) I did this in a hook\_form\_submit function and not a hook\_form\_validate function. The function below assumes your module is mymodule and your form id is advancedsearch\_form. The function looked as follows:

```
<?php
/**
 * Implements hook_form_submit()
 * Takes values from submitted form and appends them to query string
 * uses @see drupal_goto for info one $form_state['#redirect']
 */
function mymodule_advancedsearch_form_submit($form, &$form_state) {
  $qsa = array(); //for QSA arguments

  $field_nid = $form_state['values']['field_nid'];
  $qsa['field-nid'] = $field_nid;

  $form_state['redirect'] = array(
    'search-nid',
    array(
      'query' => $qsa,
    ),
    302,
  );
}

```

This may not be best practise (In fact I'm sure it isn't as it was a quick hack I implemented in about 5 mins!) but I hope it does answer your question.

---
Tags: 7, views, forms
---


title: Programmatically alter user permissions

text:
# Question
Title: Programmatically alter user permissions
The current state of the site, is configured such that authenticated members, can post specific content types and comment on everything.

What was asked of me, was the restriction of users having tagged (taxonomy) themselves as "private" (their profiles aren't accessible), not being able to perform the above operations.

Apart from assigning a new role, on user update and having one more role to manage, is there another way to do that?

Ideally I'd like to assign to a "private" user the same rights as an anonymous user but without actually making him one, since I am already filtering for authenticated users in views and such.

# Answer
> 0 votes
Well, there is a way to do this, without the need to create an extra role. The code below should give you at least a hint on how to do it. You will need to create a custom module if you don't already have one and modify the function names and code where appropriate accordingly. Be warned though: the code is not tested :)

```
/**
 * Implements hook_user_load().
 */
function my_module_user_load($users) {
  foreach ($users as &$account) {
    // Check if the user's profile is private
    if (_my_module_user_profile_is_private($account)) {
      static $drupal_static_fast;
      if (!isset($drupal_static_fast)) {
        $drupal_static_fast['perm'] = &drupal_static('user_access');
      }
      $perm = &$drupal_static_fast['perm'];

      if (!isset($perm[$account->uid])) {
        // If you want, you can add here a new "virtual role"
        // $account->roles[ROLE_ID] = 'custom role';

        // Make a copy of the roles array,
        // because we don't want to make changes on the user object
        $account_roles = $account->roles;

        // Remove the authenticated role, before querying all permissions
        if (isset($account_roles[DRUPAL_AUTHENTICATED_RID])) {
          unset($account_roles[DRUPAL_AUTHENTICATED_RID]);
        }

        // Get all permissions for user's roles
        $role_permissions = user_role_permissions($account_roles);

        $perms = array();
        foreach ($role_permissions as $one_role) {
          $perms += $one_role;
        }

        $perm[$account->uid] = $perms;
      }
    }
  }
}

/**
 * Helper function.
 *
 * Checks if a user's profile is private.
 */
function _my_module_user_profile_is_private($account = NULL) {
  if (!$account) {
    global $user;
    $account = $user;
  }
  // Check if the user's profile is private
  // ...
  return TRUE; // just for testing
}

```

---
Tags: 7, users
---