# Question
Title: How to make a callback funciton to a drupal behaviors funtion
I have this Drupal behaviors function:

```
(function ($) {

    Drupal.behaviors.modulenameSwiper = {
        attach : function (context, settings) {
        if ( location.pathname != '/en/imce' ||              location.pathname != '/fr/imce' ||              location.pathname != '/it/imce'     ) {

        var mySwiper = new Array();
        var mySwiperIndex = 0;

        $('.swiper-container').each(function (){
          mySwiper[mySwiperIndex] = new Swiper ($(this)[0],{
              mode:'horizontal',
              loop: false,
              slidesPerView: 'auto'
              });
          });

          mySwiperIndex++;

    }
    }
  }
 }(jQuery));

```

I need to call mySwiper object out of the Behaviors callback. there is anyway to make it?

# Answer
You could assign mySwiper to a property within the behavior.

```
(function ($) {
  Drupal.behaviors.modulenameSwiper = {
    attach : function (context, settings) {
      if ( location.pathname != '/en/imce' || location.pathname != '/fr/imce' ||              location.pathname != '/it/imce'     ) {
        mySwiper = this.get();
        $('.swiper-container').each(function (){
          mySwiper.instances[mySwiper.index] = new Swiper ($(this)[0],{
            mode:'horizontal',
            loop: false,
            slidesPerView: 'auto'
          });
        });
      }
    },
    /**
     * Returns an object with Swiper instances and highest index.
     */
    getSwipper : function () {
      if (this.mySwiper === 'undefined') {
        this.mySwiper.instances = new Array();
        this.mySwiper.index = 0;
      } else {
        this.mySwiper.index++;
      }
      return this.mySwiper;
    },
  };

  $(document).ready(function () {
    console.log(Drupal.behaviors.modulenameSwiper.getSwiper());
  });
}(jQuery));

```
> 1 votes

---
Tags: 7
---


title: How to delete a form element via ajax?

text:
# Question
Title: How to delete a form element via ajax?
This is my custom form with working add more and dummy delete button.

```
function mymodule_mycustom_form($form, $form_state){
   $form['checkboxes_fieldset'] = array(
    '#prefix' => '<div id="checkboxes-div">',
    '#suffix' => '</div>',
    '#type' => 'fieldset',
    '#description' => t('This is where we get automatically generated textfield'),
    '#tree' => TRUE,
  );
  $form['checkboxes_fieldset']['number'] = array(
      '#type' => 'textfield',
      '#title' => 'number',
    );
  // dummy delete button
  $form['checkboxes_fieldset']['delete'] = array(
      '#type' => 'submit',
      '#value' => 'delete',
  );
  $form['add'] = array(
    '#value' => t('add more?'),
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'mymodule_add_callback',
      'wrapper' => 'checkboxes-div',
      'method' => 'append',
    ),
  );

  return $form;
}

```

This is ajax callback for add more button

```
function mymodule_add_callback($form, $form_state) {
  return $form['checkboxes_fieldset'];
}

```

Now i want a working delete. But dont know how?

# Answer
Adding a value using that code won't actually work since you've only defined one textfield, and thus, only one value will be stored. All the new fields returned will have the same id/name as the first one so only one form value will be sent back to the server when the form is submitted.

You need to add an extra layer to the form structure to make each field instance unique, say by including an instance number in each id/name. Something like `$form['checkboxes_fieldset'][$i]['number']` where `$i` is increased by one for each field instance. That goes for all the elements inside the fieldset. You generate these fields in a loop, but before that you check how many instances of the field are already present in the form state so you know how many iterations are needed in the loop. For each iteration, you also check if the form was submitted and if the current field instance matches the name of the button used to submit the form. If so, you skip adding that field instance to the form (don't increment the instance counter this iteration to keep the total count synced).

The submit handlers for adding/removing fields simply set the 'rebuild' flag in the form state and return the fieldset to be updated (all instances get re-rendered each time). Adding/deleting field instances then become an indirect action of rebuilding the form with the correct number of field instances.

The examples module on drupal.org has an "add more" AJAX example which is fairly similar to what you want, except that it always removes the last field instance.
> 2 votes

# Answer
I don't figure out how to delete the element from the form cache. When you deny access for the element you just deleted it might work. Just remember the index you deleted.

```
$form['checkboxes_fieldset']['number'][$deleted_index]['#access'] = FALSE;

```
> 0 votes

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


# Question
Title: Can I program a check on a save on an admin page?
Take for example the CKEditor admin page, where at file browser settings you can choose IMCE at file browser type. Then you click Save.

Can you program this? I mean in PHP; because I could also find out which SQL query is done, and use drush sql-query, but that is not what I mean. I want to program it because I have a multisite with about 70 sites.

Thanks,

Eric J.

# Answer
Yes, use `hook_form_FORM_ID_alter()`

```
function MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'MYMODULE_some_validate_function';
  $form['#submit'][] = 'MYMODULE_some_submit_function';
}

function MYMODULE_some_validate_function($form, &$form_state) {
  if ($form_state['values']['foo'] !== 'bar']) {
    form_set_error('foo', t('Foo must be bar'));
  }
}

function MYMODULE_some_submit_function($form, &$form_state) {
  // Do something.
}

```

It's not possible to be any more specific than that as 'admin' pages vary in their structure. Most are created using a `system_settings_form()`, though, so there's a reasonable amount of consistency.

It's also worth noting that a form created with `system_settings_form()` saves its data in the variables table, so you can accomplish the same thing in a lot of cases with `variable_set()`:

```
variable_set('site_name', 'New name');

```
> 1 votes

---
Tags: forms, users
---


title: Rate content by the author's role

text:
# Question
Title: Rate content by the author's role
I want a five-star content rating system, for example: if a premium user creates a content this will be rated with five starts, if a simple user creates a content this will be rated with three starts etc. I dont wont users to rate the conten. Is something like this possible ???

# Answer
I'll assume your using Drupal 7, you want to look into hook\_node\_update() this will allow you to run code whenever a node is saved/created.

From there you'll have full access to the node object in which you can use user\_load() to grab the user object and check it's roles. Then you need to add logic based on the role to modify the nodes fivestar rating.
> 1 votes

---
Tags: nodes, rating
---


# Question
Title: Views won't display unpublished nodes when explicitly told to
My plan is to have a custom page view at `blog/%` so bloggers can see their own unpublished posts.

If I remove everything except these:

```
Filter criteria
Content: Type (= Blog entry)
Content: Published (No)

Contextual filters
Content: Author uid

```

I still can't see the unpublished nodes without making that user an admin. (IE: I log into uid 12 and go to blog/12 - see no nodes. Make uid 12 admin - see 1 unpublished node)

**Edit:** A look at the SQL shows for admin:

```
SELECT node.title AS node_title, node.nid AS nid, node.changed AS node_changed, node.created AS node_created
FROM node node
WHERE (( (node.uid = :node_uid ) )AND(( (node.type IN (:db_condition_placeholder_0)) AND (node.status = :db_condition_placeholder_1) )))
ORDER BY node_created DESC LIMIT 10 OFFSET 0

```

And for normal user:

```
SELECT node.title AS node_title, node.nid AS nid, node.changed AS node_changed, node.created AS node_created
FROM node node
WHERE (( (node.uid = :node_uid ) )AND(( (node.type IN (:db_condition_placeholder_0)) AND (node.status = :db_condition_placeholder_1) )))
AND ( EXISTS (
  SELECT na.nid AS nid
  FROM node_access na
  WHERE (( (na.gid = :db_condition_placeholder_2) AND (na.realm = :db_condition_placeholder_3) )OR( (na.gid = :db_condition_placeholder_4) AND (na.realm = :db_condition_placeholder_5) )OR( (na.gid = :db_condition_placeholder_6) AND (na.realm = :db_condition_placeholder_7) ))AND (na.grant_view >= :db_condition_placeholder_8) AND (node.nid = na.nid) ))
ORDER BY node_created DESC LIMIT 10 OFFSET 0

```

Obviously there's a massive amount more SQL for normal users than admins despite my not having put anything related to node\_access in there. What is views automatically doing and how can I stop it?

# Answer
Since drupal 7.15 drupal injects node\_access conditions into queries - these can be disabled with the query tag `DANGEROUS_ACCESS_CHECK_OPT_OUT` but views' query tag entry doesn't accept uppercase tags (Yay)

The only solution to remove node\_access checks is to disable query rewriting entirely in Other \> Query Settings
> 2 votes

---
Tags: views
---


# Question
Title: Get authenticated user details from a remote database
I have 2 domains say `site1.com` and `example.com`. I have separate `databases` for both these sites .

How could I perform or allow users from my `site1.com` to login to my second site `example.com` without registering. If a person is an `authenticated user` in `site1.com`, he or she could login to the `example.com` site without `signing up`, i.e by using the login credentials of `site1.com`. Are there any modules that would help or be suitable for my task?

Also I would like to know is I could access some `table` details from a `remote database`. Thanks in advance

# Answer
I recommend separating these questions.

1) Drupal Single Sign on module: https://drupal.org/project/sso

2) Again, I recommend posting this as a separate question, but could you be more specific? which table(s)?
> 0 votes

---
Tags: 7
---


# Question
Title: Can I create an "unlimited" values variable?
I'm trying to create an exclude list of sorts that is configurable via the variable admin interface. I have created lots of single value variables, but never a variable as an array where through the interface the user can "Add" another field/value like you can on nodes with "unlimited" field values.

Can this be done with the Variable module?

# Answer
> 0 votes
I'm not sure how well it will scale, but here is an example for a `multiple` variable in the Variable issue queue https://drupal.org/node/2019629

```
<?php
/**
 * Implements hook_variable_info().
 */
function MY_MODULE_variable_info($options) {
    // Use '[custom]' as a placeholder for the variable name.
    // It will set these properties ('type' and 'multiple') automatically.
    $variables['custom_vars_[custom]'] = array(
        'title'        =>    t('Custom multiple variable'),
        'group'        =>    'site_information',
        'repeat'    =>    array('type' => 'string', 'default' => 'some default value'),
    );
    // if you need to expose your custom variable as token
    // you have to set 'token' key as TRUE,
    // and ought to set the properties (name, description and type)
    // Notice that 'first' it is a name of variable defined in custom_variable_options().
    $variables['custom_vars_first'] = array(
                    'token' => TRUE,
                    'title' => 'Custom variable',                        // name
                    'description' => 'My first variable description',    // description
                    'type'    => 'string'                                    // type
                    );
  return $variables;
}
/**
 * Implements hook_variable_type_info().
 * @return
 *  An array of information defining variable types.
 *  The array contains a sub-array for each variable type
 *  with the variable type as the key.
 *  The possible attributes are the same as for hook_variable_info().
 */
function MY_MODULE_variable_type_info() {
    $type['custom'] = array(
        'title' => t('Custom variables'),
        'type'    => 'select',
        'options callback' => 'custom_variable_options',
    );
    return $type;
}
/**
 * Callback for custom options.
 * @return
 *  An array of variables with the variable name as the key.
 */
function custom_variable_options($variable, $options) {
  return array(
    'first'  => t('My first variable', array(), $options),
    'second' => t('My second variable', array(), $options),
    'third'  => t('My third variable', array(), $options),
  );
}

```

I dont think this is exactly what you want -- but may give you some ideas (it does the `multiple` value per "variable". I'm not sure offhand how you build a variable\_form to edit the values in `function custom_variable_options()`.

---
Tags: 7, configuration
---


# Question
Title: Which module can create a sitemap based on entity reference rather than menus?
Does a module exist that creates a sitemap based on entity reference rather than menus?

The site I am currently working on has it content linked using entity reference rather than using Drupal menus. The reason it has been done like this is because content can fall into multiple categories. But now I am facing the issue of generating a sitemap. Is there anyway to do this? Can it be done using Views maybe?

# Answer
> 2 votes
With the XML Sitemap module, the main alternate to menu-based sitemaps, is the **XML Sitemap Node** submodule.

Enable the sub-module, then edit each content type. There should be an **XML Sitemap** tab at the bottom of the form. Set the inclusion and priority as needed. An advantage of this, over using menu-based sitemaps, is that modified times will end up in sitemap.xml

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


title: RSS icon in QuickTabs

text:
# Question
Title: RSS icon in QuickTabs
I'm using Drupal 7.14 with QuickTabs 7.x-3.4. I have a couple of views with feeds attached to them. I've also set the "Attach To:" field for these feeds. The ones that aren't inside a QuickTab are working fine, but the ones inside QuickTabs won't display their RSS icon. How can I get the views inside QuickTabs to also display their RSS icon?

# Answer
> 0 votes
One way to resolve this is by creating required feeds page with views.

Then add this generated feed pages link manually through Global Text area field of appropriate view in footer using HTML anchor tag. Separate links will be displayed inside each view footer of QuickTabs as per setup.

---
Tags: 7, feeds, blocks
---


title: Passing info into an entityform?

text:
# Question
Title: Passing info into an entityform?
I am displaying a 'Contact Us' entityform in a lightbox (fancybox, specifically). I need the entityform to send the admin the page that the user was browsing when they decided to contact us.

However, because I am displaying the form in fancybox via an iframe (in order to use drupal's ajax capabilities), my entityform is always loading from its own node - not the one I need to email the admins about.

Ultimately, I need to know how to get arbitrary info into an entityform. Any thoughts?

# Answer
Did you try the Prepopulate module? Entityforms just use Drupal Fields so I imagine it should work. You would then just define the values per field in the URL from your email.

> The Prepopulate module allows fields in most forms to be pre-populated from the $\_REQUEST variable.
>
> For example, the following URL,
>
> http://www.example.com/node/add/blog?edit\[title\]=this is the title
>
> will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well. Prepopulate is excellent for creating bookmarklets. For examples on usage for all of these cases, please read the USAGE.txt file that comes with the module or you can read the online handbook page.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Changing a node field without going to the admin section?
I have a page listing articles (in teaser view mode), one of the fields of the article is a taxonomy term reference.

Is there a method allowing users to change this field and save the new article with this new taxonomy term chosen by the user (without going back to the admin section, just in the teaser view mode)?

Thanks in advance

# Answer
> 1 votes
Editablefields https://drupal.org/project/editablefields lets you edit many things, including terms, with ajax (without going to node edit form) but you'd have to be in fields mode.

Make a view, showing fields, and in the term's field settings you can choose "editable" and adjust some settings.

---
Tags: 7, nodes
---


title: Conflicting drupal role ids

text:
# Question
Title: Conflicting drupal role ids
I know that you can create user programtically and set a role:

```
 $roles = array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      4 => 'Member');
$fields = array(
    'name' => $username,
    'mail' => $email,
    'pass' => $password,
    'status' => 1,
    'init' => $email,
    'roles' => $roles,
    );
  //the first parameter is left blank so a new user is created
  $account = user_save('', $fields);
```

and this code works fine. However, I am going to be porting this code to different sites (and back to mine, when I need to do testing on my dev site), and I'm trying to figure out if I'm going to have role id conflicts. Instead of using the above code, and I do the following instead?

```
$roles = array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      "site-member" => 'Member');
```

and thereby never having to worry that I am overwriting a role?

# Answer
> 1 votes
One way can be to get role id from role name than use role, since we fetch the rid dynamically so there is no chance of conflict. An example will go like

```
// Helper function to get user role by username.
function get_role_by_name($name) {
  $roles = user_roles();
  return array_search($name, $roles);
}

// Role ID for Member role
$member_rid =  get_role_by_name("Member");

// Use Rid now
$roles = array(
$member_rid => 'Member');

```

---
Tags: users
---


# Question
Title: Exposed filter on field collection with unlimited values without creating duplicates in view?
I have a 'Video' content type with a 'video\_translations' field collection which is allowed unlimited values. This field collection has a 'language' and 'url' field attached and I want to be able to filter by the 'language' field.

I've created a relationship in the View for the 'video\_translations' field and set the 'Delta' value to 'All'. Then I created a filter for the filed collection item 'language'.

Filtering works okay like this, but using the Delta value of 'All' creates duplicates in my view when viewing all items. If I set that Delta value to, for example, '1', then filtering only looks at the first field collection item, and ignores other values.

e.g. if I have 2 'video\_translations' on a single Video, the first has the 'language' field set to French, and the second to Russian, then with the Delta value set to 'All', that single Video is displayed twice. Once for each 'video\_translations' value. But with the relationship's Delta value set to '1', the Video only appears once, but I'm never able to filter by the second 'language' field.

I want to display the Video once, regardless of how many values the 'video\_translations' field has, and also be able to filter by any of the field collection's 'language' field.

How can I do this in Drupal 7?

# Answer
> 1 votes
The "distinct" button exists in Drupal 7 as it did in Drupal 6 but is buried. Go into "Query Settings" under "Advanced -\> Other" and check the box for "distinct." That'll display duplicate values only once regardless of how many deltas exist.

---
Tags: 7, views
---


# Question
Title: D7 - Get Path Alias (URL) from referenced Taxonomy Value
I'm trying to avoid using the PHP filter due to security concerns.

I have a CCK type I already created called **Slide** that I am dumping out in a view. The Block dumps out all of the items with content type **Slide** which are then used in a homepage slider.

Within the CCK type, I have an Entity Reference field called *Prog Reference* that references a taxonomy value.

What I need is the URL that is associated with that Taxonomy value so I can link up the actual slide.

They click the slide -- takes them to that taxonomy term page.

Current setup:

**Referenced entity**: Prog Reference -- http://d.pr/i/10bX

```
 Entity Reference: Prog Reference

```

**Fields**: d.pr/i/oa3z *(wouldn't let me post as link)*

```
(Taxonomy term entity referenced from field_prog_reference) Taxonomy term: Term ID
Content: Slider Image

```

No **Taxonomy term: Path** :( -- d.pr/i/FtcC *(wouldn't let me post as link)*

```
Taxonomy term: Name
  The taxonomy term name.
Taxonomy term: Programming Image
  Appears in: taxonomy_term:programming_type.
Taxonomy term: Rendered Taxonomy term
  The Taxonomy term of the current relationship rendered using a view mode.
Taxonomy term: Term description
  The description associated with a taxonomy term.
Taxonomy term: Term edit link
  Provide a simple link to edit the term.
Taxonomy term: Term ID
  The tid of a taxonomy term.
Taxonomy term: Weight
  The term weight field

```

Typically you would just use the *Content: Path* field to get the referenced entity's path, but for some reason this isn't an option Taxonomy values?

**Any ideas? All help welcome!! Appreciate in advance!**

# Answer
> 1 votes
Ok then, here are a two options.

Option 1)

* Include your entity reference field.
* Use the 'Label' formatter.
* Rewrite it's output and to /taxonomy/term/\[field\_entity\_reference-target\_id\], see screenshot.

This will output the path to the term page as plain text for you to use as you will. You could output this field as a link and attempt the same pattern.

Option 2) \+ Add a relationship to the referenced entity. See screenshots.

* Once you add the relationship, add the Taxonomy term: Name field using the relationship. See screenshot.

\<\> Then configure to use link and rewrite output if desired.

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


# Question
Title: Organic Groups: Error, The website encountered an unexpected error.
I had OG working fine except I wasn't able to upload images to be displayed (but to still keep the File field for PDF uploads as private to just the group).

However I've gone through and removed the CKEditor module as people suggested to use WYSIWYG with CKEditor (js library) so I moved that.

Then I installed the IMCE - WYSIWYG bridge too and tried several things to get the images working.

They were working but I noticed PDFs were no longer private, now I seem to have narrowed it down to the OG field settings.

If I add the "Group Audience" field to the content type (which is set as OG group content), then I can no longer visit that page and get this error:

```
EntityMetadataWrapperException: Unknown data property og_group_ref. in EntityStructureWrapper->getPropertyInfo() (line 339 of sites/all/modules/entity/includes/entity.wrapper.inc).

```

As soon as I remove the Group Audience field, I can access the content type again (i.e. I can edit, add new etc. for this one content type). However I need the Group Audience field to keep the content secure/private.

# Answer
> 0 votes
I'm still unsure why the error appeared, it might have been because I had renamed the content type (and also renamed the machine name slightly), I deleted and re-built the Group Field settings a few times and cleared the cache (several times) but nothing seemed to work.

Then I was thinking to create a new content type and try that, but when I created the new content type, and went back to verify things, I noticed the Group Field settings were working fine, seems some function somewhere hadn't been called and was only called to refresh the Group Field when new content types were added.

Anyway deleted the new content type as I didn't need to use it - as the old one fixed itself...

# Answer
> 1 votes
Clearing the caches worked for me with a "drush cc all".

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


# Question
Title: How to implement autocomplete for address field using google places/maps api?
When using Eventbrite event creating form, i noticed their address field has an autocomplete feature powered by Google.
Is there a Drupal module that does something similar ?

---

---

Demo link on Google Code

# Answer
> 4 votes
I have created a working sandbox version of address autocomplete. https://drupal.org/sandbox/adammitchell/2126989. I will endeavour to get it created into a full blown project. However if you could help me and test it that would be greatly appreciated.

---
Tags: ajax, location
---


# Question
Title: How to insert a image gallery into node body?
I created a gallery using fields (gallery formatter and lightbox) but i can only add the gallery before or after the field body.

I tried the insert module but it can only add one picture and not the whole gallery.

Is there a way to insert the gallery into the field body at a specific location?

# Answer
This may or may not work for you, try WYSIWYG FIELDS module. If it doesnt work, I cannot think of another turn-key solution.

> The Wysiwyg Fields module is bridge between CCK Fields and the Wysiwyg module, allowing most (if not all) CCK fields to be turned into a Wysiwyg button for a convenient inline solution.
> 1 votes

---
Tags: entities, media
---


title: Block editing disappeared

text:
# Question
Title: Block editing disappeared
Until last week, when i logged in as administrator, on the page of nodes,
i could edit blocks by clicking "edit this block" link which appeared in upper right corner of blocks. But now i can't see edit block link, so for every time i want to edit block i go to "/admin/structure/block" which is very bad.

When i check the page source i can see the links like:

```
<div class="contextual-links-wrapper">
<ul class="contextual-links element-hidden">
<li class="block-configure first last">
<a href="/admin/structure/block/manage/block/32/configure?
destination=admin/config/development/performance">Edit block</a></li>
</ul></div>

```

What would be the problem.
How can i solve this?
Can you please help me.

# Answer
> 2 votes
Do you have the Theme Developer module enabled? I had the same problem (disappearing contextual links menu for blocks) and disabling the Theme Developer module resolved the issue. Likely something to do with the z-order being utilized by Theme Developer.

---
Tags: 7, blocks
---


# Question
Title: How to theme separately the node content and the comments
I have seen here several related questions, none of which clearly provide an answer. I am implementing a theme where I want the node content (with its title, the tabs, etc.) themed completely separately (i.e. in a different div) from the comments. The initial problem is that part of what I consider the node content (the title, the tabs) is rendered in page.tpl.php and part (the node body itself) is rendered in node.tpl.php. The problem is that the comments are an integral part of the variable $content in node.tpl.php.

I found part of the solution:

I found the template comment-wrapper.tpl.php. By reimplementing it in my theme, I can cancel the output of the comments (by blanking out the template).

Now, I would like to use mytheme\_preprocess\_page() to pull up the comments into a variable $comments so that I can add the comments where I want in page.tpl.php.

The remaining problem is how can I get all the variables originally available within comment-wrapper.tpl.php from mytheme\_preprocess\_page()?

Or do you know another (better) way to achieve the same thing?

Another way to answer the question: who calls comment-wrapper.tpl.php ?

Maybe an answer to that question would help:
$content: reworded about manipulating this variable

# Answer
A- The node\_menu (hook\_menu implementation) has node\_page\_view() as a page callback for a node page.
B- node\_page\_view() calls node\_show() which:
1- is not a themable function. 2- mixes (concatenates) the output of node\_view() (the node content itself) and of comment\_render().
C- comment\_render() calls theme('comment\_wrapper', ...)

This is where the serpent bit its tail:
As mentioned in the question, I could reimplement comment-wrapper.tpl.php to nix the output mixed with the node,
but then calling comment\_render() separately to get the comments where I want returns nothing for the same reason!

The conclusion is that the solution cannot be implemented by a theme alone. One would need to implement this in a module and override the node\_page\_view() callback and re-implement node\_show(), taking care of the fact that node\_show() is also called when viewing a node revision ('node/$nid/revisions/$vid/view').
> 0 votes

# Answer
While hideously ugly, and most probably one of the reasons D7 and beyond have gone to render arrays, you can do something along these lines:

Create a new comment-wrapper.tpl.php in your theme:

```
<?php if (isset($node->render_comments)): ?>
  <div id="comments">
    <?php print $content; ?>
  </div>
<?php endif; ?>

```

Since the "standard" `$node` object won't/shouldn't include `$node->render_comments` the various standard drupal core functions dealing with comments won't include the HTML of them.

So, now you can do something like this:

```
$node=node_load(NID); // if not loaded already
$node->render_comments=TRUE;

$comments=comment_render($node); // include `$cid` if you need it

```

with `$comments` now set to the HTML of the comments on that node.

I would put the above logic in `YOURTHEME_preprocess_node()` and not in its `node.tpl.php` template.

But also note, of course/unfortunately, that Drupal is still going to go to all the database effort of rendering the comments both times :(

If this is a performance hit on your system that you want to avoid, you could get even crazier and do something like this in your theme's `comment-wrapper.tpl.php`:

```
  <!-- COMMENTSBEGINHERE -->
  <div id="comments">
    <?php print $content; ?>
  </div>
  <!-- COMMENTSENDHERE -->

```

and then use your implementation of whichever string or regular expression functions you like to cut them out of `$content` in `node.tpl.php` itself.
> 0 votes

---
Tags: 6, theming
---


# Question
Title: How do I fetch user information on a webform?
I have a webform and I want to pull the logged-in user information using LDAP.

When a user opens the current form, I want to display something like *Hello, USER\_NAME, your current status is STATUS*. *USER\_NAME*, *STATUS*, and many other fields are stored on another form.

How can I get their values using LDAP?

I already installed LDAP on my website.

I googled, but I didn't find a working example.

# Answer
1. Figure out the raw ldap queries you need. Outside of php or drupal.
2. Write them down.
3. Use `ldap views` module to make reusable drupal ldap queries. `ldap views` can use tokens and I think parameters in queries ... parameterize as needed.

Then wherever you want your custom message embed the view results onto the page using Context, Panels, hook\_page\_build .... whatever.
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: Drush How to sync between local and server?
I always deploy drupal locally, install need modules, and then write the theme. Then I upload the local site to my server.

But when something needs a update or change, I will modify the local site, and I re-upload the local site to server.

It's very troublesome.

**I want to:**

> sync my local site to my production site, so that when my local site is changed, the updates are uploaded to the server automatically.

It seems that Drush can sync between local and server, and might be useful for this issue, but I can't find useful post explaining how to do this.

Thanks

# Answer
what your looking to learn to do is called drush aliases.

You can read this: https://drupal.org/node/670460

And here are some examples of it: http://deeson-online.co.uk/labs/drupal-drush-aliases-and-how-use-them

I would suggest you to use a virtualbox installation of drupal to test this out so you can get familiar with it first by setting this up: https://drupal.org/project/quickstart

My main local environment for developing drupal sites resides in the virtualbox quickstart. From there I do my tests and you can sync to your live environments using drush aliases. You can test syncing just using the local sites first.
> 1 votes

---
Tags: drush
---


# Question
Title: How to create custom menu link wrapper function in Drupal 7?
As you know default wrapper for menu item in Drupal 7 can be modified via function theme\_menu\_link().

by overriding

```
theme_menu_link($variables) {}

```

function we can modify the rendered html output of menu link but it will change all of menu items that their **#theme** attribute is set to this function. for example in main menu, each item has **menu\_link\__main\_menu** value in it's #theme attribute.

Now I want to create a custom wrapper function in my theme.

I searched and I found I must create a function with structure like

```
theme_menu_link($variables) {}

```

and also I must **REGISTER** the function name in my theme.

For registration, I used **function theme\_theme() {}**

```
function theme_theme() {return array('custom_menu_item_wrapper' => array());}

```

\** theme is replaced by name of theme \** custom\_menu\_item\_wrapper is the name of my function for wrapping operation

But I don't know, how should I define parameters in theme function registration because when custom\_menu\_item\_wrapper($variables) function is called $variables is NULL

# Answer
> 2 votes
Indeed, you need to register a new theme implementation. Looking about the specification of the `hook_theme()`, each information array must contain either a `variables` element or a `render element`. This is missing in your case and causes the empty `$variables` argument.

```
function YOURTHEME_theme()
{
    // define a custom theme implementation
    return array(
        'menu_link_custom' => array(
            'render element' => 'element',
        ),
    );
}

function YOURTHEME_menu_link_custom($variables)
{
    //Build and return custom HTML for your link
}

```

# Answer
> 1 votes
You should not have to register any themes. It is already registered and being used if you have the menu module enabled, which I will assume you do.
All you need to do is override the theme\_menu\_link by putting a function in the template.php file. You can just paste the current one (which I will post below), Change the 'theme' part in the function name to match your theme name, then edit as necessary.

Default theme\_menu\_link:

```
function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

---
Tags: routes, theming
---


# Question
Title: How to display multiple products under each category in a views grid?
Currently I have a views with grid display that has the fields **Content: Category** and **Content: Title**, and a filter criteria of **Content: type** (is a product). This displays all my ubercart products with their associated category above them. So I have a result like:

* Category 1: product x
* Category 1: product y
* Category 2: product z
* Category 2: product t

What I want is to have each category only appear once with a few products listed below each category. Such as:

* category 1:
    + product x
    + product y
* category 2:
    + product z
    + product t

I tried giving the field **Content: Category** and multiple field setting where all values of the field will be shown in the same row but that did not work.

# Answer
> 2 votes
1. In you view page, click **Settings** under **Format** section next to **Grid** or whatever display type you use.
2. For **Grouping field Nr.1** select **Content: Category**
3. Under **Fields** section, click on the field **Content: Category**
4. Check **Exclude from display**
5. **Save**. That's it.

# Answer
> 0 votes
you can do this with Views field view module.

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.

---
Tags: views, entities
---


title: Memory error when creating image styles

text:
# Question
Title: Memory error when creating image styles
I am getting the following error when image styles are being created on my Drupal 7.24 site:

> mod\_fcgid: stderr: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 73834563 bytes) in modules/system/image.gd.inc on line 237"

My style is doing a scale and crop down to 300x200.

I know this could be a problem with my memory limit, which is currently 128M. As this is high, this doesn't seem like an issue.

Could it be from the use of the File (Field) Paths" module for my image names?

# Answer
> 5 votes
What's the size of your image? For scale you may need roughly:

X * Y * 4 (bytes per pixel) * 2 (for source and destination image) * 2 ( to make sure there is enough RAM for computation).

Now, core can require up to 32 MB, and modules can easily double or even quadruple this. So, let's optimistically assume your core + modules only use 64MB. That leaves other 64MB. It means you can safely scale images up to 4194304px. **It seems you have enough memory for 4Mpx input images.** Anything larger can cause this error and it will not be anything surprising.

---
Tags: 7, media
---


# Question
Title: How to create views with date field of a content type?
I am using D6. I want to create a views with date field using in a content type such as "Photo Gallery". What i have done are:-

1. In argument, select Content: Date (Date Appears in: Photo Gallery) then
2. select granularity as "year", sorted descending, check "Content:Date
3. save it.
4. I separately do for both month and day respectively.

What i am getting in URL are like photo-gallery/2010, photo-gallery/2010/2010-10, photo-gallery/2010/2010-10/2010-10/10 for year, month, day respectively.

But i don't want this.

I want Url like for year- photo-gallery/2010, for month- photo-gallery/2010/10 and for day-photo-gallery/2010/10/10 I am stuck here. So how can i do this?

# Answer
You should be able to do something along these lines in a custom module if the out of the box Date and Views modules don't do it:

First off, create all your Views as Block Displays (eg, not Page Displays with a path defined by Views) with the various arguments in place. For ease of discussion later on, let's say the View is called `photo_gallery` with displays of `year`, `month` and `day`.

Then, in your module, define the paths you want, eg:

```
function YOURMODULE_menu() {

  $items=array();

  $items['photo-gallery/%'] = array(
    'title' => 'Photos By Year',
    'page arguments' => array(1),
    'page callback' => 'YOURMODULE_photos_by_year',
    'access callback' => TRUE,
  );

  $items['photo-gallery/%/%'] = array(
    'title' => 'Photos By Year/Month',
    'page arguments' => array(1, 2),
    'page callback' => 'YOURMODULE_photos_by_year_month',
    'access callback' => TRUE,
  );

  $items['photo-gallery/%/%/%'] = array(
    'title' => 'Photos By Year/Month/Day',
    'page arguments' => array(1, 2, 3),
    'page callback' => 'YOURMODULE_photos_by_year_month_day',
    'access callback' => TRUE,
  );

  return $items;

}

```

And then for your callbacks, you embed the view you want using the argument styles it wants, which would probably be something like this:

```
function YOURMODULE_photos_by_year($year) {

  return views_embed_view('photo_gallery', 'year', $year); // eg 2014

}

function YOURMODULE_photos_by_year_month($year, $month) {

  return views_embed_view('photo_gallery', 'month', $year . '-' . $month); // eg 2014-01

}

function YOURMODULE_photos_by_year_month_day($year, $month, $day) {

  return views_embed_view('photo_gallery', 'day', $year . '-' . $month . '-' . $day); // eg 2014-01-04

}

```

Now the above is all pretty broad strokes typed in directly (typos may abound) and not actually tested (I don't really know the exact format of the dates your Views arguments should be in) but should get you on your way. Things to keep in mind are argument validation (eg `photo-gallery/notayear/notamonth/notaday`) and paging of results.
> 0 votes

---
Tags: views, 6
---


# Question
Title: Programmatically trigger rules action component
I have some problem in triggering an action component.
I tryed to call it from the module function and from the devel/php page.

This is my component settings

As you can see I have one node argument followed by 4 text arguments. And i'm trying to call it with this code

```
$node = node_load( 981 );
$return = rules_invoke_event('rules_send_mail',
    $node,
    'mymail@gmail.com',
    '123',
    'nome',
    'sss' );
print_r( $return );

```

Nothing is printed on the page.. not an array or a FALSE.
The action simply send and email to client\_mail.

Can someone help me to understand why is not working?

# Answer
> 5 votes
if its a rule action component than it should be called by

```
 rules_invoke_component('name', $other_parameters..);

```

while `rules_invoke_event()` is suppose to trigger an event on which you might have different rules to act on.

---
Tags: rules, actions
---


# Question
Title: Drush policy restriction doesn't restrict sql_sync
On my @dev machine, I've installed a drush policy rule that should (?) prevent sql\_sync to my remote @prod machine,

```
cat /etc/drush/policy.drush.inc
    <?php
    function drush_policy_sql_sync_validate($source = NULL, $destination = NULL) {
        if ($destination == '@prod') {
            return drush_set_error(dt('POLICY: sql_sync TO @prod is NOT allowed'))
        }
    }

```

When I attempt the sql\_sync, instead of preventing the action and printing the error, it allows it,

```
drush -v sql-sync --simulate=0 @dev @prod
    Loaded alias @defaults from file /etc/drush/aliases.drushrc.php                                [notice]
    Loaded alias @prod from file /etc/drush/aliases.drushrc.php                                    [notice]
    Loaded alias @dev from file /etc/drush/aliases.drushrc.php                                     [notice]
    /home/drupal/drush/drush  --backend=2 --verbose --uri=https://dev.mydomain.com                 [notice]
    --root=/home/drupal/dev  sql-conf   --all 2>&1
    ssh -o PasswordAuthentication=no root@prod.mydomain.com 'drush  --backend=2 --verbose          [notice]
    --uri=https://prod.mydomain.com --root=/home/drupal/prod  sql-conf   --all
    2>&1' 2>&1
    Modification time of local dump file /home/drupal/drush-dumps/sql-sync-dev.sql is less than 24 hours [warning]
    old. Use the --no-cache option to force a refresh.

    You will destroy data in prod.mydomain.com/prodDB and replace with data from devDB.

    You might want to make a backup first, using the sql-dump command.

    Do you really want to continue? (y/n): y
    Calling system(rsync -e 'ssh ' -akzv --exclude=".git" --exclude=".gitignore" --exclude=".hg" --exclude=".hgignore" --exclude=".hgrags" --exclude=".bzr" --exclude=".bzrignore" --exclude=".bzrtags" --exclude=".svn" --stats --progress /home/drupal/drush-dumps/sql-sync-dev.sql root@prod.mydomain.com:/home/drupal/drush-dumps/sql-sync-prod.sql);
    sending incremental file list

    Number of files: 1
    Number of files transferred: 0
    Total file size: 14634184 bytes
    Total transferred file size: 0 bytes
    Literal data: 0 bytes
    Matched data: 0 bytes
    File list size: 37
    File list generation time: 0.001 seconds
    File list transfer time: 0.000 seconds
    Total bytes sent: 46
    Total bytes received: 12

    sent 46 bytes  received 12 bytes  38.67 bytes/sec
    total size is 14634184  speedup is 252313.52
    Calling system(ssh -o PasswordAuthentication=no root@prod.mydomain.com 'mysql --database=prodDB --host=127.0.0.1 --user=dbadmin --password=secretpassword --silent < /home/drupal/drush-dumps/sql-sync-prod.sql 2>&1');
    Command dispatch complete                                                                      [notice]

```

What do I need to change/add to get the policy to restrict the sql\_sync?

# Answer
> 3 votes
I added this to my sync\_enable commandfile, and it definitely worked:

```
function drush_sync_enable_sql_sync_validate($source = NULL, $destination = NULL) {
  if (strpos($destination, 'live')) {
    return drush_set_error('DRUSH_BAD_DEVOPS_NO_BISCUIT', dt("Don't sync to live."));
  }
}

```

That looks the same as what you've got, so the next thing I'd recommend that you try is `drush cc drush`, to clear the Drush commandfile cache. That will insure that Drush can see your policy file.

**UPDATE:**

Sorry, the problem was that Drush looks for site-wide commandfiles in '/usr/share/drush/commands', not '/etc/drush'. Move your policy file there, and then `drush cc drush`, and it should work.

---
Tags: drush, staging
---


title: How does drupal updates check work?

text:
# Question
Title: How does drupal updates check work?
I don't have an external crontab set up for my Drupal site. How can Drupal search for updates in this case?

# Answer
> 3 votes
There **should** be a crontab task for Drupal. If there is none, it falls back to Poormanscron \- integrated into Drupal core since 7.x

> The module inserts a small amount of JavaScript on each page of your site that when a certain amount of time has passed since the last cron run, calls an AJAX request to run the cron tasks. However, this approach requires that your site gets regular traffic/visitors in order to trigger the cron request.

When check is initiated, it loops over modules and checks their status from URLs determined in function `_update_build_fetch_url` define at line 287\* of update.fetch.inc file, in *update* core module.

For more details, examine *update* core module, code is pretty well documented.

---

* Information valid for Drupal 7.25, may slightly change with version.

---
Tags: updating
---


# Question
Title: Import translation file only for specific core module
I am creating a multilingual D7 website. I am using core module locale and i18n contrib module. I am trying to import the localization files for a language.

I know that I can download the *unified .po file* for a language from https://localize.drupal.org and import it in the multilingual website from http://EXAMPLE.COM/admin/config/regional/translate/import.

Is there a way I can export from https://localize.drupal.org a .po file *only for a specific core module* (eg contact)? I can do this for a contrib module but not for a core module.

Thanks a lot.

# Answer
Nope, you cannot.

Translations are stored per project, not per module, and core is one project. Of course there is experimental Contact project on Drupal.org, but it's translation stays pretty empty as it's not needed.

Worse, in exported files (at least in my language) there is no metadata, no comments about modules these strings originated. So manually cutting this file to your needs would be pretty hard, too.
> 2 votes

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


# Question
Title: Why doesn't my code to save an order work when invoked by AJAX?
I am programmatically creating an order in Drupal Commerce. It works perfectly with a user who is logged in, but for anonymous users it redirect to a checkout page and shows a "page not found" message.

```
$product_id = 1;
$order = commerce_order_new($user->uid, 'checkout_checkout');
commerce_order_save($order);
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;
commerce_order_save($order);
drupal_goto('checkout/' . $order->order_id);

```

# Answer
> 1 votes
The reason you are getting page not found is might be because of security check. In other words why any user can not access checkout page for any other user.For authenticated user drupal manages the mapping of order id and user id, but when user is anonymous drupal checks if the accessed order id is in current session or not, so while creating the order progammatically we do not need to explicitly set the order into session.

A nice example:

commerce\_cart\_order\_new()

> Creates a new shopping cart order for the specified user.

When you are on the commerce\_cart\_order\_new() api page, check the codes after comment

> // If the user is not logged in, ensure the order ID is stored in the session.

That is how drupal cart does while creating order for anonymous user.

Reason:

Before a user a able to move to checkout page drupal checks if the current user has access or not using commerce\_checkout\_acess().For authenticated user it simply checks if the current user id is same as the order owner user uid if so user can move to checkout page.For anonymous user drupal checks SESSION, if in current session acsessed order id exists user can move to checkout page or access is granted to user.

**Solution:**

Use of commerce\_cart\_order\_session\_save() to set the session like drupal cart does.So your code will look like

```
$product_id = 1;
global $user;
$order = commerce_order_new($user->uid, 'checkout_checkout');
commerce_order_save($order);
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;
  // If the user is not logged in, ensure the order ID is stored in the session.
  if (!$user->uid) {
    commerce_cart_order_session_save($order->order_id);
  }
commerce_order_save($order);
drupal_goto('checkout/' . $order->order_id);

```

---
Tags: commerce
---


# Question
Title: Drush API for downloading module from a script
I am trying to download module using Drush API via drush script as following:

```
#!/usr/bin/env drush
<?php

// check if we can bootstrap
$self = drush_sitealias_get_record('@self');
if (empty($self)) {
    drush_die("I can't bootstrap from the current location.", 0);
}

// goes to site directory
drush_op('chdir', $self['root']);

drush_include_engine('drupal', 'environment', drush_drupal_major_version());

//****how to download module

drush_module_enable(array('uuid'));

drush_print("Done.");

```

While i see an Drush API for enabling, i don't see for downloading a module
How to download a module via Drush API from the script? Is there Drush API for automatically detect dependencies, download them and enable? Thank You

Drupal 7, Drush 5.8, Mac

# Answer
> 4 votes
If there's an API for this, I think it would be drush\_invoke\_process. I believe Drush uses that function internally when one command wants to execute another.

The primary function that executes the download work is drush\_pm\_download(), so you could probably just call it directly as well.

And of course, as a last resort, you could use `exec``(drush @alias dl $module)`.

---
Tags: drush
---


# Question
Title: Reference to another database as a prefix
I have a problem referencing another database as a prefix in my `settings.php` file.I have a master-site\[`mysite.local`\] and a slave \[`sub.local`\].Both of them are having separate database.I need to check the `users table` of the `master-site` as well as the `users table of the slave site` ,when a user tries to authenticate to the slave which is `sub.local`.I tried adding the following in the settings.php file of the slave

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'sub_drupal', //Database for the slave site
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
                'default'   => 'sub_drupal.',
                'users'     => 'study.', //parent database
                'sessions'  => 'study.',
                'role'      => 'study.',
                'authmap'   => 'study.',
                'users_roles'   => 'study.',
            ),
    ),
  ),
);

```

But now it authenticates users only on the parent database.Is it not possible to authenticate users present in the slave database `sub_drupal` and also in the parent database `study`.Hope someone could help me with this.Thanks

# Answer
You have the format wrong for two databases you need something like this:

```
$databases = array(
  'default' => array(
    'default' => array(
      'database' => 'd7',
      'username' => 'root',
      'password' => 'root',
      'host' => '127.0.0.1',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'db2' => array(
    'default' => array(
      'database' => 'd7_parent',
      'username' => 'root',
      'password' => 'root',
      'host' => '127.0.0.1',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

You can then use `db_set_active('db2');` to change the connection and begin querying the second database.
> 0 votes

---
Tags: 7, users, configuration
---


# Question
Title: Performance - custom php block or views to use in panels
I use panels to display block with node title on a custom position. My question is about performance - what is faster - to use following php code inside block

```
<?php
$node = menu_get_object(); print $node->title;
?>

```

or to use use views to get title of current node. Thank you

# Answer
> 1 votes
Personally, I don't worry about performance of little things like this.

You also don't need to resort to Views to get this information.

If you are using the **Node template** page from Page Manager, then you can

* edit the page
* select the variant
* edit the content
* click the gear on the panel you want to **Add Content**
* click the **Node** tab
* click **Node Title**

This will then be a normal panel pane that you can place as you need it. This is one trick to get node content above the page title on complicated layouts.

---
Tags: views, 6, nodes, panels, performance
---


# Question
Title: Including a file on every page in a module
I have a module that provides about two dozen pages (in a site with 1000s of pages). I have a file that contains a number of large functions. I want to include this file on every page used by my module. My options appear to be:

1. Call `module_load_include` in every page callback - seems a slight pain
2. Add the file option to every item in `hook_menu` (which would be fine as long as I don't want the page callbacks to go in a separate files from my .module file)
3. Wrap all the functions in a class, include the file using files\[\] in my .info file and then call the functions like `myclass::myfunction()` \[which sorta seems a slight misuse of the class system as most functions are returning arrays of data unconnected to each other\]
4. Load the file in `hook_init`, which means it would be loaded for every page in my site, not just the dozen specialist pages

It looks like 3 may be the best bet, but I'm just wondering if I'm missing something that allows me to include the file in one place just for my module pages without lots of duplicate calls to `module_load_include` and without using classes.

# Answer
> 2 votes
If the file needs to be included on every page, the correct way is to use PHP's `include` or `require`, I don't think the fact that this is in a Drupal site should really make any difference.

I've seen plenty of modules that literally put the following at the top of the module file:

```
require_once('module.inc');
require_once('test.inc');

```

If you really want to do it a 'Drupal' way, you can use `module_load_include()` (which just wraps around `require_once` internally), directly at the top of the file instead of inside your page callback. This is what I tend to do normally.

```
module_load_include('inc', 'MYMODULE', 'MYMODULE.something');

```

Adding the file in `hook_init()` is perfectly fine too, I can't think of any justification to use one over the other, it would be down to personal preference.

# Answer
> 0 votes
You could put the code into classes, either as static methods or full-on OOP.

Then you can use autoload to include those files when they are needed. Either using the files\[\] key in the \*.info file, or using xautoload + PSR-0.

The benefit is that those class files will really only load when needed, and you don't need any manual include.

---
Tags: 7
---


# Question
Title: How to make URL arguments available as tokens in Rewrite Results of a Field in a View?
Is it possible to make URL arguments, e.g.

```
http://mysite.com/arg1/arg2/arg3

```

available as tokens in the rewrite results settings for a field in views e.g. for the above these would be available for use (among other existing tokens) as:

```
[arg1] [arg2] [arg3]

```

**Background**

I am developing Views using OpenLayers maps with filtered items place in an overlay on them. When the user interacts with the map to remove items, I want to retain the position of the map (an not have it revert to a default zoom and position) when the page reloads. By being able to access the URL arguments i.e. longitude and latitude, I can then rewrite the filter URL so that these are sent back to the page.

But I'm sure there are other scenarios that don't use maps that people would find answers to the question useful for.

# Answer
> 6 votes
If you do not want to actually use a contextual filter, you can use a "Global: Null" contextual filter, use the Contextual filters options to assign the value from the argument position you are interested in and then that becomes available as a %1/!1 replacement token without actually affecting the query.

# Answer
> 4 votes
If `arg2` and `arg3` are, or can be, arguments/contextual filters in the View in question, you should be able to use `!1` and `!2` in the rewrite.

I am ignoring `arg1` as that really can't easily be dynamic.

ADDITION:

This could be another case of my assuming D7 hasn't gotten rid of D6 features, but a quick screen grab here (I don't have a D7 testbed handy right at this sec, sorry) shows this as part of rewrite when arguments are present:

This is a quick View with two arguments, a node nid and type, and when I rewrite this field (the title), I can put in `Hello [title] where nid is !1 and type is !2` and it works.

2ND ADDITION:

Even though this answer no longer is valid to the issue at hand (see abounding comments on both answers), @Molot did confirm that these replacement patterns are available in D7:

so perhaps this and his answer will help someone else looking out there.

# Answer
> 3 votes
Assuming arguments you want to use are not views arguments or contextual filters, if you wantthem as tokens, you basically need to create a module that implements hook\_tokens() and hook\_token\_info(), as described in the API. I don't think anyone did it already.

Here is how I'd do it:

```
function yourmodule_token_info() {
  $type = array(
    'name' => t('GET'),
    'description' => t('Tokens related to $_GET superglobal.'),
  );
  $tokens = array();
  foreach($_GET as $key => $val) { //discard $val now
    $tokens[$key] = array(
      'name' => $key,
      'description' => "\$_GET['$key']",
    );
  }
  return array(
    'types' => array('get' => $type),
    'tokens' => array('get' => $tokens),
  );
}

function yourmodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  if($type == 'get') {
    $replacements = array();
    foreach ($tokens as $name => $original) {
        $replacements[$original] = (string)$_GET[$name];
    }
    return $replacements;
  }
}

```

Of course code above is **not production ready**, it ignores proper type handling, security issues and so on. It's meant to set you on the right track, but you need to apply your own sanity before deploying it. I take no responsibility for abuse. Read about the reasons it was removed in the first place before you decide to add it back, and be careful to restore only what you really need.

If you want parameters accesible by `arg()` instead of $\_GET, of course in hook\_tokens iterate over them with `while`:

```
function yourmodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  if($type == 'arg') {
    $replacements = array();
    $i = 0;
    while ( NULL !== ($arg = arg($i))) {
        $replacements["arg:$i"] = (string)$arg;
    }
    return $replacements;
  }
}

```

Change `yourmodule_token_info()` accordingly.

---
Tags: 7, uri, views
---


title: How do we interpret a Drupal's URL?

text:
# Question
Title: How do we interpret a Drupal's URL?
I am a newbie to Drupal, and have used CakePHP and Codeigniter frameworks earlier. In Codeigniter, a URL such as /users/show/1 would be interpreted as it invoking the `show()` method of the `Users` class, passing 1 as user ID. Can we interpret a Drupal URL in this way?

If we have a URL similar to /admin/xyz?u=1, where in the admin module can I find this?

Also, I know Drupal uses a good bit of path alias. Would that affect this in a big way?

# Answer
> 3 votes
If your looking at code, all the hook\_menu function calls is how the non alias paths get created. Things like users and nodes use a % in the path creation; this turns into the argument for the page callback function. Read more about this here: Wildcard Loader Arguments.
node\_menu()

```
function node_menu() {
...
  $items['node/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
    'type' => MENU_CALLBACK,
  );
...
}

```

user\_menu()

```
function user_menu() {
...
  $items['user/%user_uid_optional'] = array(
    'title' => 'My account',
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
    'page callback' => 'user_view',
    'page arguments' => array(1),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    'parent' => '',
    'file' => 'user.pages.inc',
  );
...
}

```

The function that handles this menu information is menu\_execute\_active\_handler().
Aliases happen as the 2nd to last part of the bootstrap in the drupal\_init\_path function. It converts `/about-us` into `node/4` for internal use.

For more in depth information check out this link: Drupal menu system (Drupal 6.x)

# Answer
> 3 votes
The answer given by mikeytown2 is correct, but it doesn't report what happens before the implementation of `hook_menu()` made from the modules are invoked.

If you have clear paths enabled in your Drupal site, a URL like example.com/node/1 is converted from the .htaccess file used by Drupal in example.com/index.php?q=node/1. The content of the index.php file is the following one (for Drupal 7):

```
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

```

It is menu\_get\_active\_handler() that, through menu\_get\_item(), finds which callback outputs the content of the required page (in the example, node/1). Drupal allows the modules to define the paths they are able to handle through wildcards, such as in node/%node, or with plain paths, such as admin/config/search/path; the difference is that in the first case the module is able to handle paths such as node/1, node/2, node/444 while in the second case the module report the exact path it is able to handle.
The modules implement hook\_menu() that allows them to define which page callback they assign to the path; that callback is the function that outputs the content that is shown when that path is required.

# Answer
> 0 votes
Drupal relies on several basic URLs such node/# or user/#. No further direction is taken from the base URL name. Path alias's can be used to hide the base URL, but its structure is up to the user. Certain modules such as views or panels will read the urls and are capable of using the alias information to perform contextual filtering or create custom displays.

# Answer
> 0 votes
I have a cakephp background too and I got what you want to know:

In Drupal a url like /admin/xyz does not necessarily mean that it is generated by a class called admin or by admin module (In fact there's no admin module).

If you want to know which function (controller action) responsible of generating the content in Drupal, let's check the following:

in cakephp

```
<?php
   class MyModuleController extends ApplicationController{
       public function hello_world($arg) {
          return 'Hello World';
       }
    }
 ?>

```

So the url will be my\_module/hello\_world/\*

let's take a look at the following drupal module:

```
<?php
    function mymodule_menu() {
        $items = array();
       // in the first line after this comment my_module/hello_world is the non aliased url
       // like the whole posts/view part
       // which can be your_module/admin/hello_george this can help in placing your menu item
       // in the right hierarchy globally
        $items['my_module/hello_world'] = array( //the url my_module/hellow_world
            'title' => 'Hello World Test',
            'page callback' => 'say_hello_world', //the function called
            'page arguments' => array(''), // the arguments like 123 in posts/view/123
            'access arguments' => array('access content'), //permission
            'type' => MENU_CALLBACK,
         );
        return $items;
    }

    function say_hello_world() {
        return 'Hello World!';
    }
?>

```

again the url will be my\_module/hello\_world. Which in the case of Drupal can be anything. So, to answer your question... you cannot know "where in the admin module can I find this?" but you can use some tools like devel module for example or anyway its not that hard to get used to Drupal way.

so, if you are on a user page for example or on a page that you know it is generated by a specific module just open the \*.module file and check the menu modulename\_menu function.

---
Tags: 7, uri
---


# Question
Title: Pass title of current node to subsequent node created in modal
I need to pass the title of the current node to the title field of an add node form that pops up in a modal using. I am using auto node title which allows the use of tokens as replacement patterns but \[current-page:title\] results in the title 'Create User Photos', the title of the add node form. Can anyone tell me how to pass the title of the review node either through auto node title or by changing the form's title to match the review node?

I am using the form block module to render the add node form as a block then using js to display it as a modal. I am trying to pass the title to make the nodes related if you will.

I am open to other ways to relate the nodes.

A little context: I've got restaurant review nodes with photo galleries. Users can add photos to a reviews gallery via a modal form that creates a new node containing the photos. I would like the title of the new photo node to match the review node's title but I haven't been able to do that.

# Answer
> 0 votes
If your form is not loaded via ajax then you can write a form alter hook in your module and alter the photo node form and provide a default value for the title field of the photo node form. You can either query or do node\_load() of the current review node to get the title. You can retrieve the nid of the current node by the arg(1) function.

When you have the title of the review node you can assign it as the default value of the photo node.

# Answer
> 0 votes
I've never used the Form Block module before, but since it's a form, I would use the "hook\_form\_alter" to update the title of the form.

```
function yourModule_form_alter(&$form, &$form_state, $form_id) {

   if ($form_id == "your_form_block_id" {

       // Get node details from URL arguments (normally /node/nid
       // I'm assuming this. Your node id can be arg(1) or arg(2)...
       // Changing it accordingly

       if (arg(1) && is_numeric(arg(1)) {

           $node = node_load(arg(1));
           $node_title = $node->title;

           // Replace form title
           $form["#title"] = $node_title;
       }
   }
}

```

# Answer
> 0 votes
So it turns out the right way to do this is by setting the title in hook\_node\_presave and using menu\_get\_object() to get the parent node.

```
    function mymodule_node_presave($node) {
        if ($node->type == 'user_photos') {
            if (!isset($node->nid)){
                $ref_node = menu_get_object();
                $node_title = $ref_node->title;
                $node->title = $node_title;
            }
        }
    }

```

---
Tags: forms, nodes
---


title: How to add Text Resize button to theme?

text:
# Question
Title: How to add Text Resize button to theme?
Whats the best way to add a Text Resize feature in the theme instead of using contrib modules.

I have tried Text Resize but it dosn't work for my custom theme. I told it to resize in entire "body" of my page but it ends up resizing only one paragraph.

are there other themes who have done this?

# Answer
> 1 votes
I would recommend against including this functionality on your site. Re-sizing text is best handled by browsers and assistive technology. Check out this discussion: https://groups.drupal.org/node/85254

The key thing is to use relative CSS units (em and %) when defining font-sizes and typography-related dimensions in your theme.

# Answer
> 0 votes
Experiment more with the selector used in the module and try also to adjust the CSS of your theme to allow the change to happen. Use element inspector tools to see what's actually going on on the page.

If you want to write that yourself - have a loot at the code in the module. The core mechanism is pretty straightforward and relies in JS + setting up the cookies to remember the user setting.

# Answer
> 0 votes
I would also suggest that instead of relying on a custom functionality, its advisable to use the browser based utilities. In the unlikely case that it i essential, plz follow the JQ cookie instructions given as part of the module in the admin page or the instructions.

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


title: Load Panel from custom module?

text:
# Question
Title: Load Panel from custom module?
Anyone know of a way to export all the data found in a panel layout, context e.g. into a custom module in order to deploy from development to production?

Something like with views via the Implements hook\_views\_api() ?

# Answer
You can use features module to export your panel page in form of a module.
> 0 votes

---
Tags: panels, features, importing-exporting
---


# Question
Title: how to check if the image field is empty or have uploaded image?
```
<?php
  $nid = arg(1);
  $path = arg(0);
  $node = node_load($nid);
  if(isset($nid) && is_numeric($nid) && isset($path) && $path == 'node' && isset($node) && $node->type == 'page') {
    $theme_img = file_create_url($node->field_page_cover_image[$node->language][0]['uri']); //origional image path
    if($theme_img) {
        //image having style
        print theme('image_style', array('path' => $node->field_page_cover_image[$node->language][0]['uri'], 'style_name' => 'page_theme'));
    }
   }
?>

```

I've loaded the above code in page.tpl.php. It is to load the uploaded styled image from individual pages.
I am getting error in line no. 6 ($theme\_img), for pages which have empty image field. It is working fine in pages which have image uploaded. How to know if this field is empty or have image uploaded.

# Answer
> 2 votes
Try this:

```
if ($node = menu_get_object('node')) {

  // Set default language if not set
  $node->language = isset($node->language) ? $node->language : LANGUAGE_NONE;

  if ($node->type == 'page' && isset($node->field_page_cover_image[$node->language][0]['uri'])) {
    print theme('image_style',
            array('path' => $node->field_page_cover_image[$node->language][0]['uri'],
                  'style_name' => 'page_theme'));
  }

}

```

Odd you're printing out the image though, must be in a tpl file. I'd suggest moving the code logic to a hook\_preprocess\_node and setting a template variable instead.

e.g:

```
/**
 * Implements hook_preprocess_node
 */
function MYTHEME_preprocess_node($variables){

  $node =& $variables['node']; // by reference
  // Set default language if not set
  $node->language = isset($node->language) ? $node->language : LANGUAGE_NONE;

  if ($node->type == 'page' && isset($node->field_page_cover_image[$node->language][0]['uri'])) {
    // Add new template variable called $page_theme_image
    $variables['page_theme_image'] = theme('image_style',
            array('path' => $node->field_page_cover_image[$node->language][0]['uri'],
                  'style_name' => 'page_theme'));
  }

}

```

and then in your tpl.php file, you just go:

```
if (!empty($page_theme_image)) {
  print $page_theme_image;
}

```

---
Tags: theming, media
---


# Question
Title: How can I debug white screen when running install script?
I'm doing a fresh install of drupal7 on Ubuntu following these instructions.

When I get to the point of running the install script (by pointing the browser at localhost/drupal7/install.php) it just gives a blank screen.

Most questions/help about the Drupal blank screen relate to site setup but as this is a new install, I haven't created any sites yet so am unable to figure out what to do.

Does anyone know how to debug or move past this issue?

# Answer
You can edit your settings.php file and add

```
ini_set("display_error" , 1);

```
> 0 votes

---
Tags: installation
---


# Question
Title: How can open add content form in modal form module
I want to load content form (example article content type ) in modal.

As **Modal module** allow to open forms in modal, but by default it given this feature to some of the form. My question is how can I use this module to add other content type forms.

**How can I add content in modal form ?**

# Answer
> 2 votes
finally I found my answer, I put it here for another than want do something like this

```
function mymodule_menu() {
  $items = array();

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

  $items['mymodule/%ctools_js'] = array(
    'page callback' => 'mymodule_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Helper function to make a link.
 */
function _mymodule_make_link($link_text = '') {
  // Set a default value if no text in supplied.
  if (empty($link_text)) {
    $link_text = 'Magical Modal';
  }

  return '<div id="magical-modal-link">' . l($link_text, 'mymodule/nojs', array('attributes' => array('class' => 'ctools-use-modal'))) . '</div>';
}

/**
 * An example page.
 */
function mymodule_page() {
  // Load the modal library and add the modal javascript.
  ctools_include('modal');
  ctools_modal_add_js();
  return _mymodule_make_link('Magical modal');
}

/**
 * Ajax menu callback.
 */
function mymodule_callback($ajax) {
  if ($ajax) {
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('MyModule Modal Form'),
    );

    // Use ctools to generate ajax instructions for the browser to create
    // a form in a modal popup.
    $output = ctools_modal_form_wrapper('mymodule_form', $form_state);

    // If the form has been submitted, there may be additional instructions
    // such as dismissing the modal popup.
    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    // Return the ajax instructions to the browser via ajax_render().
    print ajax_render($output);
    drupal_exit();
  }
  else {
    return drupal_get_form('mymodule_form');
  }
}

/**
 * Drupal form to be put in a modal.
 */
function mymodule_form(&$form, $form_state) {
  module_load_include('inc', 'node', 'node.pages');
$form = node_add('article');
  return $form;
}

```

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


# Question
Title: Adding new rows on a draggable table via jquery
I have a draggable table with preloaded "new items" - sorta like the Power Edit feature of the menu\_editor module. Everything works perfect.

However, I want to have a button that adds a new row via jquery. I was able to do this via the following code. However, the new rows added by jquery are not draggable. What can i do to make it work? Is it even possible?

```
var preloaded_items_count = '.$preloaded_items_count.';
$("#edit-add-new-item").click(function(){
  var append_tr = $("#guide-pages-table tr:last").clone();
  var replace_pattern = new RegExp("new-" + preloaded_items_count, "g");
  var new_item_id = "new-" + (preloaded_items_count + 1);

  //append_tr.find("a.tabledrag-handle").remove();
  append_tr.html(append_tr.html().replace(replace_pattern,new_item_id));
  preloaded_items_count = preloaded_items_count + 1;

  //Drupal.tableDrag.prototype.makeDraggable(append_tr);
  $("#guide-pages-table > tbody:last").append(append_tr);
  return false;
});

```

# Answer
As I can not reproduce your case, this answer just is a suggestion:

look at `misc/tabledrag.js`:

```
Drupal.tableDrag.prototype.makeDraggable = function (item) {

```

So you need re-running necessary javascript after adding new row.

```
Drupal.attachBehaviors($('#guide-pages-table > tbody:last'));

```
> 0 votes

# Answer
This is how you can do it:
(For D7, I hope it is the same or similar in D6)

```
var $table = $('<table>').appendTo($container);
var $tbody = $('<tbody>').appendTo($table);
var drupalTableDrag = new Drupal.tableDrag($table[0], {});
var $newRow = $('<tr>').appendTo($tbody);
drupalTableDrag.makeDraggable($tr[0]);

```

The essential thing to learn is that Drupal.tableDrag acts as a class constructor, and you are supposed to call makeDraggable() from the constructed object.

If Drupal already created this object for you, you will find it in Drupal.tableDrag\[base\], where base is whatever key was used in the settings.
> 0 votes

---
Tags: theming, 6, javascript
---


# Question
Title: How to pass value generated in the form submit function to another function?
I have a question related to drupal 7 form api and module development.

I have a very simple module with a function like this. It gets called by hook\_menu when a certain path xyz is visited.

```
function myview_mainpage() {

  $content .= drupal_render(drupal_get_form('myview_form'));
  $content .= "Some additional stuff here";
  return $content;
}

```

My form looks like this (it's from the examples module):

```
function myview_form($form, &$form_state) {
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('A simple form with a submit button'),
  );

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
  );

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

```

And my submit handler looks like this:

```
function myview_form_submit($form, &$form_state){

 // I do some sql stuff and generate html content based on the value that was submitted in the form
  $variable = "<div><h1>Some stuff</h1>...';

}

```

And now I need to somehow pass the value of $variable to the function myview\_mainpage() so it can print it out. So in a nutshell: User submits a from, some processing is done based on the value submitted and then the results are displayed under the form when it is displayed.

Maybe I could use $form\_state\['redirect'\] to redirect the user to the page xyz but I don't want to send the value of $variable in the address bar of a browser.

Any ideas? This feels like it should be done quite easily but I can't find a way to do it.

# Answer
You can store that information in the user session. There is always a redirect after a form submission so you need to persist it somewhere because PHP is a stateless.

Simply add your data to $\_SESSION\['yourmodule'\] and then in the mainpage() function check if something is there and display it.

If that information is not temporary and must be there on the next visit too, persist it in the database in a custom table.
> 3 votes

# Answer
Drupal way of doing this would be to do it in a theme

> #theme
>
> Used by: All elements and forms.
>
> Description: Theme function to call for element. It must render this element and all of its child elements.
>
> Values: The name of a theme function, without the initial 'theme\_'.

add `$form['#theme'] = 'myview_form'` to your form function

then use

```
function theme_myview_form($variables) {

}

```

myview\_mainpage() will be simpler

```
function myview_mainpage() {
  return drupal_render(drupal_get_form('myview_form'));
}

```

I don't think you need form\_submit() for what you are trying to do.
> 1 votes

# Answer
First off, `drupal_render(drupal_get_form('myview_form'))` would cause an error, since `drupal_render()` is expecting a value passed by reference, but `drupal_get_for()` is not returning a reference.

Rather than having a page callback that render a form, I would use the form builder for the page at the xyz path. The submission form handler, and the form builder for which the submission handler is called can share values through the `$form_state` variable, which is passed to both the functions, and which is passed as reference to the form submission handler.
The form submission handler should have the following line.

```
$form_state['rebuild'] = TRUE;

```

What the form builder should do is:

* Verifying the value set by the form submission handler in `$form_state` is set
* Using that value for rendering it before, or after the form
* Adding the form elements as a form build function would normally do

In this way, there would not be any need to pass data into the session, save the data in a database table, or use `variable_get()`/`variable_set()`.
> 1 votes

# Answer
`variable_set('id_name','value');` and after that `variable_get('id_name');`. After you don't need anymore the value, remove it.
> 0 votes

# Answer
the right way (drupal way) to do this is using hook\_preprocess. For example:

```
function MODULE_forms_preprocess_results_template(&$vars) {

```

then generate whatever you need and inject it in the form

```
$vars['your_variable'] = somefunction();

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Get value for a field from url while saving a new node
How to find a next Entity ID/Node ID?

Here is my scenario. I created my own Content Type which has 10 fields, one of these 10 fields has to save to DB thru a custom module. Value to this field is being passed thru URL filter.

Really appreciate any help.

# Answer
> 1 votes
With the comments so far , I could understand that you have a content type with 10 fields, so the time so create a node you will be putting 9 fields on the node form and the 10th field has to be filled with some value from url parameter,so lets assume your site url while adding the node looks like `www.sitename.com/node/add/your_content_type?field_value=xyz`.

One of the possible way can be to pick the value from url and make it as 10th field default value, an example code can go something like below.

```
 // Assuming 10th field as textfield.
 function mymodulename_hook_form_alter(&$form, $form_state, $form_id) {
   if($form_id == "your_node_add_form_id") {
     if (is_null($form['nid']['#value'])) {
         $form['your_10th_field_machine_name'][LANGUAGE_NONE][0]['vaue'][#default_value] = $_GET['field_value'];
     }
   }
 }

```

Rest saving of fields will be handled by drupal itself.

---
Tags: entities, nodes
---


# Question
Title: Displaying two Content Types in a single view
I have searched on this topic and have seen a number of answers, but they all seem rather complex for what (I think) is something straight-forward.

Our not-for-profit holds a monthly meeting. There are two primary program elements at the meeting: Presentation and Panel. A meeting will always have exactly one Panel and between zero and two Presentations.

I have created Content Types for Presentation and Panel. Presentation has the fields: Title, Date, Presenter, and Description. Panel has the fields: Title, Date, and Description. I would like to create a view which outputs the following: Date Panel-\>Title Panel-\>Description Presentation-\>Title Presentation-\>Presenter Presentation-\>Description

Where the Presentation block is hidden if there are none and repeated if there are two.

I believe the Filter Criteria are set correctly - Content: Type (in Panel, Presentation)

Under Format-\>Setting, I grouped by Date.

The problem is that I cannot control the output - the fields all appear, but I cannot order them as desired nor can I format them as desired. The reason, I think, is that the field have the same name in the two Content Types, thus I do not seem to be able to address either directly.

I did try a PHP control to try to see what was happening. I basically created variables for each of the five outputs I want and printed them. Each date resulted in two calls to the print statements: the first print shows nothing for the Panel variables and has the proper values for the Presentation variables, whereas the second print shows nothing for the Presentation variables and has the proper values for the Panel variables. (What puzzles me is that I was only expecting a single print due to the grouping...)

I would appreciate your providing me with some guidance.

Thank you.

# Answer
In response to Molot:

There are several ways to skin this cat. I believe that the approach I took is the easiest, though there is one remaining issue (more below).

Steps:

1. Add the References module (other options include using the Entity Reference module and one other similar module)
2. On Admin-\>Modules, under Fields, enable References and Node Reference, and click Save Configuration.
3. For the 'parent' entity type (in my example above, Panel) add a new field of type Node Reference. In the settings for this field, select the content type(s) that can be referenced (for my example above, I chose Presenter).
4. In the patent entity type, chose Manage Display. For the Referenced Node, you can choose 'Rendered Node' as the Format of the child node (and you can define this to be the default view, the Teaser view, etc.)
5. For each entity of the parent type, in the newly created reference field, start typing the title of the field to be referenced, then click the proper one.

As noted above, I am still having one problem - see Configuring View output with multiple related nodes for details.

I hope you find this helpful.
> 1 votes

---
Tags: views
---


# Question
Title: Why does my content type need to be reviewed before it can be saved?
I created a new content type and when I want to create new content of this content type, on the bottom I only get the `Preview` button, the `Save` button does not show up and I can not find in the content type settigns how I disable this "must preview before save"-feature...

# Answer
> 3 votes
In Drupal 7, you can manage this via `admin/structure/types/manage/CONTENT_TYPE` in the Submission form settings:

In Drupal 6, you manage this via `admin/content/node-settings`:

---
Tags: nodes, entities
---


title: Any good CDN integration with Drupal?

text:
# Question
Title: Any good CDN integration with Drupal?
I'd like to set up a simple gallery for users to upload pictures onto my D7 site, but uploading a bunch of images is sure to make my site run slower and my hosting costs go up. So I'm looking at a CDN (specifically, blob or object storage).

Both of the Azure modules ( and ) are not actively maintained, and the Amazon S3 module is still in beta, so I'd be hesitant to use it on a production site.

Here's my question: Is there any good Druapl module that will let me bypass the filesystem on the webserver so that users can upload images directly to a CDN? I know there are hooks in D7 that make this possible, but has anyone actually managed to do it yet? I can't believe there isn't better support for CDNs for Drupal. :(

# Answer
Drupal 7 has robust CDN integration with a number of options. You can consider the Storage API module for S3 integration among others.

> Storage API is a low-level framework for managed file storage and serving.

Also consider the CDN module.

> This module provides easy Content Delivery Network integration for Drupal sites. It alters file URLs, so that files are downloaded from a CDN instead of your web server.
> 1 votes

---
Tags: 7, cdn
---


# Question
Title: How to dynamically group content in a views listing
I've hit a massive wall in trying to group a list of nodes displayed through a view on my Drupal 7 site. Currently I have a view that lists a group of nodes that are under a specific vocab term. I then use a weight field to make sure they are in the order that I would like. This works just fine.

Here is an example on my site. In this example I have 11 videos bundled together under one taxonomy term.

What I would like to do is now create "chapters" to better organize these. Using the example above I would like to be able to have the following output:

```
HEADING 1  <-- I want to add headers like this. And then group videos in each header.
 1. Video
 2. Video
 3. Video
HEADING 2
 4. Video
 5. Video
HEADING 3
 6. Video
 7. Video
 8. Video
 9. Video
 10. Video
 11. Video

```

The big caveat is that I want to be able to assign these "chapter headings" at different spots for each video series that I have. I don't want to have Chapter 1,2,3 in the same position every time.

Here is an example of how I would like to be able to group my individual videos. Take a look at the video list on the left.

One route that I tried was to create a new Vocabulary called "Video Headers" and then create terms for each header that I wanted. I then created a new term reference field in my video content type where I would choose the corresponding "header" term that I wanted. But I am having trouble grouping this in my view. It's just not grouping correctly.

I've looked into the Book Module, but that doesn't seem like the right fit. My gut tells me that it has to come down to using taxonomy terms to group these videos.

UPDATE: Thanks to Jason below I was able to almost get it working. The problem is that all of my videos show up in the view rather then just the videos that are under a term. In order for my lists to work I have to have a contextual filter:

UPDATE #2: Figured it out! With help from Jason below, I also added a contextual filter of "Has Taxonomy: Term ID". That showed only the nodes associated with a term.

So as soon as I add that contextual filter, it ruins my grouping and groups all of the videos that I have together with one header. Somehow that is breaking it.

# Answer
Try this out.

Add the taxonomy term (or entity) reference field to your output, exclude it from rendering, and configure the format settings to group on this field.

Add a relationship to you view based on the term (or entity) reference field you are using to reference the taxonomy terms. With this relationship, you can now add a sort field using the taxonomy term's weight. When you click to add a sort field, filter the options to taxonomy term using the drop-down select to the right of the search field in the add sort dialog. Once filtered, you will now see the taxonomy term weight.

Adding this to your sort, will allow you to sort the view results based on the node's referenced taxonomy term's weight within the taxonomy vocabulary. You could also sort on the term itself, if your term names will include numbers like, "1. Chapter 1" and "2. Chapter 2", etc.

Jason.
> 1 votes

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


title: Drupal module powered by Wikitext

text:
# Question
Title: Drupal module powered by Wikitext
I am developing a website which basically has the main data source from wikipedia. The website currently needs users to copy paste text from various data sources (like wikipedia). But the problem which I realized out of it is that soon the data in the primary datasource will be outdated when people enter

Instead, I am looking in developing a module for wikipedia interface with a following workflow:

1. User will create a new page (a species page in this instance) and link it with its corresponding wikipedia page.
2. The local database will have 2 more tables (lets say) apart from the content type information of the current page of the Drupal powered website's node, in this case a species node.

* a. A table for storing the RAW wikitext of the linked wiki page with the most recent timestamp.
    * b. A table for storing the processed wikitext which will be mapped into the Drupal node's appropriate fields.
3. Provide a button in the species page which will check if the 2(a) wikitext is the current in the wikipedia's corresponding article. If not, 2(a) will be updated and user will have to perform the task of 2(b) which is mapping the new wikitext into Drupal node's fields - This can be accomplished by injecting tags in appropriate way.
4. Provide a module where the wikitext of 2(b) is pulled into the various fields of drupal's content node.

Now my questions:

Is it feasible?
How should I get going?
Any scope for enhancement in the requirement analysis?
Loopholes?

Please see, I know my question is very broad but I would need suggestions, pointers and guidance for going ahead. I believe a proper plan is much necessary before starting to implement it.

Thank you.

**EDIT:**

We have released IndianSnakes application in both Android and iOS. This is possible coz we had information of species formatted across different fields which can be visualized in the above links which I have pasted. Now, the whole point of my question stands, I need some ideas in developing a middleware with which the wealth of wiki information can be formatted across different fields for each species.

# Answer
First recommendation: Just use MediaWiki for the whole thing. It's not as nicely modular as Drupal but it has a lot of facilities. And as a bonus it's likely that upgrading will be easier (Dn-\>Dn+1 has always been a pain to me, MW upgrades have always been very smooth for me).

If you still want to use Drupal, I would use MediaWiki's parsing. E.g. fetch articles through `index.php?action=render&title=Page_Name`. It's probably best to simply fetch data when needed but with a long cache time (e.g. 1 week) to avoid Wikipedia blocking your server's IP.
> 2 votes

---
Tags: nodes
---