# Question
Title: Values missing in $form_state inside form function but available in ajax callback
I have a custom ajax form in a custom module, the form function code is over 400 lines so it's too big to post here, but hopefully I can explain the situation clearly here.

The form has a form function `mymodule_form($form, &$form_state)` and also an ajax callback attached to a button `mymodule_ajax_callback($form, $form_state)`. I put a `dpm($form_state['values'], 'form state values from form function);` in `mymodule_form` function, and also `dpm($form_state['values'], 'form state values from callback');` inside the `mymodule_ajax_callback` function.

Now when I change the values in the form, and press the ajax'd button, the form state values from the form function only has 1 element in the array, and that's the button that was pressed. All other values are missing. At the same time, the form state values from ajax callback function has all the form fields with the correct values. If I understood ajax forms in D7 correctly, you're meant to change the form inside the form function and only do `return render($form['element'])` from the ajax callback. This situation makes it impossible to do so as I can't access all the values from the form function.

There's nothing in the Recent Log Messages about ajax errors. The form has only 1 Ajax button, but it has also 1 ajax'd select dropdown which when changed, changes options for another select dropdown.

I'm currently sitting here scratching my head, ready to pull some hair out wondering what could cause such weird behavior.

I'm posting a screenshot of the dpm's for clarification:

As you can see values from form function has 1 element in array, values from ajax callback has 56 elements in array.

When I change the Ajax'd select dropdown however, the form state values from form function shows 55 elements, which is probably correct:

So it's only when I use the Ajax button this weird behavior occurs. Any help greatly appreciated. Can post the form code if needed.

# Answer
I managed to fix this, it seems another developer has put `#limit_validation_errors => array()` on the Add filter button which caused the values to be discarded.

```
  $form['step3']['addfilter'] = array(
    '#name' => 'addfilter',
    '#value' => t('Add filter'),
    '#type' => 'button',
    '#ajax' => array(
      'event' => 'click',
      'callback' => 'filters_car_callback',
      'wrapper' => 'results-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),
    '#limit_validation_errors' => array(),
  );

```

As soon as I removed that, the form started working again.
> 2 votes

# Answer
It seems you are a bit confused about how the form API works. What you are seeing is exactly as expected. I'll try to explain about how the form API works.

The ajax callback is called in a context of the form being submitted, which is why, all of the form values are passed along, the actual form function is called in the context of being initialized where no form values exist.

There are different ways of structuring ajax. One way could be to add another input like what's possible with fields that can hold many values. In that case, the ajax callback function should only worry about a subset of the form, and return this (You shouldn't call render inside ajax callbacks).

Another way to use ajax is to restructure the entire form. In that case, what you can do, is to set

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

```

Which will force Drupal to rebuild the entire form, with the current values and make it possible to fx create a multistep form. This can be done both with and without AJAX.

It sounds like you will need to rebuild the form, to get `$form_state` values into the form function. Then you can add ajax behavior to the form, where you get this working.
> 2 votes

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


# Question
Title: How can I prevent "zend_mm_heap corrupted" when adding Views programmatically?
I have created a module that has 150 views added to mymodule.views\_default.inc.

At first I could not get this to load as I was running out of memory. After increasing my memory to a sufficient limit, I now always get the error:

```
zend_mm_heap corrupted

```

Has anyone encountered this before while adding views to their modules?

# Answer
There are several bugs reported to php.net about this error (search "drupal zend\_mm\_heap corrupted). Indeed it turned out to be a PHP bug with php 5.3.

I upgraded to php 5.4 and the error goes away.

The issue is not necessarily Drupal related. However, it does seem to be related to how php includes and processes large files. In that respect, since Drupal can end up dealing with massive amounts of files and php data, this is probably the reason that many of the reported PHP bugs involved Drupal sites.

So, if you are getting this error, quite possibly you need to upgrade your PHP to 5.4
> 1 votes

---
Tags: views
---


# Question
Title: I facing a problem when i want create two registration forums by using (profile2 & profile2 registration path) modules?
i want create two registration forums ,each forum in specific page , when i looking for solution in internet, i found it using profile2 & profile2 registration path modules.

But when i working in it , i facing a new problem , the problem is the users can't find registration forums ,because they doesn't have a link or (way to access in forums ) for registration !?

Example :

i have two roles A & B.

URL path for A : {mysite/A/register}

URL path for B : {mysite/B/register\]

When user A click on page to create new account can't going to {mysite/A/register} link !!!

Any ideas ??

thanks in advance

# Answer
> 0 votes
Fully not clear problem but you can try by this way

Hook: user A, user B User: user-profile.tpl.php

if((arg(A)=='user') && is\_numeric(arg(1))) { $profile = profile2\_load\_by\_user(arg(1));

---
Tags: 7, users
---


title: Allow node creation only via services

text:
# Question
Title: Allow node creation only via services
Is there a way to allow the creation of nodes only via services and not via node/add? I want that nodes are created by the users of a mobile application, and not using the web interface.

Is this possible?

# Answer
> 1 votes
I have created a module that only allows logins through services.. therefore, you can only create a node through services if you use it in conjuction with a Session Limit, or other module which prevents multiple sessions.

http://drupal.org/sandbox/tpainton/1851382

Still experimental but please try, and if you find bugs, report. Hope it works for you.

# Answer
> 0 votes
Content Access allows you to manage permissions for content types by role. It allows you to specify custom view, view own, edit, edit own, delete and delete own permissions for each content type. You can restrict access to a content type by not assigning the content type permissions to the user role.

# Answer
> 0 votes
Using refineo's answer for inspiration and expanding you could :

1) setup a new roll X

2) Set permission on node creation such that only a user of roll X can create nodes

3) use Services via mobile to obtain a session

4) Grant a roll X to the user that just logged in via Services

5) Allow user to create node via Services

6) revoke roll x from user on logout

Granting and revoking rolls might be easier with Rules module

You'll want to expire sessions such that someone on their mobile app will not be logged in on the website (on a browser) at the same time because this way they will have access to node/add. Take a look at Session Limit

# Answer
> 0 votes
You could create the following rule.

Event: **Drupal is initializing** (though there is a performance consideration here - this will fire on every request).

Condition: **Data Comparison**: Compare the current path (using the pattern \[site:current-page:path\]) to the value node/add/article (or whichever content type you want to prevent browser users accessing).

Actions: **Page Redirect** to a node telling the user that access is denied.

Users will still be able to add content via the service url.

Adding another condition to filter for roles would allow admins or other roles to create new content in the browser.

---
Tags: services, nodes
---


title: Views slideshow countinuous rotation

text:
# Question
Title: Views slideshow countinuous rotation
I have some contents (organisms : a content type) to slide continuously... I already installed views slideshow 7.x-3.0 for another slider which has normal behavior.

Is it possible that I get my organisms rotate continuously like HTML marquee effect ?

with views slideshow or other modules ?

# Answer
> 1 votes
I've searched on drupal, and I've created a patch for views\_slideshow to make it possible.

# Answer
> 1 votes
IMHO, Views Slideshow doesn't really make things easier (unless maybe if you don't want to write a single line of code).

I prefer to create a normal view (displaying fields or a rendered entity, whatever you like) and use jQuery Cycle to turn the views rows into slides. You just need to:

1. download the jQuery Cycle plugin to your theme's javascript directory
2. add a 'Drupal behavior' to a custom javascript file which initiates the jQuery Cycle (see the example code on the jQuery Cycle site)
3. make sure both javascript files are loaded by adding them to your theme's .info file

jQuery Cycle can definitely rotate continuously, just look at the demo's on its homepage.

---
Tags: 7, views
---


# Question
Title: Tabs for Media:youtube multiple videos of single node
I am using Media:youtube in a content type and the field in which I embed youtube videos might have multiple values. I am trying to put those multiple youtube videos belonging to a node in tabs dynamically.

Eg: I have a node created with title: example of tabs underneath that I have embedded two youtube videos in the node output should be in tabs with part1 as first horizontal tab and part-2 as second horizontal tab. Part1|part2

with part1 loaded first and i should click part2 for second video

When there are 3 videos loaded in a node, then I should have like part1|part2|part3

I think using Display Suite with a add code field which i think should have a forloop with delta values of video will solve the purpose.I have no php coding knowledge

Can someone please help me to achieve this.

# Answer
Maybe you use could use the Field Collection Tab formatter module with Field collection?

Here are some more details about these modules (quotes included are from their project pages):

> ... provides a field formatter that allows you to output a multi value field collection field as a tabset, with one tab per field collection item.

> ... Provides a field-collection field, to which any number of fields can be attached. A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.
> 0 votes

---
Tags: media, files
---


# Question
Title: When shouldn't you use t(), st(), etc. with readable string literals?
Drupal coding standards dictate that nearly all string literals should be passed through `t()` or `st()` for translation; however there are some exceptions, such as titles in `hook_menu()`. When isn't `t()` or `st()` necessary? I've posted a community wiki answer hoping people will edit it.

# Answer
1. Descriptions and titles in `hook_menu()` *
2. Descriptions in `hook_schema()` \**
3. `watchdog()` messages *
4. Field/instance definition labels and descriptions \***

* potx extracts the strings
\** don't get translated
\*** can be translated with contrib, eg. i18n\_field
> 1 votes

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


# Question
Title: Allow special character in URL like curly bracket?
Any idea how I can allow special characters like `curly braces` and `equal` `({}, =)`?

The IFBYPHONE analytics asked me to add this `?ibp-adgroup=Sample_Node_Title&ibp-keyword={keyword}&ibp-matchtype={matchtype}` in the URL after the node alias.

Ex: `http://mydomain.com/sample-node-title?ibp-adgroup=Sample_Node_Title&ibp-keyword={keyword}&ibp-matchtype={matchtype}`

But currently it is being displayed like this.

`http://mydomain.com/sample-node-title%3Fibp-adgroup%3DSample_Node_Title%2526ibp-keyword%3D%7Bkeyword%7D%2526ibp-matchtype%3D%7Bmatchtype%7D`

I just tried to add it in the URL Path Settings but the result is being converted to HEX character.

Any idea?

# Answer
> 2 votes
As far as I know these characters are being escaped as specified in RFC 3986, which is the proper way.

# Answer
> 1 votes
You need to understand that your node's alias is a "path", this path can not / should not include any querystring parameters (eg. `?ibp-adgroup=Sample_Node_Title&ibp-keyword={keyword}&ibp-matchtype={matchtype}`).

The only thing I can think of, with the information you're supplying (without knowing what your IFBYPHONE analytics is doing), is that you are trying to catch if your website has been linked from a certain campaign. If that's the case you should not be using this URL in your Drupal installation but using that URL in something external. Then a Drupal module or other sort of implementation in your website should catch the querystring variables.

Can't give you more then this with the supplied info.

About the curly braces, I think those are only placeholders which you should replace.

---
Tags: 6, uri
---


# Question
Title: How to serve content type for authorized users as for anonymous?
I have content type "book". It's nodes are huge and it's takes a long time to format them by input filter. Caching works only for anonymous users.

So my goal is to give authorized users the cached version without APC, Cache Router (using a shared hosting).

I tried to change actual uid in template.php like so:

```
function mytheme_preprocess_page(&$vars, $hook) {
    if (isset($vars['node']) && $vars['node']->type == 'book') {
        global $user;
        $user->uid = 0;
    }
}

```

But it didn't help.

# Answer
Render the nodes with Panels, and you can set the caching across all users.

You could then either set it to a time based cache, or use my Panels Cache to get the cache cleared automatically when the nodes update.

See Learn Page manager! for an introduction to Panels and Page Manager.
> 1 votes

---
Tags: users, nodes, caching
---


title: "Edit This Page" functionality

text:
# Question
Title: "Edit This Page" functionality
I've searched around for quite a bit but can't find the anwer. I'm trying to add a "Edit this page" functionality to my admin menu. Is there an existing feature or module that I'm missing which allows an admin to go directly to editing the page being viewed?

If such a module doesn't exist, can I create one? I tried creating a link on my admin menu , but it doesn't seem to work:

```
function admin_edit_menu() {
     $items = array();
     $items['admin/misc'] = array(
      'menu_name' => 'management',
      'title' => 'Edit',
      'description' => 'Edit this page',
      'page callback' => 'http://www.mysite.com/node/' . $node->nid . '/edit',
      'access callback' => TRUE,
      'type' => MENU_NORMAL_ITEM,
      'weight' => -15,
    );
}

```

# Answer
> 2 votes
You can probably accomplish this by using `hook_menu_alter`.

I have made it a practice to include a site-specific module with every site to act as a repository for any custom code.

# Answer
> 2 votes
Assuming you're referring to the Admin menu module then you can head to the configuration page under `admin/config/administration/admin_menu` and under the *System tweaks* tab you can check the option for *Move local tasks into menu*.

---
Tags: nodes
---


title: How do I hide 'recent content'?

text:
# Question
Title: How do I hide 'recent content'?
On each article page I have an annoying 'recent content' part underneath the articles written, along with an extra title (see screenshot). Is there a way to not show the recent content? (I've just started out so if the answer could not involve code that would be great) I've had this issue from the start, as far as I remember, and I've changed themes a few times, which didn't help. Display Suite doesn't do anything to hide / change position either.

That extra title by the way, also appears on the basic pages--only then it's the only title and it's still on the bottom of the page.

I'd be ever so happy if someone could help me out. Thanks in advance! :)

http://img560.imageshack.us/img560/5093/recentcontent.png

# Answer
> 3 votes
Take a look under `admin/structure/block` and check if there's a block that's set to show in your Content region.

---
Tags: 7, nodes
---


# Question
Title: Rendering a form element without drupal_get_form?
I'm trying to render a simple form element without the accompanying tags and other drupal goodness (validation, etc). Is it possible to render a form element using form api methodology but without running it through drupal\_get\_form?

# Answer
I have never done this, I don't see why anyone would need it, and I cannot recommend this approach, but... you can try to define a form element by digging up the defaults, adding some properties and passing it to render().

In code, that would look something like this:

```
$element = element_info('textfield');
$element['#title'] = 'Type something';
$output = render($element);

```

Which results in:

```
<div class="form-item form-type-textfield">
  <label>Type something </label>
  <input type="text" size="60" maxlength="128" class="form-text" />
</div>

```

This seems to work for simple form elements like textfield. It will surely break for more complex types like checkboxes or date fields. Hope that helps.
> 0 votes

# Answer
You can embed a for in a template file for instance with drupal\_render\_form() in D6 or drupal\_render\_children() in D7. See this community issue.

You will still have to get the FAPI array somehow, you usually still use drupal\_get\_form() for getting the `$form` array.
> 1 votes

---
Tags: forms
---


# Question
Title: How to convert hook_xmlsitemap_links to xmlsitemap 6.x-2.x API?
While writing a test harness for a module I wrote, I discovered my implementation of hook\_xmlsitemap\_links wasn't actually called anymore.

The module doesn't work with nodes but gets data from sources other than Drupal and themes that. It implemented hook\_xmlsitemap\_links to add its urls to the sitemap.

Is there some documentation on how to replace a hook implementation with its equivalent(s) in the new 6.x-2.x API, that breaks my search-fu style?

I found it is "kinda hard to explain" and was reading the code like suggested.

# Answer
> 2 votes
There doesn't seem to be hook anymore to return links for further processing, but adding and deleting links is done with calls to xmlsitemap\_link\_save and xmlsitemap\_link\_delete(\_multiple)

I implemented a hook\_xmlsitemap\_index\_links, which normally is only called when the command `drush xmlsitemap-index` is issued:

```
function my_xmlsitemap_index_links($limit) {
  $sql = "SELECT x.id FROM {xmlsitemap} x WHERE x.type = 'my'";
  $query = db_query($sql);
  $indexed = xmlsitemap_db_fetch_col($query);
  //there isn't a lot of stuff, it fits in memory, but fetching it is costly.
  $indexed = array_flip($indexed);
  $mystuff = __my_get_stuff();
  $i = 0;
  foreach ( $mystuff as $thing ) {
    if ( !isset($indexed[$thing->id]) ) {
      # new thing
      xmlsitemap_link_save(__my_make_xmlsitemap_link($thing), $thing->id);
      $i++;
    }
    unset($indexed[$thing->id]);
    if ( $i == $limit )
      return;
  }
  #Done indexing new stuff;
  if ( $indexed ) {
    $deleted = array_flip($indexed);
    xmlsitemap_link_delete_multiple(array('type'=>'my', 'id'=>$deleted));
  }
}

```

I'm still puzzling on what to return from my hook\_xmlsitemap\_link\_info. It's not at all clear when those callbacks are called.

* The `process callback` is useless for this usecase; xmlsitemap has no way of knowing any foreign IDs.
* The `rebuild callback` is afaik only called by drush and manual action, not a means of keeping the links up to date, but it remains unclear if such a callback is required or optional (although xmlsitemap\_custom seems to manage without one)
* The `settings callback` is still a mistery to me, but it's used for the admin.

This hook\_xmlsitemap\_link\_info with `my_xmlsitemap_index_links` as `rebuild callback`, makes my module reindex when I issue a rebuild command from the admin.

```
function my_xmlsitemap_link_info() {
  return array(
    'my' => array(
      'label' => t('My Stuff'),
      'xmlsitemap' => array(
        'rebuild callback' => 'my_xmlsitemap_index_links',
        ),
      )
    );
}

```

I ended up implementing a hook\_cron that periodically calls `my_xmlsitemap_index_links`, to keep it in sync.

I might update my `hook_load`, to issue a `xmlsitemap_link_delete` on failed loads (404's).

# Answer
> 1 votes
My basic apprach for 7.x-2.x is (assume the module is called mymodule\_xmlsitemap).

```
/**
 * Implements hook_cron().
 */
function mymodule_xmlsitemap_cron() {
  mymodule_xmlsitemap_xmlsitemap_index_links(xmlsitemap_var('batch_limit'));
}

/**
 * Implements hook_xmlsitemap_index_links().
 */
function mymodule_xmlsitemap_xmlsitemap_index_links($limit) {
  xmlsitemap_switch_user(0);

  xmlsitemap_link_delete_multiple(array(
    'type' => 'mymodule',
  ));

  $results = mymodule_query();

  foreach ($results as $result) {
    $link = _mymodule_xmlsitemap_make_link($result->path, $result->id);

    xmlsitemap_link_save($link, $result->id);
  }

  xmlsitemap_restore_user();
}

/**
  * Helper for link object creation.
  */
function _mymodule_xmlsitemap_make_link($path, $id) {
  return array(
    'loc' => $path,
    'type' => 'mymodule',
    'id' => $id,
    'priority' => XMLSITEMAP_PRIORITY_DEFAULT,
    'lastmod' => 0,
    'changefreq' => 0,
    'changecount' => 0,
    'language' => LANGUAGE_NONE,
  );
}

```

As you mentioned, `hook_xmlsitemap_index_links` doesn't get invoked unless you have things defined with `hook_xmlsitemap_link_info`. In the 7.x version, I didn't see how to divorce this from database tables. If you are truly coming from an external database, this may not be possible.

So, if you look at xmlsitemap\_node (that was the inspiration for my version), you will see that the `hook_xmlsitemap_index_links()` is manually called from `hook_cron()`. With an external database, I had no idea on whether anything was new or deleted, so I blasted out all of the links, and rebuilt them. In my case, I ignore the `$limit`. You then make you query, and save off links.

Also note that there is some user switching going on to ensure that you are only indexing things that the anonymous user can access.

If you get indication when things are added / deleted from your external database, you can get rid of the `hook_xmlsitemap_index_links()`, and implement your own callbacks to `xmlsitemap_link_save()` and `xmlsitemap_link_delete()`.

---
Tags: hooks, xml-sitemap
---


# Question
Title: How to display the user edit-picture form in custom block?
I am trying to customize the user edit page in Drupal7 using Panels for user-edit page. How can i display the user edit-picture form in any specific region in Drupal 7. In my panels, i added a custom text in my sidebar region as:

```
<?php
drupal_get_form("edit-picture") ;
?>

```

However, it does not show anything. I got the form id by looking at the css. Any suggestions?

# Answer
> 3 votes
The ID you pulled from the DOM isn't the form ID, unfortunately. It's just the ID of the user image picker fieldset.

Take a look at the User Picture Field module. I haven't used it, so I can't personally vouch for it. However, it does make the user picture a field, which adds a lot of flexibility. I think Panels will let you move the field to the place where you want it to appear. You should also be able to use the editablefields module to make the image editable in the display.

---
Tags: 7, forms, users, panels
---


# Question
Title: Permission to edit own unpublished content (only)?
I have a content type Poll with an unpublished option. When a user creates a poll the poll remains unpublished for 1 hour and after that it becomes published (done with rules).

What i want to achieve is: Give the Poll author the permission to edit his poll node only while it is unpublished. **When it gets published this permission will expire.**

How can i work this out?

# Answer
hook\_node\_access() to the rescue! You need to create a new module to do this. In the new module's .module file you'll need to put this:

```
function YOUR_MODULE_node_access($node, $op, $account) {
  // Deny updating the content if it's a published poll
  if ($node->type == 'poll' && $node->status && $op == 'update') {
    drupal_set_message('This poll has been published, you may not make changes to it.','error');
    return NODE_ACCESS_DENY;
  }
}

```
> 3 votes

---
Tags: 7, users
---


# Question
Title: Caching a variable for a fixed amount of time
So I'm at odds with Twitter API which only allows 15 requests per 15 minutes (of course this encourages and promotes good behaviour by not allowing repeated request for the same data).

My task is simply to get the latest tweets for a Drupal based homepage which is easy enough but my question is as follows: is there a native function within the Drupal API to store an array or variable (...my twitter JSON request) for a fixed amount of time?

I recently implemented Twitter caching for a Wordpress site and it was super simple using Wordpress Transients API, see the example here: http://www.codeforest.net/wordpress-transients-api-caching-benchmarks

Is there an alike function in Drupal?

# Answer
> 4 votes
yes there is a native function cache\_set

```
<?php
cache_set('my_module_data', $my_data, 'cache', time() + 360);
?>

```

here is a great tutorial about caching in drupal

---
Tags: 7, caching
---


# Question
Title: Having the NOT IN SQL query equivalent in a view
I have a site in which user can choose three programmes between 9. I would like to have a view that gives me the 6 programmes a user didn't choose. I've created programmes using taxonomy so each of my users have a term reference on programmes that contain the 3 programmes.

Any idea would be appreciated, Thanks

# Answer
Forget the Views Raw SQL module. Simple SQL is not going to give you the result you need. Queries look for what is there, not what isn't.

You will need to construct two lists. First, the list of programmes the user has selected.

```
$selected_programmes = array();

foreach ($user->field_taxonomy_programme['und'] as $selected_programme) {
  $selected_programmes[] = $selected_programme->name;

}

```

Second, the list of available programs.

```
$available_programmes = array();

$vocabulary = taxonomy_vocabulary_machine_name_load('programmes');

$programmes = taxonomy_get_tree($vocabulary->vid);

foreach($programmes as $programme) {

  $available_programmes[] = $programme->name;

}

```

Then you can use the two lists to produce a list of the unselected programmes, which can then be used to construct your query.

```
$unselected_programmes = array_diff( $available_programmes, $selected_programmes);

```

There is no way around it. The only way to construct a query for values which are not present is programmatically. I would suggest the use of a block with a php snippet to display this information.
> 0 votes

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


title: Image not showing in page footer.

text:
# Question
Title: Image not showing in page footer.
I need to display an image in the page footer using tag. In my page.tpl.php I have the following block.

```
<div id="copyright">
    <img src="../images/logo.png">
     <p class="copyright"><?php print t('Copyright'); ?> © <?php echo date("Y"); ?></p>
    <div class="clear"></div>
</div>

```

I can\`t use print $logo since I can use another image for the logo.

# Answer
> 0 votes
You need to call the current theme URL and concatenate it with your alternative logo

```
<div id="copyright">
    <img src="<?php print drupal_get_path('theme', 'THEME_NAME'); ?>/images/logo.png">
     <p class="copyright"><?php print t('Copyright'); ?> © <?php echo date("Y"); ?></p>
    <div class="clear"></div>
</div>

```

---
Tags: media, 7, theming
---


# Question
Title: Circumventing Drupal's Cache for New Content
We like to post updates to Facebook and Twitter when publishing new content. We are running into a problem, however, in that anonymous users will get the "Access Denied" page until the cache recycles to show them the new content.

Currently, we're caching pages for anonymous users for three minutes. How do we keep our cache, yet allow anonymous users to see new content immediately as it's published?

For what it's worth, we are not using Memcache, Varnish or anything outside of the standard Drupal page caching.

# Answer
I'm not sure why you're getting "Access Denied" when you view new content as anonymous user. New content shouldn't be cached yet.

As a solution for your issue, you can clear all Drupal cache or only Drupal page cache after adding new content.

The following code will clear page cache after inserting new content:

```
   function MODULE_NAME_nodeapi(&$node, $op, $teaser, $page) {
      switch ($op) {
        case 'insert':
          cache_clear_all('*', 'cache_page', TRUE);
          break;
      }
    }

```

*Note: This code will not work on Drupal 7*
> 0 votes

# Answer
403 "Access Denied" on a cache miss seems odd to me. One thing to try is http://drupal.org/project/adbc as it makes the Dupal cache operate like one expects.
> 0 votes

---
Tags: 6, caching
---


title: Adding custom styles to Specific theme

text:
# Question
Title: Adding custom styles to Specific theme
I would like to add some custom stylesheets for specific theme.

for example: **Bartik** is default and **Seven** is the Administration theme.

In this case, I want to add some custom styles for only Bartik front-end theme.

How can I customize the following code for the Bartik theme?

```
<?php
/**
 * Implements hook_init().
 */
function mymodule_init() {
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_css(
        $path . '/custom.css',
        array(
            'group' => CSS_THEME,
            'every_page' => TRUE,
        )
    );
}
?>

```

# Answer
> 1 votes
Actually, what I would do is I would make my own sub-theme that uses Bartik as a base theme and add the additional css stylesheets to my sub-theme's .info file like this:

```
stylesheets[all][] = css/MY-CUSTOM-CSS-STYLESHEET.css

```

Just look at Bartik's own .info file to see how it adds stylesheets and javascript files as an example!

Here is some info on how to create a sub theme: http://drupal.org/node/225125.

The best thing about creating a sub-theme rather than adding these stylesheets using a custom module is that you'll be all set to do things like adding or overriding theme images, modifying template files and tackling a big array of potential customizations you may want to do in the future that you may not even be for-seeing now! It'll just end up being more flexible in the long run.

---
Tags: 7, theming
---


title: How do I attach files to nodes?

text:
# Question
Title: How do I attach files to nodes?
I need to add files to multiple value file field using drupal rest api (restws module). return format of restws is something like this :

```
"field_files": [

    {
        "file": {
            "uri": "http://drupal/file/445",
            "id": "445",
            "resource": "file"
        }
    }
],

```

but when I send it to `http//drupal/node/<node_id>` restws returns not acceptable.

Can anyone suggest which format I must use to send data to?

and second question : How can I upload files using restws module ?

# Answer
For my first question: I'm sending data with this format and it works now

```
{
  "field_files":[

    {
      "fid": "445"
    },

    {
      "fid":"446"
    }
  ]
}

```

Where *fid* is the *id* of an existing and accessible file.

For my second question, I've written module extending *restws classes* that user can submit data like the way user submits for services rest api.

Idea behind my module is that user submits data and module checks validation data and if data is valid saves file using drupal file\_save\_data function.
> 1 votes

---
Tags: files, 8
---


# Question
Title: Why is $node->taxonomy not populated when implementing a custom hook_nodeapi?
I have implemented a hook\_nodeapi in a Drupal 6 site. When looking into the node, I found out the node-\>taxonomy is not loaded. This means taxonomy\_nodeapi is not invoked before my hook even though the weigh of my module is greater than taxonomy.

Edit Adding code:

```
hook_nodeapi(&$node, $op, $arg = 0) {
if ($node->type == 'articles' && $op == 'load') {
  dpm($node)
 }

```

I think this may be default behaviors. Invoking taxonomy\_nodeapi() directly works for me but I am still wondering as to why this is the case.

# Answer
> 1 votes
I *think* I am explaining this right, but the issue here is that hook\_nodeapi() called with op = load returns a keyed array that is later on merged into the node object. It doesn't do this in sequence and progressively build up as each module's hook is executed, eg, it doesn't modify the node object itself. Thus it does not allow other modules to look at any other extra load information from other modules until later on.

For example, taxonomy\_nodeapi() called with op = load loads up the taxonomy term info and returns it as $output\['taxonomy'\]. So, it is never available to any other modules until the node\_load() where it is then turned into $node-\>taxonomy based upon that key. Here, all other modules that add to $node in the same way also add in their extra stuff.

So yes, this is probably best described as default behavior.

# Answer
> 0 votes
Your module might be loaded after the taxonomy module. If you want to check for this, you can update the weight information in the system table. If your module has a weight of 5 and taxonomy has a weight of 0, your module will be loaded after the taxonomy module

---
Tags: 6, taxonomy-terms, nodes
---


# Question
Title: what is '#access' => $admin in this code
im want to 3 radio buttons and user select a one save it in data base and i use following code but it gives error like this

> Notice: Undefined variable: admin in ounces\_to\_ml\_form() (line 44 of C:\xampp\htdocs\drupal7\sites\all\modules\ounces\_to\_ml\ounces\_to\_ml.module).
>
> Notice: Undefined variable: admin in ounces\_to\_ml\_form() (line 54 of C:\xampp\htdocs\drupal7\sites\all\modules\ounces\_to\_ml\ounces\_to\_ml.module).
>
> Notice: Undefined variable: admin in ounces\_to\_ml\_form() (line 64 of C:\xampp\htdocs\drupal7\sites\all\modules\ounces\_to\_ml\ounces\_to\_ml.module).

```
$active = array(0 => t('Closed'), 1 => t('Active'));

$form['settings']['active'] = array(
    '#type' => 'radio',
    '#title' => t('every time'),
    '#default_value' => isset($node->active) ? $node->active : 1,
    '#options' => $active,
    '#description' => t('Instantly: Emailed every time a donor submits a donation'),
    '#access' => $admin,
  );
//////////////////////
//////radio 02 /////////
$form['settings']['active1'] = array(
    '#type' => 'radio',
    '#title' => t('once a day'),
    '#default_value' => isset($node->active) ? $node->active : 1,
    '#options' => $active,
    '#description' => t(' Email once a day'),
    '#access' => $admin,
  );
//////////////////////
//////radio 03 /////////
$form['settings']['active2'] = array(
    '#type' => 'radio',
    '#title' => t('at given time'),
    '#default_value' => isset($node->active) ? $node->active : 1,
    '#options' => $active,
    '#description' => t('Email a day'),
    '#access' => $admin,
  );
//////////////////////

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('save'),
  );

return $form;

```

i want to know what is the error and what is mean by '#access' =\> $admin code line

# Answer
> 3 votes
`#access` property in Form API is to set whether the element should be visible to the user or not. If its value is `TRUE`, the element will not be displayed (not hidden element - `#required` will not be enforced). From Form API doc:

> Whether the element is accessible or not; when FALSE, the element is not rendered and the user submitted value is not taken into consideration.

`$admin` should be a variable you have forgotten to add/take from where you took the code.

Here is my suggestion to populate `$admin` variable. At top of the form function, populate `$admin`:

```
$admin = user_access('administer site configuration');

```

user\_access function returns `(bool) TRUE` of the user has the given permission (or FALSE if the current user doesn't). `administer site configuration` is a general permission that will be usually given to administrators. You can use whatever permission as appropriate for this.

---
Tags: 7, forms, hooks
---


title: How to Schedule a publish date and time

text:
# Question
Title: How to Schedule a publish date and time
How do I schedule a publishing date for a node I've created but don't want to publish until a certain date/time?

# Answer
> 4 votes
Use the scheduler module. This module allows nodes to be published and unpublished on specified dates.

---
Tags: nodes
---


title: How can I render an image in a theme?

text:
# Question
Title: How can I render an image in a theme?
I need to display an image in the page footer using the `<img>` tag. In the *page.tpl.php* template file, I added this code.

```
<div id="copyright">
  <img src="../images/logo.png">
   <p class="copyright"><?php print t('Copyright'); ?> © <?php echo date("Y"); ?></p>
  <div class="clear"></div>
</div>

```

I am not rendering the theme logo, so I cannot use `print $logo`.

# Answer
add image in this way,

```
<img src="/sites/all/themes/mytheme/images/logo.png" />

```
> 0 votes

---
Tags: media, 7, theming
---


# Question
Title: Permission based on nodes/section of site
Is it possible to alter permissions based on content types/individual nodes or sections of the site? If so, how?

# Answer
Giving roles different permissions for different *content types* is possible even with core drupal straight out of the box! Check it out: just create a new content type, and go to edit the permissions of any of your current roles (**/admin/people/permissions**).

Under the '**Node**' section of the permissions, you'll see you can select which content types each role can create, edit and delete. The create/edit/delete permissions under this section simply repeat for each of the content types on your site (so you have to visit this section and adjust permissions as needed each time you add a new content type).

Now, if you want different roles to have distinct permissions based on both content types and where on the website those content types appear, you'll have to add the functionality of additional modules to your site. One good one is the Organic Groups module. That modules allows your site to be organized in groups (or sections) with users having distinct permissions depending on which group/section they are members of. I cannot possible go into all the details of using that module in this answer, however, a good place to start if you feel you need this functionality, would be the module's own documentation pages: http://drupal.org/node/1114858

Good luck!
> 1 votes

---
Tags: users
---


# Question
Title: Workflow - Accepting/rejecting individual changes
Is there a way to accept/reject individual changes in the workflow process? If so, how and/or what modules are the best to do this?

# Answer
> 0 votes
I've had frustration with the Workflow module. You may want to try out the Workbench and Workbench Moderation modules. Throw in the Trigger module to send e-mail notifications when a document changes workflow state.

---
Tags: workflows
---


title: Adding classes to block title

text:
# Question
Title: Adding classes to block title
I have a block which template I'm overriding with my own.

The title in it is displayed by the following code:

```
    <h2<?php print $title_attributes;?>><?php print $title; ?></h2>

```

I just want to add some custom classes to the h2, but I can't figure out how to format it. I want to keep $title\_attributes but I can't seem to be able to add my own classes if I do.

I tried:

```
    <h2 class="a-class" <?php print $title_attributes;?>><?php print $title; ?></h2>

```

and:

```
    <h2<?php print $title_attributes .'a-class';?>><?php print $title; ?></h2>

```

But neither did anything. My PHP is scrappy at best so it's probably just me who don't know how to write what I want. Can anyone help me?

# Answer
The way to do this is by overriding variables in the template. Put the following code in your themes 'template.php' file, replacing YOURTHEME, YOURBLOCK, YOURCLASS with the obvious.

```
/**
 * Override or insert variables into the block template
 */
function YOURTHEME_preprocess_block(&$vars) {

  // var_dump($vars);

  $block = $vars['block'];

  if ($block->delta == 'YOURBLOCK') {
    $vars['title_attributes_array']['class'][] = 'YOURCLASS';
  }

}

```

You can determine what the $block-\>delta is for example by doing a var\_dump($vars) in the function. If you have the DEVEL module installed you can use dsm($vars) which gives the dump some presentation.
> 9 votes

# Answer
You may use the Block Class module.

> Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent element of a block. Hooray for more powerful block theming!
> 1 votes

---
Tags: blocks
---


# Question
Title: HIde taxonomy menu based on count? Possibly using rules?
Is it possible to hide taxonomy menu items based on their node count?

E.g. i have several zounds categories (notebooks, office, health, etc) created but they are just empty taxonomy items because the client has yet to add these products.

I'd like only the taxonomy terms with nodes to be visible.

Is it possible to accomplish this via rules or some other module?

**Background:**

I have a taxonomy menu created by taxonomy\_menu and then it's turned into a menu block and that menu block is turn into a superfish dropdown menu.

# Answer
> 2 votes
There is an option in the taxonomy\_menu "Hide empty items" to disable menu options if there are no nodes tagged with the specific term. The option can be found in the **admin/structure/taxonomy** then the vacab you are using.

Below is an image for reference.

Settings Image

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


title: Monthly magazine content organising

text:
# Question
Title: Monthly magazine content organising
I have to develop a monthly online magazine and I am looking for suggestions on the best way to organize the content.

Since it's a monthly publication, I want to organise content under **January**, for example. **January** will have multiple **articles**, **advertisements** etc all of which are nodes.

When time moves on to February, I want to unpublish January and consequently unpublish all the nodes associated with it.

Does anyone have any ideas on how I might accomplish this?

# Answer
> 1 votes
to publish or unpublished the content you should use Scheduler (http://drupal.org/project/scheduler) with this module let you to say when is publish the content and when will be unpublished.

To group the content, also you can build a field data (year-mounth) and use views to show a block with all the nodes with the same field-data, it should work like books block.

# Answer
> 1 votes
I can offer next thing, you can create a taxonomy`vocabulary` with months, and to unpublish nodes, you can do next thing:

1. Query to db to find nodes with taxonomy term inside(for example January)
2. Load node with `node_load`
3. Set the `$node->status = 0`
4. and save the node with `node_save`

This will unpublish all nodes with that month. About `associated nodes` \- can say for sure, how they accosiated with a node? Probably you will need to write your own module.

---
Tags: 7, nodes
---


title: Parent and Child

text:
# Question
Title: Parent and Child
I'm trying to solve a particular business question and I'm not sure how it translates into drupal sematics, so please excuse me if this has been asked before.

I want to use a series of content types to capture user feedback on different engineering aspects of a project: the structure is pretty much

-\> project

--\> milestone

---\> current technology set used

---\> precieved highest risks

because the cardinality of the children is always \>1, I think I need to use a separate content type for each.

Can anyone tell me how I add links to create a child object when viewing the parent, ie. create a new milestone for this project.... I can't seem to find a starting point in the documentation.

# Answer
You can try one of these modules

1. References
2. Relation

> Relations are entities and can therefore have fields. This makes Relation the most flexible and powerful relation model out there.

1. Entity reference

> Provides a field type that can reference arbitrary entities:

If youre looking for some Project management tools try these

Project Management

Open Atrium
> 1 votes

---
Tags: nodes
---


# Question
Title: What are the list of Drupal 7 image cropping modules out there?
Currently I use EPSA crop for cropping images as it uses the same image field without making a new one. What are the list of image cropping modules out there that provide a similar functionality? Epsa crop gives me the ability to crop different sized images for different image styles.

# Answer
> 1 votes
You can use the Image Javascript Crop Module.

> This module makes an Imagecache 2 (D6) or Styles (D7) 'javascript crop' toolbox action available for use with several modules.

# Answer
> 0 votes
There is more powerful Imagefield Crop module.

> imagefield\_crop provides a widget for cropping an image after upload.

It saves a cropped image rather than using some *Imagecache 2 (D6) or Styles (D7)* things on image.

---
Tags: media
---


title: Adding fuelUX help

text:
# Question
Title: Adding fuelUX help
I just started with Drupal 7 and trying to learn. I really like it so far. However I'm not sure how to add fuelUX. I linked all the relevant js and css files in my theme but for some reason it throws me errors (checked in the browser console). I know these arent Drupals fault per se but I just looking around to see if someone else sucessfully implemented fuelUX (http://exacttarget.github.com/fuelux/#wizard) and knows what I'm missing?

In my case I'm trying to get the "wizard" widget working. The error I get is "Uncaught ReferenceError: define is not defined" on both all.js which includes all widgets, and the specific wizard.js which I tried to add while problemshooting.

Any clues? =)

# Answer
> 1 votes
it sounds like you may not have an AMD loader on the page so please try using the following file:

http://fuelcdn.com/fuelux/2.3/loader.min.js

This contains all of the JavaScript for Bootstrap and Fuel UX, with no dependency on an AMD loader. In case you haven't heard of AMD, here's some info:

https://gist.github.com/4686136

http://requirejs.org/docs/whyamd.html

---
Tags: 7, javascript
---


# Question
Title: Updating to a newer dev version of a module using Drush (ignoring point/recommended releases, without trashing version control)
\[NB This question is off the back of, but separate/further to, an earlier question of mine, here.\]

I've been using Drush a good while, but every so often I get stumped. At the moment, I'm really not sure how to go about this.

Scenario: currently, the site uses a dev release, dated way in the past. In the meantime, no point release has been created, but a newer dev release has. So we have something like:

```
Reroute Email           6.x-1.x-dev (2010-Sep-27)
Recommended version:    6.x-1.0 (2008-Jul-24)
Development version:    6.x-1.x-dev (2011-Feb-25)

```

Doing `drush dl <module>-6.x-1.x-dev` overwrites the existing directory with the latest 1.x dev release. That's fine, but it trashes the .svn folder.

If I do `drush upc <module>`, it will download the point release (see edit below), which I don't want, but if I do `drush upc <module>-6.x-1.x-dev`, it just refreshes the update data and then tells me "Specified version already installed" on the relevant line on the output.

So how do I use drush to overwrite the old dev release, getting the new one in its place, without trashing the SVN folder?

EDIT: Actually, in this instance, `drush upc <module>` downloads the correct version, but I'm pretty sure if the point release was dated like 6.x-1.0 (2011-Jan-24) it would have gotten that one. Anyone want to clarify/correct?

# Answer
I found your question just now because I had the exact same question. Didn't find an exact answer, but this worked for me:

```
#svn rm <module>
#svn commit -m"removing the module... whatever you want to write"
#drush dl <module>-6.x-2.x-dev
#svn add <module>

```

For some reason, not doing the commit between the rm and the dl caused a problem with svn. I do not know enough about svn to know why, but would be grateful if someone could elaborate!
> 9 votes

# Answer
Try `drush dl module-6.x-1.x-dev --svnsync`.
> 7 votes

# Answer
There may be some install tasks that the new version of a module needs in order to work properly, for instance if the dev version has a different schema.

So before `drush dl module-7.x.2.x` take a look at the uninstall and install details in the module.

Beware if you have data that you don't want to lose in the db tables involved. Take a backup if you're worried or unsure.

If you need to, disable and uninstall the module **before** downloading and enabling the new module.

Use drush dis and then drush pm-uninstall
> 2 votes

---
Tags: 6, drush, version-control
---


# Question
Title: Views query alter but Views calc is not rendering right result
I am alter the views query with this

```
 <?php
function cc_invoice_views_query_alter(&$view, &$query) {
    foreach ( $query->where[0]['clauses'] as $key => $value) {
      $explode = explode('.',$value);
      if($explode[1] == "field_status_value = '%s'") {
         $alias = $explode[0];
         if($query->where[0]['args'][$key] == '0') {
            $query->where[0]['clauses'][$key] =  $alias . ".field_status_value IN ('%s' ,'%s')";
            #$query->where[0]['clauses'][$count] =  $alias . ".field_status_value IN '%s'";
            $query->where[0]['args'][] = -2;
         }
         elseif ($query->where[0]['args'][$key] == '1') {
            $query->where[0]['clauses'][$key] =  $alias . ".field_status_value IN ('%s' ,'%s')";
            $query->where[0]['args'][] = 8;
       }
         break;
      }
    }
}

?>

```

In this code, I just altered the views query. the result is displaying rightly, but in the views calculation section, the subtotal and total is not rendering right. It does not add the altered value while calculating the total or sub-total. Is there anything else i need to correct here. Please advise.

# Answer
I have the same problem (pagers not working for custom queries), and while I am getting close to the solution I do not have it yet. Something that helped me to understand what is happening is a piece of code from OG that generates a table with pagers.

og\_ui.admin.inc line 221

query:

```
  $query = db_select('users', 'u');
  $query->innerJoin('og_membership', 'ogm', 'u.uid = ogm.etid');
  $query
    ->condition('ogm.gid', $group->gid, '=')
    ->condition('ogm.entity_type', 'user', '=');

```

and the important part where the query gets cloned jost for the counter:

```
  $count_query = clone $query;
  $count_query->addExpression('COUNT(u.uid)');

  $query = $query->extend('PagerDefault')->extend('TableSort');
  $query
    ->fields('u', array('uid', 'name'))
    ->fields('ogm', array('state', 'created'))
    ->limit(25)
    ->orderByHeader($header)
    ->setCountQuery($count_query);
  $result = $query->execute();

```

My current solution is do not use pagers when you edit view queries, if you have to use a pager than create a whole template using the example from OG module (og\_ui\_menu() in og\_ui.module + og\_ui.admin.inc).

Hope it helps, but I would still be happy to know how to fix counter in views.
> 0 votes

---
Tags: views
---


title: Add link type field confused?

text:
# Question
Title: Add link type field confused?
There is a requirement in my website: The post content should have a link (it is for IOS device to install apps) like the following.

```
<a href="itms-services://?action=download-manifest&url=http://www.mywebsitname.com/appdown/CESBGM.plist" class="STYLE17">Install APP</a>

```

I used the Ckeditor and it can make it.

Is there any other ways to make it? I tried the Link module, but it failed.

# Answer
Drupal has a function called `filter_xss_bad_protocol` that strips unknown protocols from links created with the `l()` function - This is a very smart idea but makes it difficult when you want to include emerging link protocols like `skype://` for example. Dave Reid has created a fantastic module that works around this and allows developers to add their own protocols to the list.

http://drupal.org/project/filter\_protocols

With that module installed, and your specific protocol added to its configuration screen, it would then be possible to do something like this in your code:

`<?php print l("Displayed Text", "itms-services://?action=download-manifest"?>`

Additionally, use the `attributes` and `query` parameters of the `l()` function to pass your url parameter to the link. See this for an example... http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7 \- You'll find the particular comment regarding passing parameters on that page here: http://api.drupal.org/comment/38198#comment-38198

Hope that helps! Good luck.

P.S. To clarify, simply adding the above module and configuring it will also allow the Link module to respect the protocol since it passes everything through `l()` \- So no code required. :) Merely for completeness.
> 1 votes

---
Tags: navigation
---


# Question
Title: Views: How to display a grouped taxonomy list with node count?
I'm building a classifieds section of a website. Is it possible to create a grouped taxonomy list (by parents) with a node count at the end?

**Essentially this is what I want to appear:**

**Currently, this is my BuySell content type node. I have two taxonomy vocabularies: BuySell Category and Location.**

**Lastly, here is a snapshot of my taxonomy vocabulary buysell:**

I'm trying to use Views to create the list, however I'm not sure how to get them to group nicely together by parent terms. I can output all terms though.

Any help is greatly appreciated.

# Answer
It has been a while since I've done this, but I recall doing it with Views and setting the `Taxonomy Term` as the argument and using the Glossary option.

Alternatively, there are several snippets for doing this type of thing, as I recall. You can find a few of them here:

1. Show a list(x) of taxonomy terms with node counts
2. Drupal API - taxonomy\_get\_tree (or for D7)

In both cases, check the comments for various implementations or tweaks to functionality.
> 2 votes

# Answer
This view might help as well. It is using the summary function of contextual filters.

```
$view = new view;
$view->name = 'tags';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Tags';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Tags';
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['expose']['items_per_page_options_all'] = 0;
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Taxonomy terms on node */
$handler->display->display_options['relationships']['term_node_tid']['id'] = 'term_node_tid';
$handler->display->display_options['relationships']['term_node_tid']['table'] = 'node';
$handler->display->display_options['relationships']['term_node_tid']['field'] = 'term_node_tid';
$handler->display->display_options['relationships']['term_node_tid']['required'] = 1;
$handler->display->display_options['relationships']['term_node_tid']['vocabularies'] = array(
  'tags' => 'tags',
  'article_category' => 0,
  'book_hierarchy' => 0,
  'vocabulary_1' => 0,
  'group' => 0,
  'organization_taxonomy' => 0,
);
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'term_node_tid';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['name']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['name']['alter']['external'] = 0;
$handler->display->display_options['fields']['name']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['name']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['name']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim'] = 0;
$handler->display->display_options['fields']['name']['alter']['html'] = 0;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['element_default_classes'] = 1;
$handler->display->display_options['fields']['name']['hide_empty'] = 0;
$handler->display->display_options['fields']['name']['empty_zero'] = 0;
$handler->display->display_options['fields']['name']['hide_alter_empty'] = 0;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = 1;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Taxonomy term: Name */
$handler->display->display_options['arguments']['name']['id'] = 'name';
$handler->display->display_options['arguments']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['arguments']['name']['field'] = 'name';
$handler->display->display_options['arguments']['name']['relationship'] = 'term_node_tid';
$handler->display->display_options['arguments']['name']['default_action'] = 'summary';
$handler->display->display_options['arguments']['name']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['name']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['name']['summary']['sort_order'] = 'desc';
$handler->display->display_options['arguments']['name']['summary']['number_of_records'] = '1';
$handler->display->display_options['arguments']['name']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['name']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['name']['glossary'] = 0;
$handler->display->display_options['arguments']['name']['limit'] = '0';
$handler->display->display_options['arguments']['name']['transform_dash'] = 0;
$handler->display->display_options['arguments']['name']['break_phrase'] = 0;
$handler->display->display_options['arguments']['name']['add_table'] = 0;
$handler->display->display_options['arguments']['name']['require_value'] = 0;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Display: Tags */
$handler = $view->new_display('page', 'Tags', 'page');
$handler->display->display_options['path'] = 'tags';
$translatables['tags'] = array(
  t('Master'),
  t('Tags'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('term'),
  t('Page'),
);

```
> 1 votes

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


# Question
Title: Is there a way to show different Amazon affiliate link based on visitor locations?
I'm trying to get an Amazon affiliate link set up that directs the visitor to their local store, rather than being fixed to one particular store. I know I could set up individual links for each country and let the user choose the right one, but ideally I only want to show the one Amazon link.

Essentially what I'm looking for is a Drupal version of this Amazon Affiliate Link Localizer Wordpress plugin, or a combination of modules/tweaks that will let me do the same thing.

# Answer
> 5 votes
I wrote that plugin, so should be able to help!

There is a Javascript-only version of the Amazon Link Localiser. I don't know Drupal, but I can't see any reason why you wouldn't be able to use this - you'd just insert the JavaScript link into your template.

Cheers

Pete

# Answer
> 1 votes
You can easily use client side JavaScript to check the PCs time zone setting and then set different links accordingly. There is an examples of how to do this at http://www.tomcoote.net/code-examples.html

# Answer
> 0 votes
If you don't want Javascript or a custom Plugin, I'd suggest to have a look at A-FWD. It's a web site that lets you build a custom link that will forward the user based on the IP.

---
Tags: navigation, i18n-l10n
---


# Question
Title: Migrate custom content type from D6 to D7
I started with the **migrate\_D2D** module after did try with **migrate** 2.5. Same issue for me: Import custom content type into a fresh install of D7.

* Do I create custom content type first on the D7 intall? Is there no way to import it via d2d?
* Do I create custom CCK field into D7 db before mapping field using: `$query->addField('??','field_D6customCCKfield');
or just`
`$this->addFieldMapping('field_D7name', 'field_D6customCCKfield');` is enought ?
* Do I map subfield like field\_D6customCCKfield:data?

OK, it's better but my custom fields aren't created and I get this:

> "field\_fichier\_joint\_lycee" was used as destination field in "field\_fichier\_joint\_lycee" mapping but is not in list of destination fields
> "field\_lien\_page\_lycee" was used as destination field in "field\_lien\_page\_lycee" mapping but is not in list of destination fields

In my class do I add this?

```
$query->addField('??','field_D6customCCKfield')

```

# Answer
> 2 votes
You have to create the destination content type on the D7 site. Migrate/Migrate D2D won't handle that for you.

In your migration class you then use:

```
$this->addFieldMapping(destinationfield, sourcefield);

```

If you extend the D2D node migration class (DrupalNode6Migration) then you don't need to worry about defining a query.

---
Tags: migrations
---


title: Publish Node Confirmation

text:
# Question
Title: Publish Node Confirmation
When a user is creating content I need them to confirm (once clicking publish) that they are sure that they want to publish their post. I've been searching but cannot find an answer anywhere. I'm hoping for a modal window of some description that pops up with a message and confirm/cancel/save as draft buttons.

Any ideas?

# Answer
> 1 votes
Under /admin/structure/types/manage you can select the content type, and adjust the submission form settings to require preview before submitting.

---
Tags: 7, forms
---


# Question
Title: Question about AuthorizeNet ARB functionality with UC Recurring Module
I am confused about how the AuthorizeNet ARB functionality is supposed to work in Ubercart 2, and am hopeful that someone here has experience with AuthNet ARB recurring orders. I have the UC Recurring Payments and Subscriptions module and my AuthNet gateway set up. I created a recurring test order, and the recurring information is being displayed properly in my AuthorizeNet account. Last night, the first recurring charge took place, and I see that charge in my AuthorizeNet account, but it did not create any new order or any other message within my Ubercart account. The Recurring Fees screen for the order in question still shows that it has all of its recurring charges remaining. I ran cron, but that did not update anything.

The only thing I did not do in my AuthorizeNet gateway setup in Ubercart is the "Log reported ARB payments in watchdog." setting... I do not have that setting enabled, and I did not add the url to the Silent POST URL setting in AuthorizeNet. Is that what I'm missing? Or does it sound like there is something else missing?

Thanks!

# Answer
I enabled the "Log reported ARB payments in watchdog" setting and added the url to the Silent POST URL setting in AuthorizeNet. It is now working fine and recording the recurring transactions in my Ubercart Orders screen.
> 1 votes

---
Tags: 6, ubercart, payment-gateways
---


title: Drupal_render Profile 2 Forms

text:
# Question
Title: Drupal_render Profile 2 Forms
The main Profile can be printed in a basic PHP page using:

```
print(drupal_render(drupal_get_form('user_register_form')));
print(drupal_render(drupal_get_form('user_login_block')));

```

but how can I specify a Profile 2 profile to be printed instead?

# Answer
To print out the the profile2 profile Programmatically, you can do the following:

```
module_load_include('inc', 'profile2_page', 'profile2_page'); // Include profile2_page module
global $user; // Current user.
$profile2 = profile2_by_uid_load($user->uid, 'profile2_machine_name');
$entity_form = entity_ui_get_form('profile2', $profile2, 'edit'); // Or 'add'
print drupal_render($entity_form);

```

This should allow you to edit a Profile2 fields from the current logged in user. For registration I'm not sure how to print that other than redirect the user to the specific Registration Path from the Profile2 Registration Path, but for Logging in you can use the default form like in my question:

```
 print(drupal_render(drupal_get_form('user_login_block')));

```

P.S: Remember to clear you cache.
> 6 votes

# Answer
It's pretty simple, since profile 2 makes good use of the entity api module.

```
$profile = profile2_load($pid);
print $profile->view(); // prints the rendered profile.

```

To get the profile form

```
print render(entity_ui_get_form('profile2', $profile));

```
> 2 votes

---
Tags: users
---


# Question
Title: Query returns 0 rows on JQGrid filter due to translated rows
I have a JQGrid table that can be displayed in different languages. The data for this table is stored as English text and translated when output. The JQGrid table can be filtered by text.

The issue I have, is that when the JQGrid table is filtered, the query will run against the English text. E.g.

Original table: Yes No

Translated table: Oui Non

User is French and tries to filter for 'Oui': Database query will return zero results because 'Oui' does not exist in the database table. If the French user queries for 'Yes' then Oui will show because it matches the database and is translated on output.

This is using custom integration with JQGrid.

Since all string translation is cached and as far as I know there are no database tables available to join on, how can I get translated filtering to work?

Any ideas on the best way to handle this?

# Answer
Ok. I've solved this in what I believe is a reasonable way but it won't really scale:

As I build up the data for the table and translate each cell, I store that into an array with the foreign language string as the key and the untranslated string as the value. (This could work either way round).

```
$strings[t($my_string)] = $my_string;

```

I save that array after I've done everything with the last snippet. This array is read at the beginning of loading the table data:

```
$strings = $saved_strings = variable_get('my_translated_strings_' . $language->language, array());

```

If the array has changed then I will save it:

```
if ($strings != $saved_strings) {
  variable_set('my_translated_strings_' . $language->language, $strings);
}

```

I can then manipulate the filter rules to filter on the original untranslated strings instead of the user's language.
> 0 votes

---
Tags: database, 6, i18n-l10n
---


# Question
Title: Grant access to node; pick username from node field
I have in D7 Content access and Rules -modules. I have content type which Content access settings are limited to only admin.

In that content type I have User Reference field.

I need to have rule which picks username from that User Reference field and grants content view access to the user, so user can view that node.

So after rule has applied user from node User Reference field has view access to that content - ohter users can't see that node.

I have tryed multiple rules settings but have not got it right yet so help would be appreciated. Thanks!

# Answer
> 0 votes
Take a look at the Node access user reference module which is meant for this sort of thing (giving access permissions based on a user reference value in the content).

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

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


# Question
Title: What is the difference between hook_menu(), hook_menu_alter(), and hook_menu_link_alter()?
So, I am fairly new to Drupal (about 8 months in) and I am using Profile2 with 3 different profile types. Everything is working excellent, except for I wish I could wrap my head around how I can override the Profile2 view button when you click on, let's say Main Profile. So, if you are familiar with profile2, you know that it comes with a default profile as soon as it's activated, and when you click on it within the User Menu, you are presented with a screen with the local menu tabs called View, and Edit.

All I want to do is keep the View button, but change the path to either a panel page or an actual Views page.

I've explored `hook_menu()`, `hook_menu_alter()`, `hook_menu_link_alter()`, and to tell you the truth, I just don't get how those work. I believe hook\_menu actually adds new "nodes" or paths to the system with their own page?

I think I have a lot to learn when it comes to these three functions (`hook_menu()`, `hook_menu_alter()`, and `hook_menu_link_alter()`) I just need a savior to explain these to me.

As a sub question, along with the View, and Edit button, how would I go about adding an extra local menu button to this row? Like upgrade my account, or view your bill?

Any light would be appreciated, and I do have the Devel module installed, as well as the theme developer tool. I tried making a custom module, and running a DPM on those functions above, but it's not even outputting anything.

# Answer
`hook_menu()` -\> Define menu items and page callbacks.

`hook_menu_alter()` -\> Alter the data being saved to the {menu\_router} table after hook\_menu is invoked.

`hook_menu_link_alter()` -\> Alter the data being saved to the {menu\_links} table
> 3 votes

# Answer
To get result from those functions you will have to clear your caches. Use the admin\_menu module which has a direct link for clearing caches.

There are a lot of examples available on how to use hook\_menu. This is a comprehensive step step example: How should I implement hook\_menu()? or another example on how to create tabs: create tabs with hook\_menu() for custom module
> 0 votes

# Answer
I was investigating this more and finally came to a solution on how to add a local task menu to a profile2 page. It's kind of dirty, but it will do for now.

I basically added this to my site's glue module to modify the local task items.

```
function ch_glue_menu_local_tasks_alter(&$data, $router_item, $root_path) {
global $user;

foreach($user->roles as $k=>$v){
    if(preg_match('/paid1|paid2|paid3/i', $v)){
        $is_paid_member = true;
    }
}

if(preg_match('/profile/i', $root_path) && !$is_paid_member){
        // Add a tab linking to node/add to all pages.
        $data['tabs'][0]['output'][] = array(
            '#theme' => 'menu_local_task',
            '#link' => array(
                'title' => t('Upgrade Account'),
                'href' => 'node/3',
                'localized_options' => array(
                    'attributes' => array(
                        'title' => t('Add new content'),
                    ),
                ),
            ),
        );
}
}

```

Thanks for explaining the menu functions, but it seems like I have A LOT to learn when it comes to the drupal menu system. I'm just glad this will work for right now.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: Performance implications of many user roles
How does each additional user role affect Drupal performance? Looking for insights from benchmarking (preferred) and/or code analysis.

Specifically:

1. Do additional user roles impact performance on a per page request basis? (e.g. every page view will be slower for every user, or no?)
2. Is the performance impact of additional roles proportional to the number of modules installed? (eg performance hit proportional to #roles * #modules, or no?)

# Answer
> 3 votes
I don't have any hard stats but based on several years of experience and knowing how Drupal works I would be extremely surprised if adding another user role made any appreciable difference at the page request level. The only difference will be when a user has multiple roles, but the amount of extra data required per role is tiny.

I have profiled page loads for all sorts of different site setups and never seen an issue relating to the number of user roles.

Having said that, adding extra roles can make administration more complicated, so you won't want to add new ones without a good reason. If you were to create a hundred user roles the main permissions panel would be unusable but I would be willing to bet that the effect on normal page loads would be negligible.

---
Tags: performance, users
---


title: Contents, Flags, Users and Node views

text:
# Question
Title: Contents, Flags, Users and Node views
I am in the process of making a social networking web site with Drupal7. Most of the tasks are done. However, i am stuck at this issue big time. I have created custom content type, Challenge. Using the flag module, i have placed a flag, Accept Challenge, on the nodes of this content type. Users click on this flag and accept the challenge. Now to complete the challenge users, have to post a blog about their challenge. So is there any way that when the user goes to node/add/blog and begins blogging, in the title field he or she has a drop down to pick from the nodes he has flagged. The name of the title should be same as that of node which was flagged. Please advice. I hope i am clear. If not, please tell me and i would try my best to be as clear as i can

# Answer
As a workaround you could show a list of accepted challenges for each user and link them to node/add/blog with the title prefilled using the prepopulate module.

You could also create a node reference from blog to challenge, use a "select" widget and narrow the option with a view (that's a cool feature of the node reference module). In that view you limit the records to the current user and only the challenges they have flagged.
> 0 votes

---
Tags: 7, users, nodes, flags
---


# Question
Title: Hiding the site domain name from the content writers
I'm in dilemma. I'm hiring content writers etc for my new sites who risk getting fired from me for not meeting my expectations. I want to keep my site names confidential from the world because of competition and other concerns.

How can I hide the domain name but also allow users to add content straight-forwardly at my production site?

I was thinking to symbolic link another idle domain name to point to my site. I'd use relative URLs in my site content so the Pathauto module would take of this. Content writers would see this idle domain when working on my site.

A site can be visible from multiple domains. For example I can install the same site on my localhost PC. Secondly there are more than 50 million sites. For new sites it'd take a couple of months for a site to start appearing in the top 100 results in Google. How'd a naive person find the site in short time? Hiding the domain name means suppose I've a site name myjobs.com I want to make it visible in somejunk.com domain too and editors will add content in this site.

# Answer
As long as you have your server configured properly (ie, have your ServerName and ServerAlias directives set right for Apache), then this should work our of the box as long as you don't explicitly set the cookie domain or base URL in your settings.php. A potential complication is if you have any rewrites for canonical URLs on your site.

However, I think your best approach is to use the Domain Access module to run two sites out of the same installation. Have one affiliate be for the live domain, and the other affiliate be for the authoring domain. Then separate the content / themes as needed. When content is OK, just move it from the authoring affiliate to the live affiliate.
> 2 votes

# Answer
I don't think anything you do is a realistic option.

Content writer A (let's call him Bill) doesn't meet your expectations, and as a result gets fired. Because of your approach Bill doesn't know what site he was writing for. Bill then uses Google or Bing (apparently that's still an option) to search for a sentence or two of the content that he wrote and it lo and behold it appears in the SERPs. Bill now knows where his content went, and all the hard work in hiding the domain was a waste.

If I were Bill, I would then write a scathing blog post about how annoying that whole situation was. From what I've read around the web, the two worst kinds of people for a company/employer to p\*ss off are social media managers, and content writers ;-)

I apologise if this sounds too chatty or too informal, but I think you are trying to fight the wrong fire here. Just get a ROCK SOLID contract written up for the content writers. Also get a SOLID NDA (you can get basic ones for free here) as part of it, and make sure you set out your expectations fully and clearly from the beginning.

Ask for employment references for your content writers - if they have only written for a couple of sites, find out how long they have been writing for them. Get a history. Then still get them to sign the contract!

You also might want to try posting a similar question to one of the following members of the SE Network. Don't be put off by the beta status - the more members a beta community gets, the more likely it is to become fully fledged. Drupal Answers was a whole different community during the beta phases, now look at us ;-)

Project Management Beta

OnStartups Beta

The Workplace Beta

Personal Finance and Money
> 1 votes

---
Tags: uri
---


# Question
Title: Help me understand themes with sidebars and how to populate the sidebar from drupal
**BACKGROUND**

I'm converting a static html site to drupal. We have some pages that have content and a sidebar and some pages that just have content without a sidebar.

I plan on simply adding a new field called 'sidebar' to the article and base page content types. I can then modify the theme to render this field.

**QUESTION**

Is their any reason why adding this new sidebar field to the content type is considered bad practice?

If I want to place a block in the sidebar region it could simply be after or before the data entered into the sidebar field correct?

I'm a total newbie to drupal, I understand these are basic question but I couldn't find a definitive answer on the web regarding this.

Thanks

# Answer
> 0 votes
In Drupal, themes have regions. The sidebars are regions, just like the header, footer, conternt etc regions. Over simplifying a bit, content is places in blocks, then the blocks are placed in the regions, and changing the theme usually requires the blocks to be allocated again. Fields are part of the content, not the theme. There is no 'sidebar field'.

I would suggest that you set up a drupal test-bed, and play with it for a while before you take the leap of trying to migrate a site. Drupal is powerful, but there is no way to bypass the learning curve. You need to roll up your sleeves and work with it for a while.

Good luck.

---
Tags: theming
---


# Question
Title: build custom field in comments in drupal 6
i uses drupal 6 and i created new module. i want to add a custom filed in comments form programmatically. but i can not save my data in database .please help me

```
function mymodule_form_comment_form_alter(&$form, $form_state) {
$options = array(
    '1' => t('Yes'),
    '0' => t('No'),
    '2' => t('Empty')
);
$form['answer'] = array(
    '#title' => t('Your Answer'),
    '#type' => 'radios',
    '#required' => true,
    '#options' => $options,
    '#weight' => -1,
    '#default_value' => 'Empty'
);

```

# Answer
> 0 votes
In drupal 6 you should use hook\_form\_alter:

```
<?php
function mymodule_form_alter(&$form, &$form_state, $form_id) {

if ($form_id == 'comment_form') {

$cid = 1; // TODO See bottom comment in submit funtcion about this.
$answer = db_result(db_query('SELECT answer FROM {my_module_comment} WHERE cid = %d', $cid));
$answer = $answer ? $answer : 2;

$options = array(
    '1' => t('Yes'),
    '0' => t('No'),
    '2' => t('Empty')
);
$form['answer'] = array(
    '#title' => t('Your Answer'),
    '#type' => 'radios',
    '#required' => true,
    '#options' => $options,
    '#weight' => -1,
    '#default_value' => $answer,
);
// $form['#submit'] = 'mymodule_comment_form_validate'; Uncomment and add function like submit, for validation your and other submitted data.
$form['#submit'] = 'mymodule_comment_form_submit';
}

function mymodule_comment_form_submit($form, &$form_state) {
  $cid = 1; // TODO Here you should find CID - that will link your table record with Drupal comment Id record. Use print_r or devel dsm function for investigating structure of $form_state for seeking CID value.
  $object = array('cid' => $cid, $form_state['values']['answer']);
  drupal_write_record('my_module_comment', $object); // You table have 2 columns: cid and answer columns.
}

```

---
Tags: 7, forms, database
---


# Question
Title: How do you check to see what your drupal site looks like as different types of users?
I hope to find a way to stay logged in as admin but see what it looks like to an unauthenticated user and other types of users too, if possible.

I ask firstly because right now I am trying to make certain changes to the css file which means I need to check what the change looks like to an unauthenticated user. Sometimes it is easy to see more or less what I want in the admin pages but I do find I can get tripped up by this sometimes and also find I need to clean the cache of my browser before I can actually see how it looks. This is something that I do not really want to be taking much time over as I want to be able to correct it quickly if I made something look terrible.

Aside from that I do also have a few different kinds of users with various permission rights and when I change something I want to check that a change is doing what I want and all the users are still seeing the right things. Again, it is not an ideal situation for me to have to log out and in as each type of user for this type of thing as it can expose parts of the site if a mistake has been made or there is some bug rearing its head etc.

Aside from the aforementioned issues I have with needing to log in and out after every little change I make to the site, it makes the whole process pretty laborious. It suddenly dawned on me that someone else might have thought this too and that there is some way to work around it without compromising anything. Can anyone advise on this?

# Answer
For the anonymous user you will require a second browser (not logged in) or you will have to log out to view the changes. For other roles, check out the Masquerade module. It permits you to rapidly switch user roles by masquerading as a user with that role.
> 0 votes

---
Tags: users
---


# Question
Title: How will speed be affected by entity_metadata_wrapper()?
I'm building a big website and I'm using entity\_metadata\_wrapper() in lots of places around the website.

I'm wondering how this will affect the website's speed and server resources.

Thanks

# Answer
> 2 votes
Entity API does a lot of things, but most of them are cached.

For example, entity\_metadata\_wrapper() calls entity\_get\_info(), which uses the cache to retrieve the data. If the cache is empty, other functions are called:

```
drupal_schema_fields_sql()
cache_set()
...

```

Other modules may be involved through hooks:

```
module_invoke_all('entity_info');
drupal_alter('entity_info', $entity_info);

```

But note that no data is fetched from the database, this is because when you call entity\_metadata\_wrapper() you already have the entity loaded -it's a parameter to the function, indeed.

So if you are running critical or long processes such as importing data or running thousands of iterations inside a loop, you should better use entities directly. But even then, the cache should help a lot.

Look how Drupal looks without Entity API:

```
$field = '';
if (isset($entity->field_name[LANGUAGE_NONE])
    and isset($entity->field_name[LANGUAGE_NONE][0])) {
  $field = $entity->field_name[LANGUAGE_NONE][0]['value'];
}

```

It's ugly. This is why I use Entity API almost everywhere, and I haven't had any performance issues so far. For the benefits, I think it's worth using it.

# Answer
> 0 votes
The short answer is I'm not sure (I use it, but never benchmarked it). As a lighter alternative for getting and setting stuff see field\_extract which I use a lot too.

---
Tags: 7, entities
---


# Question
Title: Install profile with variable default language messes up translations
I'm working on an install profile for a Drupal app that can be delivered in several languages. The app was developed with English as the default language, but some installations might be in Arabic only.

The problem is that Arabic-language installations of this profile show the English menu items, field labels, etc. When I examine the strings in the localization UI, it shows the English string next to the default language, which is now Arabic. Only strings from the "default" textgroup are appearing correctly for some reason.

Now I am aware that there is an issue with default language vs source language in i18n. I would appreciate if someone could offer a workaround for my particular situation.

# Answer
> 1 votes
Turns out to be a simple solution: the variable `i18n_string_source_language` can be used to specify the source language of all strings, instead of the current site language.

I ended up setting

```
$conf['i18n_string_source_language'] = 'en';

```

in my settings.php. This worked.

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


# Question
Title: Writing to a drupal table form javascript as fast as possible
I have a table in my Drupal database this is simply a name value pair for each entry. I need to write to this table from javascript and get back as soon as possible. My first attempt was to create a menu endpoint that looks like this:

```
  $name = $_POST['propertyName'];
  $value = $_POST['propertyValue'];
  $result = db_query('SELECT * FROM {global_properties} WHERE property=:property', array(':property' => $name))->fetchAll();
  $record = array(
    "property" => $name,
    "value" => $value
    );
  $primary_key = !empty($result) ? array('property') : NULL;
  drupal_write_record('global_properties', $record, $primary_key);

```

I hit this endpoint from JavaScript using a dojo.xhrPost.

Sadly speed is quite important for this operation and it is taking me around 1000ms to get back from my post (I would like to be around 100ms). What would be a faster way to write to the Drupal table?

I am running this page on a server running MAMP Pro.

# Answer
> 3 votes
If you have zero concerns about user verification and data validation (seems to be the case given the example code) then I would post to a custom script that just boots up the database and does the write. Note that drupal\_write\_record is only available at the full bootstrap level.

Example code below:

```
/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd());

// Boot up Drupal.
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

$name = $_POST['propertyName'];
$value = $_POST['propertyValue'];
$result = db_query('SELECT * FROM {global_properties} WHERE property=:property', array(':property' => $name))->fetchAll();
$record = array(
  "property" => $name,
  "value" => $value
  );
$primary_key = !empty($result) ? array('property') : NULL;

// Load up code for drupal_write_record().
// Untested and might break stuff as we are not at a full bootstrap.
require_once DRUPAL_ROOT . '/includes/common.inc';
drupal_write_record('global_properties', $record, $primary_key);

```

If you do care about user verification and server side data validation and thus need a full drupal bootstrap but the client does not care about what is returned then httprl's httprl\_background\_processing() function might do what you need. Example of this workflow below.

```
/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd());

// Cut The Connection.
require_once DRUPAL_ROOT . '/sites/all/modules/httprl/httprl.module';
httprl_background_processing();

// Fully Boot Up Drupal.
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Do various user checks here.

// Run Example code.
$name = $_POST['propertyName'];
$value = $_POST['propertyValue'];
$result = db_query('SELECT * FROM {global_properties} WHERE property=:property', array(':property' => $name))->fetchAll();
$record = array(
  "property" => $name,
  "value" => $value
  );
$primary_key = !empty($result) ? array('property') : NULL;

drupal_write_record('global_properties', $record, $primary_key);

```

What the above example will do is return ASAP to Apache but drupal/php will run in the background. If the above example doesn't work there is one other option using HTTPRL in order to get a background worker running.

---
Tags: 7, performance, database
---


# Question
Title: Permisssions based on file folders & content collection
Can user permissions be customised based on file folders and content collections?

If so, what are the modules for this?

# Answer
The FileDepot module should do what you want.
> 0 votes

---
Tags: users
---


# Question
Title: What happens to a node/menu item once it's been deleted?
Once a node or menu item etc has been deleted, is there a way to restore it? Other than restoring the database?

# Answer
> 0 votes
When you delete a node or a menu item you cannot restore it unless reverting the DB.

You can use revisions and published status in order to emulate the node deletion or you can try modules like Recover.

---
Tags: nodes, routes
---


title: Is backlinking possible in drupal 7?

text:
# Question
Title: Is backlinking possible in drupal 7?
Is there a way to tell what pages within the site link back to a particular page within the site?

# Answer
Create a view of the pages with, for example, a list of tiles linked to the content. Then create a contextual filter using the entity reference field. In the Contextual Filter configuration for the entity reference, select 'Provide default value \> Content ID from URL' under 'When the filter value is NOT available'.

Set the view to display as a block on the page, and it will display a list of the titles referencing that page.
> 1 votes

---
Tags: navigation
---


# Question
Title: Show the latest post from multiple content types
I have three different content types like news, events, meetings. Using views i need to display only one post (the latest one) from each of this content type.

Created a view, filter criteria for all four content types selected....and stuck.

# Answer
or you can create 3 blocks view nd use menu tabs.

u have 3 content types, create a view with 3 blocks overridenn, each one display latest content of one of those content types, nd display the three blocks into one block from the theme blocks by choosing display as menu tabs from views setting. or u can use Quicktabs modules to do this, its very easy.
> 0 votes

# Answer
This would probably best be fixed by creating view blocks and creating a separate view for each of the content types. Then display the blocks in the region as needed. Or you can create a custom page template and embed the views inside that
> 0 votes

# Answer
Another solution, you can create only one view (for 1st content type) then create `Attachment` for second `Content type` and attach it to your main view `block` or `page`. And 3rd attachment for 3rd c.type(do the same thing). You can chose `Attachment position` also.

Here is video \- you can see how to use views + attachments.

Also u can do next thing - you can create one view with `3 block` \- like attachments - one block for each content type. Then create a template for field output - something like this `views-view-field--YOURVIEWNAME--page--YOURFIELDNAME.tpl.php` and use views\_embed\_view function to output results of two block u created before. - like this

```
<?php print $output; ?>
<?php print views_embed_view('YOURVIEW_NAME', 'block_name1', $row->YOURFIELDNAME); ?>
<?php print views_embed_view('YOURVIEW_NAME', 'block_name2', $row->YOURFIELDNAME); ?>

```
> 0 votes

---
Tags: views, nodes
---


title: Archiving options in drupal 7

text:
# Question
Title: Archiving options in drupal 7
Apart from unpublishing a node for example, what are the other archiving options for outdated, no longer used pages in the site?

Is there a way to somehow archive the deleted pages?

I am running drupal 7.

# Answer
> 1 votes
try to use node archive module or auto archive module, they give a lot of stuffs to do. you can also type archive in search section in drupal.org nd choose modules to display all kind of modules about archiving.

# Answer
> 1 votes
There are a lots of ways doing this.

However, *deleting* the page in Drupal will destroy its content, so if you want to archive *deleted* pages, you will have to implement an archiving solution "outside" of Drupal. For example a custom Drupal module to bundle up outdated content (including fields, tags, etc.) to a database table or flat file "outside" Drupal, and then delete it and associated fields from the Drupal database.

If writing a custom module to move the outdated content "out of" Drupal is considered too much work, my approach to this (within Drupal) would be to create a taxonomy tag `outdated`. and use it to tag outdated pages after unpublishing them. Then I would use the **Views** module to create a view listing all pages with this tag. This would be the administrator's view of the archive of outdated pages. Since the node is still managed by Drupal, it can be restored to full published status at any time, using standard Drupal administrator commands.

You may also want to add a view (or a context switch) to view all unpublished pages *without* this tag. This to give the administrator an uncluttered view of unpublished pages that is *not* outdated (e.g. those that are yet to be published).

(There is also the Node Archive module. However, it is still in development for Drupal 6 and there is no Drupal 7 port in sight, so this will not work for Drupal 7 unless you're willing to do the Drupal 7 port yourself.)

---
Tags: 7, nodes
---


# Question
Title: Why are responses for AJAX POST calls in admin UI so delayed
Just in the past day or so, something has happened to my site.

For some reason, all AJAX calls from Drupal's admin UI are now taking about 50 seconds a piece.

This is absolutely maddening because there are so many areas in Drupal's admin where one field change will result in an ajax callback.

I've been reviewing my network traffic in Chrome Dev Tools and Firebug and see that all pages and site resources are loading at an average of .2 seconds to 1 second.

Then, when I trigger a Form update in the UI, the POST to /system/ajax takes about **50 seconds**

The same is true in /ctools/content/ajax/\* -- when I am in the Panels screens, AJAX callbacks are averaging around 50 seconds of wait time for the server to respond.

I'm on a shared AN Hosting environment, D7.

Any thoughts?

EDIT --

I've found that some smaller AJAX requests (particularly those made by Inline Entity Form) do make it through without the delay... I can't see any correlation or pattern between those that do and then those that don't get through. It can't just be one module as I see problems with core Fields UI's and cTools that are totally separate from eachtother

EDIT --

The consistency between failing calls seems to be the size of the POST -- even the basic Field UI has a post size of 252B -- smaller posts seem to not have an issue.

# Answer
> 0 votes
It was apache's `mod_security`

I'm not sure exactly what was going wrong, but my host (ANHosting) was able to fix the problem.

---
Tags: 7, ajax
---