# Question
Title: how do you alter queries for node/# to select entity-referenced node titles instead of just target_id?
I am using Drupal 7 Services and the generic call of `services/node/#`. Unfortunately that only gives me the target\_id as a property of every field with type `entity reference`; and my interface does need the node title at the least.

I have...

```
function  HOOK_query_alter(QueryAlterableInterface $query) {
    if ($query->hasTag('NODE RETRIEVE')) { // WHAT TAG SHOULD I USE?
        // ..TO ONLY ALTER (service)/NODE/# QUERIES?
    }
    $fields =& $query->getFields();
    ... // AND HOW DO I ALTER TO GET REFERENCED FIELD NODE TITLES?
}

```

All said, I do realize I might be able to use node\_load and loop over the results to run subsequent queries for this data, but that seems kind of expensive, unless the resulting hook\_alter\_query would be too complicated. Please say so if you feel that's most likely the case.

# Answer
I believe @Clive was going in this direction here, but I wasn't clear that the Services does in fact invoke `Hook_node_load($nodes, $types)` when using the retrieve methods at `services/node/#`. I suppose I was avoiding the node\_load\_multiple because they are so heavy for only the few fields I want. Code is below

```
function HOOK_node_load($nodes, $types){
    if (in_array('yournodetype', $types)) {
        foreach($nodes as &$node) {
            $f = field_get_items('node', $node, 'field_your_reference_field');
            if (!empty($f) && isset($f[0]['target_id'])) {
                $refNode = _mymodule_reference_load($f[0]['target_id']); // this function simply writes a manual SQL query for my title and iata values.
                $node->field_your_reference_field[LANGUAGE_NONE][0]['title'] = $refNode->title;
                $node->field_your_reference_field[LANGUAGE_NONE][0]['iata'] = $refNode->field_iata[LANGUAGE_NONE][0]['value'];
            }
        }
    }
}

function _mymodule_reference_load($nid){
    $refNode = db_query(sprintf("SELECT N.nid, N.type, N.title, A.field_iata_value, R1.field_readmore1_value, R2.field_readmore2_value
                FROM node N
                LEFT JOIN field_data_field_iata A ON N.nid = A.entity_id
                LEFT JOIN field_data_field_readmore1 R1 ON N.nid = R1.entity_id
                LEFT JOIN field_data_field_readmore2 R2 ON N.nid = R2.entity_id
                AND A.deleted =  '0'
                AND R1.deleted =  '0'
                AND R2.deleted =  '0'
                WHERE N.nid =  '%s'", $nid))->fetchObject();
    $refNode->field_iata = array('und' => array(0 => array('value' => $refNode->field_iata_value))); // maintain same structure as node_load
    $refNode->field_readmore1 = array('und' => array(0 => array('value' => $refNode->field_readmore1_value)));
    $refNode->field_readmore2 = array('und' => array(0 => array('value' => $refNode->field_readmore2_value)));
    unset($refNode->field_iata_value);
    unset($refNode->field_readmore1_value);
    unset($refNode->field_readmore2_value);
    return $refNode;
}

```
> 0 votes

---
Tags: 7, entities, services, database, nodes
---


title: drush rsync among sites

text:
# Question
Title: drush rsync among sites
I have the following alias group set in the setA.aliases.drushrc.php:

```
  $aliases[‘site1'] = array(
      'root' => '/var/www/site1',
      'uri' => '88.88.88.11/site1',
      'remote-host' => '88.88.88.11'
  );

  $aliases[‘site2’] = array(
      'root' => '/var/www/site2',
      'uri' => ‘88.88.88.22/site2',
      'remote-host' => '88.88.88.22'
  );

  $aliases[‘site3’] = array(
      'root' => '/var/www/site3',
      'uri' => ‘88.88.88.33/site3',
      'remote-host' => '88.88.88.33'
  );

```

Now, I have updated @site1, and would like to sync with other sites in setA alias group, can I just use the following command "drush rsync @site1 @setA"?

Or how can I exclude @site1 from destination @setA as it is actually the source?

# Answer
> 0 votes
In Drush 6 and earlier, the rsync command did make some attempt to operate on site alias lists; however, we recently decided that this feature was not useful enough to continue to maintain it, so we removed it from Drush 7. Truthfully, I'm not even sure that it's working right in Drush 6 -- casual tests showed inconsistent results.

Therefore, the best way to do this would be to just call `drush rsync` once for every destination site. You could do this with a simple script.

```
#!bin/bash
for site in $(drush sa @setA --format=csv --fields=name)
do
    if [ "$site" != "site1" ]
    then
        drush --yes rsync @site1 "@$site"
    fi
done

```

---
Tags: drush
---


title: How do i add Meta Tags on panels page?

text:
# Question
Title: How do i add Meta Tags on panels page?
I want to generate meta tags on panels node pages. I am adding Meta tags using nodewords module, it works fine on other node pages except panels generated layout.

Any workaround for this?

# Answer
> 0 votes
There are set of other modules which helps you create meta tags

*Note:* Meta Tag Module supports panels too!!!

---
Tags: 6, panels, meta-tags
---


title: Is there any XML editor for textarea

text:
# Question
Title: Is there any XML editor for textarea
I want to insert XML editor for text area. Is it possible?

Currently Is there any XML data editors. If there is no XML editor for text area what is the possible way .

# Answer
> 1 votes
Try the XML Field module

> Defines an xml field type. Provides an XML widget using CodeMirror (beginning with version 7.x-1.6).Provides XML related API functions for working with XML code. Adds a theme\_xml() theme function. Defines a form type called xmltext for use in the Forms API.

Image from project page

---
Tags: 7
---


# Question
Title: Commerce line item not referenced by the orders
We have a strange situation here where some Commerce Line Items exist in the database, referencing orders through their order\_id property, but that aren't referenced by the order through it's field line\_items (field\_data\_commerce\_line\_items table). Views listing line items show these although when looking at their respective orders they aren't appearing. It is causing wrong calculation of these view.

Is there any explanation as why these line items still exist and can they be deleted safely?

I can display these line using the following SQL request :

```
SELECT * FROM `commerce_line_item` cli
LEFT OUTER JOIN field_data_commerce_line_items fdcli on fdcli.entity_id = cli.order_id AND fdcli.`commerce_line_items_line_item_id` = cli.line_item_id
LEFT JOIN field_revision_commerce_line_items frcli ON frcli.`commerce_line_items_line_item_id` = cli.line_item_id
WHERE fdcli.entity_id IS NULL;

```

\[EDIT\] I changed the the request to reference to revision table. It does happens that some lines are referenced in a revision, but most are not.

# Answer
This typically happens when an administrator adds a line item to an existing order via the order edit form and doesn't submit the form. The line item has already been created, but the order hasn't been updated to reference it. We refer to these as orphaned line items, and they're safe to delete as needed.

I implemented a much better approach with Inline Entity Form, which defers any write action for referenced entities until the form is submitted, but last I tried its line item support wasn't fully functional for the site I was working on. May be better now.
> 1 votes

---
Tags: views, commerce
---


# Question
Title: How can this buying logic be achieved using drupal commerce and/or ubercart?
I think the following scheme describes best what I am trying to achieve:

I am trying to make a ticket booking "shop" if you will.

* There are different events
* For each event you can buy tickets, like the graphic above shows
* There are different ticket types, like normal, vip and special vip (for instance)
* Each ticket type can vary in its price depending on the date
* The visitor should be able book several tickets for that event at once
* Optional: beneath the table is a summary of the selected tickets/ total price
* The visitor can checkout and pay, gets a summary (different story)

**My attempts so far**

On an existing drupal project I installed the commerce module.

I installed commerce booking since it pretty much claims to do what I am looking for. Unfortunately there has been a bug in this module for several months making it unusable, there is no fix there yet (https://www.drupal.org/node/2134449 for instance). What a bummer.

So I installed **drupal commerce kickstarter** and tried around a little bit in here.

I came up with a product type/ variation "Event", two taxonomy vocabs "Ticket Type" and "Date" and added taxonomy reference fields to the event/ product type.
The cool thing is I can now add a new event "Jam session at Alex's" and add many **product variations** in it.
For instance I can add a variation which's price is 1 €, pick a term for a date like "Date 01" and pick a term for the type of ticket like "Ticket Normal". With these fields I can add x numbers of product variations to actually depict the variety of tickets as shown in the graphic. So far so good.

However, I cant manage to create an output like shown in the graphic, how would you do that with views? How could you implement an ajax quantity indicator (it actually should work like the add to cart form, but with AJAX) and adding a payment process right after? Help would be greatly appreciated.

I havent tried to use ubercart yet, would it be far more easy to do it with uc, maybe?

# Answer
> 1 votes
This isn't going to be easy to do with either Drupal Commerce or Ubercart. What you're proposing is a very specific, custom bulk Add to Cart form. You're going to have to code it yourself in a site-specific module. The closest you can get would be Commerce Cart Extras, but you'd still have to reformat it to look like your proposed grid and also to have a live updating order total in the footer.

---
Tags: views, commerce
---


# Question
Title: Display related content in view by entity reference in views drupal 7
I want to show related content title in block view by entity reference. I have created two content type 1)Hotel Type 2)Room Type. Room Type have field\_hotel which references to Hotel Type. How cant I show content title of Room Type in block except current node.

for eg. RoomA, RoomB, RoomC are belongs to HotelX. I want show link of RoomB and RoomC on page RoomA

# Answer
> 1 votes
I think you could use

That way, current node will reference all nodes that reference it - and from this point creating a view is trivial - or **you can simply display the field** created for back reference, *without need for a views module at all*.

**Other way is to use Views**. Create a view displaying nodes from content type A, add argument *content reference field \> provide default argument \> node ID from URL* and display this block view on the nodes from content type B.

---
Tags: entities, views
---


# Question
Title: how to connect to database for form submission
I have website and on its home page there is form in which user enter his own label .As user enters label if the user with same label exists in database it through message that "This Label already exists.Use other Label OR Login". If the user is new it will be directed to other site i.e site "example.com".

The problem is I am getting the same message that "This Label is already exist.Use other Label OR Login" even I enter a new label.

Here is the code for this scenario.

```
function homepage_userlogin_form($form_state){
// drupal_set_title('Add New Person');
$form = array();

$form['name'] = array(
'#title' => '',
'#type' => 'textfield',
'#size' => '30',
'#placeholder' => "enter desired label",
);

$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Start',
"#submit"=>array('form_submit')
);

//$form['#attributes'] = array('id' => 'user-registration001');
return $form;
}

function homepage_userlogin_form_validate($form, &$form_state) {

$name = $form_state['values']['name'];
global $users;
$error=FALSE;

if (empty($name)) {
form_set_error("erorr",t("Please enter your Label."));
$error=TRUE;
}
//if(strlen($name)<6){
// form_set_error("Please Enter atleast 6 character Label.");
// }

if(!$error){

$result = db_select('users', 'u')
->fields('u',array('uid'))
->condition('name', $name,'=')
->execute()->fetchAssoc();

if($result['uid']>0){
form_set_error("erorr1",t("This Label is already exist.Use other Label OR <a
href='user/login?user_label=".$name."'>Login</a>"));
}

else{
global $users;
$user->name=$name;

}
}
}

function homepage_userlogin_form_submit($form, &$form_state) {
drupal_goto("http://example.com");

}

```

# Answer
I think there is problem with the condition in the query. Try changing it

```
$result = db_select('users', 'u')

->fields('u',array('uid'))

->condition('u.name', $name,'=')

->execute()

->fetchField();

```

You better use Webform Module to create a form without any issues!!

> Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.
> 0 votes

# Answer
The title of OP seems misleading. The code is already connecting to the db on form submission. Perhaps revise the title? Unique usernames are default behaviour, so I'm assuming you're trying to do something different here. It's difficult to debug without running the code. This part looks problematic:

```
if($result['uid']>0){

```
1. You don't need to check uid, you just need to see whether the db query returns a result, in which case you could use $result-\>rowCount()
2. What do you get if you echo $result\['uid'\]?

**General comments:**

* You could consolidate your conditional logic. You possibly don't need to test for $error: if(){}else{} statements could be combined, or you could just return FALSE.
* You're calling global $user twice.
* Further down the script, you attempt to set the username in the global array, but that's not going to affect anything permanent, and you're basically saying that if the user exists, set their username to the current username, so I don't see how this changes anything.
> 0 votes

---
Tags: 7, database, javascript
---


title: Implementation of quicktab by codes

text:
# Question
Title: Implementation of quicktab by codes
I am trying to add quick tabs from codes. I got the code from here Creating QuickTabs programmatically not working . But noone explains how to implement this , where to add the code. I am trying to add like this.

**test.module**

```
<?php
    function test_menu(){

    $items['test/quicktabs'] = array(
        'title'=> 'quicktabs',
        'page callback' => 'test_quicktabs',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
      );
    return $items;
    }

    function test_quicktabs(){
    $tabs = array();

    $tabs[] = array(
      'title' => t('Tab1'),
      'type' => 'freetext',
      'text' => 'Hello wecome to Tab1',
    );
    $tabs[] = array(
      'title' => t('Tab2'),
      'type' => 'freetext',
      'text' => 'Hello wecome to Tab2',
    );
    $tabs[] = array(
      'title' => t('Tab3'),
      'type' => 'freetext',
      'text' => 'Hello wecome to Tab3',
    );

    // Configure the QuickTabs options
    $quicktabs_options = array(
       'style'   => 'Bullets',
       'ajax'    => FALSE,
    );

    $quicktabs_name = 'dynamic_quicktabs_menu';
    $quicktabs = quicktabs_build_quicktabs($quicktabs_name, $quicktabs_options, $tabs);
    return $quicktabs;

    }
?>

```

I am not sure , this is a correct approach . How to implement quicktabs inside other modules?

# Answer
> 0 votes
I found the solution, As previously i was not using `'renderer' => 'quicktabs'`, . Also

```
 $tabs[] = array(
          'title' => t('Tab3'),
          'type' => 'freetext',
          'text' => 'Hello wecome to Tab3',
        );

```

was not working. Use this working function.

```
function test_quicktabs(){

    $quicktabs_options = array(
        'style'   => 'Basic',
        'ajax'    => FALSE,
        'renderer'    => 'quicktabs',
    );

    $quicktabs_name = 'newinstance';

    $custom_tabs = array(
        array(
            'title' => 'Tab 1',
            'contents' => 'tab1',
            'weight' => -10
        ),
        array(
            'title' => 'Tab2',
            'contents' => 'tab2',
            'weight' => 0
        ));

   return  quicktabs_build_quicktabs($quicktabs_name, $quicktabs_options, $custom_tabs);

}

```

If anyone find better implementation using quicktabs hooks. Please do answer.

---
Tags: 7, blocks
---


title: solr search in multiple fields

text:
# Question
Title: solr search in multiple fields
Now apachesolr search works only in content. It also have to work on other fields for eg: on typing "test", It searches only in content.

My requirement is to search on description,label also (which i have already indexed). `content:abcd OR description:sample_upload_document` Using  **apachesolr.api.php**,I tried hook\_apachesolr\_query\_prepare($query)

```
function MYMODULE_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {

     $query->addParam('qf','content description');
     watchdog('solr result',print_r($query,true));

}

```

refering to the site`http://knackforge.com/blog/selvam/drupal-7-filtering-solr-results`.
After performing that, i found description is added to

```
SolrBaseQuery Object
    (
        [params:protected] => Array
            (
                 [qf] => Array
                    (
                        [0] => content^40
                        [1] => description
                    )

```

But still when i give the value for description, search results would not yield any value.

Am i correct in a way? why doesnt it return the result?

How to do that? default search,searches the given text only in content.How to make it to search on other fields like description,label?

# Answer
> 1 votes
You could use Search Api Module

> This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine. For site administrators, it is a great alternative to other search solutions, since it already incorporates facetting support and the ability to use the Views module for displaying search results, filters, etc. Also, with the Apache Solr integration, a high-performance search engine is available for this module.

Using It you could create *index* for the field you choose!!

---
Tags: 7, search
---


# Question
Title: Custom panels-pane tpl based on some identifier
Is it possible to create a pane template based on some kind of identifier? Just Like you can create a page--node--123.tpl.php file to render a different page for a node with nid 123, i'd like to make a panels-pane--pid--123.tpl.php to render a specific pane with pid 123 I have tried looking on google but i have found nothing about this possibility.

# Answer
> 1 votes
After a lot of working around & trial & error methods, I got this.

1. Copy your "**panels-pane.tpl.php**" in your current theme's template directory.
2. include dpm($pane); in a php tag. This will give u the list of all the panes on ur current panel page.
3. Note down the **pid** ($pane-\>pid) here.

* If you are looking for a particular page the unqiue identifier for that whole page would be **did** ($pane-\>did) which is the display id.
    * Basically, every panel page has a unique **did** (display id) & different **pid** (pane Id) for all the panes on that particular page.
4. Now in your "**panels-pane.tpl.php**" in the div code block with class="pane-content" you could write a php code like

```
if($pane->pid=='some id' & $pane->did=='some id') {
//modify your pane data from the variables at $pane->configuration & store in $content.
   $content = your modified data;
   print render($content); // render this pane with my modified data
else
print render($content); // (and) render other panes as normal
}

```

# Answer
> 0 votes
when you use the dpm($pane), you can also use the $pane-\>type variable to get the value of pane type & use this to create a separate template file that affects all the panes of this type only.

for example: In my scenario, i had added custom-content on pane. (Pane \> Add content \> Add custom content) So i had a few of such content-panes, which i wanted to be wrapped around in different html divs for structuring.

In my case, on dpm($pane) this $pane-\>type value was "custom". (This could be view, block, etc, as per the pane data) So I created "panels-pane--custom.tpl.php". This will affect all the panes of this (custom) type. Further, as my above answer, for a given panel node, I know my page's display id ($pane-\>did).

So use an if condition on this display-id & further you can use if / else-if / switch on $pane-\>pid for altering a particular pane.

```
    if($pane->did=='some-id') {
       switch($pane->pid) {
       case 'pid1' : some code stored into $content & then - print render($content); break;
       case 'pid2' : some code stored into $content & then - print render($content); break;
       default     : print render($content);
      }
    }

```

---
Tags: theming, panels
---


# Question
Title: How to safely remove drush via pear and then install via composer?
I have drush 5 installed on my VPS running CentOS 6. Drush was installed using PEAR. Can I just remove the drush directory and the simlinks and then install drush 7 using composer?

I have been searching for a way to uninstall drush, but all I get are tutorials to install it.

# Answer
> 3 votes
Drush doesn't really have any components that need to be "uninstalled". If the drush binary is somewhere on your PATH, then it's installed. If you just go ahead and install Drush 7 via composer, and insure that the newer Drush appears first in your PATH, then you can even leave Drush 5 on your system with no ill effects. You might even want to make a 'drush5' alias as a fallback, in case -- although personally, I run Drush 6 and Drush 7 on my system. I use Drush 7 for most things.

# Answer
> 5 votes
**Uninstalling Drush using Pear**

If Drush has been installed using Pear, it can be removed using the following command.

```
pear uninstall drush/drush

```

**Installing Drush via Composer**

For the most current install instructions, refer to the Drush GitHub page.

1) Add Composer's global bin directory to the system PATH (recommended):

```
sed -i '1i export PATH="$HOME/.composer/vendor/bin:$PATH"' $HOME/.bashrc
source $HOME/.bashrc

```

2) Install Drush

```
composer global require drush/drush

```

---
Tags: drush, composer
---


title: leaflet get direction

text:
# Question
Title: leaflet get direction
Hi is it possible to make/install "a get direction button" which will use the \[widget - Geocode from another field\] and then show the route?

# Answer
> 1 votes
Maybe this link helps you: http://drupalminion.blogspot.com.au/2013/05/how-to-add-driving-directions-link-to.html

I am looking for the same answer

---
Tags: javascript
---


# Question
Title: How to specify the latest album in a images view?
I am using node galleries. I've created a view where I display all the images that are of type "gallery\_image". The problem is, I need to now get it to only show me the values for a specific album, where the specific album is whatever is the most recently created album.

So in this image:

First prize would've been if I could say:

```
operator : is equal to : value

```

And make the value something like \[\[LATEST\_ALBUM\]\] and have that somehow magically figure it out. It would be easy to do if I could add PHP there.

Any ideas how to get around this?

# Answer
I just ended up using "arguments" with a default PHP argument if one is not specified. The PHP code:

```
$res = db_query("select nid from node where type  = 'node_gallery_gallery' order by nid desc limit 1");
$res = db_fetch_object($res);
return $res->nid;

```

Works beautifully. Only side effect being that anyone that can access this view, can view other galleries using a parameters. But in my case that's not a problem.
> 0 votes

---
Tags: 6, media
---


title: remove divs and spans from view output

text:
# Question
Title: remove divs and spans from view output
In my `page.tpl.php` I'm doing this to display one of my view:

```
print views_embed_view('teaserview', 'default');

```

That gives me the following html output:

```
<span thmr="thmr_10">
<div class="view view-teaserview view-id-teaserview view-display-id-default view-dom-id-e051ba535ce9aac6cd9a0d564b3dbb29 contextual-links-region">
    <div class="contextual-links-wrapper">
        <span thmr="thmr_16">
        <ul class="contextual-links">
            <li class="views-ui-edit first last"><span thmr="thmr_17"><a href="/kbi/admin/structure/views/view/teaserview/edit/default?destination=node/3">Edit view</a></span></li>
        </ul>
        </span>
    </div>
    <div class="view-content">
        <span thmr="thmr_15">
        <div class="views-row views-row-1 views-row-odd views-row-first views-row-last">
            <span thmr="thmr_14">
            <span thmr="thmr_11"><span thmr="thmr_12"><span thmr="thmr_13"><img src="http://127.0.0.1/kbi/sites/default/files/teaser_2.jpg" width="1029" height="308" alt="" /></span></span></span></span>
        </div>
        </span>
    </div>
</div>
</span>

```

But the only thing that I really need is

```
<img src="http://127.0.0.1/kbi/sites/default/files/teaser_2.jpg" width="1029" height="308" alt="" />

```

Is there a possibility to modify the views\_embed\_view call so that I get only the needed data?

There would be the possibility to modify all the views `.tpl.php` files but I hope there's an easier way to do this.

I also read about the semantic views module but I didn't understand how to configure my view with it so that i get only the needed markup as output. it didn't seem to have any effect.

# Answer
i think i have it running ok now, you tell me if this is the most elegant way ;)

i copied the views-view--\[ViewName\].tpl.php to my theme folder and made the following changes:

```
<div class="<?php print $classes; ?>">     // delete this line
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
[...]
<?php if ($header): ?>
    <div class="view-header">   // delete this line
      <?php print $header; ?>
    </div>                      // delete this line
  <?php endif; ?>
[...]
<?php if ($rows): ?>
    <div class="view-content">  // delete this line
      <?php print $rows; ?>
    </div>                      // delete this line
  <?php elseif ($empty): ?>

```

and then i made some adjustments in the view editor (i installed the semantic views module):

**Format**: Semantic Views

**Show**: Semantiv Views: Fields

**then in the field settings:**

**multiple field settings**

\[x\] display all values in the same row

\[x\] simple seperator (and then just empty the seperator text field so that no seperator is inserted in the output)

**rewrite results:**

\[x\] strip HTML tags

\[x\] remove whitespace

Preserve certain tags: (in my case i'm displaying image fields, so depending on the content of your fields this may differ)

-\> this gives me a clean

```
<img src="http://127.0.0.1/kbi/sites/default/files/teaser_2.jpg" width="1029" height="308" alt="" />

```

at the end.
> 1 votes

# Answer
If you go into the view thru the Views UI, and look at the fields, you can configure/remove the wrapper html from the field by selecting none for the wrapper of the field, and that should take a lot, if not all, of the html away that you don't want. Also, if you go into the views admin screen and go to tools, you can check the "Do not show hover links over views" which should remove the first edit portion of all of your views when looked at via an admin type account as well.

If the above doesn't take away all the html you want, you can either modify the templates as you mentioned above, or use something like this instead of views\_embed\_view:

```
$view = views_get_view('teaserview');
$display_id = 'default';
$view->set_display($display_id);
$view->execute();

```

which will execute but not display the view ... but will create a $view-\>result which is an array of row objects basically, so you could then go in there and print out whatever you wanted.

To find out what is in there, throw in a

```
drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>');

```

and you'll see what you can work with.

PS Once you have this working, I would put it in a preprocess hook and assign this output to a variable instead of putting any/all of this code in your page.tpl, too...

PPS I also am assuming you know that the Theme Developer module is throwing a lot of html in there as well (all those thmr='s as such).
> 2 votes

# Answer
You should try the Fences module, an alternative to *Semantic Views*

> Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.
> 1 votes

# Answer
You can do it by changing the views Style settings for that particular field name . Check on the "Customize Field HTML" and select 'None' from the select options.
> 0 votes

---
Tags: 7, views, theming, entities, media
---


title: File (Field) Paths serial token

text:
# Question
Title: File (Field) Paths serial token
I have an image field type configured to accept an unlimited number of values.

Using the File (Field) Paths module I have set the file name field value to `[node:title].[file:ffp-extension-original]`

This is fine if you upload one image because it is renamed to my\_node\_title.jpg for example.

If you upload several images, they are renamed to my\_node\_title.jpg, my\_node\_title\_0.jpg, my\_node\_title\_1.jpg, my\_node\_title\_2.jpg and so on.

Is there a token I could use or create that would allow me to add a serial value rather than the default \_0, \_1, \_2? For example my\_node\_title\_a.jpg, my\_node\_title\_b.jpg, my\_node\_title\_c.jpg etc.

I'm looking at the Custom Tokens module at the moment but not having much success.

# Answer
The problem is it starts from 0, isn't it?

If you use that for your path: `[node:title]_a.[file:ffp-extension-original]`

* my\_node\_title\_a0.jpg
* my\_node\_title\_a1.jpg
* my\_node\_title\_a2.jpg

**OR**

You can use the `[file:original:fid]` pattern, it gives serial values but the `fid` increments for all the nodes, not for each nodes. I mean, if you upload 10 images to your first node and then for your second node if you upload 3 images, second node's images' names are as below:

* my\_node\_title\_a11.jpg
* my\_node\_title\_a12.jpg
* my\_node\_title\_a13.jpg
> 1 votes

---
Tags: 7, tokens, media
---


title: Domain access on views

text:
# Question
Title: Domain access on views
I am using domain\_access module for multisite. I have two different domains (www.example.com, www.example1.com). If i created a view it will be displayed in both the sites. Now i need to create a view only for the particular domain (www.example.com), It should not be displayed in another domain (www.example1.com). There is any solution in drupal?

# Answer
Domain views module

> Part of the Domain Access suite.
>
> Provides Views integration for Domain Access.
> 0 votes

---
Tags: views, domain-access
---


# Question
Title: How can I redirect users on login with PHP?
I'm trying to redirect users with certain roles to different pages on login. Sample code is below:

```
function MYMODULE_user_login(&$edit, $account) {
  // Allow users to reset their passwords
  if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {
    // Admin
    if (in_array('administrator', $account->roles)) {
      $redirect = 'admin/hud';
    }
    $edit['redirect'] = $redirect;
    dpm($edit);
    dpm($redirect);
  }
}

```

This is based on drupal.org login hook documentation about "How to redirect users after login in drupal?" and the answer to "Custom redirect on custom page for admin user".

The problem is that when I actually log in with a user having the given role, I am redirected to `/user`, not my custom path. The results for `dpm()` for `$redirect` and `$edit->redirect` show the path specified in my code, so why am I not getting redirected there?

I had this working in Rules, where there is a *Force redirect* checkbox. But I am trying to move the code out of rules because it relies on a lot of custom PHP to check various conditions.

# Answer
> 0 votes
In the end, after checking a number of sites and reading the documentation several times, this is the code that worked for me.

```
if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {

// Stop the login block from redirecting back to the page the user logged in from.
unset($_GET['destination']);

// Admin
if (in_array('administrator', $account->roles)) {
  $redirect = 'admin/hud';
}
$edit['redirect'] = $redirect;

```

# Answer
> 1 votes
`$edit['redirect'] = $redirect;` doesn't stop other operations being executed I think.. The only thing I can think is to stop them with `drupal_goto`, but you should check you won't break anything else or not:

```
function MYMODULE_user_login(&$edit, $account) {
  // Allow users to reset their passwords
  if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {
    // Under 18
    if (in_array('administrator', $account->roles)) {
      $redirect = 'admin/hud';
    }

    drupal_goto($redirect);
  }
}

```

# Answer
> 0 votes
There are too many ways to redirect users after login on different pages with their specific roles.I think you should use the rules module to achieve this. There are several ways mentioned on the d.org Because using the custom code might not break something.

# Answer
> 0 votes
Drupal always redirects to the user page (by default) ,so you can do this. Customize User Page using Panels and the Page modules by adding a custom php block where you place a drupal\_goto(). Then create your custom user page. You can create a switcher using GET arguments in order to redirect especifically where you want. Using access rules (within panels module on custom user variation) you can specify wich role or condition will be needed to perform the custom redirect.

There are many ways to do this either by site-building with core modules or a number of different contributed modules, or by building a custom module implementing the Drupal API. Be warned, the login block sometimes behaves differently than the login page. Also, make sure you test the password reset path which can be affected.

You can use this hook to redirect users to a different page on login, but you will have to make sure the password reset functionality is not impaired. Check this comment. Or look at the node number 683696 at drupal.org. There are modules like: login\_redirect Check how these modules work and make your own way out.

Thank You

---
Tags: 7, users, redirection
---


# Question
Title: EntityFieldQuery - ordering by multiplication of two fields
I need to order my news by their importance value (1, 2 or 3) which is in the field field\_importance and the date they are published. So I would need to order my news by this calculation: created * field\_importance and I haven't figured out a way to do it with EntityFieldQuery. If someone knows a way to do it without EntityFieldQuery, that's equally good. This is my code so far:

```
$query->entityCondition('entity_type', 'node')
      ->propertyCondition('status', 1)
      ->propertyCondition('type', array('news'))
      ->propertyOrderBy('created', 'DESC');

```

# Answer
If you don't have to pull in a whole bunch of linked entity stuff, just run a regular db\_query() joining your "importance" field table to your node table.

`$query = "SELECT nid, (created * field_importance_value) AS weight
FROM node n
JOIN field_data_field_importance f ON f.entity_id = n.nid
WHERE type = 'news'
AND status = 1
ORDER BY weight DESC";
$result = db_query($query);
// Add foreach loop here...`

I'm just guessing the importance table name and field name from your OP.
> 1 votes

---
Tags: 7, database, entities
---


# Question
Title: Service to browse all contrib modules on drupal.org
http://simplytest.me/ allows you to search all existing modules. I'm trying to implement a widget with the same functionality, but I'm stuck on how to browse all the projects on drupal.org... Can someone point me in the right direction? I found the module "project\_browser", but can't seem to figure out how they accomplish it...

# Answer
> 3 votes
This excellent script written by rocketeerbkw will create a text file containing the name of every d.o contrib module, giving you everything you need to get started:

```
/**
 * Download a full list of all modules on drupal.org by using the API. More info
 * at https://www.drupal.org/about-drupalorg/api.
 */
$url = 'https://www.drupal.org/api-d7/node.json?type=project_module';
$modules = array();
do {
  print $url . PHP_EOL;
  $options = array(
    'http' => array(
      'user_agent' => 'get_list_of_modules.php from https://github.com/rocketeerbkw/drupal_function_stats',
      'header' => 'Accept: application/json',
    ),
  );
  $context = stream_context_create($options);
  $response = file_get_contents($url, false, $context);
  $data = json_decode($response);
  foreach ($data->list as $module) {
    $modules[] = $module->field_project_machine_name;
  }
  $url = isset($data->next) ? $data->next : FALSE;
  // The next links are always provided without a format [#2253947].
  // Formatless URLs are 301 redirected to format URLs but strip all query
  // query parameters [#2364755].
  $url = str_replace('node?', 'node.json?', $url);
} while ($url);
$file = fopen('project_usage.txt', 'w');
fwrite($file, implode("\n", $modules));
fclose($file);

```

An example output is here:

https://raw.githubusercontent.com/rocketeerbkw/drupal\_function\_stats/master/project\_usage.txt

Once you've got that data the only tasks are deciding where/how to store it, and creating the UI to manage it.

# Answer
> 0 votes
You are looking for Project Browser Server module. Please read the documentation.

> This module provides an API as well as endpoints so that you can serve search results to the Module / Theme Browser module.

---
Tags: 7
---


# Question
Title: How to determine the modules enabled on a third party website?
When I don't have the admin access to a site, how can I find out the modules that are enabled on the site.

For example : How can I identify various modules enabled on www.drupal.org

# Answer
There are various you can find this out. But none of them are foolproof and they are just dirty tricks at best.

You can check source(view source) of the website and do the following.

1. Check the css includes in the head tag and figure out the modules from path.
2. Check the javascript includes in the head tag and figure out the modules from the path.
3. Check the classes of html tags from the body tag.
4. Do the above for multiple standard pages and you should be able to make a list of at-least 50% of the websites based on your knowledge of the modules.

But the easiest of them all is using the http://www.drupalxray.com/ website. Looks like they have automated many rules like the above and search enough paths to prepare a pretty exhaustive list of modules used on a website.
> 3 votes

---
Tags: 7
---


title: Add field linking to related node

text:
# Question
Title: Add field linking to related node
I have created a `Content Type` that allow to download PDF files. Meanwhile I want to have this file available in a `html` version; as in Modules' notes in Drupal's website.

So the easiest way is to: create this html version as a new node, and use `node reference` field type to link to this node. But this process takes two steps to do it, and within large nodes it will take while to find the referenced node.

So what is the more sufficient way to add a related node to a content type?

# Answer
> 0 votes
You can do this in two ways.

Option 1: Add a textarea field to the file content type, with the necessary text options (fe html on etc), and create two various displays via Display Suite. Create a view block with the nid as contextual filter. And select the node display for showing.

Option 2: Install the prepopulate module and setup a rule that after saving the html content type node redirects to file content type with the right url + prepopulate information. Have 2 separate content types. In the file content type add a reference field with prepopulate settings.

Now after you create the node with html information it redirects to the file content form with the reference field filled... So no searching and no hassle.

---
Tags: nodes
---


# Question
Title: How to hide title of any content type without using a module?
I want to hide the title field of a particular content type (such as *Article*), but without using any modules.

How can I do this?

# Answer
You could do it in `template.php` in your theme dir, technically not a module.

e.g:

```
/**
 * Implements hook_preprocess_node
 */
function MYTHEME_preprocess_node(&$variables){
  if ($variables['node']->type == 'article') {
    $variables['title'] = FALSE;
  }
}

```

Replace "MYTHEME" with your theme name and clear all caches at `Admin > Config > Performance` to apply.
> 4 votes

# Answer
David is right, but if you want to use the $title elsewhere in the page you can use this approach.

Step 1. Create a show/hide title variable using hook\_preprocess\_page() in your custom module (or theme template.php, if you dont want to use a module):

```
function MYMODULE_preprocess_page(&$vars) {
  $vars['show_title'] = TRUE; // so that showtitle is true by default
  if (isset($vars['node'])) {
    if ($vars['node']->type == 'event') { // set to false when the content type is event
      $vars['show_title'] = FALSE;
    }
  }
}

```

Where 'event' is the content type you want to hide the title for.

Step 2. Exclude the title in page.tpl.php by adding the show/hide title condition:

```
<?php if ($title && $show_title): ?>
  <h1><?php print $title; ?></h1>
<?php endif; ?>

```

Clear the caches
> 4 votes

# Answer
`node.tpl.php`: Check for `$type` before printing the `$title` e.g. line #87 change to something like
if (!$page && $type != "your\_type" ):
> -1 votes

---
Tags: theming
---


title: PHP - MENU_LOCAL_TASK in Drupal

text:
# Question
Title: PHP - MENU_LOCAL_TASK in Drupal
How do I add #markup or #suffix to MENU\_LOCAL\_TASK in Drupal?

```
$items['user/%/checkins_history'] = array( //add to to user's profile
            'type' => MENU_LOCAL_TASK,
            'title' => t('Checkins History'),
            'suffix' => '<div>Num'.$num_of_results .'</div>', // NOT WORKING
            'access arguments' => array('Administer Checkins'),
            'page arguments' => array(1),
            'file' => 'manager.inc',
            'page callback' => 'manager_checkins_history_page'
        );

```

# Answer
> 2 votes
What you're asking doesn't really make sense.

`MENU_LOCAL_TASK` is used as metadata for a route defined in `hook_menu()`.

`#prefix` and `#suffix` are properties for render arrays.

The two concepts are not compatible.

# Answer
> 1 votes
Your calling this from hook\_menu, correct? I don't believe that suffix can be used from here. At least it's not in the list of valid return values in listed on the hook\_menu page.

You'll need to add the suffix to whatever the output of your url is, if it's a form, it can nicely be added to the form via the form api.

Example:

Let's say your function `manager_checkins_history_page` is a form that uses the form aip, and looks something like this:

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

  $form['switch'] = array(
    '#type' => 'checkbox',
    '#title' => t('i'm a chekcbox'),
    '#default_value' => false,
  );

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

  return $form;
}

```

if you wanted to apply a suffix to the whole form, you could do something like:

```
function manager_checkins_history_page($form, &$form_state){
  $form['group1'] = array(
    '#type' => 'fieldset',
    '#title' => t('Your Name'),
    '#suffix' => "I'm a suffix for your form",
   );

  $form['group1']['switch'] = array(
    '#type' => 'checkbox',
    '#title' => t('i'm a chekcbox'),
    '#default_value' => false,
  );

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

  return $form;
}

```

That would give you a form, wrapped in a box, with a suffix at the end.

---
Tags: routes
---


# Question
Title: Migration issue: Drupal markup isn't rendered on CiviCRM pages
I've moved a Drupal 6 / CiviCRM 4.3 site to a development server, and I'm getting really strange behavior. When I visit a Drupal page on the copied site, everything renders as expected. However, when I visit a CiviCRM page, the CMS part of the markup is missing from the source. It's almost like every CiviCRM page is being delivered as a snippet.

To be more specific, when I go to /civicrm and view source, I get markup beginning with:

```
<div id="crm-container" class="crm-container" lang="en" xml:lang="en">

<div id="menu-container" style="display:none;">
  <ul id="civicrm-menu">
  ...

```

The opening and closing HTML tags, and all the HTML contained in the Drupal theme are entirely absent. The same appears to be true for every CiviCRM page.

I've tried the following:

* reviewing my CiviCRM settings file
* reviewing my directory and resource settings
* clearing Drupal caches
* emptying sites/default/civicrm/templates\_c
* deleting sites/default/civicrm/ConfigAndLog/Config.IDS.ini
* running `drush civicrm-update-cfg`
* checking error logs for Apache, Drupal, and CiviCRM
* throwing salt over my left shoulder

Any ideas what might cause such strange behavior? Suggestions for something I might have missed in my migration or a good place to put debugging code to get to the bottom of this?

# Answer
> 12 votes
Ah, I think I've seen this before, did you by chance mess with your CiviCRM settings file?

Double-check your `CIVICRM_UF` setting, Civi might be tripping up if it thinks the CMS is something other than what it actually is.

For Drupal 6 you want `CIVICRM_UF = 'Drupal6'`

---
Tags: civicrm
---


title: hour - based context

text:
# Question
Title: hour - based context
I would like to add body classes by context depending on the time of the day. One class for the morning, another for the midday, another for evening. I expected the context date module to do thatm, but it does not work when I do not put the date in (i.e. it accepts the condition, but there's a bug and the whole condition disappears afterwards). Any ideas?

# Answer
If you are adding classes which will be styled by your theme then it is best to add them with the theme in template.php. Each theme might handle this differently.

For example, if your theme is based on Fusion then you can add new classes by implementing hook\_core\_preprocess\_html()

```
<?php
function mytheme_core_preprocess_html(&$vars) {
    $vars['classes_array'][] = mytheme_hour_based_class();
}

function mytheme_hour_based_class() {
    // Return a CSS class based on the current 24 hour time
    return 'hour-of-day-'. date('H');
}
?>

```

If there isn't an existing context module which serves your purpose then you would have to create your own module which implements the context API. You can learn about the context API here.

http://drupalcontrib.org/api/drupal/contributions!context!context.api.php/7

Telling you how to do that would essentially require writing the module for you, which seems outside the scope of an answer.
> 0 votes

---
Tags: 7
---


title: Remove website field from comment forms

text:
# Question
Title: Remove website field from comment forms
I made it mandatory for anonymous users to leave contact information while commenting along with comment notify so as to improve the user engagement. There are two problems that crept in because of this:

1. A homepage field also got added with the email field. I want to remove only the homepage field, leaving the email field in place. I could not figure out how to do this.
2. People comment with fake email addresses.

Can anybody tell me a workaround for these problems?

# Answer
If you wish to allow anonymous comments but remove the Homepage field, you can do so in either a custom module or theme function that implements `hook_form_FORM_alter()`.

Via a theme function (source, mengi on drupal.org):

```
function THEME_form_comment_form_alter(&$form) {
  $form['author']['homepage']['#access'] = FALSE;
}

```

Or via a custom module:

```
function MYMODULE_form_comment_form_alter(&$form) {
  $form['author']['homepage']['#access'] = FALSE;
}

```

*Note: Anonymous comments may be reasonable if you use other anti-spam measures such as honeypot fields and javascript-filled anti-spam fields.*
> 8 votes

# Answer
You can change which fields appear on the comment for at:

```
/admin/structure/types/manage/YOUR_CONTENT_TYPE/comment/fields

```

The easiest way to cut out fake email addresses would be to get users to register before they are allowed to comment and have check the *Require e-mail verification when a visitor creates an account.* option.
> 1 votes

---
Tags: 7, comments
---


title: Resume State - Recruiter Distribution

text:
# Question
Title: Resume State - Recruiter Distribution
I have been using the recruiter distribution for a while and for some reason I remove the ability of the resume state. I have analyze the problem and the issue is that every time someone register to the website their resume is automatic on visible state. And I need to make sure that the resume remain hidden until the user at least provide their contact information. This is a critical bug on the site because on the resume search show a lot incomplete users.

Anyone can help me to figure out how to enable the resume state functionality ? Or how to troubleshoot this problem. FYI... I updated the recruiter\_features module and nothing happen.

I have post this issue on many places and I have not get any response.

https://www.drupal.org/node/2304539
https://www.drupal.org/node/2311329

Any help will be appreciated.

Views

# Answer
Reinstating and uninstalling the module again fix this issue for me.
> 0 votes

---
Tags: views, debugging, distributions
---


# Question
Title: Having each child record inherit (display) data elements from a parent record
I'm new to Drupal and have been watching lots of videos on entity relationships but am a bit lost still....trying to wrap my head around the differences between nodes, entities, etc. and how to define relationships.

What I would like to do is have 2 pieces of content - Company and Program.

The company information will be filled in by an administrator of the site (company name, address, phone, website, etc) -- these values are only editable by the administrator but can be read by any authenticated user.

Then any authenticated user can create a Program which will have its own set of fields (program name, date, program director, etc.)

Each Program is considered a child of Company and so the Program would also have read only fields that present the company info.

Can someone please point me in the right direction of how to link the Company directly to the Program. I have seen ways of adding a select list field that would allow the user to select a Company from a list of companies...but I want this to default to the same company each time.

Thank you for any ideas/help.

E

# Answer
> 0 votes
There are several modules to use in conjunction.

Firstly, you need Entity Reference and its dependency, Entity API https://www.drupal.org/project/entity https://www.drupal.org/project/entityreference

Install those two modules the normal way.

Others have written add on modules for entity reference such as Entity Reference Prepopulate: http://drupal.org/project/entityreference\_prepopulate That module can be helpful for prepopulating values for the entity reference fields you create.

So after you've installed the modules you can go to the Manage Fields page for you Program content type, and add a new Entity Reference field.

Might call this field "Company"

Click Save

On the field settings page, Select the Target type (entity type) as "Node" For the Target bundles (content types in the case of node) select your Program content type Optionally you can chose to sort the options for the entity reference field by a property of the node such as title.

Click Save

On the next screen you can set the default Company for the Reference field, or you can configure add modules such as Entity Reference Prepopulate to configure defaults based on context.

Click Save

Now you can edit or create Program nodes and reference a company node from them.

For this example I had created a Company node called "A Company"

---
Tags: views
---


# Question
Title: Sometimes shipping and/or billing address is missing
Unfortunately I have to ask a pretty vague question, and I can't provide much background because I can't reproduce.

Working on a Drupal 7 Commerce install with Domain Access we are (seemingly) randomly missing shipping and/or billing information on orders. Sometimes the order has a billing name (or shipping name) but no address information. Others, either shipping or billing is completely missing from the order view.

This is happening on ~1% of orders and I can't find any way to link them with consistency. It has happened on PayPal Express Checkout orders, Authorize.net orders, orders with different shipping methods, orders from different domains, etc. The stored API responses from the payment processors are normal.

In testing (on production), I can't reproduce; I've tried both payment methods, anonymous accounts, existing accounts, etc. I can't even get past the Billing/Shipping form without completing all the information, no matter what I've tried.

Hopefully someone has experienced this before; if not, I'm totally open for "try this" or "look here" suggestions.

Thanks

# Answer
I've had similar problems before, never did get to the bottom of it. I think it's related to the Commerce Addressbook module and the way it copies profiles but time ran out before I could confirm.

As a rather hacky (but effective) workaround I used the following to make sure the profile had been copied:

```
function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  $form['buttons']['continue']['#submit'][] = 'MYMODULE_commerce_checkout_form_submit';
}

function MYMODULE_commerce_checkout_form_submit($form, &$form_state) {
  // If the copy address checkbox is selected.
  if ($form_state['values']['customer_profile_shipping']['commerce_customer_profile_copy']) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $form_state['order']);
    $shipping_address = $order_wrapper->commerce_customer_shipping->commerce_customer_address->raw();
    $billing_address = $order_wrapper->commerce_customer_billing->commerce_customer_address->raw();

    // If the shipping and billing address aren't the same then we need to fix it.
    if ($shipping_address != $billing_address) {
      $order_wrapper->commerce_customer_shipping->commerce_customer_address = $billing_address;
      $order_wrapper->commerce_customer_shipping->save();
    }
  }
}

```

It may or may not work as-is, but even if not it might provide a starting point for debugging.
> 3 votes

---
Tags: 7, commerce
---


# Question
Title: How do I update a Drupal distribution to a newer version?
I am looking at using http://drupal.org/project/commons , but I am not sure how easy it is to update a distribution when a new version comes out.

Also, can I use drush to do it, or do I have to manually download and unpack the distribution?

# Answer
> 1 votes
I've always done it the same way as updating Drupal. Download, delete all the old files/folders, and upload the new. Some distributions (Commerce Kickstart) moves everything inside the distribution so you can't just go deleting willy nilly on some. Not sure about Commons but you can check and make sure you're not deleting anything needed. Some distribution maintainers are nice and also provide patches to update only what is necessary.

# Answer
> 3 votes
With drush for commons 7.x you can do:

```
drush up drupal -y
drush dl commons -y
drush updatedb -y

```

---
Tags: drush, 7, distributions
---


# Question
Title: Adding a second search for a specific content type
I am currently trying to build out a Video-oriented component on a longform article based site, and one of the requirements call for a Video segment/block that can be placed on any page, and it has a search bar that loads any videos with similar titles.

I know that Drupal includes search, and it can be granulated to a specific content type. But I was wondering if there was any way I could implement a separate search function that inherits the existing search logic, and search for content of this specific content type. Is it as simple as altering the logic inside the search form with hook\_form\_alter, or are there more intricacies involved?

# Answer
> 0 votes
Maybe if I was in your case I will think about views and if the website is that heavy I will create apachesolr view so I keep it simple flexible.

---
Tags: 7, search
---


# Question
Title: How to grant access to a user to all content created by certain users?
I've been looking all the options commented on Controlling Acces to Content Overview but I don't see any that allow one particular user to access all content created by other particular users.

Something like: **User A have permissions to see all nodes created by users B, C and D**. (No need to include a reference or a taxonomy term to each node).

Any insights?

Thank you so much!

# Answer
Sorry telling you that as far as I know there is nothing like this out of box. Maybe if you mention the requirement we will be able to help you. For now don't think about users and think about roles. if you want to make it more flexible I suggest using workbench access so the created content will have a section (Taxonomy term) and the section will be accesed by user A and B only. Hope that help
> 0 votes

---
Tags: users
---


# Question
Title: Multiple choice question creation change checkbox to radio
Using quiz module, I am creating Multiple Choice question. In that there is a check box to select the correct answer. Check box enables users to select multiple answers for a single question, but I want the users to select only one answer for a question. Is there any configuration to change that or can I change the check box to radio button. If so how can I change it to radio button? Should I change it in code base or is there any module available?

# Answer
If I'm not mistaken, as long as you don't check the "Multiple Answers" option in the answer settings tab, your answers for that question will render with radio buttons on the front-end. This doesn't change the checkboxes to radio buttons when you are editing a question, but that's because you are supposed to be able to mark multiple correct answers for each question, if need be.
> 0 votes

---
Tags: 7, quiz
---


title: Per node field access for paid members?

text:
# Question
Title: Per node field access for paid members?
I am setting up a site for a web series. I would like to setup the site so that members can only stream an episode if they have already paid for it. We are using Vimeo PRO to serve our videos, and are using Video Embed Field to display the videos on the site.

If the member has not paid to stream this video, I would like to display a field other than the one with the embed code -- likely a field containing either a banner or a trailer for the show.

I found a video that somewhat outlines how to do this on a node-by-node basis, but I need to restrict access to just a field within the node, and not the entire node.

Is there an optimal way to set up this workflow?

# Answer
> 1 votes
I ended up doing node-based permissions instead of field-based. To set it up, I followed the instruction in the video I linked to originally. I simply created content types for SD and HD streams, and am granting access by user to those. I'm probably going to create a view that will go on my original node that displays if the user has the correct permissions.

# Answer
> 0 votes
I'm sure there are other ways to do this but one way to tackle it would be in the theme layer. You could create a custom template for this particular content type, and within the template you could hide the full video field or the teaser video field as needed. For example, in **node--video.tpl.php** if your content type was named **video**, you could set up an if/then to check whether the user has permission to view the video (if you have a permission that works here, in a custom module for example):

```
if (user_access('view member videos')) {
  hide($content['field_video_teaser']);
} else {
  hide($content['field_video']);
}

```

If you don't have a special permission to check you could check the role, although it is usually preferred to use permissions rather than roles to be more flexible. That would look like this:

```
global $user;
if (in_array('member', $user->roles) {
  hide($content['field_video_teaser']);
} else {
  hide($content['field_video']);
}

```

---
Tags: commerce, ubercart, users, files
---


# Question
Title: How to attach a database of data to a content / entity type
I have an sqlite database representing a collection of Foo which is immutable. I would like to be able to take this collection of Foo in the GUI of Drupal, and append a few fields onto each Foo instance, these new fields are to be editable.

I see no point to inserting the data as nodes / entities directly as the data is only going to reflect what's already in the database and inserting data using node\_save is incredibly slow for duplicating the data.

How would I accomplish this so that a content-type / entity type uses data from another database, but manages a few additional editable fields?

Would it be a custom content type with a module to manage the pulling of the data from another database, or would it be a custom entity?

# Answer
I would use a custom content type that stores the primary key (pk) of an instance of Foo as text, integer or whatever you need, just that one field. Let's call the content type Bar.

Then for display create a node template for Bar that:

1. Queries your database by sending Bar-\>pk and returns the Foo row/object
2. Iterates through the fields in the row and displays them where and how you choose

In case you haven't already come across it, if you're intending to use an external database, it is best to define it in your settings file and call it when you need it as described here.
> 0 votes

---
Tags: 7, database, entities
---


# Question
Title: How to change documents to another category painlessly
I have 4 content types eg Parts, Service, Marketing, and Sales.

I've now created one category with 4 content types sub-categories instead.

Is there a painless way of changing each documents category?

I've experimented with `[Node_export][1]` but that did not allow me to import into a different category.

# Answer
Try Node Convert, it allows you to change one content type to another:

> Node Convert adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability to convert the node from its current node type to another node type. The module provides the means to transfer all the field values of the current node type into fields on the destination node type, or discard them.

Then you can use Views Bulk Operations to do it in batches.
> 1 votes

---
Tags: nodes
---


# Question
Title: Add Meta tags and Title on hook_menu "page callback"
How to add Meta and Title tags to the document head on **hook\_menu "page callback"**? Drupal 7

# Answer
> 3 votes
Assuming Drupal 7...

For the title you can use `drupal_set_title()`.

For the meta tags you can use `drupal_add_html_head()`. Example from geerlingguy in the comments of those docs:

```
$element = array(
  '#tag' => 'link', // The #tag is the html tag - <link />
  '#attributes' => array( // Set up an array of attributes inside the tag
    'href' => 'http://fonts.googleapis.com/css?family=Cardo&subset=latin',
    'rel' => 'stylesheet',
    'type' => 'text/css',
  ),
);
drupal_add_html_head($element, 'google_font_cardo');

```

---
Tags: hooks, routes, meta-tags
---


title: Resume Parsing to Profile2

text:
# Question
Title: Resume Parsing to Profile2
I'm looking for a module, integration or solution for parsing a resume on the profile fields.

Big companies like Monster.com and Indeed.com can provide you the ability to upload a resume and fill out all the fields of registration for you. One of my clients ask me for this feature on the website and I have no idea where to start.

Base of what I read online there are two module for parsing Parsing Api and Feeds extensible parsers but they do not exactly what I'm looking for.

I'm using the Recruiter Distribution and Profile2.

My goal is to be able to upload a resume and that resume will complete their resume (Profile fields) for them.

# Answer
> 1 votes
For this you have three options

a) either use third party resume services. I recommend best one RChilli . We implemented them for various client.s

b) Or you can build your own algorithm for Resume Parsing.

c) 3rd one if you are getting fixed format of resumes then write own using drupal parsing api.

Let me know if I can be of further help.

---
Tags: 7, users
---


# Question
Title: Install profile that automatically inserts data / config settings
I am trying to create a custom installation profile for small internal usage and I'd like to hide certain steps and also implement new functions as a quick-and-dirty way to pre-populate some default content (nodes, blocks, menus) and configuration settings (wysiwyg) by inserting them into the database during the profile installation.

I am using the standard profile as a guide to work from as well as following this guide, but having trouble getting this to work smoothly and since it's all pre-installation I can't use devel to troubleshoot (it's not enabled yet).

Let's call the custom installation profile `customprofile` and the files I have are:

* customprofile\_profile.info
* customprofile\_profile.profile
* customprofile\_profile.install

I've figured out (for example) how to override the "Select locale" step and hard-code that to be English in `customprofile_profile.profile`:

```
function customprofile_install_tasks_alter(&$tasks, $install_state) {
  $tasks['install_select_locale']['display'] = FALSE;
  $tasks['install_select_locale']['function'] = 'customprofile_select_locale';
}

function customprofile_select_locale (&$install_state) {
  $install_state['parameters']['locale'] = 'en';
}

```

...but I haven't been able to track down the syntax for:

1) inserting a new step at the end of the profile install

2) inserting some SQL (I found this old post but it seems to be for Drupal 6 and both the profile syntax and SQL insertion are incompatible with Drupal 7)

Any guidance for next steps on either/both of these would be appreciated!

# Answer
> 0 votes
You might find drush-make useful, especially if you already have a codebase setup that you would like to replicate. As outlined in this blog post:

> Drush Make includes 2 commands which are already built in Drush itself:
>
> * make — Turns a .makefile into a Drupal codebase.
> * make-generate — Generates a .makefile from the current Drupal site.
>
> Both commands are related to a .makefile — flat text file with Drush Make instructions. You can read more about .makefile syntax here.

---
Tags: 7, installation-profiles
---


# Question
Title: jQuery length of object to determine existence gives error?
The following jQuery in my module gives an error that breaks LOTS of other javascript on other modules on the page. I want to know why. Why?

```
 var pid = $('input[name="product_id"]').attr('value');
 if ( pid.length )
   // do stuff

```

But this works fine:

```
var pid = $('input[name="product_id"]').attr('value');
if ( typeof(pid) !== 'undefined' )
  // this works fine

```

I've been using the first example for years in other environments to test for the existence of an object and it always works. What am I missing?

TIA.

# Answer
```
if (pid.length)

```

causes a reference error in your script if `pid` is `undefined`. So, if you don't know that `pid` exists ahead of time, then you have to check to see if that object is valid before trying to reference properties on it.

FYI, you could probably just use:

```
if (pid)

```

because that would protect you from `pid` being `undefined` or an empty string.

---

It has been raised in comments that maybe you're actually just trying to test for the existence of a DOM object, not the attribute. If that's the case, then you should just be doing this:

```
if ($('input[name="product_id"]').length)

```

which tells you if the selector matched any DOM objects.
> 1 votes

---
Tags: 7, javascript
---


title: How to Migrate files having path in it?

text:
# Question
Title: How to Migrate files having path in it?
I have a custom table in drupal 6 in which file path is stored in the field like `sites/default/files/file_name.jpg`. I dont have `fid` for this field.

How can I map this with my image field?

# Answer
> 0 votes
I saved the file in `prepareRow()` and map the fid with my field.

```
$this->addFieldMapping('field_image', 'fid');
$this->addFieldMapping('field_image:file_class')
  ->defaultValue('MigrateFileFid');

```

In my prepareRow method :

```
  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    $files_dir = '/mnt/files';
    $file_name = str_replace('sites/default/files/', '', $row->image);
    $file_path = $files_dir . $file_name;
    $row->fid = _my_migration_upload_file($file_path);
    return TRUE;
  }

```

---
Tags: 7, migrations
---


# Question
Title: Generate unique barcode for each registered user
I'm using D7 and I would like my website to create unique barcode for each user when they register an account, and send the barcode to them through email. This barcode should be part of their profile.

I found that "Barcode" module can generate barcode in a page, but I'm not sure how to use this module to create barcode for user. Is there any way I can modify the codes to do this?

Just some background information:

I need a barcode generated to each user as I want to scan it in mobile as taking attendance when web admin is having an event. After event ends, web admin will export the attendance list in excel or any document style, to check on the attendance detail (name, userid, date, scanned barcode)

Anyway the scanning and retrieving list is mobile app issue. I need to start with generating barcode first.

Any suggestion on this?

# Answer
> 0 votes
* Enable the barcode module.
* Goto: admin/config/people/accounts/fields
* Add a barcode field and configure as you like
* Towards the bottom of: admin/config/people/accounts, Modify the email to include the barcode

Another option: Commerce Event Tickets, This sounds a lot like what you need.

---
Tags: users
---


title: how to export views in batch

text:
# Question
Title: how to export views in batch
Is there a module to automate exporting/importing a batch of Views (for import onto another site?)

I have a Commerce Kickstart site with demo data. I can't figure out how to remove the demo data without resetting the site, so I'm going to start over.

I want to take some Views I created myself with me. (Unless someone has the magic trick to remove all Commerce Demo data...including Product Types without using Reset() of course. :D )

TIA.

# Answer
> 2 votes
I have often been advised to just save my Views as a Feature. Any reason this won't do the required?

# Answer
> 0 votes
You are mistaken between the terms. The views you getting by default are already exported so you don't need to export what is already exported unless you made some changes. What you do want to do is delete all the content you get from the installation. The content is being migrated with the migrate module. In order to remove the data you need to enable the migrate UI module and then go to admin/content/migrate and then check all the migrate handlers and select role back.

# Answer
> 0 votes
To remove all the commerce example data, you might use Administration Views \+ Views Bulk Operations \+ (Commerce VBO Views or Commerce Backoffice) to identify and delete all your sample products, orders etc.

Note that you might run into some situations where a product can't be removed since it's referred to by a line item which is part of a product; if this happened you might need to remove the orders and associated line items before removing the products, then the product types (etc - read as hypothetical example).

However, it's valuable being able to rebuild the site from basics, and in that case the route of exporting Views as Features as Pete suggests is a sensible one. This path will have more of a learning curve but has advantages for you longer term - eg it's much easier to track development stored as code than all globbed together in a DB, big advantages when dealing with unexpected problems later on ...

# Answer
> 0 votes
This appears to have been answered previously in the Drupal Commerce forums.

> Demo store product types, content types and categories are not deletable (due to the way how the Features module works), which is why the demo store can't be used for new projects (which is something we say quite clearly on the project page)

> Please note that the "demo store" has been built to demonstrate the capabilities of Kickstart and shouldn't be used when starting new sites.

So it does appear that the correct solution is to export your customisations (Views etc via Features), and to rebuild the store from Kickstart *without* the Demo Store.

Sorry :(

---
Tags: views, importing-exporting
---


# Question
Title: Block overriding with template file doesn't work
The Drupal version I'm using is v7.34. I'm using sub-theme created from Bootstrap as base theme. My problem is, I want to override the "User Login Block" and put it in the header region (top bar), so I create these file in **templates** folder in my sub-theme:

1. **page.tpl.php**

`//this simply do
print render($page['header']);`
2. **region--header.tpl.php**

`$search_block = module_invoke('search', 'block_view', 'search');
$login_block = module_invoke('user', 'block_view', 'login');
print render($search_block);
print render($login_block);`
3. **search-block-form.tpl.php**

`//this copied from base theme and only modified some html tag`
4. **block--user--login.tpl.php**

`//this simply print out some simple text
print ("blahhhhhhhhhhhhhh");`

The result is, only search block is rendered as override, and the login block is rendered as default block, not rendered as the one I override. I did some search but nothing matches my fault.

# Answer
**To Alter User login block**

* Find the template.php file for the theme you're working on. Should be in the root of the theme folder for your theme
* Assuming the "yourthemename\_hook" function does NOT exist, at the bottom of your template.php file insert the following code:

> ```
> function yourthemenamehere_theme(&$existing, $type, $theme, $path) {
>    $hooks['user_login_block'] = array(
>      'template' => 'templates/user-login-block',
>      'render element' => 'form',
>    );
>    return $hooks;
>  }
> function yourthemenamehere_preprocess_user_login_block(&$vars) {
>   $vars['name'] = render($vars['form']['name']);
>   $vars['pass'] = render($vars['form']['pass']);
>   $vars['submit'] = render($vars['form']['actions']['submit']);
>   $vars['rendered'] = drupal_render_children($vars['form']);
> }
>
> ```

* Now create a directory inside your theme's directory called "templates" (assuming it doesn't exist already)
* Then create a php file inside that folder called: "user-login-block.tpl.php" Inside this file, put the following code:

> ```
> <div id="user-login-block-container">
>   <div id="user-login-block-form-fields">
>     <?php print $name; // Display username field ?>
>     <?php print $pass; // Display Password field ?>
>     <?php print $submit; // Display submit button ?>
>     <?php print $rendered; // Display hidden elements (required for successful login) ?>
>   </div>
>   <div class="links">
>     <a href="/user/register">Create an Account</a> | <a href="/user/password">Forgot Password</a>
>   </div>
> </div>
>
> ```

* **CRITICAL STEP** as an admin on your website, navigate to "admin/config/development/performance" and click "clear all caches" -- if you don't, then these changes won't display on your website
* Modify the html markup inside "user-login-block.tpl.php" to your heart's content, and don't forget that you can also add those css classes to your main style.css file (AFAIK)
> 0 votes

---
Tags: 7, theming, blocks
---


# Question
Title: How to insert html tags to a node content?
I am wondering is it possible to insert a plain full html tags to a node content? Currently I have a node content type having a list of fields, but if I add some html tags in tpl.php file for that node, the html tags are actually outside the main content of the node field (but I want to put new-added html tags inside that.)

Can anyone brief me what is the best way of doing that?

Regards!

# Answer
> 4 votes
To use html tags in the Body field of a Basic page content type (for example) you need to select "Full HTML" or "Filtered HTML" in the "Text format" dropdown menu below the input text box (see image). As far as I know, only fields of type "Long text and summary" and "Long text" allow you to select Full or Filtered HTML.

To configure text formats and permissions go to Configuration -\> Content authoring -\> Text formats (www.example.com/admin/config/content/formats).

For more information see Text filters and Input Formats.

---
Tags: theming
---


title: EFQ - Sort by published date

text:
# Question
Title: EFQ - Sort by published date
I'm using the module Publication Date to store when nodes are published. It uses a simple table of nid and published\_at for the timestamp. I need to use EFQ to sort nodes by this date, but I'm unsure if it's able to connect to the table it uses.

```
->propertyOrderBy('published_at', 'DESC');

```

obviously doesn't work.

Is there any way I can connect to this table using EFQ, or does it have to be a db\_query?

# Answer
> 1 votes
It can be done. You have to add a tag to your EFQ, for example:

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->addTag('published_at')
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

```

Then you wil have to implement hook\_query\_tag\_alter, in your case:

```
function mymodule_query_published_at_alter($query){
  // Extend your query with some joins and order statements:
  $query->join('table');
  $query->orderBy('field');
}

```

The above code is an example, it won't work, but you get the picture :)

---
Tags: database
---


# Question
Title: Adding a reference to a bundle in a node
I would appreciate suggestion for this common scenario in Drupal 8, which may be different to how I do it in Drupal 6. I don't want to do any programming.

I have two content types: (1) Articles (title, author, body) (2) Authors (First name, Surname, Biography). Authors are not users.

When adding a new article, I want the option to select either (a) An existing author from a list, or (b) Add a new author to the list, and select it.

When displaying the article, I want to see the author's First Name and Surname, and optionally a Biography teaser, and then the body of the article.

# Answer
> 2 votes
Enable the Entity Reference module that is the part of drupal 8 core. Create the two content types.

> I have two content types: (1) Articles (title, author, body) (2) Authors (First name, Surname, Biography). Authors are not users.
>
> When adding a new article, I want the option to select either (a) An existing author from a list, or (b) Add a new author to the list, and select it.

Add a entity reference field in the Articles content type. Go to Home Administration Structure(admin/structure/types) click on Manage fields in front of Article content type.Add a new field(Authors) and choose its field type to be Entity reference and after save, The field configuration screen will open.Choose "Type of item to reference" to **Content**. Then on the next screen choose the reference type(authors content type).

> When displaying the article, I want to see the author's First Name and Surname, and optionally a Biography teaser, and then the body of the article.

There are several options to do so :

1)Load the authors entity in articles template and display its result like that.

2)Use the Display suite module which is still has alpha available.

3)Create the view block which displays the author information like you want to show.and embed this view in your node article template.

4)Go to Manage Display of that content type(admin/structure/types/manage/article/display) and use a separate display mode to do so.

5)etc....

I would suggest to use the Display suite because I love to use it as it made my life easier at many places.

# Answer
> -1 votes
This module: https://www.drupal.org/project/entityreference is the way to go in D7. D8 has only a dev release: https://www.drupal.org/node/1246440/release?api\_version%5B%5D=7234, so it might be buggy.

For displaying the correct content of the author, you should use Display Suite: https://www.drupal.org/project/ds. Again, be carefull, D8 modules might be buggy.

---
Tags: nodes, 8, entities
---


# Question
Title: Changing page orientation of a pdf of a views generated by the Print module
The Print module (https://www.drupal.org/project/print) allows users to generate a PDF of nodes, views and panels. It allows for the selection of a default page orientation (portrait or landscape), and it allows for administrators to override the default orientation in specific nodes.

However, I can't figure out how to override the default orientation when creating a PDF of a specific Views output. I have one View that needs to be printed in landscape format, the rest in portrait. Perhaps a PHP snippet in the header of the view?

Any help will be appreciated!

# Answer
If you used MPDF as your library then add this function to your themes' template.php:

```
function MYTHEME_print_pdf_mpdf_alter(&$mpdf, $html, $meta) {
  //return;
  if(is_view_path()) {
    $paper_size = variable_get('print_pdf_paper_size', PRINT_PDF_PAPER_SIZE_DEFAULT);
    $format = $paper_size . "-L";
    // set document information
    $mpdf = new mPDF('UTF-8', $format);
    $mpdf->SetAuthor(strip_tags($meta['name']));
    $mpdf->SetCreator(variable_get('site_name', 'Drupal'));
  }
}

```

I could not find a way to alter the paper orientation after the object was instantiated, so I opted to just create it again (orientation is set in class creator).

You should then implement a function called `is_view_path` that returns true if it detect the printpdf path of the view, so that the code only runs for your specific view.

```
function is_view_path() {
  $path = current_path();
  return $path == 'VIEWPATH'; // just add your view path here
}

```

If you used TCPDF you should look at the function print\_pdf\_tcpdf\_print\_pdf\_generate in print-pdf-tcpdf.page.inc at how to instantiate the $pdf object, and then implement an alter hook similarly to what I did above. I could not do it as for some reason I cannot get the tcpdf library to detect.

For DOMPDF I could not find an alter hook.
> 2 votes

---
Tags: views, files
---


title: Migrate map Issue

text:
# Question
Title: Migrate map Issue
This is a weird issue with the Migrate module 2.6 I'm migrating a users table "mysql" database to a test node and I'm getting a error with the migration map here is the error :

```
Migration failed with source plugin exception: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.migrate_map_usersmigration map ON u.user_id = map.sourceid1 WHERE ( (map.source' at line 1

```

and here is my code:

```
class UsersMigration extends myBaseMigrationClass {

  public function __construct($arguments) {
    parent::__construct($arguments);

    $this->description = t('Just for testing');

    $query = Database::getConnection('default', 'mydb')
      ->select('users', 'u')
      ->fields('u', array('user_id', 'full_name', 'birthday'));

    $this->source = new MigrateSourceSQL($query);

    $this->destination = new MigrateDestinationNode('test');

    $this->map = new MigrateSQLMap(
    $this->machineName,
      array(
        'user_id' => array(
            'type' => 'int',
            'not null' => TRUE,
            'alias' => 'u',
        ),
      ),
      MigrateDestinationNode::getKeySchema()
    );

    $this->addFieldMapping('title', 'full_name');
  }
}

```

Do I'm doing something wrong here?

* Also to clarify, the source query is working fine and I'm getting the correct data out when I print it out.

# Answer
Finally I was able to find a solution for this weird issue, according to the Migration examples (beer, Wine) modules. the code I have posted above should work fine, However it's throwing that weird error. it turns out that I needed to pass the database name again like this:

```
$this->map = new MigrateSQLMap(
$this->machineName,
  array(
    'user_id' => array(
        'type' => 'int',
        'not null' => TRUE,
        'alias' => 'u',
    ),
  ),
  MigrateDestinationNode::getKeySchema(),
 'mydbName'
);

```

even the example modules that using SqlSource class wont work with migrate "7.x-2.6-rc1+57-dev". I will try to report that issue to the developer
> 1 votes

# Answer
I was also experiencing this issue.

I tried to do the same actions on another machine. The problem does not occur there, which is very strange. I suspect this is a problem with my LAMP stack (native OS X Mavericks stack).

So it could be your PHP version, try upgrading it.

See Migrate examples failing
> 0 votes

---
Tags: migrations
---


# Question
Title: Adding "Create New Node" link in views pages
SO I have two content types, a "Candidate" and a "Job Opening". "Candidate" has an Entity Reference field that points to a Job Opening. I've currently got separate views for both, but on the "Job Opening" view I'd like to have a field that users can click to apply for a job, which would ideally create a new Candidate node with the Job Opening ER field pre-filled so users don't have to fill that in.

I tried adding a Custom Text field containing

```
<a href="/node/add/candidate">Apply Now!</a>

```

but I just get an "object not found" error when I click on it.

Is there any way to accomplish this be it with existing modules or built-in stuff, or am I gonna have to dive in and start coding?

Edit: So I've managed to get half of what I want. Turns out because my installation is at "/localhost/drupal", then my link needed to be

```
<a href="/drupal/node/add/candidate/">Apply Now!</a>

```

So now I just need to find out how to pass a reference to the job opening its from and I'm golden.

# Answer
Ok, so I'm writing my own answer because I used a bunch of different things from this thread.

First, I decided to use Entityreference Prepopulate since all of the affected fields were already created using the Entity Reference module and I didn't feel like re-making them with Node Reference.

Next, I used views PHP to give me access to the Global: PHP field in Views, and I filled the output code section of the relevant nodes with the following:

```
<?php print l("Apply Now", $GLOBALS['base_url'] . "/node/add/candidate?field_job_opening=". $row->id); ?>

```

I used the l() function to ensure that the links are properly formed regardless of Clean URL settings and it should work if/when the sites base url changes.
> 0 votes

# Answer
It's possible without writing any PHP etc. and you'll need one of the modules mentioned Entityreference prepopulate, Prepopulate, etc.

1. Add Global: Custom text to your fields, in the Text field enter Apply Now!
2. Under Rewrite results, check Output this field as a link
3. In the Link path field enter node/add/candidate (this will get passed through the l() function and correctly deal with subfolders, etc.)
4. Add Global: Unfiltered text to your header/footer, etc. in the Text field enter \[nothing\], check Display even if view has no result and check Use replacement tokens from the first row
5. Test this is working correctly and Exclude from display the Global: Custom text in your fields
6. Play around with the Link path field to correctly pass the correct variables so your fields are populated correctly - this will probably require trial and error to get this correct which is why this is the last step.
> 2 votes

# Answer
If you have views php module installed in your drupal installation than you can use `$GLOBALS['base_url']` i.e the base\_url to get the path of your drupal root and than you can dynamically create the node add link.

One more thing, its better to create the node add link with the l(), as the above example will not work on a site with clean URLs turned off.
> 1 votes

# Answer
Requirement is pretty much as Event-Registration scenario.I would recommend you to go through a very nice video video-tutorial by yaworski. Try to get hold of the key logic behind it,you will get job done doing required modifications.

**Edit:**

So now I just need to find out how to pass a reference to the job opening its from and I'm golden. -- you can pass node reference from url as well, check out node reference url module

again going with demo videos , will be worth watching.
> 0 votes

# Answer
I aggree with using l() function to write a link

Then to prepopulate a referenced node/entity, Entityreference prepopulate module can be usefull

Also Node Reference URL Widget module do this

Both have an ID in the url to prepolutate your referenced field when accessing the node/add form

Url looks like : `node/add/article/field_parent=112` or `node/add/article/112` depends which module your are using

Write your custom link directly in your view with using l() function
> 0 votes

# Answer
It's been said a couple times here to add the link using the `l()`. I'd like to add a complete example to conditionally add a button/link to Add Another Node of whatever content using `l()` to avoid caring where your site is hosted and to make it so unauthorized users won't see the link. It also adds a destination of the current page in the simplest way possible so that after hitting Save, the user gets taken back to the page (View) wherever the thing is displayed (like in a block throughout the site).

```
$links = array();
if (user_access('create event content')) {
  $link = l('Add Event', 'node/add/event',
    array(
      'query' => drupal_get_destination()
    )
  );
  $links[] = $link;
}
if (user_access('create performer content')) {
  $link = l('Add Artist', 'node/add/performer',
    array(
      'query' => drupal_get_destination()
    )
  );
  $links[] = $link;
}
if (count($links)) {
  print "<p>" . implode(' | ', $links) . "</p>";
}

```

In the example above, I am outputting two links side by side with independent user\_access checks, one for each content type.

This snippet would go, for instance, in the Header of a View with the checkbox "Display even if View has no result" checked and Input Type filter set to PHP.
> 0 votes

---
Tags: views
---


# Question
Title: How to sort terms in Views by their weight
I have Dictionary with several taxonomy terms. When I use Edit tab near each term in Structure/Taxonomy I see that I can give weight for any term. Also I can drug and drop them in any order in list of terms for my vocabluary. More than it, when I after this procedure go and look at weights - they are in new order.

So, problem is that then I use Views to make block with my taxonomy terms (I use unformated list) and use Taxonomy weight as sorting criteria - sorting always goes in alfabetic order.

And when I made additional field in View to show terms weight - I found out that all terms have weight -8. How I can make term order in my Views display according to their weight?

Thank you.

# Answer
I've done same setup and working fine. Might be you've missed something. Import the below code into your view.

```
$view = new view();
$view->name = 'List of Tags';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Tags 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'] = 'List of Tags';
$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'] = 'fields';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Filter criterion: Taxonomy term: Vocabulary */
$handler->display->display_options['filters']['vid']['id'] = 'vid';
$handler->display->display_options['filters']['vid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['vid']['field'] = 'vid';
$handler->display->display_options['filters']['vid']['value'] = array(
  1 => '1',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'tags-list';
$translatables['sdf'] = array(
  t('Master'),
  t('List of Tags'),
  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

---
Tags: views
---


# Question
Title: Accessing Drupal 6 data using Drupal 7 entities
I have a project where we have a legacy system built in Drupal 6 that has been heavily customized, with much of the data stored in custom tables. We are currently planning a D6 to D7 upgrade, but we have an immediate need to access that data in a Drupal 7 instance, leaving the D6 site intact for now.

I would like to access that data using Drupal Entities and wrap each D6 table in a Drupal 7 Entity; however I'm having trouble making that work since the underlying assumption with the Entity API is that the data is stored in the local database, and this database is remote. We can access the database directly from the Drupal 7 instance, and I have the database credentials loaded in settings.php. I can query the data using Database::getConnection('default', 'legacy')-\>select(), so I know my connection is good; however I have no idea how to go about structuring an Entity class so that I can leverage EFQ, Views, etc. on this data.

I looked at Remote Entity API, but I"m not dealing with a RESTful service here, I have a direct connection to the D6 database.

Any assistance or hints would be greatly appreciated. I've worn Google out.

# Answer
> 0 votes
As I understand it you're discounting the Remote Entity API module because you don't have a RESTful service...

The module actually relies on the Web Service Clients module, which provides that REST service for you:

> Parallel to the Services module, the Clients module provides the ability to implement pluggable clients to external web services, including external Drupal sites running the Services module, the main use case being connecting to other Drupal installs via the Services module with either the REST or XMLRPC server.
>
> Clients module allows you to create connections to remote services with an admin UI. These handle fetching a result from a remote service. Different types of connection are provided for different types of services. **There is a Drupal client connection type for different versions of Services (5.x-0.92, 6.x-2.x, 7.x-3.x), hence Clients can be used to connect to sites with different versions of Drupal.**

Emphasis mine.

# Answer
> 0 votes
If it was me I would properly migrate the data from the old database into Drupal 7.

I would plan out the entities in the new site that will take the data from the old site. They may be nodes, custom entities, data module tables, users, taxonomy terms, etc.

Then I would migrate the data from the old database into those native Drupal 7 entities.

Then I would completely do away with the old legacy database.

By hanging on to the old database and somehow hacking it into your new website you are adding much unnecessary complexity and it will likely cause you lots of headaches in future.

As for the migration, I would use the Migrate module, the Migrate extras module and depending on your needs maybe the Drupal-to-Drupal data migration module.

The migrate module is fairly complex and has a bit of a learning curve but is very powerful. It follows consistent patterns though so once you've learned it it's not so scary.

---
Tags: 7, entities, database
---