# Question
Title: How to allow users to export data from custom module to a CSV file?
I have a custom module that's a multi-page form that collects one value from a user for each page of the form (3 pages, 3 total values collected). On the final page of the form (the recommendations page) it displays recommended resources from our database that match the user's selections. Because we need to put all 'timely events' first, followed by 'quick study' events, and finally 'deep dive' events the recommendations page uses 3 SQL queries to output the data to the screen.

All that works fine. However, now we'd like to add some way to allow the user to EXPORT the recommendations they see on the screen to a CSV file (or some other type) with an 'export' link. That's why I'm here asking you guys...does anyone know a great way to make this happen?

Here's the recommendations page code:

```
// function to return results from DB based on what user entered
function pathfindertool_recommendations_page() {

    //first test if variables passed from Pathfinder tool
    if (isset($_SESSION['role']) AND isset($_SESSION['level']) AND
    isset($_SESSION['topic'])) {
        // set variables
        $role = $_SESSION['role'];
        $level = $_SESSION['level'];
        $topic = $_SESSION['topic'];

        // gather session variables and give them string values
        if ($role == 0) {
            $role = "Grant Writer";
        }
        elseif ($role == 1) {
            $role = "Nonprofit Administrator";
        }
        elseif ($role == 2) {
            $role = "Nonprofit Founder";
        }
        else {
            $role = "Consultant";
        }

        if ($level == 0) {
            $level = "Novice";
        }
        elseif ($level == 1) {
            $level = "Experienced";
        }
        else {
            $level = "Professional";
        }

        if ($topic == 0) {
            $topic = "Grants Research";
        }
        elseif ($topic == 1) {
            $topic = "Grant Writing";
        }
        elseif ($topic == 2) {
            $topic = "Grant Management";
        }
        else {
            $topic = "Strategic Planning";
        }

        // set $output var
        $output ='';

        // print and email link styling
        $output .= '
Printer-friendly version
';

        // progress bar
        $output .= '
Primary Role > Experience Level > Topics of Interest >
    Recommendations
';

        // remind user what they selected in form
        // but first, set pro and grants research to the preferred edits
        if ($level == "Professional") {
            $level2 = "Advanced";
        } else {
            $level2 = $level;
        }
        if ($topic == "Grants Research") {
            $topic2 = "Grant Research";
        } else {
            $topic2 = $topic;
        }
        $output .= '
You selected ' . $role .
    ', ' . $level2 . ', and ' . $topic2 . '.
';

        // sql for Timely Events
        $result = db_query("SELECT n.title, n.nid, n.status, n.type,
    fdfty.field_type_value, fdfi.entity_id, fdfi.field_icon_tid,
    fdfti.entity_id, fdfti.field_taxonomy_icon_fid, fm.uri, fm.fid,
    ua.source, ua.alias, el.field_experience_level_value, fdb.body_value,
    fdfr.field_role_value, fdft.field_topics_value,
    fdfed.field_event_dates_value, fdfed.field_event_dates_value2,
    fdfl.field_location_value, fdfl.entity_id,
    fdfo.field_organization_value, fdfo.entity_id FROM {node} AS n LEFT JOIN
    {field_data_field_type} AS fdfty ON n.nid=fdfty.entity_id LEFT JOIN
    {field_data_field_icon} AS fdfi ON n.nid=fdfi.entity_id LEFT JOIN
    {field_data_field_taxonomy_icon} AS fdfti ON
    fdfi.field_icon_tid=fdfti.entity_id LEFT JOIN {file_managed} AS fm ON
    fdfti.field_taxonomy_icon_fid=fm.fid LEFT JOIN {url_alias} AS ua ON
    CONCAT('node/', nid)=source LEFT JOIN
{field_data_field_experience_level} AS el ON n.nid=el.entity_id LEFT JOIN
    {field_data_body} AS fdb ON n.nid=fdb.entity_id LEFT JOIN
    {field_data_field_role} AS fdfr ON n.nid=fdfr.entity_id LEFT JOIN
    {field_data_field_topics} AS fdft ON n.nid=fdft.entity_id LEFT JOIN
    {field_data_field_event_dates} AS fdfed ON n.nid=fdfed.entity_id LEFT
    JOIN {field_data_field_location} AS fdfl ON n.nid=fdfl.entity_id LEFT
    JOIN {field_data_field_organization} AS fdfo ON n.nid=fdfo.entity_id
    WHERE n.status=:status AND n.type=:resource AND
    (fdfty.field_type_value=:webinar OR
    fdfty.field_type_value=:workshoptraining OR
    fdfty.field_type_value=:conference) AND
    el.field_experience_level_value=:level AND fdfr.field_role_value=:role
    AND fdft.field_topics_value=:topic AND ((fdfed.field_event_dates_value
    IS NULL) OR (fdfed.field_event_dates_value >= CURRENT_DATE())) GROUP BY
     n.nid, n.title ORDER BY CASE WHEN fdfty.field_type_value='1' THEN 0
    WHEN fdfty.field_type_value='2' THEN 1 WHEN fdfty.field_type_value = '3'
     THEN 2 END, fdfed.field_event_dates_value, n.title", array(':status' =>
    '1', ':resource' => 'resource', ':webinar' => '1', ':workshoptraining'
    => '2', ':conference' => '3', ':level' => $level, ':role' => $role,
    ':topic' => $topic));

        // count how many results returned
        $num_rows = $result->rowCount();
        $counter = $num_rows;

        // test if results
        if ($num_rows > 0) {

            // output header
            $output .= '
Timely
    Events
';

            // return results to page
            while ($row = $result->fetchAssoc()) {

                // set variables
                $date1 = $row['field_event_dates_value'];
                $timestamp = strtotime($date1);
                $date2 = $row['field_event_dates_value2'];
                $timestamp2 = strtotime($date2);
                $title = $row['title'];
                $nid = $row['nid'];
                $alias = $row['alias'];
                // set image to display correctly for category
                $icon = image_style_url('thumbnail', $row['uri']);
                // select price image
                $result2 = db_query("SELECT n.title, n.nid, fdfp.entity_id,
     fdfp.field_price_tid, fdfcm.entity_id, fdfcm.field_costs_money_fid,
    fm2.fid, fm2.uri FROM {node} AS n LEFT JOIN {field_data_field_price} AS
    fdfp ON n.nid=fdfp.entity_id LEFT JOIN {field_data_field_costs_money} AS
    fdfcm ON fdfp.field_price_tid=fdfcm.entity_id LEFT JOIN {file_managed}
    AS fm2 ON fdfcm.field_costs_money_fid=fm2.fid WHERE n.nid = :nid",
    array(':nid' => $nid));
                while ($row2 = $result2->fetchAssoc()) {
                    if ($row2['uri'] == 'public://dollar-sign.png') {
                        $dollar = image_style_url('thumbnail', $row2['uri']);
                    } else {
                        $dollar = "";
                    }
                }
                $desc = $row['body_value'];
                $ftv = $row['field_type_value'];
                // set dates to display correctly and add other output to
    make page styled
                if ($date1 != $date2) {
                    $output .= '
';
                        if ($dollar != "") {
                            $output .= '';
                        } else {
                            $output .= "";
                        }
                    $location = $row['field_location_value'];
                    $organization = $row['field_organization_value'];
                    $output .= '
' . $title . '

' . date('l, F j, Y',
    $timestamp) . ' to ' . date('l, F j, Y', $timestamp2) . '

';
                    if (($location != NULL) && (($ftv == '2') || ($ftv ==
    '3'))) {
                        $output .= '
' . $location .
    '
';
                    }
                    if (($organization != NULL) && (($ftv == '1') || ($ftv
    == '2') || ($ftv == '3'))) {
                        $output .= '
' . $organization .
    '
';
                    }
                    $output .= '
' . $desc  . '

';
                } elseif ($date1 == $date2) {
                    $output .= '
';
                        if ($dollar != "") {
                            $output .= '';
                        } else {
                            $output .= "";
                        }
                    $location = $row['field_location_value'];
                    $organization = $row['field_organization_value'];
                    $output .= '
' . $title . '

' . date('l, F j, Y',
    $timestamp) . '

';
                    if (($location != NULL) && (($ftv == '2') || ($ftv ==
    '3'))) {
                        $output .= '
' . $location .
    '
';
                    }
                    if (($organization != NULL) && (($ftv == '1') || ($ftv
    == '2') || ($ftv == '3'))) {
                        $output .= '
' . $organization .
    '
';
                    }
                    $output .= '
' . $desc  . '

';
                } else {
                    $output .= '
';
                    $output .= '/>';
                        if ($dollar != "") {
                            $output .= '';
                        } else {
                            $output .= "";
                        }
                    $location = $row['field_location_value'];
                    $organization = $row['field_organization_value'];
                    $output .= '
' . $title . '

';
                    if (($location != NULL) && (($ftv == '2') || ($ftv ==
    '3'))) {
                        $output .= '
' . $location .
     '
';
                    }
                    if (($organization != NULL) && (($ftv == '1') || ($ftv
    == '2') || ($ftv == '3'))) {
                        $output .= '
' . $organization .
    '
';
                    }
                    $output .= '
' . $desc  . '

';
                }
            }
        }

        // sql for Quick Study items
        $result = db_query("SELECT n.title, n.nid, n.status, n.type,
    fdfty.field_type_value, fdfi.entity_id, fdfi.field_icon_tid,
    fdfti.entity_id, fdfti.field_taxonomy_icon_fid, fm.uri, fm.fid,
    ua.source, ua.alias, el.field_experience_level_value, fdb.body_value,
    fdfr.field_role_value, fdft.field_topics_value,
    fdfl.field_location_value, fdfl.entity_id,
    fdfo.field_organization_value, fdfo.entity_id FROM {node} AS n LEFT JOIN
     {field_data_field_type} AS fdfty ON n.nid=fdfty.entity_id LEFT JOIN
    {field_data_field_icon} AS fdfi ON n.nid=fdfi.entity_id LEFT JOIN
    {field_data_field_taxonomy_icon} AS fdfti ON
    fdfi.field_icon_tid=fdfti.entity_id LEFT JOIN {file_managed} AS fm ON
    fdfti.field_taxonomy_icon_fid=fm.fid LEFT JOIN {url_alias} AS ua ON
    CONCAT('node/', nid)=source LEFT JOIN
    {field_data_field_experience_level} AS el ON n.nid=el.entity_id LEFT
    JOIN {field_data_body} AS fdb ON n.nid=fdb.entity_id LEFT JOIN
    {field_data_field_role} AS fdfr ON n.nid=fdfr.entity_id LEFT JOIN
    {field_data_field_topics} AS fdft ON n.nid=fdft.entity_id LEFT JOIN
    {field_data_field_location} AS fdfl ON n.nid=fdfl.entity_id LEFT JOIN
    {field_data_field_organization} AS fdfo ON n.nid=fdfo.entity_id WHERE
    n.status=:status AND n.type=:resource AND
    (fdfty.field_type_value=:articlereport OR fdfty.field_type_value=:blog
    OR fdfty.field_type_value=:recweborpodcast OR
    fdfty.field_type_value=:newslettermagazine) AND
    el.field_experience_level_value=:level AND fdfr.field_role_value=:role
    AND fdft.field_topics_value=:topic GROUP BY n.nid, n.title ORDER BY CASE
    WHEN fdfty.field_type_value='4' THEN 0 WHEN fdfty.field_type_value = '5'
    THEN 1 WHEN fdfty.field_type_value = '6' THEN 2 WHEN
    fdfty.field_type_value = '7' THEN 3 END, n.title", array(':status' =>
    '1', ':resource' => 'resource', ':articlereport' => '4', ':blog' => '5',
    ':recweborpodcast'=> '6', ':newslettermagazine'=>'7', ':level' =>
    $level, ':role' => $role, ':topic' => $topic));

        // count how many results returned
        $num_rows = $result->rowCount();
        $counter .= $num_rows;

        if ($num_rows > 0) {
            $output .= '
Quick
    Study
';

            //return results to page
            while ($row = $result->fetchAssoc()) {

                // set variables
                $title = $row['title'];
                $nid = $row['nid'];
                $desc = $row['body_value'];
                $alias = $row['alias'];
                // set image to display correctly
                $icon = image_style_url('thumbnail', $row['uri']);
                $result2 = db_query("SELECT n.title, n.nid, fdfp.entity_id,
    fdfp.field_price_tid, fdfcm.entity_id, fdfcm.field_costs_money_fid,
    fm2.fid, fm2.uri FROM {node} AS n LEFT JOIN {field_data_field_price} AS
     fdfp ON n.nid=fdfp.entity_id LEFT JOIN {field_data_field_costs_money}
    AS fdfcm ON fdfp.field_price_tid=fdfcm.entity_id LEFT JOIN
    {file_managed} AS fm2 ON fdfcm.field_costs_money_fid=fm2.fid WHERE n.nid
    = :nid", array(':nid' => $nid));
                while ($row2 = $result2->fetchAssoc()) {
                    if ($row2['uri'] == 'public://dollar-sign.png') {
                        $dollar = image_style_url('thumbnail', $row2['uri']);
                    } else {
                        $dollar = "";
                    }
                }
                    $ftv = $row['field_type_value'];
                    $output .= '
';
                    if ($dollar != "") {
                        $output .= '';
                    } else {
                        $output .= "";
                    }
                    $organization = $row['field_organization_value'];
                    $output .= '
' . $title . '

';
                    if (($organization != NULL) && ($ftv == '6')) {
                        $output .= '
' . $organization . '
';
                    }
                    $output .= '
' . $desc  . '

';
                }
            }

        // sql for Deep Dive items
        $result = db_query("SELECT n.title, n.nid, n.status, n.type,
    fdfty.field_type_value, fdfi.entity_id, fdfi.field_icon_tid,
    fdfti.entity_id, fdfti.field_taxonomy_icon_fid, fm.uri, fm.fid,
    ua.source, ua.alias, el.field_experience_level_value, fdb.body_value,
    fdfr.field_role_value, fdft.field_topics_value,
    fdfl.field_location_value, fdfl.entity_id,
    fdfo.field_organization_value, fdfo.entity_id FROM {node} AS n LEFT JOIN
     {field_data_field_type} AS fdfty ON n.nid=fdfty.entity_id LEFT JOIN
    {field_data_field_icon} AS fdfi ON n.nid=fdfi.entity_id LEFT JOIN
    {field_data_field_taxonomy_icon} AS fdfti ON
    fdfi.field_icon_tid=fdfti.entity_id LEFT JOIN {file_managed} AS fm ON
    fdfti.field_taxonomy_icon_fid=fm.fid LEFT JOIN {url_alias} AS ua ON
    CONCAT('node/', nid)=source LEFT JOIN
    {field_data_field_experience_level} AS el ON n.nid=el.entity_id LEFT
    JOIN {field_data_body} AS fdb ON n.nid=fdb.entity_id LEFT JOIN
    {field_data_field_role} AS fdfr ON n.nid=fdfr.entity_id LEFT JOIN
    {field_data_field_topics} AS fdft ON n.nid=fdft.entity_id LEFT JOIN
    {field_data_field_location} AS fdfl ON n.nid=fdfl.entity_id LEFT JOIN
    {field_data_field_organization} AS fdfo ON n.nid=fdfo.entity_id WHERE
    n.status=:status AND n.type=:resource AND (fdfty.field_type_value=:tool
    OR fdfty.field_type_value=:bookorworkbook OR
    fdfty.field_type_value=:certificateordegreeprogram) AND
    el.field_experience_level_value=:level AND fdfr.field_role_value=:role
    AND fdft.field_topics_value=:topic GROUP BY n.nid, n.title ORDER BY CASE
     WHEN fdfty.field_type_value='8' THEN 0 WHEN fdfty.field_type_value =
    '9' THEN 1 WHEN fdfty.field_type_value = '10' THEN 2 END, n.title",
    array(':status' => '1', ':resource' => 'resource', ':tool' => '8',
    ':bookorworkbook' => '9', ':certificateordegreeprogram'=>'10', ':level'
    => $level, ':role' => $role, ':topic' => $topic));

        // count how many results returned
        $num_rows = $result->rowCount();
        $counter .= $num_rows;

        if ($num_rows > 0) {

            $output .= '
Deep Dive
';

            //return results to page
            while ($row = $result->fetchAssoc()) {

                // set variables
                $title = $row['title'];
                $nid = $row['nid'];
                $desc = $row['body_value'];
                $alias = $row['alias'];
                // set image to display correctly
                $icon = image_style_url('thumbnail', $row['uri']);
                $result2 = db_query("SELECT n.title, n.nid, fdfp.entity_id,
 fdfp.field_price_tid, fdfcm.entity_id, fdfcm.field_costs_money_fid,
fm2.fid, fm2.uri FROM {node} AS n LEFT JOIN {field_data_field_price} AS fdfp
ON n.nid=fdfp.entity_id LEFT JOIN {field_data_field_costs_money} AS fdfcm ON
fdfp.field_price_tid=fdfcm.entity_id LEFT JOIN {file_managed} AS fm2 ON
fdfcm.field_costs_money_fid=fm2.fid WHERE n.nid = :nid", array(':nid' =>
$nid));
                while ($row2 = $result2->fetchAssoc()) {
                    if ($row2['uri'] == 'public://dollar-sign.png') {
                        $dollar = image_style_url('thumbnail', $row2['uri']);
                    } else {
                        $dollar = "";
                    }
                }
                    $ftv = $row['field_type_value'];
                    $output .= '
';
                    if ($dollar != "") {
                        $output .= '';
                    } else {
                        $output .= "";
                    }
                    $location = $row['field_location_value'];
                    $organization = $row['field_organization_value'];
                    $output .= '
' . $title . '

';
                    if (($location != NULL) && ($ftv == '98')) {
                        $output .= '
' . $location .
'
';
                    }
                    if (($organization != NULL) && ($ftv == '98')) {
                        $output .= '
' . $organization .
 '
';
                    }
                    $output .= '
' . $desc  . '

';
            }
        }

            if ($counter == "0") {
                // if no entries matched what user entered give them
alternative text.
                $output .= '

'
 . "Sorry, your selections did not result in any recommendations at this
time. " . '' . "Go here to try again" .
'

';
            }

        // return variable to display results
        return $output;

        // if user went directly to rec page without taking questionnaire
    } else {

        $output = "";

        // progress bar html/css styling
        $output .= '
Primary Role > Experience Level > Topics of Interest >  Recommendations
';

        $output .= '
' . "You haven't yet taken the
questionnaire; please " . '' . "go here to get
started" . '.
';

        return $output;
    }

}

```

# Answer
> 1 votes
**If** it would be an option to create that "report" on your recommendations page using the Forena module, **then** it would be just a matter of specifying what kind of hyperlinks you want to make available for performing such "export". These hyperlinks correspond to various supported "formats", such as: CSV, PDF, XLS, XML, DOC, HTML ...

To get an idea of how that would look like, visit the demo site samples. Checkout the samples such as the Master detail with nested blocks. There is a link "PDF" (upper right), which in this case would "export" the results there in a PDF doc. Though it could as well (or "also") be a CSV, XLS, DOC, etc (if that is what the "report designer" would have selected as one of the allowed/enabled export formats).

For more details about Forena, 2 types of documentation are available:

* Community documentation, which includes a child page Video demos and tutorials.
* Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

+ **Forena documentation** \- use the link 'Reporting documentation' or visit relative link /reports/help.
    + **Forena samples** \- use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

**Access to reports (and export links)**:

* Who can "Access" a specific report is a matter of granting access to the "data block" (= results of an SQL query). While access to those (export) links is a matter of being able to access the report (via its data block). So if "Anonymous" is allowed to access some data block, then those links on its report can be accessed also (and hence perform a save/export also). Those PDF links in the demo site samples are an illustration of that (since you visit that site anonymous).
* Extra feature: yes or no showing a link for (eg) `CSV` or `PDF` export and (eg) not for `XLS` is something you can specify when designing / creating a report. Though that yes or no then applies to anybody.

**Reports audience**:

The "audience" of reports can be however you want it to be, which is typically implemented using what's called report "categories". As an illustration (based on various reports delivered out-of-the-box):

* the Forena 'Sample' reports are a set of reports with a specific category (= 'Samples' also), for which Anonymous users are granted access also.
* the Forena 'Drupal Admin' reports is another set, with some other category, and which can only be accessed by users with role "admin". So if somebody installs Forena in some Drupal site, and they have the "admin" role, then they get access to all sorts of Drupal admin related reports (like watchdog reports) in their "own" environment. Some of those reports are:

+ **Active Users** \- A variation of D7's admin/people, including hyperlinks to the Logs for User report.
    + **Logs for User** \- Most recent watchdog log entries for a user (specified as a report parameter).
    + **Role Details** \- A table displaying all users for a Drupal role (specified as a report parameter), and the Drupal permissions granted to them, with for each user hyperlinks to either view or edit the user's profile.

**Disclosure**: I'm a (co-)maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.

---
Tags: importing-exporting
---


title: Rendering theme_item_list items

text:
# Question
Title: Rendering theme_item_list items
My module provides a simple block which needs to contain an unordered list with some images. From a block function, I am returning a renderable array:

```
$block['content'] = array(
    'list' => array(
        '#theme' => 'item_list',
        '#type' => 'ul',
        '#attributes' => array('class' => 'foo1'),
        '#items' => array(
          /* ...  what should go here? */
        ),
    ),
);

```

I would like to have some *renderable arrays* as items in the item list, but I seem to be unable to insert any arrays into the `#items` array.

The Drupal 7 theme\_item\_list API docs says:

> items: An array of items to be displayed in the list. If an item is a string, then it is used as is. If an item is an array, then the "data" element of the array is used as the contents of the list item. If an item is an array with a "children" element, those children are displayed in a nested list. All other elements are treated as attributes of the list item element.

I tried using both "data" and "children" elements, but I get either empty `<li>`'s or there is a word `Array` inside them.

**What is the proper way to do this?** Is theme\_item\_list the right/up-to-date solution?

# Answer
> 5 votes
Something like this:

```
foreach ($images as $image) {

  // New array for readability
  $options = array(
    'path' => $image->url,
    'alt' => $image->alt,
  );

  // Push the image tag onto the items array
  $block['content']['list']['#items'][] = theme('image', $options);
}

```

# Answer
> 4 votes
I ran into this exact same problem. From what I can tell reading the source code for `theme_item_list()` it can't use renderable arrays as items for the list. I ended up passing the renderable array with all the images to my own theme function to output the list. You can basically take your current code and change the `#theme` property to your custom theme function and add your renderable arrays as children of your `list` array. To make your function easier, you can add the `<li>` and `</li>` tags as `#prefix` and `#suffix` respectively to your image render arrays and call `drupal_render_children()` on your array, then you just wrap it in a `<ul>` and your good.

# Answer
> 0 votes
I'm using following code and it render's the list after an ajax call

```
$test = array("type"=>"ol","items"=>array('data'=>'1'),'attributes'=>array());
$commands[] = ajax_command_replace('#item-'.$ot->nid,theme_item_list($test));

```

main difference is the "#", if you read the code of the function at Drupal API function theme\_item\_list, you'll see there are no hashes for the variables

```
    function theme_item_list($variables) {
        $items = $variables ['items'];
        $title = $variables ['title'];
        $type = $variables ['type'];
        $attributes = $variables ['attributes'];
    ... }

```

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


# Question
Title: module_load_include fails on WebTestCase post
I am writing test cases for my website using SimpleTest module. One of my test cases uses the following sequence

```
    $this->drupalGet( "myurl" array('query' => $params));
    $this->assertFieldByName('giftaid_granted','', "Giftaid checkbox exists");

    // now we will also attempt to submit a form and check that it goes out
    $this->drupalPost(NULL, array(), t('Submit'));

```

When I run this code, I get an exception in the test

```
Fatal error: Call to undefined function module_load_include() in ...sites/all/modules/mymodule/includes/entities.inc on line 3

1   0.0001  235336  {main}( )   ../index.php:0
2   0.0023  660936  drupal_bootstrap( ) ../index.php:20
3   0.0025  678144  _drupal_bootstrap_page_cache( ) ../bootstrap.inc:2236
4   0.0029  757040  drupal_bootstrap( ) ../bootstrap.inc:2378
5   0.0044  1174072 _drupal_bootstrap_variables( )  ../bootstrap.inc:2244
6   0.0046  1199928 variable_initialize( )  ../bootstrap.inc:2480
7   0.0102  1626520 array_map ( )   ../bootstrap.inc:935
8   0.0102  1631120 unserialize ( ) ../bootstrap.inc:935
9   0.0102  1652040 spl_autoload_call ( )   ../bootstrap.inc:0
10  0.0102  1652112 drupal_autoload_class( )    ../bootstrap.inc:0
11  0.0102  1652376 _registry_check_code( ) ../bootstrap.inc:3107
12  0.0143  2484552 require_once( '...sites/all/modules/mymodule/includes/entities.inc' )   ../bootstrap.inc:3186

```

The offending line is apparently the `module_load_include('inc', 'mymodule', 'includes/shared');` on top of my `entities.inc` file.

As best I can guess from the trace, there is some sort of cached variable causing class autoloading in bootstrap, before `module_load_include` function is defined. But form submission on a normal page works just fine.

Am I using `module_load_include` incorrectly? Or is it some problem with the SimpleTest?

# Answer
> 0 votes
I figured it out for myself. This is an issue with SimpleTest. `DrupalWebTestCase` stores emails sent in the database, in a varialbe `drupal_test_email_collector`. If an email sent during a test case includes parameters, the parameters are saved. My parameters were classes. `bootstrap.inc` attempts to load and cache variables before modules are loaded. In restoring the emails with parameters, it was attempting to autoload the relevant class, and that was causing the crash.

This could happen, in principle, in other situations - any time a class got saved to a variable, though I have only encountered it with this test setup.

---
Tags: forms, testing
---


title: Periodically invoking modules

text:
# Question
Title: Periodically invoking modules
So I have the module import\_html and I'm trying to figure out if there is a way to periodically invoke it so that it imports new html files. Is there a way to periodically invoke modules with a script? I'm hoping someone can direct me to a good starting source as I am really new to Drupal.

# Answer
> 0 votes
The answer is yes. The import\_html module has a few tools available for this. You can:

1. Build a custom module that makes use of `hook_cron()` to trigger importing import functions in import\_html. This would be good for standard periodic import based on certain times of the day.
2. Utilize the module's Drush integration and use the `drush import-html` command inside a shell script that's executed with crontab. This would be good for periodic import as well as one time imports that you can do with the command line.

The module also has an API to take action upon various parts of its import process too if you need it (e.g. alerting site admins of new imported site content).

As a starting point, you should review the documentation on the project page. It has a help document that walks you through the usage of the module. If #1 is your preferred goal, you'll want to get familiar with the Drupal API, so you can understand how to create modules and understand the code of import\_html module. For #2, you'll need to install Drush, learn how to use the `drush import-html`, and write out a shell script.

---
Tags: 7, importing-exporting
---


# Question
Title: How can I put the feed import page on a different page and not have it on the node add page?
I want the user to be able to either add a new asset by using node/add or import a CSV, but on different pages. Right now both options come out on the add page.

How can I put the feed import page on a different page and not have it on the node add page?

# Answer
> 2 votes
There is an option on the Feeds importer edit page that lets you toggle off the form on the node add page. Just select the *Use standalone form* option on the **Attach to content type** setting.

---
Tags: feeds
---


# Question
Title: View of users-profile who had flagged me "subscribe"
Using Drupal7 Views 3 and Flag 3, I have been able to display users-profile I have flagged "subscribe" but no luck to display users-profiles that flagged me "subscribe".

Below is what I currently have but the result is still displaying users that the given url has flagged.

I used filter"user ID from url" and for relationships, I used "flags:subscribe(by any user) and checked/unchecked include only flagged content.

Please help.

# Answer
I have cracked it!

1. **First add relationship**
    * Flags:User's flaggings
        + Check Include only users who have flagged content.
        + Pick your flag type (in my case "subscribe")
2. **Second add relationship**
    * Flags:User
        + relationship remains the same(user flagged content).
3. **Third add Contextual filters**
    * Flags:Entity ID
        + relationship remains the same(user flagged content)
        + provide default value (User ID from URL)
        + specify validation criteria (validator-user) in my case i have usernames (Allow both numeric UIDs and string usernames)
4. **Fourth add filter criteria**
    * Flags:User uid
        + relationship remains the same(user flagged content).
        + operator(tick "Is not empty (NOT NULL)") do not insert a username.

Save your view.
> 0 votes

# Answer
1. Create view with type "User"
2. Add Relationships "Flags: User's flaggings". Choose your flag name and set checkbox "Include only users who have flagged content."
3. Add Contextual filter "Flags: Entity ID". Choose in the filter settings "Provide default value" -\> "User ID from URL"
> 1 votes

# Answer
I assume you named your flag `subscribe`. Create a view of type `USERS`, Add the `USER` as Fields and In the Relationships add

```
Flags: subscribe (by current user)

```

Then the users subscribed will be shown. I used this method to follow users like what Instagram does. I mean your configuration should be like this (Instead of Follow select your flag):
> 0 votes

---
Tags: views, flags
---


title: Creating RSS feeds for individual nodes

text:
# Question
Title: Creating RSS feeds for individual nodes
Is there any way to have rss feeds for individual nodes, taxonomies and so on.Right now we have rss feed for the entire website.

for example : I'd like to access a node feed through http://www.musite.com/node/1.xml

# Answer
Yes. Using Views you can add a *Feed* display, with a path that contains a with a wildcard component (e.g. **/rss/%/feed**), & *Content: Nid* for a contextual filter. This will create a path that will have an RSS feed for each nid (e.g. http://www.example.com/rss/1/feed. http://www.example.com/rss/2/feed, etc.).
> 0 votes

---
Tags: feeds
---


# Question
Title: Limit number of event registrations per month
I'm creating a membership-based site in D7, using Date, Calendar, and Entity Registration (which was very easy to setup). Only authenticated users may register for an event.

I'm trying to limit the number of events an authenticated user may register for during a certain time period (probably by month or by quarter), and I'm stuck. I created a field called 'Registration Count' for user accounts. And I created a rule that increments the counter when the user registers for an event.

But I'm trying to figure out:

1. How do I prevent a registration based on the user's current registration count? I got as far as creating a rule that is triggered prior to a registration and checked his current registration count. And I can display a warning, but the registration still goes through. Isn't there an action I can assign that would halt the registration?
2. How can I reset the registration counter field for all user accounts back to zero at a certain interval? I can't find access to user fields on that broad level.

---

Adding more details:

I have a node type called "Event". My registrations are entities. This is out-of-the-box functionality for the Entity Registration module, and it was very simple to get it up and running.

Each user has a field called field-registration-count. When a user registers for an event, I have a rule set up as follows:

1. Event: After saving a new registration
2. Action: Set value site:current-user:field-registration-count, add offset 1. This increments the user's registration count by 1.

I have another rule:

1. Event: Before saving a registration
2. Condition: site:current-user:field-registration-count \> 2
3. Actions: Page redirect, and then Show a Message on Site

On the third registration, the page redirect happens as expected, and the message is displayed, but the registration is still saved. Based on the provided event named "Before Registration", I think I'm tapping in a the right time; I just can't find an action to cancel the registration itself

**Note:** When a user actually registers, it doesn't create a node. The Entity Registration module creates an entity type instead, and each registration is an entity.

# Answer
# Action to halt registration

Use "Page redirect", with a value for "URL" that could be either one of these:

* some special node that you want to display to inform the user that the maximum number of events was reached.
* the same URL that the user uses to add the event, combined with "Show a message on the site" whereas the message content provides appropriate information to the user that the maximum number of events was reached.

If that doesn't help/work, then you may want to try a variation of my answer to the question about How to restrict access to a node via node/12 and allow access via a path like content/sometitle? (that question was about "Node is '*going*' to be viewed, while yours is about something like "entity is '*going*' to be created").

# Reset registration counter

Similar to the "Registration Count" field that you added, add another field like "Count start date". And each time a user tries to create a new event, just use that "Count start date" to compare it with the "current date": if then the time span between those 2 dates is longer then that "certain interval", then reset the "Registration Count" to zero.
> 1 votes

---
Tags: 7, rules, datetime
---


title: Page layout - removing footer

text:
# Question
Title: Page layout - removing footer
How do I remove the grey footer on my site? It's using the Bartik theme.

# Answer
The footer is hardcoded, especially Bartik. It's a default theme of Drupal.

1. You can alter the color of the footer under admin/appearance/settings/bartik
2. Make a subtheme and alter the css
3. Or, for minor changes, use the module CSS injector
> 1 votes

---
Tags: 8, theming
---


title: How to show logout link in drupal

text:
# Question
Title: How to show logout link in drupal
I have created a user account. Then signed out of admin and logged in with the new user account. But the new account does not have a logout link, So how can i show it to the other users ?

# Answer
Create a link to `user/logout`. It can be a menu item or an HTML link in a block.
> 10 votes

# Answer
The logout link is included in the user menu that is standard to drupal.

Make sure the equivalent user menu block is active in an appropriate region and you will have your logout link
> 2 votes

# Answer
Step by step instructions:

In the view that you want to add 'logout' link

1. Add new field
2. Select 'Global: Custom Text'
3. Uncheck 'Create a label'
4. In textarea put: 'Logout'
5. Click 'Rewrite Results'
6. Check 'Output this field as a link'
7. Link path: 'user/logout'
8. Save

That's it.
> 1 votes

# Answer
For this you have to follow the following Steps: --Login with Admin --Go to the option of People --Now you have to click on "permissions" option --Here a list of various permissions is open --Now search "Toolbar" where you have to tick on the option of "Use the administration toolbar" for authenticated user --Just save it and it done.
> 1 votes

---
Tags: 7
---


# Question
Title: Views Entity reference (user): how to show profile values of respective user only
i have a rather complex view and have troubles with showing the correct values. im trying to focus on the main issue.

there is a node (team) with entity reference fields to multiple users. the node has for instance two referenced user (UID 80 with 56 points on his profile, UID 23 with 23 points). now, my problem is that i cant get the view to show the correct values (points) of the respective user only. i have installed the views distinct module, but i still cant get the correct values.

what i would need is something like this:

user / points

80 / 56

23 /23

what it does is now is that it shows the values of all users that are referenced (without the views distinct module). with the views distinct module enabled it shows sometimes the values of the first user, sometimes the values of the second - but it does not show the correct values.

i hope this makes some sense. if not, i can post the whole view, but its rather complex.

# Answer
came up with a solution that works for me. first, ive added to the view the username field for the referenced users. this outputs the (two) different usernames of the people who are referenced.

second, ive added a global field as **a filter** called "Global: Fields comparison" that compares the name of the team\_member with the name of the referenced user. now this shows only one correct entry.

hope this helps someone.
> 0 votes

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


# Question
Title: Drupal 8 - url rewrite don't work on beta12 after installation
I don't have this problem on Drupal Beta 11, but with Beta 12, after installation, urls don't work, example :

**The requested URL /Beta12/admin/structure was not found on this server.**

Why I have this bug please ? It's a Drupal 12 problem ? Thanks.

# Answer
Last Drupal 8 Beta release don't have .htaccess.
> 0 votes

---
Tags: 8
---


# Question
Title: Get User ID from a Profile Page to use in a View
I'm creating Views blocks on profile pages such as drupalsite.com/users/testuser. I need to display blocks such as "Test User's Posts" and "Test User's comments." What is the best way to get the User ID of the profile pages' subject in order to filter the content based on this User ID?

# Answer
> 1 votes
In this case, `/user/testuser` is just an alias of `/user/n` where n is the user ID. Which means the user ID is available in the unaliased URL, allowing you to do this.

---
Tags: views, users
---


# Question
Title: How to restrict access to a node via node/12 and allow access via a path like content/sometitle?
**Problem**: I want to restrict direct node access using node number `www.example.com/node/12` and allow access using pathauto alias `www.example.com/content/sometitle` to anonymous user. This user should be allowed to see all content of node using only Pathauto title path but not with node number to snoof.

Mostly I want to target anonymous users. Admin always has access to everything.

In simple terms, I want to redirect all **node/Number path**s (not **node/add/ContentType**) to say the *Home page* or *No Access* page.

# Answer
> 7 votes
The Global Redirect module does what you want (and more).

> ... Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method.

**It redirects the node/xx to content/your-content etc if clean URLs feature is enabled.**

# Answer
> 5 votes
# Option 1: Using the Rules module

Using the Rules module you can implement a rule that looks similar to this:

```
{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

```

The above rule does not (yet) take into account to only apply the "action" for anonymous users only. But for anybody a bit familiar with the Rules module, that is a straight forward "Condition" to add ...

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function. Then further edit/refine to make it fit in your own environment (e.g the "Sorry, ..." message to be shown).

# Option 2: Using theRabbit Hole module

Consider using the Rabbit Hole module. Here is an excerpt from its project page:

> ... providing multiple options to control what should happen when the entity is being viewed at its own page. You have the ability to
>
> * Deliver an access denied page.
> * Deliver a page not found page.
> * Issue a page redirect to any path or external url.
> * Or simply display the entity (regular behavior).
>
> This is configurable per bundle and per entity. There is also a permission that lets certain roles override Rabbit Hole completely.

# Advice:

From both options provide above, I'd pick the Rules based solution ... Either because you might already have Rules installed, or if you have to still install it you'll discover tons of other use case to also be resolved by the same Rules module (possibly complemented with the Flag module soon ...)

# Answer
> 4 votes
You can by pass Drupal altogether with an Apache mod\_rewrite rule. Place this in your root **.htaccess** file in between the `<IfModule mod_rewrite.c>` directive.

```
RewriteRule ^node/([0-9]+)$ / [R=301,L]

```

It will redirect all www.example.com/node/\* to www.example.com. If you're want to redirect to another path, append it the single "/" character.

---
Tags: nodes, users, redirection, uri
---


# Question
Title: How can I set a flag to be flagged unlimited number of times?
I have a flag on a node that anyone can flag. The flag is tied to a Rule that executes an action. Essentially I need to be able to allow any user to flag a node as many times as they wish and track the flag count.

The problem: It appears that with the Flag module, the flag needs to be unflagged for the user to be able to flag it again. This essentially makes the flag count pointless as they are adding, removing and re-adding the same flag over and over.

# Answer
As Triskelion mentioned, the Flag module might be the wrong tool for your use case. Despite that, if you're looking to allow multiple flagging (instead a flag/unflag toggle) you can add a *Unflag a Node* action (or whatever your flagged entity is) to the other action you have on a flag event.
> 0 votes

---
Tags: flags
---


# Question
Title: Why is 'Confirm Order' pane being skipped?
I’m trying to determine why the ‘Confirm Order’ pane is being skipped in my Drupal Commerce Kickstart website.

Configuring the checkout process is here.

admin/commerce/config/checkout

In the configuration settings i’ve set

‘Display this pane in a non-collapsible fieldset.’

i’ve also checked boxes of info to be displayed in the pane, such as Shipping service.

Anyone know why it is being skipped? and how to fix? this seems like a bug

# Answer
> 1 votes
This checkout pane / page is added by the PayPal Express Checkout module. PayPal EC has a step where you return from PayPal after authorizing payment to finalize the order, including taxes, shipping selection, coupon entering, etc. For other payment methods, this page is skipped.

---
Tags: commerce
---


# Question
Title: Making both Site name & Site slogan to be one single link in mini-panels
I use the **Mini Panels** module and have created an header with both **Page elements** "Site name" & "Site slogan".

The Site name (H1) is a clickable link that leads to the home page, but the site slogan (H2) is just a text that links nowhere.

Can I make both of them a single link to the homepage (but still keep them different elements with different CSS, etc)?

# Answer
> 1 votes
I see three options that I think you could do.

1. Update the content in the theme layer which you can try to check in this page and it's other related pages. https://www.drupal.org/node/1678810
2. Use panel pane hooks to add additional settings for the *Site Slogan* panel pane.
3. Create a custom panel pane

---
Tags: navigation, panels
---


# Question
Title: path issue with translated (entity_translation) nodes
I use Drupal 7, entity\_translation and pathauto with 2 languages: `EN`, `FR`.

I create a new content (of a content type with "entity translation") and I title it "test". Since `Generate automatic URL alias` is enabled, the URL `/test` displays the content.

I then translate this to French and submit.

On the sidebar I have a language selector which for `FR` links to `/fr/node/1`.

How is it possible to automatically make it link to `/fr/test`? The only way to solve this is by manually typing `test` in the alias of the French translated content. Why isn't `pathauto` working in the translations of the node?

# Answer
> 2 votes
Entity Translation `7.x-1.x-dev` solves this.

Hint provided in the Packt Drupal-7-Multilingual-Sites book:

> Pathauto works fine for nodes using the node translation model as each language has a separate node. At the time of writing, for feld translation, the Pathauto and Entity Translation module maintainers have been ironing out some issues. To get the automatic URL aliases to work in Drupal 7 for feld-translated nodes, you must use at least Entity Translation version 7.x-1.0-alpha2, if available, or the most recent dev version.

# Answer
> 2 votes
Latest dev version of entity translation didn't change anything so we solved it by changing line 1959 in entity\_translation.module

```
if ($context['op'] == 'bulkupdate' && !empty($info[$entity_type]['token type']) && !empty($context['data'][$info[$entity_type]['token type']])) {

```

to

```
if (($context['op'] == 'update' || $context['op'] == 'bulkupdate') && !empty($info[$entity_type]['token type']) && !empty($context['data'][$info[$entity_type]['token type']])) {

```

This way pathauto\_create\_alias() is fired also when updating/creating content.

# Answer
> 1 votes
You can use the Synchronize Translation Paths module.

Without it, URL path aliases are not synchronized across translations. When translations are saved, the URL path alias is assigned to the corresponding language, thereby eliminating any language-neutral aliases in the database. So if you surf to a different language, there won't be any alias set unless you go and add them from the UI or DB client.

# Answer
> 0 votes
Entity Translation `7.x-1.x-dev` does not solve this for me.

I had to implement next hooks as a workaround:

```
/**
 * Implements hook_url_inbound_alter().
 *
 * Resolves alias if the content is not translated.
 */
function MYMODULE_url_inbound_alter(&$path, $original_path, $path_language) {
  // Check if no url alias has not been found for incoming path.
  if ($path && $path == $original_path) {
    // Resolve alias if the content is not translated to current language. Get
    // alias of existing translation.
    foreach (array_keys(language_list()) as $language) {
      if ($source = drupal_lookup_path('source', $path, $language)) {
        // Check if we are at the document page.
        if (strpos($source, 'node/') === 0) {
          $path = $source;
          break;
        }
      }
    }
  }
}

/**
 * Implements hook_url_outbound_alter().
 *
 * Resolves alias from node language if the content is not translated.
 */
function MYMODULE_url_outbound_alter(&$path, &$options, $original_path) {
  if (preg_match('/^node\/\d+$/', $path) && $node = menu_get_object('node', 1, $path)) {
    if ($alias = drupal_get_path_alias($path, $node->language)) {
      $path = $alias;
    }
  }
}

```

---
Tags: 7, path-aliases, uri, i18n-l10n
---


title: Dynamically add options for widget

text:
# Question
Title: Dynamically add options for widget
I'm developing a field widget for Drupal 8, similar to 'select' but with more functionality. Since the number of options is large and should be determined after querying an external API I was planning to retrieve options from ajax calls.

However AJAX - How to dynamically add options to select? states that it's not possible. What will be the possible workarounds or solutions?

# Answer
> 0 votes
The solution I used is below for anybody else who might have similar questions.

You can use the **autocomplete\_route\_name** property to get the options for autocompletion.

```
$element += array(
    '#type' => 'textfield',
    '#default_value' => $items[$delta]->value ?: NULL,
    '#autocomplete_route_name' => 'example.myroute',    //your route name
    '#placeholder' => $this->getSetting('placeholder'),
);

```

The route should be defined in your *module\_name*.routing.yml file

```
example.myroute:
    path: <url>
    defaults:
      _controller: <controller>::<method>
    requirements:
      _permission: <permission>

```

Hope this helps :)

---
Tags: ajax, 8, entities
---


# Question
Title: How to get varchar type input from users on my website?
I want to add a field to get a bank account, swift code, card no and IBAN type values from users on my Drupal 7 website.

These fields require a mix of numbers, alphabetical characters and "-".

How can I get this type of info from users?

**Note**: Core Text field is not sufficient to get varchar type input from users.

# Answer
# Use the Custom Formatters module

Consider using the Custom Formatters module, which is very easy to use and configure. And it integrates with various other modules.

Here is an excerpt from its project page:

> ... allows users to easily create custom Field Formatters without the need to write a custom module.
>
> * Pluggable editor/renderer engines:
>
> + Formatter preset: Create simple formatters from existing formatters with preset formatter settings.
>     + HTML + Tokens: A HTML based editor with Token support.
>     + PHP: A PHP based editor with support for multiple fields and multiple values.
>     + Twig: A Twig based editor provided by the Twig filter module.
> * Supports for all fieldable entities, including but not limited to:
>
> + Drupal core - Comment, Node, Taxonomy term and User entities.
>     + Field collection module - Field-collection item entity.
>     + Media module - Media entity.

The Community Documentation for this module seems to only be a placefholder for now (which is also where the *Read documentation* links to on the module's Project page).

However there are a few other resources about it that are worth checking out:

# Create your custom module

Here are some tutorials about how to solve your question using a custom module (all for D7):
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Create custom entity type programmatically
maybe my title is not correct but I have written a module that creates a new entity. Now I would like to create a few of these entities on hook\_install. I can create a new entity, that's not the problem, but I cannot create the entity types.

This is my code I use to create a new entity:

```
/**
 * Implements hook_install()
 */
function skilt_badge_install(){
  $entity = entity_create('skilt_badge', array('type' =>'test'));
  $entity->title = "Testtitle";
  $entity->description = "Testdescription";
  $entity->save();
}

```

Now, when I create a new **Skilt badge type** with the machine name "test" in the drupal interface it works. But first I would like to know how I create the **Skilt badge type** programmatically.

I've tried something like this first, thinking the type is also an entity:

```
/**
 * Implements hook_install()
 */
function skilt_badge_install(){
  $entity = entity_create('skilt_badge_type');
  $entity->title = "Testtitle";
  $entity->description = "Testdescription";
  $entity->save();
}

```

But that didn't really work because entity create requires a type...

Could you guys help me?

# Answer
As some have commented, Entities are VERY complicated. The reason your code is not working is because entity\_create() is used to create an **INSTANCE** of an entity of an already defined ***entity type***. What you are doing in the UI creates the entity type.

You must first create your entity type in your module before you can create an instance of that entity. Refer to the links in the comments above on how to do this. And get ready to spend a little time if this is your first time doing this -I assume it is.
> 1 votes

---
Tags: entities
---


# Question
Title: Possible to add a organic group role programmatically?
Im trying to programmatically add OG group roles and assign permissions through an update hook. Is this possible?

# Answer
It seems that hook\_og\_default\_roles() will only **assign** the role to new group members. The role must first exist in the roles table. You can do this by creating it in the OG UI or by using og\_role\_create() and og\_role\_save () as above.
> 1 votes

# Answer
If you just want to add a role, the recommended way is through hook\_og\_default\_roles(). This will add the og role when the module is enabled.

If you have to add it in an update or only when a certain condition is met, then you can use the API function og\_role\_create() (using only the first parameter) and og\_role\_save().

Permissions can be created through hook\_og\_permission() and granted to the role with og\_role\_grant\_permissions().
> 0 votes

---
Tags: organic-groups, users
---


# Question
Title: How to display an image from theme directory to a drupal block by php code?
I want to load an image from my theme directory inside a block. I am using the following code:

```
<img src="<?php print $base_path .$directory; ?>/images/oil-ad.png" alt=''oil ad">.

```

But it is not working. However I have enabled PHP Filter and php text format.

# Answer
In your image "alt" attribute, you have 2 single quotes before ***oil ad*** and a single quotation mark following it. That syntax doesn't look right to me. Maybe THAT is causing some error somehow? If not then read on below for further narrowing down your issue.

Assume you used admin/structure/block/add to create that block, with a "body" in which you added that `img` tag.

When doing so, you also need to select the "*text format*" (below the body) to be used. You wrote you used "php text format", though I'm assuming you mean "test format"="PHP code".

To further ivestigate where your problem is actually coming from, try to further narrow down your issue. By FIRST creating such image tag without using any PHP code. And instead use some text format like 'Full HTML' and/or 'Filtered HTML', something like so (I intentionally did not correct the syntax of the alt attribute, because that might produce the error you're searching for ...):

```
<img src="/some/path/that/is/hardcoded/images/oil-ad.png" alt=''oil ad">.

```

If that works then have a confirmation that your issue is NOT because of some text format configuration issue related to using the "img" tag.
> 0 votes

---
Tags: theming
---


# Question
Title: How to configure URL paths using the pathauto module for multilingual sites?
I am working on multilingual drupal website.To generate content path(i.e url) I am using pathauto module. I have not configured this module.

When I add content from basic page it sets **content/\[node:title\]** as url path seetings. It is fine for english language. But for other language content I want to set url same as english content.

What path pattern I have to set so that url path for nepali content is same as english content ?

Any help is welcome!

# Answer
Consider using the Pathauto i18n module for this. Excerpt from its project page:

> ... by default Pathauto creates alias only for one language or for all languages one alias. This module provides functionality to create aliases for each language. Also this module will be helpful, if you use field translation and you want show node on all language with paths, different from node/nid.

This module contains 3 submodules which can be used to enable separate functionality for each entity:

* pathauto\_i18n\_node (for nodes).
* pathauto\_i18n\_user (for users).
* pathauto\_i18n\_taxonomy (for taxonomy).

# Example (also from project page):

When you create node without pathauto\_i18n:

* English alias: en/articles/first\_article
* Italiano alias: not exist
* Deutsche alias: not exist

When you create node with pathauto\_i18n:

* English alias: en/articles/first\_article
* Italiano alias: it/articolo/first\_article
* Deutsche alias: de/artikel/first\_article
> 1 votes

---
Tags: i18n-l10n, path-aliases
---


# Question
Title: Downloading custom module with drush make
I am trying to download a custom module from a private repo using drush make. This is the make file:

```
core = 7.x
api = 2
projects[cs_all][type] = "module"
projects[cs_all][subdir] = "contrib"
projects[cs_all][download][url] = "git@bitbucket.org:myrepo/cs_all.git"
projects[cs_all][download][branch] = "master"

```

I run the following command:

```
drush -d make --no-cache --no-core my.make build

```

The output is as follows:

```
Starting Drush preflight. [0.46 sec, 2 MB] [preflight]
Cache HIT cid: 7.0.0-commandfiles-0-4ea41d3d78dd4cb8ebf6ca2ee09bd808 [0.61 sec, 2.05 MB] [debug]
Bootstrap to phase 0. [3.31 sec, 8.02 MB] [bootstrap]
Bootstrap to phase -1. [3.35 sec, 8.03 MB][bootstrap]
Found command: make (commandfile=make) [3.36 sec, 8.03 MB] [bootstrap]
Bootstrap to phase -1. [3.36 sec, 8.03 MB][bootstrap]
Loading release_info engine. [3.38 sec, 8.03 MB][notice]
Calling hook drush_make_validate [3.42 sec, 8.23 MB][debug]
Returned from hook drush_make_validate [3.42 sec, 8.23 MB][debug]
Calling hook drush_make_pre_make [3.42 sec, 8.24 MB][debug]
Returned from hook drush_make_pre_make [3.43 sec, 8.24 MB][debug]
Calling hook drush_make [3.43 sec, 8.25 MB][debug]
Beginning to build my.make. [3.44 sec, 8.27 MB] [ok]
Downloading release history from https://updates.drupal.org/release-history/cs_all/7.x [3.45 sec, 8.35 MB] [notice]
c:/Users/myname/.drush/cache/download/https---updates.drupal.org-release-history-cs_all-7.x retrieved from[notice]
cache. [3.45 sec, 8.35 MB]
No release history was found for the requested project (cs_all). [3.46 sec, 8.36 MB][error]
Returned from hook drush_make [3.46 sec, 8.35 MB][debug]
Command dispatch complete [3.46 sec, 8.32 MB]

```

Basically drush looks for the module release history file on drupal.org.

I have not found any specific documentation regarding downloading from private repos. However various snippets taken from presentations show the same make parameters that I have used.

I am using drush 7.0.0., php 5.5.26 and Windows 7.

How to fix the issue?

# Answer
> 0 votes
Add a line to the make file to make it look like so:

```
core = 7.x
api = 2
projects[cs_all][type] = "module"
projects[cs_all][subdir] = "contrib"
projects[cs_all][download][url] = "git@bitbucket.org:myrepo/cs_all.git"
projects[cs_all][download][type] = "git"
projects[cs_all][download][branch] = "master"

```

So add the line to indicate 'type = git' . That would make it look closer to what is documented on https://www.drupal.org/node/1432374 ...

Curious to hear what results you'd get then.

# Answer
> 0 votes
On my work I use private repo with custom modules and profiles, and works out of the box

Do you use a different ssh to access to your private repo?

And try to use drush cc drush just in case you have a corrupted files on your drush cache

---
Tags: drush
---


# Question
Title: Embedding a custom form in node.tpl.php does not trigger validation
I'm trying to render a custom form in `node.tpl.php`.

The form is rendered properly and submit handler works.
However, the validation handler is not triggered properly upon submitting. If I refresh the page, the error message is only then displayed.

Here's the sample module code:

```
function sample_custom_form() {
  $form['sample_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Enter something'),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function sample_custom_form_validate(&$form, &$form_state) {
  if ($form_state['values']['sample_field'] == 'error') {
    form_set_error('sample_field', t('This is a validation error'));
  }
}

function sample_custom_form_submit(&$form, &$form_state) {
  drupal_set_message(t('You entered: @value', array('@value' => $form_state['values']['sample_field'])));
}

```

In `hook_preprocess_node()`:

```
$form = drupal_get_form('sample_custom_form');
$variables['custom_form'] = drupal_render($form);

```

In `node.tpl.php`:

```
<?php print $custom_form; ?>

```

Any ideas what am I doing wrong?
Why isn't the validation handler invoked properly?

# Answer
*$form\_state\['values'\]\['sample\_field'\]* this value is set after submit, so you validate the old result instead of your actual form.

maybe this workflow helps you
> 0 votes

---
Tags: 7, forms
---


title: Off canvas menu for drupal 6

text:
# Question
Title: Off canvas menu for drupal 6
Are there any modules for Drupal 6 that provide an off-canvas menu? My site has mobile users and I want to hide the navigation bar when they view it. I want something like this:

I have searched both Drupal's contributed modules and themes and drupal.SE with no luck: I haven't been able to find any modules or themes with this feature for Drupal 6.

# Answer
# Bootstrap theme

There is the Bootstrap base theme for D7 (and even an upcoming D8 version), which bridges the gap between Drupal and the Bootstrap Framework, with also quite a few (contributed) sub-themes available for it already.

But your question is about D6, for which there is "some" D6 backport of it available on github ... Via Drupal.org there doesn't seem to be any D6 versions, however there "is" some D5 version of it also ... Maybe upgrading the D5 version to D6 is another approach to consider?

# Fluid Baseline Grid theme

According to issue #1855478 the Fluid Baseline Grid is the *Best responsive theme for Drupal 6* ...
> 0 votes

---
Tags: 6, routes, navigation
---


title: views project management module

text:
# Question
Title: views project management module
I'm having a hard time understanding Views and Entity Reference in the context of the Project Management modules.

I have created Project and Task Content types. For each of the Tasks I have chosen a Parent Project. I installed PM Gantt, but it does not list more than one project. I am trying to create a view to simply list all projects followed by that project's associated tasks, if any. Some projects will not have tasks.

How can I do this?

# Answer
> 0 votes
Problem solved!

In Format/Settings set Grouping Field 1 to Parent.

---
Tags: views
---


# Question
Title: Simple click alternative to Draggable views?
I'm trying to find an alternative solution to the Draggable views module. But instead of **dragging** the rows, you just **click** some simple **up and down arrows** once, and you click any of them to reorder them.

Any suggestions?

# Answer
> 2 votes
The standard ordering for lists of nodes or entities in Drupal is first by the "sticky" attribute and then by the created date. Many content modules have some facility to change this ordering, but only for their content type. The modules described in the Community documentation about Comparison of node ordering modules attempt to provide a more controllable ordering in a variety of ways.

Here is the list of modules mentioned in that documentation (quotes are from their project pages):

* Outline Designer:

> ... is a user experience module that makes book management more intuitive. Essentially it overlays on the admin book outline page so that you can use AJAX to build and edit site outlines much faster then Drupal traditionally allows.
* Weight:

> ... adds a weight option to enabled node types. Nodes with lower weight will float to the top of lists, while heavier items will sink.
* Nodeorder:

> ... gives users an easy way to order nodes within their taxonomy terms.
>
> By default, the taxonomy module orders listings of nodes by stickiness and then by node creation date -- most recently posted nodes come first.
>
> The nodeorder module gives the user the ability to manually put nodes in any order they wish within each category that the node lives.
* Nodequeue:

> ... allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:
>
> + A block listing teasers for the five top news stories on a site
>     + A user’s favorite music albums
>     + A group of favorite from which one is randomly displayed
* DraggableViews:

> Have you ever rearranged Blocks?, sorted Taxonomy terms? or reordered Menu items at the Drupal administration pages? All these pages use the tabledrag.js javascript that enables Drag'n Drop on HTML-tables.
>
> With DraggableViews you can apply this tabledrag.js to any Views-generated table.
* Flag Weights:

> ... very simple module that adds a 'weight' field to the tables already used by the excellent Flag module.
>
> This weight can then be used to provide ordering of flagged items. This module also provides a Views field which can be used to sort flagged items. One interesting use of this ability is to integrate with Draggable Views to create a user-sortable list of flagged items.
* Sortable Grid Views Plugin:

> ... provides a Views plugin for the user to be able to show a grid composed of draggable elements and save the displayed order of these element.
>
> The user may then create other displays to show the elements in the order defined above.
>
> This project is very similar in its goals to Draggable Views, yet a lot simpler as there is no hierarchy management. It doesn't depend on Draggable Views though.
>
> The added value resides in the presentation, a grid rather than a table list, and the therefore possible uses which Draggable Views doesn't permit.
* JQGRID - View integration:

> ... provides views integration for the jqGRid jQuery plugin, which provides advanced interaction controls to HTML tables such as dynamic pagination, on-the-fly filtering, and column sorting.
>
> For full documentation and examples, visit the jqGRid jQuery plugin page
* Nodeflow:

> ... gives a drag and drop interface for publishing nodes and positioning them in your desired order. This is useful for large publishing sites where editors can get a bird's eye view of all nodes currently on the frontpage and all nodes waiting to be published. A drag and drop interface helps to publish nodes quickly into desired positions.
* Queues:

> + Adds new Queues entity
>     + Revisionable
>     + Support multiple Bundles
>     + Support reference to any Entity/Bundle
>     + Full State Machine Support (Queues Workbench)
>     + Supports Revision Scheduler Module (Queues Workbench)
>     + Revision Revert Operation
>     + Revision Delete Operation
>     + Revision Publish Operation (Queues Workbenc integration)
>     + Revision Unpublish Operation (Queues Workbenc integration)

---
Tags: ajax, views
---


# Question
Title: File save upload doesn't replace existing file despite FILE_EXISTS_REPLACE
I'm trying to force replacement of existing file with same name, if a new version is uploaded by user. I've seen a lot of posts about this topic but none that I could find addresses how to force the replacement.

I'm using a custom form, and here's the code I've been trying to make work during the form validation:

```
  $file = file_save_upload(
      'file',
      array(
        'file_validate_is_document' => array(), // Validates file is really a document.
        'file_validate_extensions' => array('pdf doc ppt pps avi mpg mov wmv'), // Validate extensions.
      ),
      'public://',
      FILE_EXISTS_REPLACE
  );

```

The revised file (let's say "file.jpg") is uploaded, but inevitably Drupal creates a new copy and renames it file\_0.jpg, file\_1.jpg, etc for each new version.

I even tried to programmatically delete the original file using "file\_delete" prior to committing the upload but I still get the copy!

Any help would be appreciated.

# Answer
> 5 votes
This is drupal's default behaviour and a known issue. It has been addressed a couple of ways.

The Upload File Replace module addresses this issue by swapping the filenames so the new file retains the original name.

The Media Update module allows in situ replacement of media files (part of the Media project).

You could either make use of one of these modules, or use them as a model for your own function.

# Answer
> 0 votes
I managed to make it work using the following code.

```
$file = file_save_upload('file', $validators);
// If the file passed validation:
if ($file) {
    // I PLACED IT IN THE NEXT LINE
    if ($file = file_move($file, 'public://', FILE_EXISTS_REPLACE)) {
        // Save the file for use in the submit handler.
        $form_state['storage']['file'] = $file;
    } else {
        form_set_error('file', t('Failed to write the uploaded file to the site\'s file folder.'));
    }
} else {
    form_set_error('file', t('No file was uploaded.'));
}

```

# Answer
> -1 votes
```
$file_temp = file_save_data($attachment->data, 'public://<my_files_locatioin>/<my-filename.pdf>' , FILE_EXISTS_REPLACE);

```

---
Tags: 7, forms, files
---


title: How does drupal send emails by default?

text:
# Question
Title: How does drupal send emails by default?
I have a site working on drupal 6 , and i uses drupal's default email function `drupal_mail()` to send emails , but unfortunately its not sending email and gives me `"email not send , please contact site administrator"` error , is there any smtp settings i need to include ?

When i tried like follows :

```
$to = "test@example.com"; // to e-mail address
$from = "test@example.com"; // from e-mail address
$subject = "text to display in e-mail subject"; // subject of e-mail
$body = "text to display in e-mail body";
//params is the array passed to hook_mail function
$params = array(
    'subject' => $subject,
    'body' => $body,
    );

if(drupal_mail('test', 'information', $to, language_default(), $params, $from)){
     echo "mail send successfully";
}

```

it gives me `mail send successfully` message but mail is not delivered .

# Answer
Next to drupal\_mail you also need https://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook\_mail/6 to send the mails.

This hooks tells Drupal what to do with 'params'. $params\['body'\] does not automaticaly becomes the body.

From the example module:

```
function email_example_mail($key, &$message, $params) {
  global $user;

  // Each message is associated with a language, which may or may not be the
  // current user's selected language, depending on the type of e-mail being
  // sent. This $language variable is used later in the t() calls for subject
  // and body to ensure the proper translation takes effect.
  $language = $message['language'];

  switch ($key) {
    // Send a simple message from the contact form.
    case 'contact_message':
      $message['subject'] = t('E-mail sent from @site-name', array('@site-name' => variable_get('site_name', 'Drupal')), $language->language);
      // Note that the message body is an array, not a string.
      $message['body'][] = t('@name sent you the following message:', array('@name' => $user->name), $language->language);
      // Because this is just user-entered text, we do not need to translate it.
      $message['body'][] = $params['message'];
      break;
  }
}

```

Take extra notice the body is an array! Edit: some clarification: The subject of the message is a string, like you would expect. So you can fill the subject line like this:

```
$message['subject'] = 'Any string, with '. $param['subject'] .  ' or not.';

```

The body however is not a string, and can not be filled this way. It's an array of strings. The very least you need one part. e.g.:

```
$message['body'][] = $params['body'];

```

In the end, Drupal wil implode the array to one big string.

Putting the body in parts allows for other modules to use hook\_mail\_alter, to change only parts of the e-mail, e.g. only the heading of the message.

/end edit

However, without this hook your mail should have been sent. But it is very likely it was blocked by a spam filter (empty body and empty subject from, probably, an unauthorized source).
> 0 votes

---
Tags: 6, emails
---


title: One page website with Drupal 7

text:
# Question
Title: One page website with Drupal 7
I saw many personal or company websites with one-page website style. the one-page design is very good for giving as quick as possible all information that you have without letting users click around to find out who are you and I really want to apply them in Drupal. I also tried to implement one-page website by using the single page website module (http://drupal.org/project/single\_page\_website) and it's quite nice for the simple pages. So my questions are:

1. Which is the best way for making one-page design: create one-page templates or using contributed modules?
2. The advantages and disadvantages for Drupal to make one-page design?

I haven't done any one-page design before so can someone give me the right direction for that.

# Answer
> 3 votes
Well if you want ideas for one page websites you can look here for some awesome one page websites. onepagelove.com

you can pick any one of these as design however you will have to heavily custom theme your drupal site.

# Answer
> 3 votes
Here is another possible solution; Pageflow. This module is theme agnostic & provides single page navigation support which is very handy. Here's a general list of features;

* Single page navigation support
* Sticky header & footer toggle
* Horizontal & vertical scrolling support
* Unlimited Pageflows
* Theme agnostic
* Administration UI
* CSS & JS aggregation works as expected
* Boost & core caching support

This module has been tested with a number of popular caching mechanisms.

# Answer
> 2 votes
Yes you can use drupal for a one page site. But Drupal was not made for that - it\`s a very powerful and weightful. There are plenty of other lightweight cms you might use for this purposes.

The advantages could be if you had not worked with any other cms or/and want to use drupal flexebility and possibilities.

The disadvantages were mentioned: you could hardly achieve a fast page load, even if this would be the only page on your site and without any unneeded modules enabled.

I would prefer any of javscript mvc frameworks to make a one page application. It would work lightning fast.

# Answer
> 1 votes
I'd vote for the module Single Page Site since it is not theme dependent. (Not to confuse with another module Single Page Website.)

**Single page Site:**

> This module provides functionality to create a single page website. It allows you to automatically create a single page from a menu. The module will render all the content from the links, that are configured in the menu, on one page. It will then override the menu links so that they refer to an anchor instead of a new page.

---
Tags: 7, theming
---


# Question
Title: Trying to create a custom menu link in a menu
So I want to have different menu links depending on if a user has received a message or not.

I make a hook\_menu() instance, like this:

```
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  global $user;
  $items = array();
  $items['user/' . $user->uid . '/messages'] = array(
    'access callback' => 'user_is_logged_in',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'title' => t('Messages'),
  );
  return $items;
}

```

However it only takes me to my user page, and not the messages (which should be a view at the path specified).

Is there a way to make it so that I can directly go from this item link in the menu to the view?

# Answer
Got it from here:

http://zufelt.ca/blog/embedding-view-menu-hook-drupal

Changed my hook instance to this:

```
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  global $user;
  $items = array();
  $items['user/' . $user->uid . '/messages'] = array(
    'access callback' => 'user_is_logged_in',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'title' => t('Messages'),
    'page callback' => 'views_embed_view',
    'page arguments' => array('message_private', 'page_1'),
    'file path' => drupal_get_path('module', 'views'),
    'file' => 'views.module',
  );
  return $items;
}

```

This will embed the view into the hook\_menu() instance.
> 0 votes

---
Tags: views, routes
---


title: Where can I change this value?

text:
# Question
Title: Where can I change this value?
I'm trying to change the phone number displayed in sidebar window with the chinese lady in it. However I'm trying to find out where it's content is coming from.

This is how the HTML looks

```
<div class="headsetButton">
    <a href="#" class="clickSpan yyModChatLink"><?php print variable_get('yingyang_online_title1');?></a>
    <a href="#" class="youhuiSpan yyModChatLink"><?php print variable_get('yingyang_online_title2');?></a>
    <span class="numSpan"><?php print variable_get('yingyang_online_phone');?></span>
    <span class="hr"></span>
    <a class="onlineConsultation yyModChatLink" href="<?php print url('customer-contact-request') . '?width=790' ?>"></a>

    <div class="headsetHide"></div>
</div>

```

and the thing I need to change in particular is `<?php print variable_get('yingyang_online_phone');?>` but I can't find where *yingtang\_online\_phone* is set.

do you guys have any ideas where to look?

# Answer
> 0 votes
`variable_get()` is used to store and retrieve systemic variables , you can found them in `system` table in DB, or you can change them using `variable_set()`

# Answer
> 0 votes
You should find form element 'yingtang\_online\_phone' in code of your site.

```
$form['yingtang_online_phone'] = array(
  '#type' => 'textfield',
  ...
);

```

---
Tags: views, database
---


# Question
Title: Need help with my form with duplicate file and resetting form
Need help with my form for uploading an image on my theme's settings. I have a form that uploads an image that can be used as a background image. I have two problems with my form: first is how to delete the uploaded file or reset the form and second is an error message appears when uploading the same file again after resetting the theme's settings.

This is my form code I'm using:

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

$form['slideshow'] = array(
'#type' => 'fieldset',
'#title' => t('Background'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);

$bg_path = theme_get_setting('bg_path');if (file_uri_scheme($bg_path) == 'public') {
$bg_path = file_uri_target($bg_path);
}

$form['slideshow']['bg_path'] = array(
'#type' => 'textfield',
'#title' => 'Path to background image',
'#default_value' => $bg_path,
'#disabled' => FALSE,
);

$form['slideshow']['bg_upload'] = array(
'#type' => 'file',
'#title' => 'Upload background image',
'#description' => 'Upload a new image for the background.',
);
$form['reset'] = array(
'#type' => 'markup',
'#markup' => '<input type="reset" value="Reset All Values" class="form-submit">',);

$form['#submit'][] = 'tsaudio_settings_submit';}
function tsaudio_settings_submit($form, &$form_state) {
$settings = array();
// Get the previous value
$previous = 'public://' . $form['slideshow']['bg_path']['#default_value'];

$file = file_save_upload('bg_upload');
if ($file) {
$parts = pathinfo($file->filename);
$destination = 'public://' . $parts['basename'];
$file->status = FILE_STATUS_PERMANENT;

if(file_copy($file, $destination, FILE_EXISTS_REPLACE)) {
  $_POST['bg_path'] = $form_state['values']['bg_path'] = $destination;
  // If new file has a different name than the old one, delete the old
  if ($destination != $previous) {
    drupal_unlink($previous);
  }
}
} else {
// Avoid error when the form is submitted without specifying a new image
$_POST['bg_path'] = $form_state['values']['bg_path'] = $previous;}

}?>

```

And this is the error message I get when uploading the same file again after resetting the theme's settings to default.

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
Duplicate entry 'temporary://ctrldailybg4_1.jpg' for key 'uri':
INSERT INTO {file_managed} (uid, filename, uri, filemime, filesize,
status, timestamp) VALUES (:db_insert_placeholder_0,
:db_insert_placeholder_1, :db_insert_placeholder_2,
:db_insert_placeholder_3, :db_insert_placeholder_4,
:db_insert_placeholder_5, :db_insert_placeholder_6); Array (
[:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] =>
ctrldailybg4.jpg [:db_insert_placeholder_2] =>
temporary://ctrldailybg4_1.jpg [:db_insert_placeholder_3] =>
image/jpeg [:db_insert_placeholder_4] => 1344028
[:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] =>
1436760809 ) in drupal_write_record() (line 7316 of /homepages
/9/d539887599/htdocs/towersignal_com/includes/common.inc).

```

# Answer
> 1 votes
As described in the docs file\_save\_upload

```
file_save_upload($form_field_name, $validators = array(),
$destination = FALSE, $replace = FILE_EXISTS_RENAME)

```

the last parameter `$replace`

> $replace: Replace behavior when the destination file already exists:
>
> **FILE\_EXISTS\_REPLACE**: Replace the existing file.
>
> **FILE\_EXISTS\_RENAME**: Append \_{incrementing number} until the filename is unique.
>
> **FILE\_EXISTS\_ERROR**: Do nothing and return FALSE.

---
Tags: 7
---


title: Drupal multiple node url aliases

text:
# Question
Title: Drupal multiple node url aliases
Is it possible to take a field from my node and create a url alias from the content of that field?

Say I have a node type `article`. This gets its normal url via pathauto, but I also wish to be able to create a short url so I can go to `example.com/LS` and I will be redirected to the node.

How can this custom short url be created automatically?

# Answer
When you create a node they will always use the url `node/[nid]`.

You can use the path auto module to create an url alias for the standard node. Path auto uses the token module to create the url alias for the nodes.

What you can do, is to create a token for the value of the field, and then setup path auto to use the contents of the field when creating the url alias.

Another thing you could do is to use the ShURLy module, to actual create short urls. You could make a custom module where you created or update the short url for the node when saved, and let ShURLy handle the redirects.
> 0 votes

# Answer
You can use `hook_node_insert` and `path_save` like so:

```
function mymodule_node_insert {
  $nid = $node->nid;
  $path = array(
    'source' => 'node/' . $nid,
    'alias'  => 'my/other/path',
  );
  path_save($path);
}

```

This will add an additional alias after the node is created. This won't interrupt Pathauto, so you'll have both aliases active.
> 0 votes

---
Tags: 7, nodes, redirection, path-aliases
---


title: Change format view data export module

text:
# Question
Title: Change format view data export module
I want change format display View Data Export from table to unformatted list

# Answer
> 0 votes
* First you need to create a view page
* Display & filter those information which you want to export
* Click on **+Add** & select Data Export
* Under format you get an option to change to unformatted list
* Save & check

For detailed description click on the **LINK**.

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


# Question
Title: Displaying Webforms on Content Types in Page Manager/Panels
The Webform module allows for a webform to be attached to each Content Type of the site. I can "Enable webform functionality" on my Page and Blog Content types and don't need to use a separate "webform" content type, very cool! This works great with Entity View Mode displays.

However, when using the Node Template in Page Manager, I can't get the Webform to render after adding the "Node being viewed" Webform element.

My goal is to use Page Manager to display every node, with the possibility of a unique webform attached to that node.

I brought this up at a meetup recently and was advised that it may be a bug. But I didn't think to ask where! So, if you think I should bring this up in an issue queue, where do you think that would be, Webform, ctools, or Panels?

Thanks, Jim

# Answer
> 0 votes
Have you tried the following way:

---
Tags: 7, webforms, panels, chaos-tool-suite
---


# Question
Title: How to sort view by the weight of referenced nodes?
I'd like to display the list of studies and their authors in a view. Authors are stored in a node reference field. It's very important to keep the original order of referenced authors in the view which is repredented by their weight.

I looked through View UI for a solution for this problem but didn't find any useful option.

# Answer
> 0 votes
I found out that the :delta component of the field (e.g. field\_authors:delta) can do this trick.

-- EDIT--

Some more explanation: Let's say field\_authors contains the reference to connected authors. Among the sorting options there's a field\_authors:delta which contains numbers for each referenced node (0, 1, 2...) and represnts their actual order.

---
Tags: 7, views, nodes
---


title: Multisite Cache Clear

text:
# Question
Title: Multisite Cache Clear
I have a site with multisite settings

There is one main site, where all the news are created and those are gotten by the other sites via a direct db\_query via a taxonomy tid. This is the part that I managed to work after all.

Now the problem. When I create or update a news node on the main site, the others have to be somehow notified of this. But I don't know how I can clear the cache of a different site

* Is there some module which can do this?
* If not, do I have to delete from cache tables directly on hook\_node\_update(), hook\_node\_delete(), hook\_node\_insert() ?
* If yes, which table(s) does drupal store the cached rendered output (or doesn't she?)?
*
* I cannot use drush

# Answer
> 0 votes
One thing might help you(not sure)is that you can write your function in **hook\_cron** and run that **cron in background**. So let's say your cron run after every 5 min, which means your page is refreshed and cache will get clear on every cron hit.

---
Tags: 7, caching, multi-sites
---


# Question
Title: How to add an edit and delete button to a custom html table?
I've a `db_select` to fetch data from sql table, and `$output .= theme('table'...)` to generate an html table to display these data in columns. My question is, how can I add `edit` and `delete` buttons to each row?

Also, given initially these data are stored in the sql table from dropdowns, how can I redirect to the link containing the dropdowns load again and if for example I edit a row which has data from formID=5, each dropdown then shows the corresponding data for this ID, and allow me to modify accordingly to save again to the same sql table, and update the html table's view?

Example of my current sql is:

`db_select('mytable')
 ->fields('mytable', array('formID', 'field1', 'field2'))
->execute();`

# Answer
> 1 votes
```
    $query = db_select('mytable', 'n')
    ->fields('n')
    ->execute();
  $rows = array();
  while($data = $query->fetchAssoc()){
  // Fill the table rows
    $data['operation'] = l(t('Delete'), 'admin/mid-modules/component/' . $data['cid'] . '/delete');
    $data['operation'] .= "|";
    $data['operation'] .= l(t('Edit'), 'admin/mid-modules/component/' . $data['cid'] . '/edit');
    $rows[] = array('data' => $data, 'style' => 'word-break:break-all;',);
  }

  // Prepare table header
  $header = array( t('S.No'),t('Component Name'));
  // Output of table with the paging
  $output = theme_table(
    array(
      "header" => $header,
      "rows" => $rows,
      "attributes" => array(),
      "sticky" => true, // Table header will be sticky
      "caption" => "",
      "colgroups" => array(),
      "empty" => t("Table has no row!") // The message to be displayed if table is empty
    )
  );
  return $output;
//following menus that delete or edit your selected content

    $items['admin/mid-modules/component/%ctools_js'] = array(
    'page callback' => 'popup_callback',
    'page arguments' => array(3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'popup.inc'
  );
 $items['admin/mid-modules/component/%/delete'] = array(
    'title' => 'Delete Component item',
    'page callback' => 'delete_me',
    'page arguments' => array('delete_component_record_comfirm',3),
    'access arguments' => array('administer users'),
    'type' => MENU_CALLBACK,
    'file'=>'delete_record.inc',
  );

/**
 * Delete  Record Confirmation ------------------------------------
 */
function delete_component_record_comfirm($form, &$form_state, $cid){
   // print_r($cid);exit;
 $form['delete'] = array(
    '#type' => 'value',
    '#value' => $cid,
  );
  return confirm_form(
    $form,
    t('Are you sure you want to delete this?'),
    'admin/mid-modules/component/'. $data['cid'],
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}
/**
 * Delete Survey Record Function
 */
function delete_component_record_comfirm_submit($form, &$form_state) {
  $record = $form_state['values']['delete'];
  if ($record ) {
    $num_deleted = db_delete('mid_components')
      ->condition('cid', $record )
      ->execute();
    drupal_set_message('The record has been deleted!');
  }
  $form_state['redirect'] = "admin/mid-modules/component";
}

```

---
Tags: 7, forms
---


title: metatag for custom path

text:
# Question
Title: metatag for custom path
I need to set some info for SEO and sharing. I know that I can use the Metatag module for nodes, views and front page. In fact, I use it for them. Now I need to set some information for custom paths (create via `hook_menu()`). I know that I can use something like `drupal_add_html_head($metatag_description_custom, 'description')`, but I want to give to my client the possibility to change this and others tags (e.g. og:description, og:image).

Is there a way (or a module) to do this without create and change a custom module's code?

# Answer
> 0 votes
It can be done with Path metatags module

> Path metatags module helps you to create metatags for any page with any selection rules and load any entity from the URL!

---
Tags: meta-tags
---


title: Store query result on an array

text:
# Question
Title: Store query result on an array
This is a simple query

```
$sql = db_select('node','n');
$sql->fields('n', array('uid','title'));
$s = $sql->execute();

```

I need to check the uid of all records :

```
if('n.uid' !=1 ) { do some stuff}

```

Should I store query result into an array before the if condition ? If yes how to do it ?

# Answer
Here you can replace $sql with $result.

```
<?php
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();

// Retrieve all records into an associative array keyed by the field in the result specified.
$result->fetchAllAssoc($field);

// Retrieve a 2-column result set as an associative array of field 0 => field 1.
$result->fetchAllKeyed();
// You can also specify which two fields to use by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be field 0 => field 2
$result->fetchAllKeyed(1,0); // would be field 1 => field 0
// If you need an array where keys and values contain the same field (e.g. for creating a 'checkboxes' form element), the following is a perfectly valid method:
$result->fetchAllKeyed(0,0); // would be field 0 => field 0, e.g. [article] => [article]

// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($column_index);
?>

```
> 2 votes

---
Tags: database
---


# Question
Title: Append parameter to URL accross all pages
I am on Drupal 7. My website will have a country select form on the first page where users will pick one country from a list. All these countries speak the same language (Spanish), so they are basically under the same language pack. My idea is to create a Vocabulary with all the countries I need. Then, in order to guarantee consistency accross pages (allowing me to filter content when necessary), I want to append a parameter to the URL like this:

```
path/to/my/page?country=ur

```

I want this parameter to be added to all the links on the menu in my website. Drupal will read the parameter currently in the URL and will append that same parameter to all URLs on the menu.

My idea is to use Rules to catch the current country code and append that same parameter to all links on the menu, both on top of the page AND on the footer (yes, there are two menu bars). What would be the code to add those parameters to each menu link? Do I have to run the code twice in order to change URLs from both top and bottom menus, or is it possible to inject the querystring into a single resource that will be pulled to build both menus? For the menus, I am using Menu Block module.

If you have a better idea to tackle this, please, suggest. Thank you!

# Answer
The best hook for this is hook\_url\_outbound\_alter. This affects links generated by url(), which is used by most/all code generating urls and links in Drupal.

```
function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  // If the param of interest is present and the url being generated is internal.
  if (!empty($_GET['country']) && !$options['external']) {
    $options['query']['country'] = $_GET['country'];
  }
}

```
> 3 votes

# Answer
I have used this idea to maintain COUNTRY CODE without URL parameter. These are the procedure to implement it and use in \_init function

1. Based on front page country selection pass one URL parameter like ?country=ur to set COUNTRY CODE IN SESSION.
2. Use the same SESSION value until changed from user(through front page or direct URL parameter).
3. If the user is directly typing the URL (no SESSION value and no URL parameter) better to set default country value otherwise redirect to front page to country selection.
> 1 votes

---
Tags: uri
---


# Question
Title: Adding a field with an automatic link in a content type from entity registration module
I'm using Drupal to create a website which allows an "*employer\_role*" user to create a "*Post Job*" content type that has a field type of registration from entity registration module and inside that registration should contains information about an "*applicant\_role*" user EX: Name, Job, Letter, and a automatic link generator where it will link it to the "*Applicant's*" resume content.

I'm quite new to Drupal and the only thing I can manage is a textbox where the applicant should mannually link his resume content path, which I also don't want the applicant's to put a link from another website.

Any suggestions to help me?

**Content type: "Post Job"**

> fields:
>
> Title : text
>
> company name: text
>
> job title : text
>
> body: text //job description
>
> register: registration // apply form

**registration form fields**

> Applicant Name: Text
>
> Applicant Job: Text
>
> letter: long text
>
> my profile/resume: auto link field which will direct to the applicant's resume content

# Answer
> 0 votes
Not sure if I correctly understand the question, but it sounds to me that using the Entity Reference module might be the solution you are looking for. Here's a quote from the module's project page:

> Provides a field type that can reference arbitrary entities

If that's not what you're looking for, then consider editing your question to rephrase it somehow or to add more details to it.

---
Tags: entities, users, navigation
---