# Question
Title: How to use search_excerpt() function from core search module?
I want to use the function search\_excerpt() to generate excerpts. Unfortunately this function is returning exactly same text as I submit. For example I tried this:

```
$test = (search_excerpt('test', 'this is a test'));
print $test;

```

This is returning "this is a test".

I was expecting more something like:

> "this is a **test**"

What is wrong in my code?

# Answer
> 2 votes
Try this code.I have just added a space after the string and this will surely work

```
$string = 'this is a test';
$test = (search_excerpt('test', $string.' '));
print $test;

```

In the search\_excerpt() if the search text is the last one, then preg\_replace omits the search text.In order to overcome this I just added a empty space to the string.

```
// Highlight keywords. Must be done at once to prevent conflicts ('strong' and '<strong>').
  $text = preg_replace('/' . $boundary . '(' . implode('|', $keys) . ')' . $boundary . '/iu', '<strong>\0</strong>', $text);

```

# Answer
> 0 votes
Normal behaviour for this function, see the documentation: https://api.drupal.org/api/drupal/modules!search!search.module/function/search\_excerpt/7

Try this code:

```
$test = (search_excerpt('test', 'this is a test'));
print '"'.$test.'"';

```

---
Tags: search
---


# Question
Title: Drupal Commerce, behaviour when you disable order status
There is possibility do disable order statuses with "hook\_commerce\_order\_status\_info\_alter" but I am wondering what happens then. Example is. Alipay has many pending statuses. I would summarize them into few or just one. But wondering what would happen then when Alipay returns some status which is not available or disabled?

# Answer
> 0 votes
I dig in a bit and run some custom code.

```
$order = commerce_order_load($order_id);
$order_status = 'payment_received';
commerce_order_status_update($order, $order_status);

```

and changed status. So even if status is disabled, it still is changed. Only way is to remove the status, unset it in

hook\_commerce\_order\_state\_info for whole parent state or hook\_commerce\_order\_status\_info for particular status.

What happens then is if you try to change status to the one that is not there, status will be undefined.

---
Tags: commerce
---


# Question
Title: Twitter like notification when new posts are made
I was wondering if there was a module out there that could replicate something to what Twitter do when you have new Tweets you haven't seen in your timeline (so a notification of how many new items there are without refreshing the page).

See examples of what I mean, not the best at explaining things. preferably without using node.js as it hasn't worked for me so far!

Thanks in advance

# Answer
> 0 votes
You can use nodeJS to push live updates to your website without refreshing it, thus you also can count the new items.

There is a module that integrates with nodeJS: https://www.drupal.org/project/nodejs

You will need SSH access to make this work I think.

---
Tags: views, notifications, social-network
---


# Question
Title: Guard/LiveReload/Sass/Compass CSS Caching Issue
Here is a quick primer on my setup.

Running an aurora sub theme that utilizes guard, guard compass, guard livereload.

Basically what is happening is I make a change in a sass file, the files compile and the style change is shown right away on the browser. Great.

The problem arises when I click a link to go to another page, the CSS that is on the newly visited page is from the previous state. So my test cases are.. change the background color from blue to red. Background changes to red on the screen. Click a link to another node, background remains blue. Simple browser refresh, background turns to red.

I've been trying to find some info on this specifically, but having a heck of a time.

Things I've tried so far

1. Turn off sass caching in my config.rb file, so no .sass-cache generation {:cache =\> false}.
2. Reference my stylesheet via a hard coded entry in the html.tpl.php template instead of via the info file.
3. Tried a basic 2 .html page test case, nothing to do with drupal, and I get the results I wanted (no css cached).
4. I've even looked at Chrome settings before really deciding I felt this is a Drupal thing.
5. I made a color change, watched the result in my browser, went into the sites/default/files/css/ directory and deleted all the css files, went back to my browser and clicked on a link to another node, and the same result happened, previous CSS rendering.
6. Did the same thing above except instead of deleting CSS files from the folder, I just ran a drush cc css-js in terminal, then went and visited the second node link, and still old CSS renders.
7. I have not implemented this, but I know I can run drush commands via guard shell and was wondering if I can do the above in 6, just automate it.
8. Messed around with config.rb settings such as debug, line\_comments, environment or production variables, etc.

I am running out of ideas on how to get this to work a bit better.

Any suggestions?

# Answer
There are some other people here: https://www.drupal.org/node/1990926 having similar issues.

Make sure that you don't have caching and or Aggregation turned on when developing. These settings can be changed under configuration \> development \> performance.
> 1 votes

# Answer
Ensure that you have scss files in your LiveReload "files to watch" option, this will ensure your changes apply from node to node, without having to manually refresh just because you changed pages. Not sure of any side effects as of yet.
> 0 votes

---
Tags: theming
---


# Question
Title: User list with View: display only on role
In addition to the Administrator role, I've created several roles. I'm still using the Administrator role for users who needs administrator access.

However, in my user list, I've created with Views, I'd like to hide the Administrator role, so it only displays the one role I've chosen instead of listing all the roles associated to the user.

I've already configured a *filter criteria* where I haven't included the Administrator role and only the roles I'd like to display, but Views disregards this and display the Administrator role.

You can see the members page here: You can see the list here: http://xpeek.dk/sas-members

I hope any of you can assist me in this.

Regards, Frederik

# Answer
> 0 votes
I think you should use Views PHP module. here you can able to write custom code. May be it'll helpful to you. You want approx this kind of view?

For that you should try View Php Module. After that choose **Global Php** option in field tag and then write your code. I tried this may be it's not feasible, but here is the code.

In output section:-

```
<?php
$roles = array();
$user = user_load($row->uid);
$roles = $user->roles;
if (array_key_exists("7",$roles)) {
   // admin role has rid 7
   unset($roles[7]);
}

foreach ($roles as $key => $val) {
 echo $val."<br>";
}

?>

```

---
Tags: views, users
---


title: Prevent redirect after node save

text:
# Question
Title: Prevent redirect after node save
I have overlay turned off in Drupal. When I am editing a node, I want to prevent the redirect to the node after I hit save and just stay in the back-end. (It is really a pain to have to hit "edit" and have the page re-refresh each time when one is making a little tweak. As this can be easily achieved by having to tabs open; one for the node view and one for the backend edit form)

Is there an easy way to solve this in the configuration UI?

# Answer
You can alter the form and add your own submit handler in which the user will be redirected back to the edit form:

```
function <MODULE>_form_alter(&$form, $form_state, $form_id) {
    if (strstr($form_id, '_node_form')) {
      $form['actions']['submit']['#submit'] = array('<MODULE>_form_submit');
    }
}
// Custom submit handler for '_node_form'.
function <MODULE>_form_submit($form, &$form_state) {
  // Call default action.
  node_form_submit($form, $form_state);
  // Redirect back to the edit page for this node.
  $form_state['redirect'] = url('node/' . $form_state['nid'] . '/edit', array(
      'absolute' => TRUE
    )
  );

  $_GET['destination'] = $form_state['redirect'];
}

```

You might have to tweak the above code to suit your needs.
> 4 votes

# Answer
There is also the Content Type Extras module that will give you an option to configure a "save and new" buttons as well as a "save and edit button". Allows also to set defaults for other things in the content type forms.
> 1 votes

---
Tags: nodes
---


# Question
Title: Best way to unpublish a node, given the nid, while bypassing any node update hooks?
To unpublish a node, I set status=0 and call node\_save(). Unfortunately, this invokes the Geocoder module and it sends a request to the Google API for a geocode that I already have. There is apparently no way to turn this off.

I am looking for an alternative to node\_save() that does not trigger this behavior or any other hooks, for that matter.

(btw, for fields I am achieving this with field\_attach\_update, but to unpublish I need to update the node itself)

# Answer
> 4 votes
If you have an array of nids you could just run this piece of code

example will unpublish the nodes with nid 1,2,3:

```
$nids = array(1, 2 ,3);

foreach($nids as $nid) {
    db_query("UPDATE {node} SET `status` = '0' WHERE `nid` =:nid ;"
,array(':nid'=> $nid));
}

entity_get_controller('node')->resetCache($nids);

```

---
Tags: 7, nodes, location
---


# Question
Title: Missing feeds plugin after Drupal core update
I have inherited a Drupal site from another developer and since I updated Drupal (Commerce Kickstart) to the lates version I have a warning "Missing Feeds plugin FeedsEntityProcessor..". I am not familiar with wthe Feeds module before so have no idea what is actually missing and where to look for it. Any ideas?

# Answer
> 0 votes
Have a look at this issue, should fix your problem: https://www.drupal.org/node/2397763

---
Tags: commerce, feeds
---


# Question
Title: In form alter what is the different way of hiding fields and what is the difference between them?
I am currently using the following code to hide the fields in the form

```
1.  $form['field_name']['#access'] = FALSE;
2.  hide($form['picture']);
3.  unset($form['picture']);
4.  $form['account']['mail']['#disabled'] = TRUE;

```

i saw this post https://stackoverflow.com/a/21041471/2251933 , https://drupal.stackexchange.com/a/49985/36808 explains some of the point but not all.

i want to retain the values in the form after form save but for some reason i want to hide the fields in the form.

what is the best way to do it and why it is so.

# Answer
The basic differences are:

`$form['field_name']['#access'] = FALSE;` hides the form element. When saving the form Drupal will not touch the field. That means the initial value will remain. Maybe interesting: Other users can do with that node's field what ever they want. You saving the node will not undo their changes, although you only know about the old value of that field.

`hide($form['picture']);` is afaik used in theme functions only. It can cause forms to break because after saving a form this field is expected to have a value but is not even rendered. So use this with care. When you hide a field that is important make sure to manually render it later. Calling hide will also hide all child elements of the element you hide. A use case could be: Render child elements of a form manully and call `hide` on those elements. When you now render the parent element only those child elements are rendered that did not go through hide.

`unset($form['picture']);` should not be used. It just drops parts of an array. It is better to use one of the other three functions that keep the data consistent and not delete stuff Drupal expects.

`$form['account']['mail']['#disabled'] = TRUE;` will not hide the element but just make it unchangable (greyed dropdowns, etc.). It acts like a normal field but the initial value cannot be changed by the user.

In addition to what you asked, Clive added something:

Form elements are commonly converted to `array('#type' => 'value', '#value' => 'foo')` to remove them from the form but keep them server side, and not mess up the submission process. It's the best of all available methods IMO

Hope that help although I am not completely sure about the consequences of unset.

cheers, j
> 12 votes

# Answer
I think you should try

```
$form['field_name']['#access'] = FALSE;

```

Because you want to retain the values in the form after form save. It just hide your field.
> 0 votes

---
Tags: 7, forms
---


title: Show special roles on user profile

text:
# Question
Title: Show special roles on user profile
I have a little issue on drupal 7. I want a **little object/field on the userprofile**. This object/field shoud **show special roles** of the user (special = "admin, moderator ..."). And is it possible that this object comes directly after the username ?

(I am very sorry for my bad english. I hope you understand my question)

# Answer
> 0 votes
So I found a solution that works for me.

Modules used:

* Display Suit
* Display Suit Extra
* PHP filter (I hope I didn´t forget one)

Here is how I did it ...

1.Go to a Profil

2.Click on "Edit"

3.Switch to the tab "Manage display" (right upper corner of the overlay)

4.scroll down to "custom fields" and click it

5.click "Add a code field"

6.check "User" on *"Entities"* and change the Text format in the *"Field code"* to "PHP code"

7.Now type the following in the "Field code" (Add/Change the Roles You have)

```
<?php $account = user_load(arg(1));?>
<div class="user-roles">
    <ul>
        <?php foreach($account->roles as $role): ?>
            <?php if($role != "authenticated user"): ?>
<?php //--------------HERE YOU NEED TO ADD/CHANGE THE ROLES YOU HAVE------------------- ?>
                    <li class="user-role- <?php
                    if($role == '[Your Role]'){ echo 'user-role-[your role]'; }
                    elseif($role == '[Your Role]'){ echo 'user-role-[your role]'; }
                    elseif($role == '[Your Role]'){ echo 'user-role-[your role]'; }?>">
<?php //------------------------------------------------------------------------------- ?>
                    <?php print $role; ?>
                </li>
            <?php endif; ?>
        <?php endforeach; ?>
    </ul>
</div>

```
8. Press "Save"

That´s it. I hope it works for You too.

(Again I apologize for my bad English. It can gladly edit for correcting my grammar)

---
Tags: 7, entities, users
---


title: Where did drush language-add disappear?

text:
# Question
Title: Where did drush language-add disappear?
I was using it for a long time in the install script and today it stopped working and I don't remember changing anything related.

> The drush command 'language-add' could not be found.

Was it part of `l10n_update` (I have it enabled), drush itself or something else?

This https://drupal.org/project/drush\_language is not what I'm looking for. It doesn't work and I've never seen it before.

# Answer
The problem is caused by not installing *drush\_language* in the correct directory. If you stil have the problem:

First remove anything related to drush\_language:

1. Go to your drupal folder and do `drush pmu drush_language`
2. Go to `/drupal/sites/all/modules` and delete the directory `drush_language`, if it's there.
3. check your system for a global `drush_language`: e.g. do `updatedb` & `locate drush_language`. Then delete any folders called `drush_language`.
4. Go back to your drupal root folder an do: `drush dl drush_language --destination=./sites/all/modules/`
> 1 votes

---
Tags: drush, i18n-l10n
---


title: Find the origin of a redirection

text:
# Question
Title: Find the origin of a redirection
I work on a Drupal project in business and we are facing a problem. We have a webform node with an alias ..../contact. We also have a page view .../news listing a specific type of content. Recently, when we want to go on / contact, we are redirected to the page /news. By enabling dlevel, it displays: "The user is being white Redirected to /en/news."

We have the "Pathauto" and "Global redirect" modules, but we never had a problem with these two.

We have no idea from where this redirection can come ... :(

# Answer
You can see what page is the referer by using

```
$_SERVER['HTTP_REFERER'];

```
> 1 votes

# Answer
It might be useful to examine the exact series for requests and responses that are taking place on the client side. That can provide clues about what redirects the server may be issuing, especially if there is some sort of chain involved. You'll find common browser plugins for this like "Live HTTP Headers" (firefox, chrome, etc.). When using these tools its helpful to tell them to exclude image/css/js files as those can really make the results difficult to scan.

On the server-side, there are a few modules to check:

* Global Redirect is certainly a possible variable. You may want to disable it just long enough to isolate/eliminate it as a factor.
* You'll want to see if you have the "Redirect" module installed (it's a common addition), and if so check it's configured redirect patterns.
* Check if you have the core "Contact" module enabled as I believe this can introduce a menu entry for the /contact path that could be conflicting in a strange way.

The other key suspect is of course the web server itself. If you have any custom mod\_rewrite rules in place, such as in your .htaccess file, you'll want to double-check those. I've also seen strange cases, especially on shared hosting environments, where the hosting provider issues it's own redirects on special paths, like /contact, that you may not have control over. That's probably an unlikely explanation, but it might not hurt to try changing your webform page's alias to something other than /contact to see if any behavior changes.
> 0 votes

---
Tags: views, redirection
---


# Question
Title: How to search more fields using single text field textbox
I have a content type with fields title, body, short description & long description. In view i added these fields. i need to add an exposed search text-field in view to search the search term in title, body, short description & long description fields. Views search term is not happening for me. Combine search is only taking maximum 2 fields. Please help

# Answer
> 1 votes
I implemented a solution for this problem. I added a field to my content type and made it hidden. In my hook\_pre\_save, i merged all my fields data together separated by a space and saved that data to my hidden field. in my exposed filter form, i added the hidden field and exposed it to user to search.

# Answer
> 1 votes
It's Global: Combine fields filter.

Follow Up:-

**process No 1:-**

> Add fields to filter criteria
>
> Add Global: Combine fields filter to filter criteria
>
> Check fields you want to combine in filter's settings

**Process No 2:-**

> Add Fields
>
> Install Views filters populate module.
>
> Add Global:Populate filters to filter criteria
>
> Check fields you want to combine in filter's settings

I think this answers are resolved your problem.

---
Tags: search, views
---


# Question
Title: Change the add content look and feel for an specific content type?
So, I would like to change how the Add Content form looks like. Right now the user sees it like this (everything's in spanish, sorry)

But I would like to change it to something like this (all text in spanish again, sorry)

The text in grey would be the latest saved node, the button on the right ("Agregar Siguiente") acts like the "save" button, but it comes back immediately to this same page.

I know I would have to develop a Module to do this, could you direct me in the right direction to do something like this? Thanks in advance.

# Answer
You will want to create a theme override template for that content type for the edit mode. Then you can style it how you want. See this link for more information about how to do this: https://www.drupal.org/node/1142800#comment-4433994
> 0 votes

# Answer
you could also take a look at Panels:

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Importing Published status from xml using Xpath parser
I have an xml page that I want to import. Although I'm able to successfully import the Title and Body, Im unable to import the published status and promoted-to-front-page settings for the page. Here is what my xml code looks like:

```
<nodes>
<node>
<Title>This is the Title
</Title>
<Body>
This is the Body
</Body>
<Order>1</Order>
<Path>
/clips/this-is-the-path
</Path>
<Post-date>Tuesday, February 17, 2015 - 09:33</Post-date>
<Promoted-to-front-page>No</Promoted-to-front-page>
<Published>Yes</Published>
</node>
</nodes>

```

Here are what my Xpath settings look like:

Could anyone suggest what I'm doing wrong here?

# Answer
Alright, After some search online, I was able to use the innate Xpath functions, so it works with the following expressions:
> 3 votes

# Answer
I suggest installing feeds tamper (https://www.drupal.org/project/feeds\_tamper) with this module you can easily convert the yes to a 1 and no to a 0 before saving to the database. This should solve your issue.
> 3 votes

---
Tags: feeds
---


# Question
Title: Organic Groups and Workbench or Revisioning together. Will this work?
I'm building a D7 site using Organic Groups and would like some revisioning control.

Is it likely that something like Workbench or Revisioning will work nicely with Organic Groups?

I'm interested in hearing of any good or bad experiences or advice.

I've done some initial tests and Workbench appeared to work okay. Of course the number of configurable options tends to explode with two node access modules. It gets quite complicated. The Revisioning module wasn't quite so smooth. I seemed to get into a situation where an item wasn't visible to a normal group member when it should be but it could be fixed if the author / moderator simply edited the item and saved without doing anything. Maybe I need to have another play with that.

These modules actually do a lot more than we need. We don't really need multiple roles for author, moderator etc. Mostly "all" we'd like is the ability for a user to edit and save an existing node but see what it looks like before making it public. The "Preview" button does that (sort of) but it would be nice to be able to save changes, take a break, and come back later. Also, the public view maybe in a panel so "Preview" doesn't really show the final result.

Thanks

# Answer
> 1 votes
We've built a D7 site with Organic Groups and Revisioning and have found that installing Organic Groups causes a pretty major problem with Revisioning in that the Author and Moderator roles cannot see unpublished content. We've confirmed on a clean Drupal installation that Organic Groups Access Control is the cause of the issue.

The only workaround that we found was to check the Bypass Access Control checkbox for those roles. That means those roles bypass all security checks on content on the site so they can edit/delete/publish any content. That is an okay work around for our site but did present a problem when we wanted a separate moderator role for just one content type.

See this post for full details -\> http://drupal.org/node/1494232

We are planning on looking at Workbench for a different D7 site because Revisioning and Rules isn't going to be sufficient for the workflows.

# Answer
> 0 votes
I think you'd want to go with one of these options:

...depending on whether you prefer Workflow or Workbench Moderation. To help with that decision, What is the difference between the Workbench and Workflow modules? may be useful.

At the time of this writing, Workbench OG is more popular by a factor of 6.

There doesn't seem to be a good Revisioning solution because of Revisioning and Organic Groups Access Control - requires rebuild perms all the time.

---
Tags: organic-groups, nodes
---


# Question
Title: In Yosemite not able to generate the styles folder, I upload the project in a ubuntu test server, and it works
I know this is a question related to permission. The only thing I have changed in my environment is that I upgrade to Yosemite, I check apache everything is working fine.

This question has been asked in here and in others. I checked every possible solution. Here is what I have done:

1. Change the permission in every possible way even to 777 in local environment. It still gives the error
2. Change the apache user to my username and staff group, and make sure I have the set the right user and group
3. Clear the cache every time that I make a change
4. Use drush to flush the image as recommended in here

I have uploaded my site to a ubuntu server. It generates the files perfectly there without any trouble. Any ideas what it is happening in my local machine that it is not generating the styles folder and give an access denied error? I can upload files btw, it is just not able to create the folder styles and its files.

# Answer
> 3 votes
Probably not a permissions problem: the default php GD library on yosemite comes without png support, so drupal can't generate png images (like the default sample.png). You can very easily install another version of php.

# Answer
> 1 votes
Looks like a PHP issue.

I use Acquia Dev Desktop for my local environment, and things were working fine until the upgrade to Mac OS X 10.10.2 yesterday, when similar things started occurring.

From what it looks like, there were system level changes that affect local MySQL setups (my Apache runs fine). PHP version seems to be irrelevant (have tried three).

For the moment, it looks like Guardian's post above to run Vagrant (a Linux VM running on your system) may be your best bet.

# Answer
> 0 votes
Yosemite is no fun when it comes to your local dev environment. I have had a lot of similar issues when upgrading to Yosemite.

The first thing that comes to mind here is to check the PHP version on your ubuntu server and your local dev environment.

That might also be what is causing your problem here.

Another workaround is to give Vagrant a try. You can find all the info you need on Vagrant on https://www.vagrantup.com/

# Answer
> 0 votes
If the problem is your local environment. I would recommend to used a VM with Lazy Dubuntu. If you still want to use Yosemite for your local environment you should try MAMP or Acquia Dev Desktop.

# Answer
> 0 votes
Run MAMP or AMPPS, http://www.ampps.com or install another PHP, MAMP is nice since you can switch PHP versions anytime and set per project etc. I'd only run a VM if I were working in a team and we all had to run the same environment.

---
Tags: media, files
---


# Question
Title: Adding multiple taxonomy terms to a single node programmatically
I have the following iteration:

```
  foreach($category as $cat) {
              insert_term_if_not_exists($cat, 'tags');
              $term_tags = taxonomy_get_term_by_name($cat);
              $tid_tags = key($term_tags);
              $lang_tags = field_language('node', $node, 'field_tags');
              $node->field_tags[$lang_tags][0]['tid'] = $tid_tags;
            }
          }
       }
  node_save($node);

```

which relies on the following function to create non-existent taxonomy terms:

```
function insert_term_if_not_exists($term_name, $vocabulary_name) {
  $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  $matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);
    if(empty($matched_terms)) {
      $term = new stdClass();
      $term->vid = $vocabulary->vid;
      $term->name = $term_name;
      taxonomy_term_save($term);
    } else {
      $term = array_shift($matched_terms);
    }
return $term;
}

```

This couple pieces of code work great to create new taxonomy terms (taken from $category array) and to associate a node with the last taxonomy term. And I need to add all of the taxonomy terms which went through iteration above to the node.

Looking everywhere to find proper instructions to add multiple taxonomy terms to a single node programmatically without much success. Hope someone here can point me to the right direction, thanks!

# Answer
Finally I have a working code:

```
insert_term_if_not_exists($cat, 'tags');
              $term_tags = taxonomy_get_term_by_name($cat);
              $tid_tags = key($term_tags);
              array_push($tids, $tid_tags);
              $lang_tags = field_language('node', $node, 'field_tags');
            }
          }
          foreach ($tids as $index => $tid) { $node->field_tags[$lang_tags][$index]['tid'] = $tid; }

       }

```

All the credit goes to user Albright in IRC channel #drupal at http://webchat.freenode.net who pointed out to me that I needed to collect the tids in an array, then add a second loop which loops through that array and adds the tids one at a time to field\_tags.
> 4 votes

---
Tags: taxonomy-terms
---


# Question
Title: Display external link using theme settings
I'm using theme-settings.php to store links to external pages (like Facebook, Twitter, etc.) and the links aren't storing correctly. In theme-settings.php, I have:

```
function mytheme_form_system_theme_settings_alter(&$form, $form_state) {
 $form['mytheme_facebook'] = array(
'#type'          => 'textfield',
'#title'         => t('Facebook Link'),
'#default_value' => theme_get_setting('mytheme_facebook'),
'#description'   => t("Appears in sidebar block."),

```

);

On my Theme Settings page, I enter https://www.facebook.com/ in the "Facebook Link" field. When I hit save, I see that only "www.facebook.com" has been saved in that field.

So, when I call the field on my site, using

```
print theme_get_setting('mytheme_facebook');

```

the link that gets outputted is http://www.myurl.org/www.facebook.com/.

How can I get I get rid of the "myurl" stuff, so I get a working link to Facebook? Oh, and I'm using Drupal 7, if that helps.

Thanks in advance for any tips!

# Answer
> 0 votes
Drupal is probably applying your default text format to your field.

Try adding a `#format` value to the array that matches one of your less strict input formats.

---
Tags: navigation
---


# Question
Title: How can I add custom fields to Commerce Discounts?
We would like to add a long text description and an image to each Commerce Discount which we will display to Users.

How do I do this, since the Discount data structures are not available in the Admin?

# Answer
You'll need to implement the field api to attach fields to certain entities. Or you could within hook\_entity\_info() (I think), there is a 'fieldable' array key you could set to TRUE. From there, you may need to programmatically add a field to it. A good way to get field definition code is to use Field Inspector module, add a field to an entity using the UI, and export that field definition as a base to code yours.
> 1 votes

---
Tags: commerce
---


# Question
Title: Rewriting a link field to link to 2 different places depending on what's given
I have a content type which contains a website field of type "link." I am creating a view that should have the title which links to the content for each piece of content, unless a link is provided in the website field - then the title should link there.

This is what I am currently trying:

* title field is hidden
* website field results rewritten so that \[title\] is the text and it is outputted as a link to \[field\_website-url\].
* website field no results are set to go to: \[title\]

However, this method is not working. It works when there is actually a website URL specified in the website field, but for all others, clicking on the titles links to ".com/link\].

Any help figuring this out would be greatly appreciated!

# Answer
The problem lies in trying to use the 'link to original content' in 'no results'.

Try putting the fields in this order with these formats:

* Title - just plain text
* Link to content - raw URL
* Website field - raw URL

Then set *Rewrite Results* to `<a href="[token for website]">[title]</a>`

And set *No Results Behaviour* to `<a href="[token for link raw URL]">[title]</a>`

Note you'll have to find the right token for the links in the *Replacement Patterns* section that shows up when you tick 'Rewrite the output of this field'

Don't use 'Output this field as a link' or the link will apply to the *No Results Behaviour* as well, I think.
> 1 votes

---
Tags: navigation, views
---


# Question
Title: Coloring rows in returned drupal search results
I'm trying to modify search-result.tpl.php and template.php to color the backgrounds of search results returned such that every row has a different color than the one that preceded it. Only two colors are used. so, row #1 returned would have background #eee and row 2 would have #ff0000 as its background color. It would start over again at row #3 having #eee and so on. This is easily enough accomplished with PHP. But how can I implement this with Drupal?

Here's how I'm trying to print it out in search-result.tpl.php:

```
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <div class="search-snippet-info">
    <?php $inc=0; ?>
      <?php if ($inc %2 == 0) {
                $color = '#eee';
              } else {
                $color = '#ff0000';
              }
              ?>
      <div style="background-color: <?php print $color ?>">
      <div class="icon" style="float:left;"><?php print render($teaser['field_icon']); ?></div>
      <div class="teaser">
      <header>
      <h2><a href="<?php print $result['link']; ?>"><?php print $result['title']; ?></a></h2>
      </header>
      <em><?php print render($teaser['field_type']); ?></em>
      <strong><?php print render($teaser['field_event_dates']); ?></strong>
      <?php print render($teaser['body']); ?>
      </div>
      <?php $inc++; ?>
      </div>
  </div>
</li>

```

Not getting errors, but the results are not what I was expecting. Each row is just returning the same color background #eee, the first color). So either the $inc variable is not getting incremented or (perhaps more likely) it's becoming '0' again after every returned result. So then I'm thinking maybe I need to add something to my preprocess\_search\_result function in my template.php file...but I don't know what to add there.

Any help would be greatly appreciated.

# Answer
> 1 votes
In your search-result.tpl.php you should have a $zebra variable available for your use, which will be either "odd" or "even" so you can use that in place of trying to track your $inc variable. The $zebra variable is added by template\_preprocess().

# Answer
> 1 votes
I would create your search results page using views, this has the odd/even class functionality built-in. The current code you provided won't work since the $inc value starts as 0 and there is no loop where $inc++ occurs so everytime this template is loaded $inc will start as 0 and end as 1.

---
Tags: search
---


title: Requesting a new password

text:
# Question
Title: Requesting a new password
I need to request a new password via services.

I used the URL: `<endpoint>/user/password?args['name']=test2`

but it returns `Access denied for user anonymous`

It's supposed to be used by non authenticated users so why does it return this error?. What am I doing wrong here? What is the URL should I use?

# Answer
> 4 votes
This feature was added with the resolution of this issue:

To use this resource, make a ***POST*** to:

```
?q=rest/user/request_new_password.json

```

...and send along a name

```
name=john

```

...or e-mail address:

```
name=john@example.com

```

# Answer
> 1 votes
According to this sandbox (from two years ago):

> Services module provides integration with User module but it does not provide the service to request a new password in case a user has forgotten it.

The sandbox claims to fix that.

---
Tags: services, 8
---


# Question
Title: Drupal views contextual filter: use last argument as filter value
I would like a views contextual filter to only use the last argument in the url. Given the following taxonomy structure, I would want `/term-a` to return `Term A1` and `Term A2` only (which works fine). However, if the url is `/term-a/term-a1` I would want only `Term A1a` to be returned, which isn't working, it's still returning `Term A1` and `Term A2`

Within views, I don't see a way to use the last part of the path for the filter. I tried to remove the argument from the path and then use the following as a default argument:

```
$path = arg();
return array_pop($path);

```

Here is the sample term hierarchy:

```
- Term A
  - Term A1
    - Term A1a
  - Term A2
- Term B
  - Term B1
  - Term B2

```

Just to reiterate what is returned:

The path `/term-a` returns:

* Term A1
* Term A2

The path `term-a/term-a1` returns:

* Term A1
* Term A2

The path `/term-a1` returns:

* Term A1a

# Answer
One solution would be hook\_views\_pre\_view()

```
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
    if ($view->name == 'view_machine_name' && $display_id == 'my_display_id') {
        $args = array(end($args));
    }
}

```

For a view with one contextual filter this would always set the argument to the last argument from the URL.
> 1 votes

# Answer
Use one view with two page displays.

The first display will take one contextual filter of /term-a

The second display will take two contextual filters. The first filter will be global null (so you can throw it away), and the second will be term-a1
> 0 votes

---
Tags: views
---


# Question
Title: Adding class to image-link in render array
In the render array of an image with link, i tried to add the class 'colorbox-load' to the link, i.e. the `<a>` tag of the link, but i can't get the adding of the class to work:

```
$node = node_load(52);
$my_image = field_view_value('node', $node, 'field_image', $my_image[0], array(
          'type' => 'image',
          'settings' => array(
          'image_style' => 'thumbnail',
          'image_link' => 'content',
          ),
        ));

$my_image['#path']['path'] = 'http://www.example.com';
$my_image['#attributes']['class'][] = 'colorbox-load';

```

What am i doing wrong?

# Answer
> 1 votes
To get your class on the image's link you'll need to set it in the path options:

```
$my_image['#path']['options']['attributes']['class'][] = 'colorbox-load';

```

---
Tags: navigation, theming
---


title: Drupal 7 - create own login form

text:
# Question
Title: Drupal 7 - create own login form
Is it possible to create own login form? I need to insert it into my basic page. It is campaign for my client and he wants to be able login from specific basic page. I have tried to use block from classic login, but without success. But it still has many things around (like remember me etc..), and I need only basic username/password

thanks for any help

# Answer
> 1 votes
You should be able to just retrieve the form and print it on your node template. In your theme's template.php (a custom module would work too):

```
function MYTHEME_preprocess_node(&$variables) {
    if ($variables['view_mode'] == 'full' && $variables['nid'] == 9 && user_is_anonymous()) {
        $variables['login_form'] = drupal_get_form('user_login');
    }
}

```

And then in either your theme's node.tpl.php or a specific node template if you're using one:

```
<?php if (isset($login_form)): ?>
  <?php print render($login_form); ?>
<?php endif; ?>

```

This will just print the same form you'd find at /user/login wherever you want it. Just make sure to replace the 9 with your node's nid.

# Answer
> 1 votes
Or, if you're looking for a way to do it without writing code, consider the Login Toboggan module.

---
Tags: forms, theming, users, 7
---


# Question
Title: How to I add a node reference field using the Webform module?
Is it possible to add a node reference field using the Webform module?

If it is, how can I add it in my webform?

# Answer
I done this but for a user reference by creating a new module and a new webform component.

This new component effectively recreates the user reference functionality and allows you to choose it on the webform. You could try the same approach to do it for a node reference.

Also there are some good examples in the webform examples to help you with the basics in creating a new component with hooks like `_webform_defaults_component()`.

The main thing which will help you is the `'#autocomplete_path' => 'autocomplete/node',` in `_webform_render_component()` which you will need in the component.

...In the module add something like the below (obviously change for node lookup):

```
//create a url path for the autocomplete
function hook_menu() {
  $items['autocomplete/users'] = array(
    'path' => 'autocomplete/users',
    'title' => 'Auto Complete Users',
    //page callback to a custom function
    'page callback' => 'hook_autocomplete_users',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );
  return $items;
}

//custom function created to mimic auto complete functionailty
function hook_autocomplete_users($string = '') {
  $matches = array();
  $query = "SELECT u.name, u.uid FROM {users} u WHERE name LIKE LOWER('%s%%')";
  $result = db_query_range($query, $string, 0, 10);
  while ($user = db_fetch_object($result)) {
    $matches[$user->name.' uid:'.$user->uid] = $user->name;
  }
  //print drupal_to_js($matches);
  drupal_json($matches);
  //exit();
}

```

You will need to choose what you want in the node reference too as by default it would just be the nid which in an email would be pretty useless..
> 8 votes

# Answer
You should dump the old Webform module and take a look at Entity Form :)

It allows you to add for example Node reference field for your form. Were neat module!
> 2 votes

# Answer
Entityforms module uses the standard Drupal fields which means you can use any standard Drupal fields. For those of you who have used Webforms, this module brings Webform's functionality into the "standard" Drupal field / entity world.

While Webform is a great module with a huge following, it does not integrate with standard Drupal field or entity aware modules. So for Drupal 7 sites, it is recommended to use Entityforms module!

Like Webform, it integrates well with Rules module for form submission notifications and allows for complex notifications logic.
> 2 votes

# Answer
Check out Webform References module. I think it perfectly suits your case.

As the module page reads

> Provides a webform component that can reference a node/term in webform. Currently, the module includes node/term reference components. It provides "Select List" and "Autocomplete" as widget. User reference will be added later.
> 2 votes

# Answer
```
function MY_MODULE_webform_select_options_info() {
  $items = array();
  $items['my_custom_list'] = array(
    'title' => t('Custom list'),
    'options callback' => 'MY_MODULE_custom_list'
  );

  return $items;
}

function MY_MODULE_custom_list() {
  $my_custom_list = array(
    'foo' => 'bar',
  );

  return $my_custom_list;
}

```

You now have a new pre-built option list. When you create a new field type "select options" you can choose "Load a pre-built option list" and there is your new list
> 0 votes

---
Tags: webforms, nodes
---


title: Rewrite field for a specific row?

text:
# Question
Title: Rewrite field for a specific row?
I see that in views the Rewrite the output of this field option affects all rows. Is there a way, using php or something, to rewrite the output of row #4 only?

# Answer
Put this code in your theme's template.php file:

```
function THEME_preprocess_views_view_fields($vars){
  dpm($vars);
  if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['id'] == 4){
    $vars['fields']['title']->content = 'blahblah';
  }
}

```

Clear the cache.

Replace VIEWNAME, DISPLAY and 4 with your appropriate values.

Then inspect the $vars\['fields'\] with dpm output and rewrite the output how you want for the field in question. You may use 'raw' value, but remember to sanitize.
> 3 votes

# Answer
just thought of a solution using the views php module.

I added a view result counter field and then a php field which I put:

```
<?php
    if ($row->counter == 4) {
      print 'HELLO THERE!';
    }
    else {
       print $row->title;
    }
?>

```

# **After reading the accepted answer to this question What are the downsides of using 'custom' PHP code in blocks, nodes, views-args, etc?** which was mentioned by f0ns (see comment below)

The biggest reason being:

> If your CMS allows execution of PHP then an attacker who finds a security vulnerability of XSS or privilege escalation can now use your server for enormously malicious things (as part of a DDOS, sending spam, hosting malware, hacking into other sites/databases on the server, hacking into other servers on the network that might be behind firewalls). In addition to making small vulnerabilities more painful, this makes the site a more likely target of attack if its known that it can be used to execute php.

**Thus, I decided to go with the answer I accepted, which does not use Views PHP**
> 0 votes

# Answer
Use the view template file and use `$id` variable. If you are using `$id` variable then you will get id 4 for row 4.
> 0 votes

---
Tags: 7, views
---


# Question
Title: What happened to the og-list view in organic groups?
The new version of Organic Groups (7.2) does not have a the view og-list, which used to display a list of all the groups. Any idea why it was removed and how to get the list of all groups?

# Answer
I don't know why it was removed, but here's a sample view you can import and tweak as needed. To import, go to /admin/structure/views/import.

```
$view = new view();
$view->name = 'og_list';
$view->description = 'A list of all Organic Groups';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'og list';
$view->core = 7;
$view->api_version = '3.0';
$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'] = 'All Groups';
$handler->display->display_options['use_more_always'] = FALSE;
$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['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
$handler->display->display_options['row_options']['links'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* 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';
/* 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'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'group' => 'group',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'og-list';
$translatables['og_list'] = array(
  t('Master'),
  t('All Groups'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Page'),
);

```
> 1 votes

# Answer
The OG Extras module could solve some of your needs, among other useful displays and features -

> Extra functions, blocks, and views for Organic Groups 7.2. In particular, this module adds views and blocks needed by sites that are not using Panels, although it also may be useful to sites that do use Panels. This module is for Organic Groups 7.2. It will not work with Organic Groups 7.1.
>
> This module was created because the default views and blocks that come with Organic Groups only work in Panels. It restores some of the functionality of the D6 version of Organic Groups.
> 1 votes

---
Tags: organic-groups
---


title: Change node during saving it

text:
# Question
Title: Change node during saving it
I am using Drupal 7.34 and I have a problem..

My module is reacting on node changes. When a node is updated one or more other nodes are automatically being updated, too. I call a function that triggers that update in `hook_node_save`.

Everything is fine until I try to make changes to the node that was initially saved and is passed to the `hook_node_save`. The reason is actually pretty obviuos: The changes prepared during the inital save process are overwriting the changes made during the function that is called in `hook_node_save`.

So here is my question with an example: I want to change field\_a of node 100 after node 100 is updated from somewhere around the system. How do I achieve that while having access to the initially updated values of node 100?

**Edit 1:**

My `hook_node_presave`:

```
if (!$node->is_new) {
  $items = field_get_items('node', $node, 'field_oc_revision');
  if ($items) {
    _trigger_steps($items[0]['value'], $node);
  }
  debug($node);
}

```

The \_trigger\_steps() function changes the $node object passed by reference.

Now when I click save on a node form `hook_node_presave` is triggered twice. The first time the debug shows that the field is changed in the normal `$node` field, but not in the `$node->original` field. The second time the debug shows that the field is changed in the `$node->original` field, but not in the `$node` field.

Hope that gives more insight.

**Edit 2:**

One more thing to mention: When using the same code with manually calling `$node = node_load(100); node_save($node);` everything works like it should.

**Edit 3:** This is the part of the code of the `_trigger_step` function that is executed.

```
$connected_node = user_activity_get_step_base_node($base_nid, $step['connected_node_type']); // In this special case this loads the node that was just updated

$items_base_field_name = field_get_items('node', $connected_node, $step['base_field_name']); // $step is a definition of a step to trigger.

$expert_uid = $process['coordinator_user'];

$expert_nid = $items_base_field_name[0]['target_id'];
$expert_nid = node_load($expert_nid) ? $expert_nid : '';
// check if expert uid is set and node is not already linked
if($expert_uid && !$expert_nid) {
  $expert_node = new stdClass;
  $expert_node->type = $step['node_type'];
  node_object_prepare($expert_node);

  $expert_node->language = LANGUAGE_NONE;
  $expert_node->title = $node_type_names[$step['node_type']];
  $expert_node->uid = $expert_uid;
  $expert_node->promote = 0;
  // connect the nodes
  $expert_node->{$step['assignee_field_name']}[LANGUAGE_NONE][0]['target_id'] = $connected_node->nid;
  // tree assignment
  $expert_node->field_oc_revision[LANGUAGE_NONE][0]['value'] = $base_nid;
  $expert_node->field_oc_tree_element[LANGUAGE_NONE][0]['value'] = $step['sid'];

  // save new node
  node_save($expert_node);

  // if the updated node is the one that we want to change here, we just change the passed node. it is saved after hook_node_presave.
  if($updated_node) { // $updated_node is passed by reference
    $updated_node->{$step['base_field_name']}[LANGUAGE_NONE][0]['target_id'] = $expert_node->nid;
  // if not we set save it directly
  } else {
    $connected_node->{$step['base_field_name']}[LANGUAGE_NONE][0]['target_id'] = $expert_node->nid;
    node_save($connected_node);
  }
}

```

Thanks a lot! cheers j

# Answer
> 0 votes
After a long night of debugging I finally found the bug. I always thought that hook\_node\_presave is called twice when submitting a form. That is wrong. Took me a while to find out.

I then searched for `node_save` operations in my code through like 20 modules and found a module calling `node_save` in a custom node form submission handler. I removed it and it works now.

Thank you all for your help!

---
Tags: 7, nodes
---


title: Low Maximum execution time

text:
# Question
Title: Low Maximum execution time
I was installing drupal commons on xampp server i got this error, PHP Max Execution Time 30 Your PHP execution time is too low, please set it greater than or equal to 120 seconds. How do i adjust the php execution time so that i can proceed with the installation?

# Answer
Follow below steps and change that file.

1. Go to your XAMPP installation Folder and edit - ..\xampp\php\php.ini file.
2. Use the FIND function of your editor an look for "max\_execution\_time"
3. in that line you will see the value attributed to "max\_execution\_time" change it to **max\_execution\_time=120**
4. Save the php.ini file.
5. Restart the XAMPP Server
6. Proceed with Drupal Commons installation.
> 1 votes

---
Tags: installation, 7
---


title: How can I show Arabic dates in a block?

text:
# Question
Title: How can I show Arabic dates in a block?
I have used Drupal7 and I want to add Arabic date in Hijri formate; I have used the Calendar Systems module, but it doesn't add dates as block. How can I implement `hook_block()` to show dates in Hijri format?

# Answer
> 2 votes
its approved now I just added the new release yesterday

Hijri

> This is a smart module that basically extends Drupal's display date to provide Hijri Date integration with Drupal core date field and with other Drupal contributions.

# Answer
> 0 votes
There is a sandbox module that should allow you to format dates this way:

> This is a smart module that basically extends Drupal's display date to provide Hijri Date integration with Drupal core date field and with other Drupal contributions.
>
> This module is integrated very well with Views module. You can use it to display Hijri date instead of Gregorian date or you can have them both by mention "\[had to remove Arabic text\]". Also this module coming with Hijri block that will showing Hijri today date on your website wherever you want to show today date in your header for example.

I do not know when/if this module will be approved and promoted to a full project.

---
Tags: 7, datetime
---


# Question
Title: Auto Complete displaying wrong for non-admin users
I've recently started a module that runs an autocomplete via the taxonomy. It's attached to a form textarea element:

```
$form['bb_occupation'] = array(
    ...
    '#autocomplete_path' => 'taxonomy/autocomplete/field_occupations_list',
);

```

My issue is as follows, The options returned from the auto complete display correctly for admin/logged in users:

*Full size image*

While, if a non-admin/non logged in user visits said site, they're greeted with this:

*Full size image*

Where the options appear well off screen. I did a little research on Drupal & Google and came up with these:

Autocomplete fields appear in wrong place for non-admins in...

Which lead to an answer that did the following sort of deal (*taken from here*):

```
$($input).parent().addClass('autocomplete-wrapper');

```

in the `autocomplete.js` and this:

```
.autocomplete-wrapper {
  position: relative;
}

```

to the `system.base.css` files. That didn't work for me, and I've been playing with positioning for practically the whole day now, do you guys have any suggestions as to how I can amend/fix this?

It is **not** related to anything like this:

(custom )Autocomplete won't work when the user is not logged

as it isn't a custom function doing the autocomplete, it's through the taxonomy. It can't be a permissions error either because the menu with suggestions shows up, just not where it's supposed to.

# Answer
I think anonymous user doesn't have a permission of autocomplete. Can you please visit permission tab of your site. May be you get some luck!

Hold on, you are using taxonomy right, then please check this module permission. I think that time you get some luck.
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: Does node_delete() function deletes the attached media files as well?
I'm deleting my `'articles'` created before `Sat Nov 1 00:00:00 2014 GMT` from `Drupal 7.34` site, but I'm not sure whether the `node_delete()` delete the media files as well?

Below is my processing code:

```
<?php

// Fetch the NIDs of 'articles' created before Sat Nov 1 00:00:00 2014 GMT
$query = db_select('node', 'n')
->fields('n', array('nid'))
->condition('type', 'article')
->condition('created', 1414800000, '<') // 1414800000 = Sat Nov 1 00:00:00 2014 GMT
->orderBy('created', 'DESC')
->range(0, 100);
$result = $query->execute();

// Code to delete my articles in bulk
while ($record = $result->fetchAssoc()) {
  $nid = $record['nid'];
  echo $nid;
  node_delete($nid);
}

?>

```

# Answer
> 2 votes
It depends.

If the file has no references left to it in the `file_usage` table, then yes, it will be deleted.

If there are remaining references, it won't be deleted.

Either way, `file_delete()` is definitely invoked for the file.

# Answer
> 0 votes
Yes node\_delete function delete all the media files as well.

# Answer
> 0 votes
As far as I know node\_delete() does it all for you ,, it removes associated fields and everything ..

# Answer
> 0 votes
You are right **node\_delete()** will delete all associated files uploaded in the file system and in **managed\_files** table and all entries related to that node id you pass.

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


# Question
Title: Render page callback output in another region than "content"
I am implementing `hook_menu` and I want to render the output of one `page callback` in a certain region, other than `content`.

Is there a way of doing this?

# Answer
Instead of defining a page via `hook_menu` it is better to define a block that you can place everywhere across the site.

Is there any requirement that restricts you to using a page?

If not the following code creates a block:

```
/**
* Implements hook_block_info().
*/
function YOUR_MODULE_block_info() {
  $blocks = array();
  $blocks['YOUR_BLOCK_ABC'] = array(
    'info' => t('YOUR BLOCK NAME'),
  );
  return $blocks;
}

/**
* Implements hook_block_view().
*/
function YOUR_MODULE_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'YOUR_BLOCK_ABC':
      $block['subject'] = '';
      $block['content'] = _YOUR_MODULE_BLOCK_ABC_CONTENT();
      break;
  }
  return $block;
}

function _YOUR_MODULE_BLOCK_ABC_CONTENT() {
  // This is where you code you use for the page goes.
  return t('Hello world');
}

```

Code from http://kahthong.com/2013/06/create-your-own-custom-drupal-block-programmatically

You can restrict the block visibility in the block settings to only be shown on single pages. Maybe this might solve the problem. To access arguments from the current page you can use the arg function.

Cheers j
> 1 votes

# Answer
I have managed to move the output from the `content` region to the `content_top` custom region like this:

```
function MYMODULE_page_alter(&$page)
{
    list($path) = explode('/', current_path());

    if ('shopping-list' == $path) {
        $page['content']['#region'] = 'content_top';
        $page['content_top'] = $page['content'];
        unset($page['content']);
    }
}

```
> 0 votes

---
Tags: theming, routes
---


# Question
Title: Enable/disable a menu item programatically depending on a variable value
I need to show a menu item only in certain moments. Imagine that I've a form with some options. If 'A' is selected, I need to enable a menu item that has a form for adding information about 'A'.

I have done a module that has a hook\_menu like this:

```
> function secciones_menu() {
>
>
>   $items = array();
>
>       $items['secciones'] = array(
>           'title' => t('Crear Sección'),
>           'description' => t('Crear Secciones'),
>           'page callback' => 'drupal_get_form',
>           'page arguments' => array('secciones_wizard'),
>           'access callback' = TRUE,
>           'type' => MENU_NORMAL_ITEM,
>           'menu_name' => 'main-menu',         'customized' => 1, // Must be 1 in order to not dispaly the link in any language
>           'language'  => 'es', // language is required in order to make the item translatable   );

return $items; }

```

And then have my form for 'A'. So how I can enable or disable the menu item, depending a variable value?

Thank you !

EDIT 1:

What I've done is change the access callback and the menu type:

```
function agenda_menu() {

  $items = array();

  $items['agenda'] = array(
        'title' => t('4. Crear agenda'),
        'description' => t('Crear agenda'),
        'parent'=>array('Configurar Revista'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('agenda_wizard'),
        'access callback' => 'agenda_access_callback',
        'type' => MENU_DEFAULT_LOCAL_TASK,
        'menu_name' => 'main-menu',
        'customized' => 1, // Must be 1 in order to not dispaly the link in any language
            'language'  => 'es', // language is required in order to make the item translatable
  );

  return $items;
}

```

And then I've done the next code:

```
function agenda_access_callback(){

    //db query
    //insert that query in $options array
    foreach ($result as $row) {
        $options[$row->id_seccion] = $row->id_seccion;
    }

    if(isset($options)){ //if the array is not empty
        return TRUE; //the menu item is visible
    }
    else{
        return FALSE; //otherwise, is not visible
    }
}

```

Ok, this is what I have done, but it doesn't work. Any idea? Thank you.

# Answer
> 0 votes
The usual way to enable a menu item only in certain circumstances is to use a custom access callback, in which you would evaluate whether this option is set. So:

```
'access callback' = 'my_module_access_callback',
...

function my_module_access_callback() {
   return my_module_test_option_is_true();
}

```

But it's a little hard to be sure if this will work for your case as you haven't given us much to go on.

---
Tags: forms, routes
---


# Question
Title: SelectQuery row_number won't work with PDO
I'm working on a project that needs to query a MySQL database and select the row number (among other columns) for each row. To be more specific, I have the table `test` and want to get the table `result`:

```
**test        result**
**a | b     a | b |counter**
1 | 1     1 | 1 |  1
1 | 3     1 | 3 |  2
1 | 5     1 | 5 |  3
2 | 1     2 | 1 |  1
2 | 2     2 | 2 |  2
3 | 1     3 | 1 |  1
3 | 3     3 | 3 |  2

```

where column `counter` counts the number of occurences of `a` with different `b`

I have found the solution for MySQL in a post, using variables inside the query:

```
SELECT
  o.a AS a,
  o.b AS b,
  @num := IF(@a = a, @num + 1, 1) AS counter,
  @a := a AS dummy
FROM
(
  SELECT
    t.a AS a,
    t.b AS b
  FROM test t
  ORDER BY a ASC
) o

```

which gives me the exact result (with the addition of one dummy column).

The problem arises when I try to implement it in Drupal 7 using the following code:

```
$tq = db_select('test', 't')
  ->fields('t', array('a', 'b'));
// Order rows for correct numbering
$tq->orderBy('a');
$t2q = db_select($tq, 'o')
  ->fields('o', array('a', 'b'));
// Add counter
$t2q->addExpression('@num := IF(@a = a, @num + 1, 1)', 'counter');
// Add dummy column
$t2q->addExpression('@a := a', 'dummy');
// Store results
$r = array();
foreach($t2q->execute() as $row)
  $r[] = (array)$row;
dpm($r, $t2q->__toString());

```

The prepared query is correct and exactly the same as the above query:

`SELECT o.a AS a, o.b AS b, @num := IF(@a = a, @num + 1, 1) AS counter, @a := a AS dummy FROM (SELECT t.a AS a, t.b AS b FROM {test} t ORDER BY a ASC) o`

but the result is:

```
**test        result**
**a | b     a | b |counter**
1 | 1     1 | 1 |  1
1 | 3     1 | 3 |  1
1 | 5     1 | 5 |  1
2 | 1     2 | 1 |  1
2 | 2     2 | 2 |  1
3 | 1     3 | 1 |  1
3 | 3     3 | 3 |  1

```

I have no idea of the internals of PDO and the reason why variables inside `SELECT` statements won't work.

If I try with db\_query feeding it the prepared query (as in the following code) I get the same results.

```
$tq3 = db_query($t2q->__toString());
while($row = $tq3->fetchAssoc())
  $r[] = $row;
dpm($r);

```

But if I first call `execute` on the query I get the correct results (but can not use `extend` on `DatabaseStatementInterface`).

```
$tq3 = db_query($t2q->__toString());
$tq3->execute();
while($row = $tq3->fetchAssoc())
  $r[] = $row;
dpm($r);

```

Does anyone have any helpfull idea?

# Answer
> 0 votes
In order to count the number of occurence you can use groupBy and having cluases but as you mention above your format is completely different. So it is not feasible to you. Try this one may be it'll helpful to you.

```
$query = db_select('temp', 't');
$query->fields('t',array('a','b'));
$query->orderBy('t.a');
$result = $query->execute();

$field_sum = 1;
$prev = NULL;
foreach ($result as $record) {
   if ($prev ==  $record->a) {
      $field_sum++;
   }
   else {
   $field_sum = 1;
   }

   echo "\n a " . $record->a . " | b " . $record->b . " | Counter ". $field_sum;
   $prev = $record->a;
}

```

Also ensure that these list of function can't be chained:

```
addExpression()
addField()
addJoin()
extend()
innerJoin()
join()
leftJoin()
rightJoin()

```

---
Tags: database
---


# Question
Title: how to update my custom table after execution of rules
i have created a table as follow

```
<?php

/**
 * @file
 * Implements hook_schema
 */
function core_sms_schema() {
  $schema['core_sms_details'] = array(

    'description' => 'This table is used to keep track of sms sent/failed on specific date.',
    'fields' => array(
      'id' => array(
        'description' => 'The primary identifier for a node.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'date' => array(
        'description' => 'Date',
        'mysql_type' => 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP',
        'not null' => TRUE,
      ),
      'sms_sent' => array(
        'description' => 'The SMS sent on particular date.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => '0',
      ),
      'sms_failed' => array(
        'description' => 'The SMS failed on particular date.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => '0',
      ),
    ),
    'primary key' => array('id'),
  );
  return $schema;
}

```

After a sms has been sent i have to update the columns with number and date. i already have rules also but not able to get how to update the custom table using rules.

# Answer
In rules you have option to add PHP code inside the **Action -\>PHP-\> "Execute custom PHP code** " in that have a code to update the custom table.

The following variables are available and may be used by your PHP code:

**Variable name Type Description**

**$site** Site Site information

**$node** Content updated content

**$node\_unchanged** Content unchanged content

you can use for updating the table if its a node

Note : here node represented as a example
> 0 votes

---
Tags: hooks, rules, database
---


# Question
Title: How to disable AVS check in commerce cybersource SASOP
Using Commerce CyberSource SASOP it is possible to ignore the results of AVS verification? There is an option for this as specified in the CyberSource Development Guide on the page 74.

# Answer
It is possible to add parameters to the data using `hook_commerce_cybersource_sasop_transaction_data_alter($data)`

```
<?php
my_module_commerce_cybersource_sasop_transaction_data_alter($data) {
  // Ignore AVS check
  $data['ignore_avs'] = 'true';
}

```

Issue in Drupal.org
> 0 votes

---
Tags: 7, commerce
---


title: Views PDF pagination

text:
# Question
Title: Views PDF pagination
Is it possible to add a pagination to a pdf when using views pdf module in drupal 7. Or is there any custom module.

# Answer
> 0 votes
Yes it is possible with https://www.drupal.org/project/views\_pdf. Just make the view page as any other view.

---
Tags: views, 7
---


title: Align fields in created webforms

text:
# Question
Title: Align fields in created webforms
I am new to drupal, and currently i am creating a webpage in drupal from html . i have almost completed. I have created web form for "Contact us" form, after creation it is not in proper alignment. So, my form should be look like the picture shown as below.

So, right now it is like as below image.

So, please someone help me to get out of this issue.

# Answer
> 0 votes
You can theme the webform. Create a new file: webform-form-81.tpl.php
(Replace the number 81 with the node ID of your webform)

Place this file in your sites theme directory (sites/all/themes/yourtheme/webform-form-81.tpl.php)

Inside this new webform-form-81.tpl.php file, insert the following code:

```
<table border="0">
<col style="width: 50%" /> <col style="width: 50%" /> </colgroup>
<tr>
    <td><?php print drupal_render($form['submitted']['name']); ?><br>
    <?php print drupal_render($form['submitted']['email']); ?><br>
    <?php print drupal_render($form['submitted']['phone']); ?></td>

    <td><?php print drupal_render($form['submitted']['notes']); ?></td>
</tr>

```

```
<?php
// Always print out the entire $form. This renders the remaining pieces of the
// form that haven't yet been rendered above (buttons, hidden elements, etc).
print drupal_render_children($form);

```

Save the file, then clear your Drupal cache. Refresh the page with the form on it.

# Answer
> 0 votes
This is rather a CSS issue. No need to rewrite the whole tpl.php. First issue regards input\[type="email"\] which is longer than other 2. Then there's a problem regarding textarea field wrapper. But we need form code (html), to provide proper css modifications.

---
Tags: webforms
---


# Question
Title: How can I categorize nodes by countries?
I have a created a content type "person", added to it custom field "country". I have downloaded the "countries" module and installed it.

I would like to categorize "person" nodes by countries, i.e. by clicking on the person's country, I could see all persons who live in the same country.

I don't think taxonomy could do the trick since I will have to add around 140 vocabulary terms also, node reference seems not to work properly...

Any help?

Thanks Sam

# Answer
You can achieve this by using views:

1. Create a new view that displays persons.
2. Under "Advanced" add a contextual filter for your country
3. As path use: "my\_path/%"
4. All users for country "Belgium" Will be available on "my\_path/BE"
> 0 votes

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


# Question
Title: Cannot use object of type Profile as array
Write a script to filter content by country.

> I have problem Cannot use object of type Profile as array in .... on line 19

Part of code with error

```
global $user;
$country = "";
if($user->uid!=1 && $user->uid!=0){
  $user_full = profile2_by_uid_load($user->uid);
  if(!empty($user_full['client'])){
    $country_parent = taxonomy_get_parents($user_full['client']->field_clcountry['und'][0]['tid']);

```

# Answer
> 3 votes
This

```
$user_full = profile2_by_uid_load($user->uid);

```

Returns an object, which you are then accessing as an array:

```
$user_full['client']

```

Which is illegal in PHP. You should access objects as objects, e.g.

```
$user_full->client

```

Or whatever it might be for that object type.

# Answer
> 1 votes
You can also use this to load profile2

```
global $user;
$country = "";
if($user->uid!=1 && $user->uid!=0){
    $user_full = profile2_load_by_user($user);
    if(!empty($user_full['client'])){
        $country_parent = taxonomy_get_parents($user_full['client']->field_clcountry['und'][0]['tid']);

```

---
Tags: views
---


title: How would I make a basic select list?

text:
# Question
Title: How would I make a basic select list?
So I am learning the ways of the jedi Drupal, but I have come across a part of a problem in what I am doing. I am currently trying to make a basic select list with two options. So far I have something like this.

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

  $form['select_list'] = array(
    '#type' => 'select',
    '#title' => 'Select One for Data Rundown',
    '#value' => t('Okay'),
  );

```

# Answer
> 1 votes
This is taken directly from Form API Reference. Familiarize yourself with it.

```
$form['selected'] = array(
       '#type' => 'select',
       '#title' => t('Selected'),
       '#options' => array(
         0 => t('No'),
         1 => t('Yes'),
       ),
       '#default_value' => $category['selected'],
       '#description' => t('Set this to <em>Yes</em> if you would like this category to be selected by default.'),
   );

```

EDIT

To print the result from the selection, you could consider a few things:

1. Do not use a form at all. Just use theme\_item\_list wherein you create hyperlinks to pages with nodes or users.
2. Use the form, but persist the user's selection (node or user) to the database or SEESION. Then when the form is created you reload the persisted value from the database or SESSION (if not present use default) as the default value so it always reflects the user's last choice, and you create a markup element wherein you show either the nodes or users that were the result of the selection or the default. In the submit you only persist the value to the database or SESSION. In the form creation you look at the persisted or SESSION value (if present, else use default), and display it in the markup element.
3. Use the form, do not persist anything in the database, and in the submit you inspect the select list value, and depending on the value you redirect (using $form\_state) to a page that will show either nodes or users.
4. Create a jump list: for example ARCHIVE: Example: How to Create a 'Jump Menu' from a List View

# Answer
> 1 votes
All you're missing is options:

```
$form['select_list'] = array(
  '#type' => 'select',
  '#title' => 'Select One for Data Rundown',
  '#value' => t('Okay'),
  '#options' => array(
    'option-1' => 'bar',
    'option-2' => 'baz',
  ),
);

```

The array key of options is used as the `<option>`'s value attribute, and the array value is used for the element's inner text.

---
Tags: 7, forms
---


# Question
Title: How to add a extra products fields on ubercart check out pane table?
Hi im looking to add some extra fields on the check out pane, i mean fields from the product like some attributes, theres any possibility?

Please if someone how to do this let me know!

Thank's to everyone who can help me!

# Answer
> 2 votes
You can go for Ubercart Webform Integration

```
This module integrates two other modules: webform and ubercart. It allows you sell
products directly from your webforms. It is particularly suited to be used as part of a
registration system.

```

---
Tags: 7, ubercart
---


# Question
Title: How to get Form API #states selected value onchange?
When I'm using `#states` to set the visibility of a form field I'm checking an input element for its value. Is there then any way to grab the selected value the moment it's selected?

In the working sample below I'm displaying some markup when a select list's `value != '_none'`. It works good so far. But how do I get the markup to display the value I selected?

Background is: it's a node reference select list and I'm trying to maybe load some fields from the selected node as preview inside the markup. The moment I'm writing this I think it's a stupid idea. I'm in Ajax with `#states`, right? And there might be no way to call `node_load()` or anything the like, right?

```
/**
 * Implements hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'MY_FORM') {

    $form['my_container'] = [
      '#type'   => 'container',
      '#states' => [
        'visible' => [
          ':input[name="my_field_name[und]"]' => ['!value' => '_none'],
        ],
      ],
    ];

    $form['my_container']['markup'] = [
      '#type'   => 'markup',
      '#markup' => /* selected value here */ ,
    ];
  }
}

```

# Answer
> 5 votes
Drupal `#states` is nothing more than the page containing JS data, and `states.js` reading them and adding necessary JS events to hide/show/etc fields. At the moment, there is no `#states` based method to get the selected value.

Note that it's perfectly OK to add `#states` to elements that are passed through Ajax. The beauty is that, whenever something containing `#states` is rendered, Drupal pipes these JS data along with the Ajax response. Since behaviours are run everytime after an Ajax response, `states.js` can update its visibility rules even for Ajax-changed elements.

I think your solution would be to use `#ajax` to do this. Your `[#ajax]['callback']` will contain just-selected values in `$form_state['input']`, so you can use them.

# Answer
> 2 votes
Thanks @AyeshK and @Beebee for pointing me in the right direction. Here is how I finally got hold of the selected value and displayed it via an `['#ajax']['callback']` I attached to the `node_reference` select list. From there on it's quite simple to modify the markup to more advanced needs like displaying a preview of a node or a field.

In the end you might want to add a second wrapper with the same ID to hold the default value when editing an existing node.

```
/**
 * Implements hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'MY_FORM') {

        // add an Ajax callback to the select list and define a wrapper the action should happen in
        $form['field_node_reference'][LANGUAGE_NONE]['#ajax']['callback'] = '_MY_MODULE_ajax_callback';
        $form['field_node_reference'][LANGUAGE_NONE]['#ajax']['wrapper'] = 'MY-ID';

        // create a wrapper
        $form['MY_WRAPPER'] = array(
            '#type' => 'markup',
            '#prefix' => '<div id="MY-ID">',
            '#suffix' => '</div>',
            '#weight' => 3,
            );

        // do some magic
        if (isset($form_state['values']['field_node_reference'][LANGUAGE_NONE][0]['nid']) && $form_state['values']['field_node_reference'][LANGUAGE_NONE][0]['nid'] != '') {

            $nid = $form_state['values']['field_node_reference'][LANGUAGE_NONE][0]['nid'];
            $form['MY_WRAPPER']['#markup'] = t('You selected node number: @nid', array('@nid' => $nid));
        }
    }
}

function _MY_MODULE_ajax_callback(&$form, &$form_state) {
    // return the wrapper
    return $form['MY_WRAPPER'];
}

```

---
Tags: 7, forms
---


title: Registration field not to be saved

text:
# Question
Title: Registration field not to be saved
After a lot of searching, I've been unable to find the answer by myself, so here's my problem (with Drupal 7) :

I've been able to add new fields to my user registration form (config/people/accounts/fields) and even hide fields on the form... But I would like to do the opposite : display a field on the registration form whose only purpose would be to assign a value to another field upon validation. There would be no need for this field to be stored in the database (like a transient property in Java).

Is there a way to achieve that ? Thx

# Answer
> 3 votes
Yep! Take a look at:

```
yourtheme_form_user_register_form_alter

```

Add a new value to the form there, and then change the form's saving function. In your new saving function you can do whatever you need to do with custom validation and re-assigning that value.

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_form\_alter/7

---
Tags: entities, users
---


title: View filter by nid via relationships

text:
# Question
Title: View filter by nid via relationships
I have a content type **Project** with an entityreference user field `field_project_team` where you can assign users to the project.

I also have a content type **Task** with an entityreference field `field_parent_project` pointing to its parent Project and an entityreference user field `field_responsible` where you can choose one of users to be responsible for this Task.

I want the **Task** field options to include only those users who are mentioned in `field_project_team` of the parent node.

I've created a user type view with entityreference display for this, where I want to filter users by their belonging to field\_project\_team of the project with nid from `field_parent_project`, but can't configure it correctly.

What i'm actually trying to do:
**1)** When you create a Project node, you can select users who will be a working team for this very project. I've already done it with a `field_project_team` \- an entityreference user select list, which selects users with the role I need via user view with entityreference display.
**2)** You can create Task nodes for each Project. Each Task node should be connected to its parent Project. I'm doing it like this: on a Project node page I have a button "Add task" which opens Task node add page via the link like *node/add/task/\[xxx\]* (where \[xxx\] is a nid of the parent Project node). Then in the **Task** content type i have an entityreference field `field_parent_project` which is prepopulated from URL, so I can get the parent node reference filled automaticly when adding a new task.

All above mantioned works fine, but i try to achive one more thing:
**3)** When adding/etiting a Task node you should be able to assing this very task to some users to make them responsible for performing this task. In the **Task** content type I have an entityreference user select field called `field_responsible` where you can select users. But I want to see in this field not all site users, but only those who are already selected as a Project team - in the `field_project_team` of the parent Project. To get such a filtered user list I've changed the `field_responsible` settings ENTITY SELECTION mode to **Views: filter by an entity reference view** and created a user view with Entity Reference display called "Project team users" to filter users.

My problem is that I can't configure the display in a right way to get only those users I need, i.e. those who are already selected to be a Project team of a parent Project referenced from a Task via `field_parent_project` field.

This is my View display:

And some explaination:
1. A bridge to the Content entity that is referencing User via `field_responsible`
2. A bridge to the Content entity that is referenced via `field_parent_project` (relationship with Content referencing User via `field_responsible`)
3. Context filter via **Content:Nid** (relationship with Content referenced via `field_parent_project`)to get the Nid of parent Project
4. Was trying to add Content:Nid filter related with Content referenced via field\_parent\_project to filter by the Nid of parent Project.
5) "5" is a Nid of a test Parent project. The Project node with such a Nid exists on the site and some test Taks have reference to it as to parent Project.

In final, it doesn't work. I think I'm missing smth very simple with this but can't realize what... Will be very thankful for any help.

# Answer
> 0 votes
Please take a look at the views export below, this will give you user values. This will work on editing the task but not when you are initially creating the task (as the field\_parent\_project does not yet have a value stored against it).

```
$view = new view();
$view->name = 'test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Test';
$view->core = 7;
$view->api_version = '3.0';
$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'] = 'Test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Entity Reference: Referencing entity */
$handler->display->display_options['relationships']['reverse_field_project_team_node']['id'] = 'reverse_field_project_team_node';
$handler->display->display_options['relationships']['reverse_field_project_team_node']['table'] = 'users';
$handler->display->display_options['relationships']['reverse_field_project_team_node']['field'] = 'reverse_field_project_team_node';
/* Relationship: Entity Reference: Referencing entity */
$handler->display->display_options['relationships']['reverse_field_parent_project_node']['id'] = 'reverse_field_parent_project_node';
$handler->display->display_options['relationships']['reverse_field_parent_project_node']['table'] = 'node';
$handler->display->display_options['relationships']['reverse_field_parent_project_node']['field'] = 'reverse_field_parent_project_node';
$handler->display->display_options['relationships']['reverse_field_parent_project_node']['relationship'] = 'reverse_field_project_team_node';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['relationship'] = 'reverse_field_parent_project_node';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Entity Reference */
$handler = $view->new_display('entityreference', 'Entity Reference', 'entityreference_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'entityreference_style';
$handler->display->display_options['style_options']['search_fields'] = array(
  'name' => 'name',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'entityreference_fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;

```

---
Tags: views, entities
---


# Question
Title: Is this the proper way to create a recipe page
Hi I have created a website that need to be able to filter between recipes.

Currently displayed everything I create in content. It is intended that the dishes should be first, and not the recipes.

How is it possible? it is a better system to do this?

# Answer
> 1 votes
Views have a "Sort Criteria".

You can sort by "Content Type" in there, assuming you're only showing 2 content types you should be able to set Ascending or Descending order to get them displaying the way you want.

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


title: Views field: & content: different

text:
# Question
Title: Views field: & content: different
What is the difference between the 2 fields as follows:

Content: Abbreviation This is an alias of Field: Abbreviation.

Field: Abbreviation

And if they are the exactly the same, why is Drupal listing them twice? Check the attached screen shots for more details.

# Answer
> 4 votes
This is something that Views does when a particular field is used in more than one Entity type. In your case, the "Abbreviation" field is used both by node entities (the "Content" views group) and by taxonomy term entities.

It represents the field in both the "Content" and the "Taxonomy Term" group, so that if you were filtering the list by group, you wouldn't be missing it in the list. But it also represents itself canonically in the "Field" group, to correctly inform the user that the field is available in multiple entity type contexts. This would be important knowledge if you had both entity types available in your View because of a relationship.

---
Tags: views, entities
---


# Question
Title: Ubercart thumbnail saving in sites/default/files - Its messy - How would I get it to save in a specified folder?
All of my ubercart thumbnail images are saving in sites/default/files and its getting way too messy. Is there a way I can tell them to save in a folder inside this directory? There is a media style for them and they get the prefix thmb\_ but I cannot figure this out. Thanks

# Answer
> 0 votes
Try the File (Field) Path Module:

> The File (Field) Paths module extends the default functionality of Drupal's core Upload module, the FileField module and many other File Upload modules by adding the ability to use node tokens in destination paths and filenames.
>
> In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

This can be applied to the Field holding the image

---
Tags: ubercart, media
---


# Question
Title: Why does drupal commerce create an empty order for every anonymous user?
Drupal Commmerce is creating an empty order for every single anonymous user in my website (over 13000 in just a few hours).

Users on my website have no direct access to the shopping basket, nor do they have any means of adding products to the cart, since for the moment, I'm only planning to use the Drupal Commerce functionality for specific users (i.e. I will create a product in the backend, then send the URL to the customer).

It doesn't seem right that so many orders are created for users who don't even have the shopping basket block in their page.

Why does this happen?

Is there a way to prevent it?

You can see in the screenshot how the empty-basket orders are being created for every anonymous user, this is slowing down the site!

# Answer
> 3 votes
There's nothing in core Drupal Commerce that would create an empty order for every anonymous session. Core Commerce will only create an order when an anonymous user adds a product to the shopping cart. This means some other module must be creating those orders for every session. I'd look to your contributed modules, especially if any are facilitating adding products to the cart via links instead of forms.

# Answer
> 0 votes
As long the users click on the cart link that is a normal behavior. Why ? The far I'm concern Drupal Commerce assign an unique order id for each user. This can help you to determine when the user leave your site before they did not make the purchase. In addition, if the user leave and comeback this is going to keep the all the order information where they left out last time.

---
Tags: commerce
---


# Question
Title: Is it possible to Insert a view in a content type in drupal 7?
Is it possible to Insert a view in a content type in drupal 7? Is so can you help me do that?

# Answer
The Entity Views Attachment module is the successor of the Views attach let you attach the output a view to the content of any entity.
> 4 votes

# Answer
There is also http://drupal.org/project/viewfield which gives you CCK fields of "view" type. Like, you add a viewfield field to a content type, and for every node of that type you can choose a view and parameters to add to the node.
> 4 votes

# Answer
In addition to Pierre Buyle's answer
Let's say you have a content type named 'Product'

You want to attach a view to it.
Here are the steps using the Entity Views Attachment (eva) module :

On your view edit page :

**Section Displays**
+Add : Eva field

**Section ENTITY CONTENT SETTINGS**
Entity type:Node
Bundles:Product

That's it : Going to a node product type will now display the view

Nota : You can choose where it is displayed among your content type fields here : /admin/structure/types/manage/\[your\_content\_type\]/display
> 3 votes

# Answer
Use PHP input filter for the content and use the following snippet:

> > $view = views\_embed\_view('views\_machine\_name', 'display\_id');
> > print $view;

To get the display\_id, hover the display option in the view, e.g. page, block, default etc. At the bottom of your browser, you'd see a url. display\_id would be of the form: page\_1, block\_1, block\_2, default.

For more control, you may use:

> // This would return an object of view.
>
> $view = views\_get\_view('views\_machine\_name');
>
> //print\_r($view) to get the available data.

You may also have a look at Insert view module.
> -2 votes

---
Tags: views
---


# Question
Title: How to print a block in node.tpl.php only for admin?
What is the simplest code that checks if user is admin and then prints a block to that user in node.tpl.php? I have seen different examples, but they are all either complicated and deal with other problems at the same time or they include editing template.php, which I want to avoid. I have tried with this, but it doesn't work:

```
<?php if ($is_admin->true): ?>
<?php print views_embed_view('myview','block'); ?>
<?php endif; ?>

```

Is there such a simple way to achieve this?

# Answer
> 4 votes
You can do something like this:

```
global $user;
if (in_array('admin', $user->roles)) {  //if not "admin", maybe "administrator"?

}

```

Or you can use the built-in block access control, under your block's configuration you'll see "Visibility Settings" and in there is a way to restrict by user role.

Edit: what the hell, it's friday and I'm bored.

Take this in small steps before you conclude it's "not working".

Step 1)

```
global $user;
if (in_array('admin', $user->roles)) {  //if not "admin", maybe "administrator"?
    echo "<hr>admin user!<hr>";
}

```

If that works, then start making it more complex. This is the best way to learn how to do new things, especially with PHP since you get to see your stuff immediately!

# Answer
> 0 votes
try this:

```
<?php global $user; ?>
<?php if ($user->roles[5]): ?>
<?php print views_embed_view('myview','block'); ?>
<?php endif; ?>

```

just make sure of the role number from **admin/people/permissions/roles** hover the link on your Administrator **edit role** you'll see the number of the role at the end of the link

---
Tags: 7, theming
---