# Question
Title: Taxonomy view representative node contextual filter leads to incorrect results
I have a view that is outputting incorrectly, perhaps not according to the code, but according to what I need it to do. So, a challenge?

The view lists **colors** (taxonomy terms from vocabulary '**Color**') which have content assigned to them.

```
View type:      Taxonomy
Format:         Unformatted list
Show:           Fields
Fields:         Taxonomy term: Name
Relationships:  Taxonomy term: Representative node (required)
Filters:        Taxonomy term: Vocabulary (= Color)

```

The site must display different content depending on which area the user lives in. There is an 'Area' vocabulary, currently with two terms: East (tid = 1) and West (tid = 2).

Because of this, all relevant content types have an "Area" term reference field which can either be set to "East" or "West".

To get this to work, I added a contextual filter for the view.

```
Type: (Representative node) Content: Has taxonomy term ID.

```

A fixed value comes from this PHP:

```
$url = explode('/', $_SERVER['REQUEST_URI']);
$tid = 0;

if($url[1] == 'east') {
  $tid = 1;
} elseif($url[1] == 'west') {
  $tid = 2;
}

return $tid;

```

Values that don't validate cause the view to be hidden.

The problem: Taxonomy terms with content assigned to 'East' are being hidden from the list. I know that there is content using these 'Color' terms, but they are being excluded.

Here is what I think is happening:

1. View is executed for path 'domain/east'.
2. Representative nodes for each 'Color' taxonomy term are selected.
3. Contextual filter is applied to the representative node for each term - if the single representative node does NOT have the correct value for the URL (eg. 1, 'East' in this case) it is excluded.
4. Views output displays trimmed results, which are not representative of the actual data.

Does anyone know how I could get it to work properly? **I'm hoping to avoid creating views for each area**, as later, adding 'North', 'North West', 'South', 'South South East', etc, would get very frustrating. Ideally I'd be able to use a hook.

For example, would I be able to alter the representative node query, to get the contextual filter and change the SQL based on that?

Thanks for reading. :-)

# Answer
First off do NOT put PHP code in the fixed value. This gets stored in the db which is a bad idea. Instead use taxonomy term ID from URL for the default value.

If that does not work as is use a hook. I would probably use `hook_views_pre_view` in this case. You can use the same code you have in your example to change your `$args` or `$view->args` can't remember which off the top of my head.
> 1 votes

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


# Question
Title: How to restrict what content types can be added to a Book?
In activating the book module, I've noticed that all other content types on a Drupal 7 site have an option to add their nodes to a book. It would be ideal to restrict only the book nodes to go into a book. Does anyone know how to prevent other content types from being allowed to join the book party?

# Answer
> 0 votes
The answer seems to be within the permissions. For books there are a few main permissions (plus others in the Node section):

* Administer book outlines
* Create new books
* Add content and child pages to books

*Removing* the '**Administer book outlines**' will allow roles who have the other two permissions to create book pages but not see the option to add other content type nodes into a book. This is exactly what I was looking for.

---
Tags: nodes
---


# Question
Title: Get fields out of an entity returned by EntityFieldQuery
I have a video content type. I run the following query in `hook_cron`:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'video');
$query->propertyCondition('status', 1);
$results = $query->execute();

```

This returns number of entity object with property `nid`, `vid` and `type`. I want to use this object to find a value of a particular field of the video (say duration). I don't want to use `node_load`, because I would have done that in the first place instead of using the query. How can this be done?

# Answer
> 5 votes
The EntityFieldQuery Extra Fields module could solve your problem.

The query, as show below, will return an object that contains the entity id, entity type, and an object that contains entity\_type, entity\_id, revision\_id, bundle, and the requested field. Your code would be:

```
$query = new EntityFieldQueryExtraFields();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'video')
  ->addExtraField('field_duration', 'value', 'value')
  ->propertyCondition('status', 1);

$results = $query->execute();

```

I am currently using this solution on a site.

# Answer
> 11 votes
It can't - an `EntityFieldQuery` will only ever load the entity ID, and the bundle keys.

There's no choice but to use `node_load_multiple()` (or the equivalent if using a different entity type).

```
$nodes = node_load_multiple(array_keys($results['node']));

```

Bear in mind that the `$conditions` parameter of `node_load_multiple()` is deprecated; in favour of `EntityFieldQuery` as I understand it.

You could theoretically subclass `EntityFieldQuery` and override the `execute()` method to return the fully loaded entities - but you'll also need to extend the class so it always knows what entity type it's querying for; otherwise it won't know which key to use in `$results`.

---
Tags: 7, database
---


title: Right side overlay panel Solution

text:
# Question
Title: Right side overlay panel Solution
quickie,

I want to create a right-hand side sliding overlay panel for my drupal site. I have been googling and testing solutions for hours. The exact effect that I want can be found here. The jQuery Mobile overlay panel.

Of course, this script is not working with drupal and bootstrap 3 theme.

Question(s): Does anyone know a way to make this script work with drupal 7 and bootstrap 3?

The closest substitute that I can find is the Mobile Menu Module (MMenu) module, but it appears to be for navigation purposes only. I need to add a FAQ with animated expanding divs. The documentation is unclear if this possible with MMenu. Can anyone tell me if it is possible?

If I am barking up the wrong tree with jQuery Panel and MMenu is there a better solution? Simple, right hand side overlay panel.

Much appreciate, any suggestions.

# Answer
> 0 votes
I believe in owning the silliness, when you're being silly. I answered my own question in the process of posting the question.

Using MMenu module, I simply took my animated divs and put them in a block and loaded the block as content for mmenu. The js scripts work and the content looks great, only one last hurdle. But I will do that is an actual question if I can't find a solution.

---
Tags: modal-dialogs
---


title: How to make one facet default?

text:
# Question
Title: How to make one facet default?
I want to set facet value default, when we search it will automatically checked 1st facet.

# Answer
You should define hook\_search\_api\_solr\_query\_alter and something like this:

```
/**
 * Implements hook_search_api_solr_query_alter().
 */
function MODULE_search_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  $call_args['params']['fq'][] = 'FACET_MACHINE_NAME:YOUR_VALUE';
}

```

I hope it helped you.

The other way to do this described here http://www.eilyin.name/note/how-set-value-facet-default-drupal-54
> 1 votes

---
Tags: search
---


# Question
Title: Field with unique and auto-increments values
I have a content type that in one of their fields need a value that is unique and auto-increment. There are several obvious solutions:

* Use the node id that is unique and auto-increment.
* The Serial module.

The problem with these solutions is that they use the MySQL auto-increments.

Drupal, by default, auto-increments the node ID (nid) and other IDs by one digit for each piece of content you create. You can see this if you visit your site by the node ID path:

```
http://www.example.com/node/1
http://www.example.com/node/2
http://www.example.com/node/3

```

However, sites that use database replication as a backup strategy (is my case) often will have non-sequential ids, meaning that you could see nids jump by two or more digits.

```
http://www.example.com/node/10
http://www.example.com/node/15
http://www.example.com/node/20

```

The MySQL auto\_increment\_increment variable determines how many digits to jump for each successive auto\_increment value.

And then I have this problem:

How I can do to have a field with unique and auto-increments values?

# Answer
> 0 votes
You can achieve it yourself in your custom form submit, lets suppose your field name is `myfield` ( machine name will be `field_myfield` and it is text) and your content type is `news` ( change them with your data) first in form alter you can hide it ( it you don't want user see it ) Get idea from my code

```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'news_node_form'){
        if($form['nid']['#value']){
          // if we are in adding new node hide that field and add custom submit handler
                hide('field_myfield');
                $form['#submit'][]='_my_autoinrement_submit_handler';
            }
    }
}

function _my_autoinrement_submit_handler($form, &$form_state) {
$lastValue=0;
// search for the last value
$query= db_select("field_data_field_myfield","mf") ->fields("mf")
 ->condition('bundle', 'news','=')
    ->condition('status', 1)
    ->orderBy('field_myfield_value', 'DESC')
     ->range(0,1);
     $result = $query->execute()->fetchAll();
     if($result){
         //get last value entered before this
        $lastValue= current($result)->field_myfield_value;
     }
     // increment last value ( biggest one )
     $lastValue ++;
   //set it in node
    $form_state['values']["field_myfield"]['und'][0]['value']=$lastValue;

}

```

---
Tags: 7, database
---


# Question
Title: Views: how to remove ending zeros from decimal field
Suppose, we have a view with a decimal field:

It is output like this:

```
5 000.000

```

Is it possible to remove the ending zeros, so it looked like this:

```
5 000

```

But if there are meaningful values in the field, it should output all of them. For example:

```
5.100 -> 5.1
5.010 -> 5.01
5.001 -> 5.001

```

# Answer
I created a file /theme/bartik/templates/views-view-field--open-events--page--field-coefficient.tpl.php:

```
<?php
print (float) $row->_field_data['id']['entity']->field_coefficient[LANGUAGE_NONE][0]['value'];

```

And it worked.
> 5 votes

# Answer
You could write a custom field formatter in a custom module. See drupal-root/modules/field/modules/number/number.module and copy the related stuff for 'number\_decimal' and adapt it to "trim\_decimal".

```
number_field_formatter_info()
number_field_formatter_settings_form()
number_field_formatter_settings_summary()
number_field_formatter_view()

```

In custom\_module\_field\_formatter\_view() define your formatter (here named: trim\_decimal) like this:

```
...
case 'trim_decimal':
      foreach ($items as $delta => $item) {
        $output = number_format($item['value'], $settings['scale'], $settings['decimal_separator'], $settings['thousand_separator']);

        // If scale, we want to remove trailing 0 and the decimal separator,
        // if there are no digits after decimal separator.
        if ($settings['scale']) {
          $output = rtrim(rtrim($output, '0'), $settings['decimal_separator']);
        }

        if ($settings['prefix_suffix']) {
          $prefixes = isset($instance['settings']['prefix']) ? array_map('field_filter_xss', explode('|', $instance['settings']['prefix'])) : array('');
          $suffixes = isset($instance['settings']['suffix']) ? array_map('field_filter_xss', explode('|', $instance['settings']['suffix'])) : array('');
          $prefix = (count($prefixes) > 1) ? format_plural($item['value'], $prefixes[0], $prefixes[1]) : $prefixes[0];
          $suffix = (count($suffixes) > 1) ? format_plural($item['value'], $suffixes[0], $suffixes[1]) : $suffixes[0];
          $output = $prefix . $output . $suffix;
        }
        $element[$delta] = array('#markup' => $output);
      }
      break;

```
> 0 votes

---
Tags: 7, views, entities
---


# Question
Title: Change search results pager to mini pager?
How to change search result's pager to mini pager. I want to change default pager to mini pager in that search result page. Please help me. Thank you.

# Answer
you can override template\_preprocess\_search\_results in your `template.php` and instead

```
   $variables['pager'] = theme('pager', array('tags' => NULL));

```

use

```
   $variables['pager'] = theme('views_mini_pager',array('tags' => NULL));

```

( just make sure you installed views module)
also this question can get you some clue

How do I customize the search result page?
> 0 votes

---
Tags: search, paging, views
---


# Question
Title: Print selected fields from a referenced node
Using entity reference, i have been able to link a node of type blog to another node of my custom content type, "challenge", by creating a field under blog of type entity reference. Great. Now, when the blog is published, some fields (not all) from the linked custom content type should also be displayed there. For ex, in my custom content type, there are some fields as title,body,image1,image2,sponsor, some flags using the flag module and other fields. I want that only some fields which i mentioned should be displayed on the blog (no flags etc to be displayed). SO what i do is under Manage Display for blog i select Rendered Entity for display. What this does is gets all the fields from the referenced/linked node. However i want some fields not all. Now what i do is write a custom node--blog.tpl.php. I then hide everything from content as:

```
<?php
   hide($content['title']);
   hide($content['field_blog_pic']);
   hide($content['field_challenge_name']);
   hide($content['field_challenge_pic']);
   hide($content['field_sponsor']);
   hide($content['field_sponsor_logo']);
   hide($content['field_sponsor_description']);
 ?>

```

Then i tried rendering the fields one by one. It is ok for the field of type blog but the moment i do a `print_render($content['field_challenge_name'])` then all fields from the referenced node (of my custom content type, challenge) get displayed. How can i just select a few fields for display of the referenced node.

If it helps, here's my node--blog.tpl.php:

```
    <div class ="in-blog-pic">
     <?php
       print render($content['field_blog_pic']);
     ?>
    </div>

    <div class ="in-blog-title">
     <?php
        print $title;
     ?>
    </div>

    <div class="in-blog-comment-count">
     <?php
        print $comment;
     ?>
    </div>

    <div class="in-blog-name-user">
     <?php
        print $name;
     ?>
    </div>

    <?php
    /** $user = user_load($user->uid);
      print theme_image_style(
                    array(

                        'path' => $user->picture->uri,
                        'attributes' => array(
                            'class' => 'in-blog-user'
                        )
                    )
                );
    */
    ?>
    <div class="in-blog-user-pic">
 <?php
   $user = user_load($uid);
   print theme('user_picture', array('account' =>$user));
 ?>
</div>

<div class="in-blog-title-below">
 <?php
  print $title;
 ?>
</div>

<?php
   hide($content['title']);
   hide($content['field_blog_pic']);
   hide($content['field_challenge_name']);
   hide($content['field_challenge_pic']);
   hide($content['field_sponsor']);
   hide($content['field_sponsor_logo']);
   hide($content['field_sponsor_description']);
   hide($content['field_categories']);
?>
<div class="in-blog-body">
 <?php
  print render($content);
 ?>
</div>

<?php /*
<div class="in-blog-challenge-name">
  <?php
     print render($content['field_challenge_name']);
  ?>
</div>
*/?>

```

All fields get displayed of the referenced node once i do the last few lines

```
<div class="in-blog-challenge-name">
      <?php
         print render($content['field_challenge_name']);
      ?>
    </div>
    ?>

```

So after all that blabbering, all i want to ask is how to print some selected fields of a referenced node (here my custom type, "challenge") onto the referencing node (here, blog)...

Regards

# Answer
I would use Display Suite for this problem. Using it, you can define an extra view mode for the referenced node type, with just the fields you want, then configure the display of the entity reference field to use that view mode. We are doing this in the current project I am working on, and it's just the ticket.
> 4 votes

# Answer
Try this module field extractor For more advanced features use views eva
> 0 votes

# Answer
I found your question trying to solve a similar problem - I want to grab an image from a referenced node without having to render all the rest of the content. I wanted to do it without adding another module to my already heavy install, and I ended up doing it with a custom display mode instead of template files.

The Token module - now in Core in Drupal 7 - lets you choose custom formatting for a given field in a "Tokens" display mode. Say, if you wanted an image to just link to its full-sized version in its own content type, but you wanted to be able to reference it in another and set it to link through to its original content there. See this post: https://www.drupal.org/node/1299662

It also makes it easy to only render a single field from the referenced content:

On the original content type (the one you're referencing content FROM), go to "Manage Display" and create a new view mode, Tokens. It's the bottom of the list of options - just tick the checkbox:

From there, you just get a new place to manage display settings: hide everything you don't want and configure it as you will:

Then, go back to the content type you want to add a reference into and click "Manage Display". In the display settings for your Node Reference field, select Format \> Rendered Content. Select "View Mode: Tokens" and you'll get a nice single field to style as you want!
> 0 votes

# Answer
Another way is to use module Entity view modes. It's a lightweight alternative to Display Suite and let's you create custom view modes.

How to create view modes programmatically can be found in this tutorial
> 0 votes

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


title: How to add js file in only 1 node?

text:
# Question
Title: How to add js file in only 1 node?
I made a custom js script for a little calculator. I want to use this in only 1 node (article or page) so I do not want to load it via tpl files etc because I do not need it sitewide. And also: if every custom script (that I use only in 1 node) has to be loaded sitewide I would get an immense head section after some time. Does anyone have experience with how to do this in a simple and safe way?

Thanks. Frank

# Answer
> 2 votes
In the `template.php` you will write this small piece of code:

```
function MYTHEME_preprocess_node($vars) {
 if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'yournid') {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . "/script/js");
 }
}

```

Replace foo with values related to your need.

# Answer
> 0 votes
code for adding JS to particular path:

```
if ($_SERVER['REQUEST_URI'] == '/path/to/node') {
  drupal_add_js('somefile.js');
}

```

to attach js to node:

```
function my_module_node_view($node, $viewmode, $langcode) {
  $node->content['#attached']['js'][] = array('type' => 'file','data' => drupal_get_path('module', 'my_module') . '/my_script.js',);
}

```

Thanks!

# Answer
> 0 votes
Another option is JS Injector. Though I haven't used this module. This requires no programming as it provides user interface to administrators.

# Answer
> -1 votes
you need to use php filter or need to create tpl file for single node to accomplish this. With php filter or tpl you need to put only this code.

```
<?php
  drupal_add_js('jQuery(document).ready(function () {
    jQuery("p").hide();
    jQuery("p").fadeIn("slow");
  });', 'inline');
?>

```

---
Tags: javascript
---


# Question
Title: How to submit multiple patches to a contrib module?
I'm building a web application and use some contrib modules. I heavily rely on a particular module, for which I already submitted a patch a couple of months ago, which was eventually committed.

On these days I had some new requirements, so I added a new functionality to the module and discovered and solved two (unrelated) bugs.

Now a stupid doubt grips me and I'm stuck. My question is: what should I do now?

1. Create three issues (or write in the existing ones, if the bug was already known) and submit right away my code in three different patches (which are independently written on the current dev version). This means that when a patch will be committed, I'll have to create a new version of the remaining patches for the new dev version
2. Create a issue with patch for one of the bugs/features, wait that it gets committed, open another issue for another one of the bugs/features, submit a patch on the updated dev version, wait that it gets committed, then open the third issue, submit the patch for the last bug/feature on the again updated dev version. This could potentially take weeks or months.

Usually I would say 1, but due to the short timeframe between patches (a couple of minutes, just the time to create the issues) and the fact that only one person is the creator of all of them, gives me the impression of spamming. It's not a problem for me to create and "maintain" three issues and the related patches, I jut want to do it in the right way.

# Answer
> 2 votes
Submitting all the patches, in different issues, at the same time is actually a problem just in the case they conflict with each other; this means that, once applied a patch, it would not be anymore possible to apply the other ones without rerolling them.

Since you cannot say which of them is going to be applied first from the maintainer, I would submit all the three issues at the same time. In that way, even if two of them are not going to be applied first, there is still a discussion going on about the necessity of applying them, or about what needs to be changed in them. If then the applied one doesn't allow to apply the other ones, you will need to reroll them, or somebody else could reroll them.

As for the short timeframe between patches, that is never taken as spamming an issue queue. If you want to be taken in consideration from the maintainer, you should make a good use case for your patches, or make evident there is a issue to be fixed (in the case it is not so evident); if the patch is going to fix a problem that happens in very few cases, be prepared to make clear what the benefits from your patches are. Being a maintainer doesn't mean knowing all the problems the users of a module could have; in some cases, the maintainers need just some data to make evident what the problem is.

# Answer
> 2 votes
if these 3 fixes/patches unrelated, I would go with first option as it keeps things clear and if any of these patches introduces any other issues/conflict it will be easier to maintain it. I understand how this is time consuming, but it's better if you do it the right way.

# Answer
> 1 votes
# Separate the issues/patches

For sure create 3 separated issues, with each of them containing 1 of your patches. This has advantages such as:

* Any community member can "cherry pick" any of your 3 issues to either use them (apply the patch(es) they need/like), review them, etc.
* It might potentially lead to the 3 issues being processed in parallel (by 3 different users/reviewers), so possibly also reducing the elapsed time to get them RTBC-ed also.
* It reduces the risk that 'all' your patches are rejected, in case something happens in the dev version of the module due to which "your" patch needs to be rerolled: if you have 3 separated patches, only 1 or 2 or them might require a re-rolling (read: that's not a showstopper for those patches that are not impacted).
* ... (there are more advantages to this approach).

# Choose your battles

Even though you should separate them (see above), "you" have some level of control about the order of review and commits to the dev version. I would make a ranking like "which one is most important **to me**, and which one is more like a nice to have (eg because you have a work around)".

Based on **your** ranking, you could submit the most important one first, and wait "some time" (up to you to decide how long) before submitting the 2nd one. Later on the 3rd one. This approach avoids that the other people involved (reviewers, committers, etc) start working on "the" issue that "they" find most important (which is different from your ranking). Optionally, when submitting the 1st (or 2nd) issue/patch, you may want to add some type of comment like "after this gets addressed, I have another one coming up (which IMHO is lower priority)".

# It works

I've used the above approach in the past also. After a while the module owner started to realise the value of my contributions ... it resulted in receiving commit access to the module, whereas I got 'carte blanche' for anything related to "what I found important to be fixed / enhanced".

---
Tags: version-control
---


# Question
Title: How to automatically assign child taxonomy terms?
I'm building a virtual network like Instagram but its contents (images) are about a certain event. The strategy of selecting taxonomy terms is to display all of the tags (about 20 ones) and a checkbox and users can check any one of them. I use ttr\_configurable\_widget to do so.

The problem is there are many synonyms for a word and I don't want to display the synonyms, as an example in tagging the words `female`, `women`, `girl`, `sister`, `daughter`, `lady` are almost the same so when some one search for `female` the `lady` tag should be searched as well, furthermore this tag should be displayed as a hidden element in the web page(for search engines)

So there is a main tag like `women` and a set of synonyms. What I need to do is to format the tags as follow

Then only display the `woman`, when a user selects `woman` its synonyms also be attached to the content.

It is also preferred to load the synonyms but hide them in the node display page.

How can I do this?

The Taxonomy Term Reference Tree Widget and Taxonomy Group Fields are almost doing this but in these widgets users can check or uncheck the children even if the parent is selected.

# Answer
The best way to achieve this job is using JQUERY,load all terms in the page ,hide all of children terms and when the parent term checked show the children terms of it( also when unchecked hide all children of it).
> 1 votes

---
Tags: 7, nodes, taxonomy-terms, meta-tags
---


title: MMenu Module Per Page Configuration

text:
# Question
Title: MMenu Module Per Page Configuration
Ok drupalers,

A good one. I am using the MMenu module to implement right hand side overlay panels. The site that I am building has two different types of users "Group A" and "Group B". They each need to see different content displayed inside of the right hand overlay created by the MMenu module.

**Problem:** MMenu module displays the same content on ALL the pages for "Group A" and "Group B".

The site is a demo site for anonymous users to review, so there are no user login url's to distinguish a user in Group A from a user Group B.

basically, I need a way to dynamically change the content block based on what page loads.

Anybody got any good ideas?

# Answer
> 1 votes
Ok for a non-programmer (my last course was literally 2 decades ago) I feel pretty good at about this one, but invite folks to provide better solutions. :-)

To solve the problem described above, I utilized a little jquery javascript via js injector (into the head section) and added the following:

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

$("div#page_key_features").appendTo("div#right_panel_overlay_content");

});
}( window.jQuery )

```

From there, within the block that I will add to the Mobile Menu right overlay panel, I added the following HTML:

```
<div id="right_panel_overlay_content">
<p style="margin-bottom: 0px;"> </p>
</div>

```

Then via CKEditor (source) within the body of the page I added the following HTML:

```
<!--outter div for invisibility--><div style="display:none;">
<!-- holds the content to be displayed in the right overlay panel     --><div id="page_key_features"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/200px-FullMoon2010.jpg" /><br />
This content is invisible in the body content of the page, but becomes   visible within the mobile menu block called "right_overlay_panel_content". This means I can edit content using ckeditor, then add the "display:none" style to the outter div to hide in the body of the page, but display it when the user triggers the right overlay panel.  I can change the content on every page if I choose.</p>
</div>
</div>

```

NOTE: I had to use nested divs. This allows me to hide the content of the right overlay panel within the body of the page, then display it when the user clicks the trigger showing the panel.

Now I can add custom, per page content to the Mobile Menu right overlay panel.

Here's the JS Fiddle for anyone who wants to use/tweak my little solution.

---
Tags: blocks
---


# Question
Title: Reading textarea values per row: what is the internal method?
If I'd like to create a textarea field for a admin configuration form that would include different configurations on multiple rows then how can I read these values/rows?

I know there must be a internal method for this since it is very common form field/input type. I just wouldn't like to invent it again.

And I just ran into a module that was using this same principal but it matched the rows with regex \n\r which turned into few gray hairs if you had only one value since it didn't then match if you didn't deliberately press enter. And for clarity it obviously didn't check that if the first line included text, just that regex and therefore no settings were saved.

That was also a wake up for that there must be some more intelligent and elegant way...

# Answer
Drupal doesn't provide a method for that.

Just use whatever PHP splitting method makes sense for your use case. A very simple example might be:

```
$text = str_replace(array("\r\n", "\r"), "\n", $text);
$vals = explode("\n", $text);

```
> -1 votes

---
Tags: forms
---


# Question
Title: What is the feasibility of using Entity Reference instead of Taxonomy?
I read an opinion that argues for using Entity Reference to content types as a complete replacement for Taxonomy, on the basis of UX and performance. The UX issue appeals to me - happy content managers (who don't have to go dig around in Taxonomy ever) is important!

In considering this strategy for a new site that will be essentially built around one content type that can be tagged lots of different ways, I have a couple questions:

* Is there *really* a performance difference? Can it be quantified?
* I need hierarchy support. Is there a good option? Searching around, the land of Entity Reference hierarchy options exists but seems like a wild west at this point.
* Are there better solutions if my only complaint is site admin UX?
* Taxonomy is the best-practice, as it is in core, for the general use case. I'm wondering what else I haven't considered in going off the beaten path here.

(Note a very similar question has been asked before, but it is talking about using Entity Reference to taxonomy terms, rather than replacing the Taxonomy module. I also understand the purpose of Taxonomy, but am wondering what would make alternatives worth considering.)

# Answer
> 1 votes
> Is there really a performance difference?

For sure! Totally different and independent pieces of code was used for it, so there must be.

> Can it be quantified?

You can measure it, but because taxonomy is pretty well defined, and references are open to configuration, your mileage will vary. Overall, taxonomy is older, and optimized for speed - a lot of terms on one node is common. Also, it's easier to optimize something that works only one way.

> I need hierarchy support. Is there a good option? Searching around, the land of Entity Reference hierarchy options exists but seems like a wild west at this point.

Exactly! Everyone consider different things good, so implementations vary. I don't know what your "good" means, so I can't tell if it happened to be similar to one of already implemented "good".

> Are there better solutions if my only complaint is site admin UX?

Again - it depends on what exactly you consider better. There are things like Taxonomy Manager, but it addresses things it's creator considered that need to be addressed, in a way that's better - for him.

> Taxonomy is the best-practice, as it is in core, for the general use case.

Not really... But that was a claim, not a question anyway.

> I'm wondering what else I haven't considered in going off the beaten path here.

And this is simply too broad for Q&A

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


# Question
Title: Recursive Drush make, working with different git branches
# Setup

For every site we make a custom Drupal install profile is created, copies of which are built using `drush make` (through Aegir, though that should not make a difference).

There is a top-level build makefile for downloading Drupal core and our install profile, and the install profile contains a makefile specifying Features to download, each of which have a makefile specifying their dependencies (either custom modules in private git repos or contrib modules).

The build makefile (`build-SITENAME.make`) specifies the install profile like this:

```
projects[SITENAME_profile][type] = profile
projects[SITENAME_profile][download][type] = git
projects[SITENAME_profile][download][url] = git.hostname:drupal-sites/SITENAME_profile

```

Then the install profile's makefile will specify a bunch of Features to download, for example:

```
projects[blog][type] = module
projects[blog][subdir] = features
projects[blog][download][type] = git
projects[blog][download][url] = git.hostname:drupal-features/blog

```

Which will then download custom and contrib modules and so on.

The above setup has worked well for a couple of years.

# Problem

The problem occurs when trying to use git branches for managing different stages of development, e.g. development, staging and production; and having CI automatically manage Drupal sites for each branch. If a build is triggered for the development branch, `drush make` has to get the correct branch for every one of our repos it downloads.

Given our multi-repo and recursive makefile structure, how would `drush make` be used to recursively download the correct branch from our git repos?

# Things already tried

1. `drush make` allows downloading from a git branch, which seemed good for our use-case. For example, for each makefile (in the build, install profile and Features repositories) a line is added that looks like:

```
projects[blog][download][branch] = development

```

When the branch of the repo being downloaded matches the branch of the repo the makefile is in, custom modules specified in the development branch of the 'blog' Feature will be downloaded from that module's development branch. Great!

However, this causes problems merging the branches of any repo containing a makefile (given our setup that's quite a lot), we will have to be extremely careful not to accidentally merge `[branch] = development` into master on any of them.
2. Checked `drush make` documentation for a command-line option to specify the default branch for git repository downloads. Found nothing.
3. Searched the Internet for people with similar quandaries, it seems many are dumping all the dependencies for whole projects into single make files, but that breaks the modularity of Features.

**Note**: I'm not polling or asking for discussion. I believe there's something silly I'm missing and/or something *everyone* else is doing that I'm not.

# Answer
This is a great question! I maintain both Aegir and Drush Make, but I'm not certain that I have a really good answer for you.

1. I think that you're suggestion in (1) is probably the best bet at the moment. It has the virtue of already working, as you've mentioned. The issue with accidentally merging these `[branch]` attributes is still valid though. The solution though, lies not in Drush Make, but in Git!

Check out this article. It describes using *Git attributes*, along with a custom (null) *Git merge driver*. To summarize, each developer would have to run the following:

```
git config --global merge.ours.driver true

```

This basically means that when an item is flagged to use the '*ours*' merge driver, it'll just call `/bin/true`, hence my earlier reference to it being a null operation.

But, how do you flag your makefiles to use this driver? That's where *Git attributes* come into play. Create a `.gitattributes` file at the root of your repo (i.e., along side `.gitignore`). Then add the following line:

```
build-SITENAME.make merge=ours

```

You'll probably want to do the same for your feature repos as well.
2. As for solutions leveraging Drush Make, I don't know that there's a solid solution.

A few years back, I experimented with using overrides trying to do something similar, as described in the Drush Make documentation. The basic idea is that you can change (override) attributes from included makefiles.

However, in the case of recursive makefiles, they are built separately, instead of being merged into the parent makefile prior to build. As a result, there's no opportunity to override their attributes. This may have changed in the time since I tested it, but I think the underlying mechanics remain largely the same, and so it's unlikely to work.

Setting a default in a parent makefile would be a nice way to accomplish something like this too. I haven't tested this, but again, I'm pretty sure the default wouldn't apply to the recursively built makefile.

Instead, an option would be to build your parent makefile without recursion, but rather including the feature makefiles directly. You can now include makefiles directly from within a Git repo (using the new YAML syntax):

```
includes:
  # A file from a git repository.
  makefile: "example_dir/example.make"
  download:
    type: "git"
    url: "git@github.com:organisation/repository.git"
    branch: "master"

```

You'd either want to call `drush make` with the `--no-recursion` option, or specify it in your makefiles:

```
--no-recursion                   Do not recurse into the makefiles of any
                                 downloaded projects; you can also set
                                 [do_recursion] = 0 on a
                                 per-project basis in the makefile.

```

I'm sure there are other options available, but those are the ones that I think would least impact your existing workflows. I'd be very curious to see other suggestions.

There is a feature request to allow the use of variables in .make files, which might address such a use-case more directly, if it were implemented. Perhaps we could look for such variables in options passed on the command line, or in environment variables.

That said, in the long run, I believe that Drush Make will be supplanted entirely by Composer, so it might be more fruitful to explore in that direction, if the suggestions above don't work out.
> 2 votes

# Answer
Consider using composer which could be a bit more flexible regarding the recursive dependencies as it can analyze the whole dependency tree which you can set-up and many more.

See example composer.json:

```
...
    "require": {
        "composer/installers": "^1.0.20",
        "drupal/core": "8.0.*",
        "drush/drush": "8.*",
        "drupal/console": "~0.8",

        "drupal/devel": "8.1.*@dev",
        "drupal/token": "8.1.*@dev"
    },
...

```

See:
> 1 votes

# Answer
If you're interested in managing different branches, please have a look how this is achieved in ADS distribution (GitHub).

Basically you can set-up CI to load the file appropriate for specific branch, e.g.:

```
build-SITENAME-BRANCH.make

```

then in this file you can have specific components of specific branch (e.g. profile) and everything else (e.g. common contrib modules) can be included from different `.make` files (`includes[] = contrib.make`). See: build-ads-latest-dev.make.

---

If this won't help, alternatively use editing in-place before running the build which will set the appropriate branches.

For example having this line where you specify your branch:

```
projects[foo][download][branch] = master

```

you can alter it via:

```
ex -s +"%s/master/develop/" -cwq build-SITENAME.make

```
> 1 votes

---
Tags: version-control, drush, aegir
---


# Question
Title: Change content "Author" to the last "Editor"
On the admin/content page. The field "AUTHOR" shows who created the content, but this is not very helpful for seeing who last edited it.

How would you change this to show who last edited it?

# Answer
> 1 votes
If you have a custom module to use, or aren't afraid to make one, then a hook\_node\_presave is the first method I would try.

```
function yourmodule_node_presave($node) {
  // php5 passes objects by reference
  // so this should not need a & or return
  global $user;
  $node->uid = $user->uid;
}

```

If you do not want to go with code, then try the Rules module. Rules has a trigger for node about to be saved. Set the condition that the current user is not anonymous (because rules likes you to confirm in a condition any data you want to use in the actions) and then set the author field in the action to the current user. All done in the ui, no new code needed.

---
Tags: nodes
---


# Question
Title: How can I only show the first image of a multi-value image field in the teaser?
I have a content type with an image field that can contain an unlimited number of images. The field is used to display an image gallery in the full node view, but I also want to use the first image of the field in the teaser.

I vaguely remember doing something like this years ago in Drupal 6, but now I can't find any option to do this in Drupal 8. I'm not sure if I'm misremembering, or just looking in the wrong place.

How can I display only the first image of an image field in the teaser?

# Answer
> 7 votes
You can do this on your own easily by extending core's `ImageFormatter` class from a custom module. Simply copy core's `ImageFormatter.php` into a custom module. Rename everything properly, remove all methods except `viewElements()` and then add only one simple `break;` at the last line of the `foreach` in `viewElements()`. After enabling the module (or after flushing cache if you added the formatter to an existing custom module) you can choose the new formatter under display settings for your teaser view mode of your content type. Works in views, too.

Did that for you in a quick custom module: image\_first\_formatter.

---
Tags: 8, media
---


# Question
Title: Is there any way to cancel Panels' overlay edit windows?
I don't want to edit Panel panes via overlay edit-windows and therefore I tried to disable the core "Overlay" module at `admin/modules` but it seems to effect everything except the overlay of the Panels module.

Note: The reason I want to disable Panels' overlay is because it's slow to me (especially in Dev periods when I disable cache, and that it sometimes stuck and loads "Forever")... Besides, it cannot be open in a new tab, as I would prefer.

Do you know how to disable it?

# Answer
I did some research and looked into Panels 3 code so far I don't see any nojs fallbacks. You can also check if there are fallbacks when you try to disable Javascript in the browser.

This may not be the answer on how to disable Panels modals but you may increase PHP, MySQL and or Apache settings and increase memory to your local host.
> 6 votes

---
Tags: panels, performance, modal-dialogs
---


title: Hook form upload

text:
# Question
Title: Hook form upload
I need to show a modal message like "Uploaded file exceeds X MB" when the user tries to upload a large file. I have set maximum size in the field settings and when I try to upload a large file Drupal shows a label with custom error. I need to trap this event and launch the `js` with modal message.

I have a;

```
 function hook_file_validate($file) {

     ....
 }

```

It is invoked in ajax so I cannot make a `drupal_add_js` call with the javascript code to execute. How can I execute JS method for solving this problem?

# Answer
It sounds like you're wanting to do file size upload validation with complicated method of server/client code. If all you need is size validation, you can do that client-side without the need of the server.

There are many ways to do this; one example would involve adding a JS `onchange` event handler to your file field.

```
MYMODLE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id = "my_form") {
    $form['field_MYFILEFIELD']['#attributes']['onchange'] = "
      if (event.srcElement.files[0].size > (8 * 1048576)) {
        alert('Uploaded file exceeds 8 MB');
        jQuery(this).replaceWith(jQuery(this).clone());
        return false;
      }";
  }
  //@TODO: move the validation code to a function & use better modal
}

```
> 0 votes

---
Tags: 7, files, javascript
---


# Question
Title: Assigning content from one user to another user automatically after a payment
I am evaluating Drupal for a new project but I am not very experienced with Drupal so far.

The project is based around a custom content type created by role-A user and then re-assigned to role-B user once role-A has accepted the re-assignment and role-B user has made a payment. When the node is re-asssigned to role-B user, role-B user will only be able to modify one of the fields of the node.

Does anybody have any ideas of how to do this without the need for the admin to manually re-assign each node to a different user and change the permissions for the fields?

# Answer
> 1 votes
Use the Node access user reference module for this purpose. About this module (quote from its project page):

> Gives content access permissions to users for content that references the users with User reference or Entity reference.
>
> This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

And use the Entity reference module to implement your "assignments".

To actually "use" (configure) these settings, refer to the module's README.txt, which includes these instructions:

> Create a field to reference users in a content type using the Field UI. The field's configuration page will contain the settings for Node access user reference. For detailed instructions on using the Field UI see: https://www.drupal.org/documentation/modules/field-ui

Possibly you also might want to use the Field Permissions module.

---
Tags: nodes, users
---


# Question
Title: How to trigger an action when a site receives an email?
In Drupal 7, is it possible for users to send an email to a website, which will trigger an action?

For example, the user sends an email to offers@mydrupalsite.com. The Drupal site receives this and then sends the user an email with a PDF attachment.

I've searched extensively; however, the nature of the query means that it usually turns up relevant results.

# Answer
Here is how you might get it to work:

* Use Mailhandler to create nodes by eMail. The content of the node could be the actual content of the request as contained in the eMail.
* Use Rules to react to the event "after saving content" and combine it with the Message module to send the eMail back to the user.

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters. For more details about the Message module, refer to some interesting Use Cases detailed within its Community Documentation.
> 1 votes

---
Tags: 7, emails
---


# Question
Title: Drupal Facets Block Show everywhere (in non search page)
I use facets search and work well but i want to show block everywhere in website please for your help.

I try to create new views with my search index and add facets block in views but i get wrong url ?f\[0\]=field\_places%3A72

# Answer
Depends on what module you are using with facetapi. If you are using search\_api, then when creating the view you can add a view display of type "Facets Block" (like you would add a page, block or panel display).

Using that display you can add a facet block anywhere on your site, even on non search pages. And you can also set the search\_path you want to redirect to when using the facet block.
> 0 votes

---
Tags: search
---


# Question
Title: Report complains about Unsupported Release but no modules listed
On my report page, I get a warning about Unsupported Release of modules or themes.

but when I click the "available updates" link, the next page tells me that all my projects are up to date.

I've tried clearing my cache and running cron but I get the same result.

EDIT:

Apparently this is a known bug that I missed in my searches. Unfortunately, the link to the bug below doesn't include any info on how to find out WHICH modules are unsupported. :( So, I have no way to figure out which things I need to upgrade or remove.

Where can I find a list of the unsupported modules in my installation?

# Answer
If using Drush, try:

`drush pm-updatestatus`

**Note**: It gives you a list of the individual modules with their status, so you can determine which one is unsupported!
> 5 votes

---
Tags: 7
---


# Question
Title: Printing printer friendly version of nodes in bulk
My scenario is this, a user selects a bunch of nodes and selects to print all the nodes. What I'd like to happen is, once the user clicks the print button, the print dialog opens up and all the nodes are printed at once. I'm using the Print module and I'm having a hard time figuring out how to print programmatically and all at once.

# Answer
While the print module doesn't have much of an API, you can look at `print_controller_html()` to see how it renders printed pages:

```
$query = $_GET;
unset($query['q']);

$html = theme('print', array('node' => $node, 'query' => $query, 'format' => $link['format']));
drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
drupal_send_headers();
print $html;

```

For your purposes, you can changes a few arguments to the theme function and wrap it around a loop of nodes you wish to print. Something like

```
$html = '';
foreach($nodes as $node) {
  $html .= theme('print', array('node' => $node, 'query' => $_GET, 'format' => 'html'));
}

```

The theme function makes use of a template that you can override in case you want alter the HTML printed in a significant way.
> 1 votes

---
Tags: 7, theming, nodes
---


# Question
Title: How to do translation via csv file imported from PHP my admin
I'm experimenting with a variety of modules to translate, but I find that a simple CSV file would be best.

TMGMT doesn't work for me as I get a lot of bugs that I can't resolve.

Is there a way to translate from CSV export from PHP my admin, translate and then re-import?

# Answer
You can trnslate `Po` files with POEDitor but if you insist use `csv` I suggest you use csv2po , export drupal translate in `po` file, convert `po` file to `csv` translate them in excel (or anywhere you want) then convert back it to `po` and import it to your site.

some quote from its documentation

> csv2po allows you to create CSV files from PO files. This allows you to send translation work to translators who do not or cannot use PO Editors but who can use a Spreadsheet.
>
> po2csv allows you to send CSV files, which can be edited in any spreadsheet, to a translator. This document outlines the process to follow from the raw po files -\> CSV files -\> back to PO. We also look at a case where you may have submitted a subset of the PO files for translation and you need to integrate these.
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: Workbench Moderation - Admin Preview - Show Current Revision in Front-End
Can someone please help me on the following use case related to workbench module showing current revision but in the front-end.

**What I need:**

When we hit the preview button on edit content type (editorial) form, I need a LIVE PREVIEW, to show the current version edited, using my front-end theme I've, to show the article details. I don't want the default preview of Drupal.

# Answer
> 0 votes
It sounds like you want Page Preview.

> **Page Preview** is a low-impact alternative to Drupal's core node preview functionality.
>
> **Why would I need this?**
>
> Drupal's regular node add/edit form provides a "Preview" button that allows you to see what your node content will look like after all of the input filters are applied, without having to first save the node. However, it doesn't allow you to see what the entire node will look like within the context of a fully rendered page

---
Tags: workbench
---


# Question
Title: Webform to add row to specific sql table
I have drupal running and have enabled a few modules including the webform module. I have opened phpmyadmin and added a new table with specific rows.

Now I want to link the two so that a user can log in to the site, fill out the webform with some data each day and I can insert a new row in the table and send each field to a specific column in that row. Later I will build a page for the user to view his inputs, maybe with graphs etc.

Am I on the right track? Is a webform the correct way to do this? And how do I make that link between the two?

# Answer
Sorry, but no, you are on the wrong track.

Webform module is nice and easy, but it uses it's own storage. And whilst you can indeed use hooks to store a copy in your own table, it would take a pretty huge amount of work to do it properly.

It will be easier if you simply write your own module for that. If you don't know where to start, see Examples for Developers.
> 0 votes

---
Tags: webforms, database
---


# Question
Title: How can I check in a condition if an image field has value?
Is there any way to check if an image field has no value after saving the content? I tried with *Data Value is Empty*, but it doesn't work.

These are the exported rules I am using.

```
{ "rules_autos_featured_listing_without_image" : {
    "LABEL" : "Autos: featured listing without image",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "autos" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--listing" : { "bundle" : "listing" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_listing_grouping" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_feature" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_images" } },
      { "data_is" : {
          "data" : [ "node:field-feature" ],
          "value" : { "value" : { "feature" : "feature" } }
        }
      },
      { "data_is_empty" : { "data" : [ "node:field-images" ] } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-listing-grouping" ], "value" : "1302" } }
    ]
  }
}

```

# Answer
> 0 votes
Make sure the field you are trying to "test" (for its value), is available at the time Rules tries to do so.

That's why I always add a `entity_has_field` condition (and put it as the first condition) which looks something as in this example (part of a rules export of some rule):

```
"IF" : [
  { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_appointement" } }
],

```

In my sample here, it is related to entity `account`, and my field's machine name is `field_next_appointement`.

So retry your rule with the `Data Value is Empty` condition, but put such `entity_has_field` condition in front of it. So that in the end your rule has 2 conditions (no PHP coding at all involved), something like so:

* `entity has field` ...
* NOT `Data Value is Empty` ...

Below is a (simple) rule from my training class examples. It'll display a message like "*Watch, this is ONLY 100 EUR !!!!*" for a node which has a `field_article_price` field, whereas that price is exactly 100 EUR.

```
{ "rules_this_article_is_for_sale" : {
    "LABEL" : "This article is for sale",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_price" } },
      { "data_is" : { "data" : [ "node:field-article-price" ], "value" : "100" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Watch, this is ONLY 100 EUR !!!!", "type" : "warning" } }
    ]
  }
}

```

Looking at your (updated) question (now including your current rule), I think you should try to work step-by-step to investigate which part of your rule "doesn't" work. If I was in your shoes, I'd experiment with these variations (only for debugging):

1. Replace the ACTION with just a `drupal_message`:

* if you get a message then, your problem is within ACTION. Todo: fix the Action.
    * if not your problem is in the EVENT of CONDITION(s). Todo: go to item 2.
2. Remove all CONDITION(s):

* if you get a message then, your problem is within CONDITION(s). Todo: fix the CONDITION(s).
    * if not your problem is in the EVENT. Todo: go to item 3.
3. Review the EVENT: if the event you're trying to use to make the Rule work does not actually happen, or if you're "too late", then of course that needs to be fixed/reviewed. In my experience, there are quite a few Rules scenarios where you should use "When Drupal is initializing". My (personal favorite) sample of that is about "before content is going to be viewed" ...

I realize the above 3 steps do not actually "answer" your question, but they may help to debug what's actually the problem.

---
Tags: 7, rules
---


# Question
Title: Creating nodes from json including image field upload
I am trying to create a node programmatically from the data(JSON) sent by my front-end template.

```
<input id="title" name="title" type="text" >
<input id="body" name="body" type="text">
<input type="file" name="pic" id ="pic1" accept="image/*">

```

^^ This is my front end html

```
jQuery(document).ready(function(){
jQuery("#save").click(function(){
    //alert("The paragraph was clicked.");
  var postData =  [{
      "content-type" : "article",
      "title": jQuery("#title").val(),
      "body" : jQuery("#body").val(),
      "pic1" : jQuery("#pic1").val(),
  }];
        jQuery.ajax({
            type: "POST",
            dataType: "application/json; charset=utf-8",
            url: "my-module/create-artcle/", //This is the menu hook I created
            data: {'article': postData},
            success:function(data){
            //if(data.status === "success"){
              alert(data);
            //  window.location = "/user";
            //}
          }
    });
  });

});

```

^^^ This is my json.

This data is sent to the hook\_menu I created, which triggers a callback function to create the node. here is the code for that.

```
function create_article(){
  global $user;

  if(isset($_POST['article'])) {
      $json = $_POST['article'];
      $decodedData = json_decode($json, true);

      $contentType = $decodedData[0]["content-type"];
      $title = $decodedData[0]["title"];
      $body= $decodedData[0]["body"];
      $image1 = $decodedData[0]["pic1"];

       //Create a article
       $node = new stdClass();

       //Set values to fields
       $node->type = $contentType;
       $node->title = $title;
       $node->body[LANGUAGE_NONE][0]['value'] = $body;

       node_object_prepare($node);
       $node->language = LANGUAGE_NONE;
       $node->uid = $user->uid;
       $node->status = 1;

       $node = node_submit($node);
       node_save($node);
  }
}

```

So far I am getting my code to work except saving the image, because I'm seriously confused in saving an image to my node. The value that I get from front-end is simply the name of the image. my question is : can I save an image to the node I am creating with what I am getting from front-end ? If so I am confused with this reference https://www.drupal.org/node/201594

could any one guide me to extend this code to save my image.. $image1 this variable contains the image name.

Thank you.

# Answer
> 0 votes
The best way to achieve that is through Services module

In your case you have to post the image itself and use the file data in node object as a value for the field see that snippet:

```
  //$file_array is the result from saving the file
  //assuming you have the field name is image
  $file_array = api_save_file($_POST['image'], $title);
  $node->field_image[LANGUAGE_NONE][0]['value'] = $file_array

```

Note that you have to save the image base64 encoded like

```
//save base64 images as files
//@return object file object

 function api_save_file($file, $name, $entity_type = 'node', $entity_id = 0){
$data = base64_decode($file);

$finfo = finfo_open();
$mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
finfo_close($finfo);
// get file type png. jpg
$ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
$file_name = str_replace(' ', '-', $name);

$file = file_save_data($data, 'public://'.$entity.'/'.$file_name.'.'.$ext, FILE_EXISTS_REPLACE);
file_usage_add($file, 'file', $entity_type, $entity_id);

return array(
    'fid' => $file->fid,
    'width' => 800,
    'height' => 600,
    'display' => 1,
    'alt' => $name,
    'title' => $name
);

```

}

---
Tags: 7, media, nodes
---


# Question
Title: Status report says database out of date, but update.php and drush say up-to-date
Drupal 7.39, all modules updated to their latest version using Drush 6.6.0. When I look at the status report it says 'database out of date'. When I do `drush updb` or call `update.php` both report that the database is up-to-date.

How can I find out where the problem is?

# Answer
Here are the steps I took to solve the problem. @rooby gave the URL that helped to determine which module.

As you can read on the given URL (https://www.drupal.org/node/1263908) the problem is caused by a module having a version of -1 in the system table. The URL has instructions how to find out which one is acting up. I've followed the one in this comment: https://www.drupal.org/node/1263908#comment-9059569

This basically means:

* open \[drupalroot\]/modules/system/system.install
* find the line `$requirements['update']['severity'] = REQUIREMENT_ERROR;` In drupal 7.39 this is on line 412
* add the watchdog line as described: `watchdog('module update db', $module); // <-ADDED THIS LINE`
* open the status page again
* now open the watchdog page. You should see a line that starts with 'module update db'. After it you can read the module that causes the problem.

In my case that was environment\_indicator. I'm no PHP developer, so I solved the problem by opening the database in Sequel Pro and checking the version column of the system table of this module.

The file environment\_indicator.install shows several updates, the first one creating a table. Since the table was present, I entered its version number (7200) in the system table. Now I was able to run the update.php which showed there were 2 updates. I let it update the database, which ran without problems.

When opening the status page everything was fine and I deleted the watchdog line from the system.install file.

I'm just curious why update.php doesn't find any updates, while status page does.
> 1 votes

---
Tags: database
---


title: Drupal website is broken on localhost

text:
# Question
Title: Drupal website is broken on localhost
I have moved a drupal website from live server to localhost.

But the problem I am facing is that everything is broken. no css, no images only text is visible on pages.

On my live website when I click on login button a popup for login appears. But on local host its not working. I have tried using different login URLs but non of them worked for me.

Here is a URL of one image : localhost/sites/default/files/Screen%20Shot%202015-02-24%20at%206.08.54%20PM\_0.png

Similarly I have viewed source code of page and here are URLs of CSS and JavaScript files

localhost/sites/default/files/css/css\_UCtZrZRD9npGm4D7o8VXPkl5qDJq-m8IlhuR9ccf\_tY.css

localhost/sites/default/files/js/js\_0gj6QcpfRH2jzTbCQqf7kEkm4MXY0UA\_sRhwPc8jC1o.js

These images and files are not found in this location, is this a cache problem ? All these files and images are missing from this location : localhost/sites/default/files

> Note : Most of you are pointing me to following Path :

```
admin/config/media/file-system

```

> Here is what I have

```
Public file system path : sites/default/files
Temporary directory : /mnt/tmp/test

```

> Now should I make both these paths empty ? or change the path ?

# Answer
> 0 votes
It seems that drupal can't process your files due to not writeable file system paths. Go to admin/config/media/file-system and specify public and temporary directories. After that clear all cache here admin/config/development/performance.

# Answer
> 0 votes
I gust it is because you test it on windows, in windows the directory of temp file is different form Linux so you just need go to

`admin/config/media/file-system` end empty "Temporary directory " field then save form , and finally clear the cache

# Answer
> 0 votes
It's definitely the tmp directory issue. Try configuring `tmp` directory or just remove `/tmp` in `admin->Configuration->media->file-system-> Temporary Directory` and save.

Also, the css and Js files you're pointing are caused because the site has `Aggregate css and Javascript` option enabled. You need to disable `Aggregate CSS and JS`, then do backup. To disable it, `admin->config->performance`

---
Tags: media, javascript, theming
---


title: How to enable tokens for custom entity?

text:
# Question
Title: How to enable tokens for custom entity?
I had the impression that in Drupal 8 all entity tokens are provided automatically since it uses the new field structure but I don't see anything available for my entity.

Do I need to enable something in the annotation or did I get it wrong and tokens have to be provided manually like in D7?

# Answer
> I had the impression that in Drupal 8 all entity tokens are provided automatically since it uses the new field structure but I don't see anything available for my entity.

That impression is wrong. Drupal (core) doesn't provide any generic tokens for entities, all that are in core are hardcoded.

Now, token.module, just like in D7, provides some tokens for *configurable* fields. Simply because the existing functionality was ported to D8. It is possible to extend that to all fields and it shouldn't even be that hard. In fact, there's an explicit check that ignores anythig that's not a configurable field, so we just have to remove that and see what happens.
> 1 votes

---
Tags: entities, 8, tokens
---


# Question
Title: Generate image style from existing one instead of original image
How can I make Drupal to generate image style from existing style, instead from original image. For example, original image is 3000x2000. I have a style medium (1000x700). And then I need a style thumbnail (100x100). How can I make Drupal to resize 1000x700 -\> 100x100 and not 3000x2000 -\> 100x100 (for optimization purposes).

# Answer
Instead try to do this job you can have the same result with create another image style and apply sequential this means first apply `1000x700` then `100x100`. I think you don't consider that in one image style we can multi image effect.

I suggest you for better understanding image style read this article
> 0 votes

---
Tags: media
---


title: Import date to Drupal

text:
# Question
Title: Import date to Drupal
I am receiving data from a third party company through XML. I want to add this to my website as drupal nodes, having some information like title, body, summary, image,...

I am able to make a cron job that reads all the data from the XML & write it to a database.

Now I was wondering:

1. Can I write this to the database directly without creating any inconsistenties?
2. What tables do I have to write this to? only the node table and the field\_data tables? Or do I also have to add it to field\_revision tables etc? Am I forgetting any others?
3. Is there a module that's doing this? I tried the Feeds & the Migrate modules, but I can't seem to find anything to set up XML or SQL Data import on those. Either of the 2 is fine, whether it goes directly from the XML, or if I have to import it from SQL, cause then I can just add them to a temp table first.

Thank you very much

# Answer
1. Can I write \[the external data\] to the database directly without creating any inconsistenties?

* Hypothetically, yes. On a practical level, I'd avoid this approach like the plague. For example, in your next question, you ask…
2. What tables do I have to write this to? only the node table and the field\_data tables? Or do I also have to add it to field\_revision tables etc? Am I forgetting any others?

* Thanks for the segue. Why not use Drupal's Feeds module to consume your data and let Drupal and Feeds manage the consumption process? This will ensure all the data modeling, processing, security and coding best practices inherited by the larger community. Why would you bypass all the work that's gone into this development?
3. Is there a module that's doing this? I tried the Feeds & the Migrate modules, but I can't seem to find anything to set up XML or SQL Data import on those. Either of the 2 is fine, whether it goes directly from the XML, or if I have to import it from SQL, cause then I can just add them to a temp table first.

* As ar7Max indicates, you can use the Feeds and Feeds XPath Parser. It's stable, mature and has a large user base. We rely on this combination heavily (50+ sites, 100's of specific feeds imports) mostly without a hitch. The hitch tends to be poorly formed XML output which can break an import — again, this is rare and addressable at the source OR using Feeds Tamper. where you can rewrite the XML data as needed. If you wish, ask your XPath Parser specific questions here — once you understand it, it's trivial to manage.
> 1 votes

---
Tags: datetime, importing-exporting
---


# Question
Title: Can I use sites.php to resolve subdomain on my multi-site installation?
I have a Drupal multi-site setup on Ubuntu.

One of the multi-sites is **cyber.site.edu**.

Our requirement is to have another virtul host named **cyber1.site.edu**.

cyber1.site.edu should also resolve to cyber.site.edu

Can I use example.sites.php? I read the documentation at this link but it is not clear to me.

Any help would be appreciated.

# Answer
> 0 votes
This assumes your multi-site structure is as follows:

```
sites/site.edu
sites/cyber.site.edu

```

Let's start at the top by addressing a few key things:

### 1. Is there a DNS entry for your subdomain?

When working locally, you should add the subdomain to your hosts file.

***Hint:** If browsing to cyber1.site.edu generates "This webpage is not available", the answer is no.*

Help: (AskUbuntu) Setting up subdomain on Ubuntu server

### 2. Have your Virtual Hosts been properly configured?

You need to inform Apache how to pass the correct domains to Drupal.

***Hint:** If browsing to cyber1.site.edu generates a Drupal site installation page, the answer is no.*

Help: How To Enable Multiple Sites on a Drupal Installation On Ubuntu 12.04

### 3. Do you have a folder in *sites/* bearing the actual hostname, including the subdomain?

In this case, we already know the answer is no. If the answer were yes and you had a folder in *sites/* named *cyber1.site.edu* then Drupal would be able to auto-discover it in the usual way. Since you do not, we need to tell Drupal what to do.

This is where *sites.php* comes in handy:

---

### Setting up sites.php

From the docs in *sites/example.sites.php*:

> This file allows you to define a set of aliases that map hostnames and pathnames to configuration directories. These aliases are loaded prior to scanning for directories, and they are exempt from the normal discovery rules. (...)
>
> To use this file, copy and rename it such that its path plus filename is 'sites/sites.php'.

Add this line to the end of the file and save.

```
$sites['cyber1.site.edu'] = 'cyber.site.edu';

```

---
Tags: multi-sites
---


title: Views autocomplete exposed filter

text:
# Question
Title: Views autocomplete exposed filter
I am using autocomplete exposed filter in views for country/city with depth which is working fine but there are many identical city names.

When user types XYZ he sees 2 entries: "XYZ" "XYZ" and has no clue which one belongs to which country.

I would like to show depth of the tree: "ABC-XYZ" "DEF-XYZ" in autocomplete.

# Answer
Hierarchical Term Reference Autocomplete module have the option to show the children with their parent.

> This module provides a new widget for a term reference field that displays the parents of a term matching the autocomplete as well as providing actual TIDs back to the form handlers.
> 0 votes

# Answer
Try Views Reference Filter. Basically you create a second view of type entity reference, which will be used to provide options for the exposed filter in the main view. In this way you can customize how the options will be displayed. For the autocomplete widget you have to apply this patch.
> 0 votes

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


# Question
Title: drupal form with password_confirm field not showing validation
I am writing a profile task which allows the installer to create a user account during the installation process. I have built a form for that task which uses the confirm\_password field.

Unfortunately when I get to the task during the installation process, the form does not show the password strength bar or any other element that should be part of the password confirmation process.

However if I hit reload, then the form does show the confirm password fields properly. If the php form validation function is called, the resulting form display again shows the confirmation password fields properly. At this point I am at my wits end, why the password validation is not showing the JavaScript based elements upon initial load. Below is the code that I have written for this, and I desperately hope that someone can figure out what the devil is going on with this.

```
function development_install_tasks($install_state) {

    $tasks['development_create_default_owner_form'] = array(
        'display' => TRUE,
        'display_name' => st('Create Site Owner'),
        'type' => 'form',
    );

    return $tasks;

}

function development_create_default_owner_form($form, &$form_state, &$install_state) {

  drupal_set_title(st('Configure owner'));

  drupal_add_js(drupal_get_path('module', 'system') . '/system.js');
  drupal_add_js('misc/timezone.js');
  drupal_add_js(array('copyFieldValue' => array('edit-site-mail' => array('edit-account-mail'))), 'setting');
  drupal_add_js('jQuery(function () { Drupal.cleanURLsInstallCheck(); });', 'inline');
  drupal_add_js('jQuery(function () { Drupal.hideEmailAdministratorCheckbox() });', 'inline');
  menu_rebuild();

  drupal_get_schema(NULL, TRUE);

  // Return the form.
return _development_create_default_owner_form($form, $form_state, $install_state);

}

function _development_create_default_owner_form($form, &$form_state, &$install_state) {

    include_once DRUPAL_ROOT . '/includes/locale.inc';

    $form['owner_account'] = array(
        '#type' => 'fieldset',
            '#title' => st('Site owner account'),
            '#collapsible' => FALSE,
        );

        $form['owner_account']['account']['#tree'] = TRUE;
        $form['owner_account']['account']['name'] = array(
            '#type' => 'textfield',
            '#title' => st('Username'),
            '#maxlength' => USERNAME_MAX_LENGTH,
            '#description' => st('Spaces are allowed; punctuation is not allowed except for periods, hyphens, and underscores.'),
            '#required' => TRUE,
            '#weight' => -10,
            '#attributes' => array('class' => array('username')),
        );

        $form['owner_account']['account']['mail'] = array(
            '#type' => 'textfield',
            '#title' => st('E-mail address'),
            '#maxlength' => EMAIL_MAX_LENGTH,
            '#required' => TRUE,
            '#weight' => -5,
        );
        $form['owner_account']['account']['pass'] = array(
            '#type' => 'password_confirm',
            '#required' => TRUE,
            '#size' => 25,
            '#weight' => 0,
            '#description' => st('To create a new user password, enter the new password in both fields.'),
        );

        $form['actions'] = array('#type' => 'actions');
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => st('Save and continue'),
            '#weight' => 15,
        );

        return $form;

    }

    function development_create_default_owner_form_validate($form, &$form_state) {
        if ($error = user_validate_name($form_state['values']['account']['name'])) {
            form_error($form['owner_account']['account']['name'], $error);
        }
        if ($error = user_validate_mail($form_state['values']['account']['mail'])) {
            form_error($form['owner_account']['account']['mail'], $error);
        }
    }

    function development_create_default_owner_form_submit($form, &$form_state) {

        // Setup the user account array to programatically create a new user.
        $account = array(
            'name' => $form_state['values']['account']['name'],
            'pass' => !empty($form_state['values']['account']['pass']) ? $form_state['values']['account']['pass'] : user_password(),
            'mail' => $form_state['values']['account']['mail'],
            'status' => 1,
            'init' => $form_state['values']['account']['mail'],
        );

        $account = user_save(null, $account);

        // Assign the client to the "owner" role.
        $role = user_role_load_by_name('administrator');
        db_insert('users_roles')
            ->fields(array('uid' => $account->uid, 'rid' => $role->rid))
            ->execute();
    }

```

# Answer
> 0 votes
Ok. I am not sure what went wrong, but after I shut down my server and restarted it, the code worked as advertised. The only explanation I have must be that the code was cached and doing a restart cleared it. I know that I had restarted the apache server multiple times, but for some strange reason that was not enough. Who knows. But rather than sheepishly deleting my own post, I figured I'd leave this available for anyone else who would like to reuse the code. Chalking this up to me being stupid.

# Answer
> -1 votes
In `hook_menu` change value of `page callback` to `drupal_get_form`.

---
Tags: 7, installation
---


title: EntityFieldQuery in rules - no result

text:
# Question
Title: EntityFieldQuery in rules - no result
I try to set a new variable in rules. I try to get nid of a node selected by efq like this:

```
<?php
$termid = $node->field_terms['und'][0]['tid'];
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'mybundle')
->fieldCondition('field_terms', 'tid', $termid)

$result = $query->execute();
$nid = array_keys($result['node'])->nid;
print $nid;
?>

```

The problem is that no matter I do, I am not getting nid output. Can anybody help? Thank you.

# Answer
`array_keys($result['node'])` isn't going to return an object that you can select a `nid` property from; it's going to return an array of nids that have `$termid` tagged in its `field_terms` field. If you're just looking for the first nid in the query results you can do `$nid = array_keys($result['node'])[0];`
> 0 votes

---
Tags: rules, database
---


# Question
Title: How can I publish all the nodes authored by a user when the user's role changes?
I'm using the SMSFramework module for my user validation. I have a rule that changes user role to *Confirmed* when the cellphone number is confirmed. All the nodes authored by that user are published.

I am using the *After updating an exisiting account* event. It means I have no access to the users's nodes, but I need to trigger actions on them.

How can I achieve this?

# Answer
> 1 votes
Yes this can be done with the Rules module. Here is a summary of what you'll need to get it to work:

1. Keep track of all node IDs of a user that still need to be published later on (after the user approves the cellphone number). For this add an entity reference to the user's profile (multiple values allowed). And each time such unpublished node get's saved you need to add the reference to that node as an extra value in this entity reference field (= **Rule 1**). So basically this is the "queue" of nodes for a user that need "post processing" after the user approves the cellphone number. It is will serve as your entry point starting from the user's id to "access (find) the exact node ids again later on".
2. Create a rules component (= **Rule 2**, though of type "component") with parameter just a "node id". All this Rules component has to do, is to "publish" the node indicated in the parameter. But you can add any Rules "Conditions" also if you'd need any (already now or later on if requirements change). E.g: check that the node is not published yet, only for specific content types or user roles, etc.
3. Create a rule (= **Rule 3**) containing a *Loop* that should be triggered after the user approves the cellphone number. The goal of this rule is to loop over each of the nodes in the reference field from Step 1, and in each iteration of that loop you use an action which is to invoke the Rule Component as detailed in Step 2 (and which uses the node id as a parameter). By using a Rules Component, you'll be able to add any "Conditions" you might need inside the "Loop".

# Video tutorials

If you're not familiar (enough/yet) with using *Loops* in rules, then watch the video about List and loops.

For a video that is fairly similar to what's needed in step 2 and step 3, refer to the 2nd video (= Solution video) about Creating multiple back links. Some more details about how your scenario slightly differs from what is shown in that solution video:

* You are creating an entity reference **to** nodes also, but **from** a user (not a node).
* You only need the first parameter (= *Node to link to*) in your Rules component (you don't need the 2nd parameter).

---
Tags: 7, nodes, rules
---


title: Master page and details page for Views

text:
# Question
Title: Master page and details page for Views
I have created a new content type and I called it `Opinion`. Then using views, I have created a page with path `/opinion` to be a view for all nodes of type `Opinion` listing i.e. a master page.

The problem is that I could not able to access a the details something like `/opinion/the-node-title`. however, It accesed like `content/the-node-title`

I tried to create a new page from the regarded view with contextal filter `Content title` it works fine using direct access from the browsers address bar. I tried to rewrite the content on the linked title field but I could not able to find a suitable token:

`<a href="[title]">[title]---</a>`

i.e I could not find any way to convert `title` into a slug.

Another thing for SEO, I don't want the same content to be accessed from more than one resource i.e in my case `content/the-node-title` and `opinion/the-node-title`

# Answer
> 2 votes
You need to use pathauto module and configure **URL alias** \>\> **patterns** \>\> **content paths** set opinion/\[node:title\] path alias for opinion content type. All content path for opinion now change as your requirement.

---
Tags: views, tokens, path-aliases, 7
---


# Question
Title: Render scald atom with image style, without new scald context?
We have a field or type "Atom Reference", that references scald images. I want to render these in a node display, using an image style. For this we need a formatter that will render the scald atom with this image style.

The way we currently do this:

1. Create the image style.
2. Create a scald context, and configure it to use a "transcoder" based on this image style.
3. Use the scald context as a formatter in "manage display" for the node view mode.

This means, we need to create a separate scald context per image style.

What I would prefer is to have just one formatter, and then choose the image style in the formatter settings. Maybe with a "flexible" scald context, and then let the formatter alter this context programmatically.

Does something like this exist?

# Answer
The module Scald style contexts aims to provide a context for an image style, I think it potentially addresses some of the additional configuration.
> 1 votes

---
Tags: media, scald, entities
---


# Question
Title: how we can upload file on media browser type field programmatically
> how we can upload file on media browser type field programmatically.
>
> Below are my code:

```
$temp_attachpath = MYFILEPATH;
        $attachpath = drupal_realpath($temp_attachpath);
        if(file_exists($attachpath)){

            $file = (object) array(
                'uid' => 1,
                'uri' => $attachpath,
                'filemime' => file_get_mimetype($attachpath),
                'status' => 1,
            );
            // We save the file to the root of the files directory.
            $file = file_copy($file, 'public://');
            $new_node->field_upload_file[$new_node->language][0] = (array)$file;
        }else{
            $new_node->field_upload_file[$new_node->language][0] = '';
        }
        node_submit($new_node);
        node_save($new_node);

```

# Answer
i change my code and its working for me now.

```
$temp_attachpath = MYFILEPATH;
$attachpath = drupal_realpath($temp_attachpath);
if(file_exists($attachpath)){

    $file = (object) array(
        'uid' => 1,
        'uri' => $attachpath,
        'filemime' => file_get_mimetype($attachpath),
        'status' => 1,
    );

    $file = file_save_data(file_get_contents($attachpath), 'public://'.basename($attachpath));
    $file->filename  = basename($attachpath);
    $file->display = 1;
    $file->description = "";
    $new_node->field_upload_file[$new_node->language][0] = (array)$file;
}else{
    $new_node->field_upload_file[$new_node->language][0] = '';
}
node_submit($new_node);
node_save($new_node);

```
> 1 votes

---
Tags: files, media
---


# Question
Title: How to redirect a menu item to the anchor?
I have created menu with sub-menus. The menu block is placed on the specific page.

Drupal menu path allows only allows normal path to be given to menus(like node/nid and pagepath). I want to give path like **node/256#myblock**.

I do not want to go with contributed modules(void menu or any other) as this is for the single link in my site.

# Answer
Modules are how you extend Drupal's functionality; there's very little point saying you want to achieve something without a module, as if one exists, you're just going to end up copy/pasting its code into your own module/theme anyway to get the same effect.

Drupal core has no functionality to link to an anchor, so you need to install a module which does, or copy the code from one to your own.

Whichever of those methods you decide to use, Special Menu Items has the functionality you require (you can either install and use it as normal, or pick the relevant bits of code out into your own module/theme).
> 0 votes

---
Tags: routes, blocks, hooks, path-aliases
---


title: Extra checkbox in tableselect rows

text:
# Question
Title: Extra checkbox in tableselect rows
I have a list form in a module, which is giving me three columns, the first of which is a checkbox column.

```
function popups_list_form($form, &$form_state){
        global $base_url;
        $header = array("Title", "Popup");

        $result = db_query("SELECT * FROM popups");
        }
        # build the table fields
        $rows = array();
        $options = array();
        $ppups = array();

        foreach ($result as $row){
            $rows[$row->popup_id] = array($row->title, $row->popup_org_name);
         }

        $form['table'] = array(
            '#type' => 'tableselect',
            '#header' => $header,
            '#options' => $rows,
            '#default_value' => $ppups,
            '#empty' => t('No Popups Available'),
        );
        return $form;
    }

```

Why is it happening?

# Answer
That happens because you are using a #tableselect form element, which is clearly described as follows:

> A table created with a far left column of radios or checkboxes. Build the table headings and columns with the #headers property, and the rows with the #options property. See Adding checkboxes to a table for a full explanation.

What you are looking for is a table, which is a theme function. See for example the following code, used by Drupal core.

```
function aggregator_view() {
  $result = db_query('SELECT f.fid, f.title, f.url, f.refresh, f.checked, f.link, f.description, f.hash, f.etag, f.modified, f.image, f.block, COUNT(i.iid) AS items FROM {aggregator_feed} f LEFT JOIN {aggregator_item} i ON f.fid = i.fid GROUP BY f.fid, f.title, f.url, f.refresh, f.checked, f.link, f.description, f.hash, f.etag, f.modified, f.image, f.block ORDER BY f.title');

  $output = '<h3>' . t('Feed overview') . '</h3>';

  $header = array(
    t('Title'),
    t('Items'),
    t('Last update'),
    t('Next update'),
    array(
      'data' => t('Operations'),
      'colspan' => '3',
    ),
  );
  $rows = array();
  foreach ($result as $feed) {
    $rows[] = array(
      l($feed->title, "aggregator/sources/$feed->fid"),
      format_plural($feed->items, '1 item', '@count items'),
      ($feed->checked ? t('@time ago', array('@time' => format_interval(REQUEST_TIME - $feed->checked))) : t('never')),
      ($feed->checked && $feed->refresh ? t('%time left', array('%time' => format_interval($feed->checked + $feed->refresh - REQUEST_TIME))) : t('never')),
      l(t('edit'), "admin/config/services/aggregator/edit/feed/$feed->fid"),
      l(t('remove items'), "admin/config/services/aggregator/remove/$feed->fid"),
      l(t('update items'), "admin/config/services/aggregator/update/$feed->fid", array('query' => array('token' => drupal_get_token("aggregator/update/$feed->fid")))),
    );
  }
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('No feeds available. <a href="@link">Add feed</a>.', array('@link' => url('admin/config/services/aggregator/add/feed')))));

  $result = db_query('SELECT c.cid, c.title, COUNT(ci.iid) as items FROM {aggregator_category} c LEFT JOIN {aggregator_category_item} ci ON c.cid = ci.cid GROUP BY c.cid, c.title ORDER BY title');

  $output .= '<h3>' . t('Category overview') . '</h3>';

  $header = array(t('Title'), t('Items'), t('Operations'));
  $rows = array();
  foreach ($result as $category) {
    $rows[] = array(l($category->title, "aggregator/categories/$category->cid"), format_plural($category->items, '1 item', '@count items'), l(t('edit'), "admin/config/services/aggregator/edit/category/$category->cid"));
  }
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('No categories available. <a href="@link">Add category</a>.', array('@link' => url('admin/config/services/aggregator/add/category')))));

  return $output;
}

```

In your case, your code should simply be similar to the following one. (See also the comments in the code.)

```
function popups_list_form($form, &$form_state) {
  // This variable is never used; remove it.
  // global $base_url;

  $header = array("Title", "Popup");
  $result = db_query("SELECT * FROM popups");

  // The following bracket is wrong placed. Remove it from your code.
  // }

  $rows = array();

  foreach ($result as $row) {
    $rows[] = array($row->title, $row->popup_org_name);
  }

  $form['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No Popups Available'),
  );

  return $form;
}

```
> 1 votes

---
Tags: forms
---


# Question
Title: How to provide option to select geographic part for content
I'm working on Drupal6 travel website and stuck with how to provide option to users to select the right geographic part of the world that they are going to write story about that place.

Should I provide AJAX drop down for example: 1 - Countries (So when user select country) then 2 - Cities/States (Related to the selected country)

If there is something else for that ?

Any help would be appreciated :)

Zafar

# Answer
Try the Location module. It will help you to attach location info with nodes. More details from the module's project page:

> The Location module allows real-world geographic locations to be associated with Drupal nodes, including people, places, and other content. The Location module allows admins to collect addresses, geocode them (translate addresses to lattitude/longitude), and associate locations with Drupal nodes and users. Location data is automatically used to generate GeoRSS within your existing RSS feeds.
> 0 votes

# Answer
Check out these modules:

Leaflet

> Field formatter that can show a map for fields that contain geospatial data. Views integration that plots data on a map (using the sub module Leaflet Views). Lightweight and easy to use API for defining maps and displaying data on a map

Address Field

> Standardized storage of international postal addresses based on the xNAL standard (the same format used by Google Maps for geocoding) Per-country edit form and formatting of addresses Proper formatting of address forms and output on a country by country basis as they are added to the module; see the address formats issue queue for pending country support Feeds integration for address importing Rich snippets / semantic markup via the Schema.org module

Gmap

> The GMap module provides an interface to the Google Maps API within Drupal. It integrates with the Location module to provide users a clickable map for entering latitude and longitude, as well as to display maps of Drupal nodes and users. GMap can be used to create interactive maps with various map markers and content in map bubbles, taking advantage of Drupal's other content management features. The module also provides a Views display plugin which allows users to display the results of a view on a Google map.
> 0 votes

---
Tags: nodes, google-maps, location
---


# Question
Title: Automatically close webform after submission
I have created a Webform with some terms & condition. I have added this webform in **node/upload** page. When user access node/upload page webform comes as overlay on the page. When user selects all terms & condition and submits it redirects to another page which as **close** link. When close link is clicked webform hides.

What I want is instead clicking on **close** link to hide the webform. When user submits the terms & conditions the webform must be hidden. How can i achieve this. I have added screen shot of webforms.

I have added this code to get the webform in node/upload page

```
 if (!isset($user->data['guided'])) {
  $form['#attached']['js'][] = drupal_get_path('module', 'my_module') . '/js/my_module_ajax.js';
}
ctools_include('modal');
ctools_modal_add_js();
if (!isset($user->data['guided'])) {
$form['guideline'] = array(
  '#markup' => '<p>' . t('Review and follow the guidelines outlined in the <a href="@guideline-page" class="ctools-use-modal">Submission guidelines</a> before uploading an item.', array('@guideline-page' => url('modal_forms/nojs/webform/' . 31))) . '</p>',
  '#weight' => -0.01,
);
}

```

# Answer
I think the code mentioned in #4 should work.

```
  function my_module_form_id_alter(&$form, &$form_state) {
    $form["#submit"][] = "my_module_submit";
    if ( $form_state['submitted']){
      $commands[] = ctools_modal_command_dismiss();
       print ajax_render($commands);
       exit;
    }
    return $form;
 }

 function my_module_submit($form,&$form_state) {
   $form_state['rebuild'] = TRUE;
 }

```
> 0 votes

# Answer
You need to use hook\_form\_alter() and on submit of the form you need to set action like this

```
$form["#submit"][] = "ajax_modal_form_submit";

```

and add function

```
function ajax_modal_form_submit($form,&$form_state) {
    ctools_include('ajax');
    ctools_include('modal');
    $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
    $form_state['ajax_commands'][] = ctools_ajax_command_reload();
    drupal_set_message(t("You detail submitted successfully!"));
  }

```
> 0 votes

---
Tags: webforms, javascript, chaos-tool-suite
---