# Question
Title: How to display fetched data in the form of html table?
I have created a custom module & used below code to display data from Database. But I want to show that data in the form of html table. Please help.

```
<?php
function custom_table_menu(){
 $items = array();
 $items['custom_table'] = array(
  'title' => 'Custom Table',
  'page callback' => 'custom_table_page_display',
  'access callback' => TRUE,
);
 return $items;
}

function custom_table_page_display() {
$result = db_query('SELECT * FROM {users}');
  $records = $result->fetchAll();

  $content = '<pre>' . print_r($records, TRUE) . '</pre>';

  return $content;
}
?>

```

# Answer
Try this example to output your data in table format with Pager (ie. table with page. 1,2,3.. )

```
function custom_table_page_display() {

  $header = array(
    array('data' => t('Name'), 'field' => 'id', 'sort' => 'desc'),
    array('data' => t('Address'), 'colspan' => 3),
  );

  $query = db_select('users', 'u');

  $query->fields('u', array('name','address'));  // select your required fields here

  $table_sort = $query->extend('TableSort') // Add table sort extender.

                      ->orderByHeader($header); // Add order by headers.

  $pager = $table_sort->extend('PagerDefault')

                      ->limit(20);  // here you can limit the number of data per page.

  $result = $pager->execute();

  $rows = array();
  foreach($result as $res) {
    $rows[] = array($res->id,
                    $res-> title,);
  }
  // If rows are not empty theme and display the rows.

  $output = '';

  if (!empty($rows)) {

    $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'sort-table')));

    $output .= theme('pager');

  }

  else {

    $output .= t("No results found.");

  }

  return $output;

}

```
> 2 votes

# Answer
Below is the Code, you can create the listing page with sortable header and pagination. This code using the 'TableSort' theme.

```
function custom_table_menu(){
 $items = array();
 $items['custom_table'] = array(
  'title' => 'Custom Table',
  'page callback' => 'order_listing',
  'access callback' => TRUE,
);
 return $items;
}

function order_listing() {
    global $base_url;

        $header = array(
            array(
                'data' => t('OrderID'),
                'field' => 't.OrderID',
            ),
            array(
                'data' => t('OrderDate'),
                'field' => 't.OrderDate',
            ),
            array(
                'data' => t('PaymentAmount'),
                'field' => 't.PaymentAmount',
            ),
            array(
                'data' => t('BillingFirstName'),
                'field' => 't.BillingFirstName',
            ),
            array(
                'data' => t('BillingLastName'),
                'field' => 't.BillingLastName',
            ),
            array(
                'data' => t('OrderStatus'),
                'field' => 't.OrderStatus',
            ),
            array(
                'data' => t('ShipDate'),
                'field' => 't.ShipDate',
            ),
        );
        $cust_id = arg(2);

                        $query = db_select('Orders', 't')->extend('TableSort');
        $query->fields('t', array('OrderID', 'OrderDate', 'PaymentAmount', 'BillingFirstName', 'BillingLastName', 'OrderStatus', 'ShipDate'));

        $table_sort = $query->extend('TableSort')->orderByHeader($header);
        $pager = $table_sort->extend('PagerDefault')->limit(50); // 5 rows per page.

        $result = $pager->execute();

        $rows = array();
        foreach ($result as $row) {
            $rows[] = array('data' => array( $row->OrderID, $row->OrderDate, $row->PaymentAmount, $row->BillingFirstName, $row->BillingLastName, $row->OrderStatus, $row->ShipDate));

        }
        $output .= theme('pager');
        $output .= theme('table', array('header' => $header, 'rows' => $rows, "empty" => t("No Records Found"), 'attributes' => array('id' => 'sort-table', 'class' => array('tbl-data'))));
        $output .= theme('pager');

    return $output;
}

```
> 1 votes

---
Tags: 7
---


# Question
Title: Need to make Anonymous user create node through a Form but can't
I need to make anonymous user create a node through my site. The node which is create would be unpublished, which an admin can publish later.

I wrote the following code which works perfectly but the only gripe is that Anonymous can't submit it.

I also gave the permission in the Permission - Node: Create new content but nothing works ...

Any Idea please ....

## This is what I did:-

```
<?php
       if (isset($_POST['submit'])) {

                  //Core Form Elements.
                  $employee_name = $_POST["EName"];
                  $role          = $_POST["Role"];
                  $office        = $_POST["Office"];
                  $location      = $_POST["Location"];

                  $my_node = new stdClass();
                  $my_node->type = "my-node-type";
                  node_object_prepare($my_node);

                  $my_node->title    = $title;
                  $my_node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled

                  $my_node->field_employee_name[$my_node->language][0]['value']    = $employee_name;
                  $my_node->field_employee_role[$my_node->language][0]['value']    = $role;
                  $my_node->field_office[$my_node->language][0]['value']           = $office;
                  $my_node->field_location[$my_node->language][0]['value']         = $location;

                   $my_node->uid = $user -> uid;

                  $my_node->body[$my_node->language][0]['value']   = $story;
                  $my_node->body[$my_node->language][0]['format']  = 'filtered_html';

                  $path = './sites/default/files/animage.png';

                  $path = 'node_created_on' . date('YmdHis');
                  $my_node->path = array('alias' => $path);

                  if($my_node = node_submit($my_node)) {

                      node_save($my_node);
                      echo "<h2> Thank you, Node Recieved.</h2>";
                      echo "Node with nid " . $my_node->nid . " saved!\n";

                  }
              }

              else {

              ?>
                <p><?php print render(field_view_field('node', $node, 'body', array('label'=>'hidden'))); ?></p>

                <form method="post" enctype="multipart/form-data" id="node_submission" action="<?php echo $PHP_SELF;?>">

                  <label for="Name">Name:</label>
                  <input type="text" name="EName" id="employee_name" value="<?php echo $user -> name; ?>" placeholder="Full Name" required />

                  <label for="Role">Role:</label>
                  <input type="text" name="Role" id="role" value="" placeholder="Your Role in the Firm" required/>

                  <label for="Office">Office:</label>
                  <input type="text" name="Office" id="office" placeholder="Your Primary Office" required/>

                  <label for="Title"> Title</label>
                  <input type="text" name="Title" id="title" placeholder="A Concise Title to your Story"/>

                  <label for="Name">What's your description:</label>
                  <textarea type="text" name="Story" id="story" placehold="Your Amazing Story" required></textarea>

                  <input type="submit" name="submit" value="Submit" class="submit-button btn btn-lg btn-primary" />
                  <input type="reset"  name="clear" value="Clear" class="clear-button btn btn-lg btn-secondary" />

                </form>
              <?php
              } ?>

```

# Answer
The correct way to implement this as to follow the drupal standard to create a form and save the contents of the node on submit.

```
 function MYMODULE_menu() {

        $items['Demo'] = array(
            'title' => 'Demo',
            'description' => 'Example form',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('user_detail_form'),
            'access callback' => TRUE,
        );

return $items;

}

function user_detail_form(){

 $form['employee_name']= array(
      '#title' => 'Employee Name :',
      '#type'  => 'textfield',
      '#required' => TRUE,
      '#attributes' => array('placeholder' => 'Full Name'),
     );

     $form['role']= array(
      '#title' => 'Role',
      '#type'  => 'textfield',
      '#required' => TRUE,
      '#attributes' => array('placeholder' => 'Your Role in the Firm'),
     );
 $form['office']= array(
      '#title' => 'Office',
      '#type'  => 'textfield',
      '#required' => TRUE,
      '#attributes' => array('placeholder' => 'Your Primary Office'),
     );
 $form['title']= array(
      '#title' => 'Title',
      '#type'  => 'textfield',
      '#required' => TRUE,
      '#attributes' => array('placeholder' => 'A Concise Title to your Story'),
     );
 $form['story']= array(
      '#title' => 'What's your description:',
      '#type'  => 'textfield',
      '#required' => TRUE,
      '#attributes' => array('placeholder' => 'Your Amazing Story'),
     );
 $form['submit']= array(
      '#type'  => 'submit',
      '#value' => 'Submit'
     );

return $form;

}

function user_detail_form_submit($form, $&form_state){

   global $user;
 $employee_name = $form_state['values']["employee_name"];
                  $role          = $form_state['values']["role"];
                  $office        = $form_state['values']["office"];
                  $location      = $form_state['values']["location"];

$my_node = new stdClass();
                  $my_node->type = "my-node-type";
                  node_object_prepare($my_node);

                  $my_node->title    = $title;
                  $my_node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled

                  $my_node->field_employee_name[$my_node->language][0]['value']    = $employee_name;
                  $my_node->field_employee_role[$my_node->language][0]['value']    = $role;
                  $my_node->field_office[$my_node->language][0]['value']           = $office;
                  $my_node->field_location[$my_node->language][0]['value']         = $location;

                   $my_node->uid = $user -> uid;

                  $my_node->body[$my_node->language][0]['value']   = $story;
                  $my_node->body[$my_node->language][0]['format']  = 'filtered_html';

                  $path = './sites/default/files/animage.png';

                  $path = 'node_created_on' . date('YmdHis');
                  $my_node->path = array('alias' => $path);

                  if($my_node = node_submit($my_node)) {

                      node_save($my_node);
                      echo "<h2> Thank you, Node Recieved.</h2>";
                      echo "Node with nid " . $my_node->nid . " saved!\n";

                  }

           //Add desired code to implement

}

```

For more information click Here

Hope it works for you!
> 0 votes

# Answer
1. Create a new content type, with fields as per your requirement.
2. From content type edit page, uncheck the 'Published' option.
3. From the permission page (/admin/people/permissions) Give the Anonymous User to permission : Create new content

Hope it will work for you.
> 0 votes

---
Tags: forms, users
---


# Question
Title: How can I moderate user's edits of user profile?
I need to create approval for editing a user's profile - I want all revisions to a profile to be subject to moderation.

I have found module called User Revision, but that is not a solution for me as it's only revisioning.

Is this possible with Workbench or something similar?

I am not using Profile 2; and I am working on the newest Drupal 7 version (7.23 at time of writing).

# Answer
There is drupal module Profile2 Moderation to achieve this. It enables moderation on user profiles.

> A "quite hackish procedure"™ to enable moderation on user profiles but it works
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to insert a theme table form inside an existing form?
I would like to put form fields and submits inside a table (generated with theme\_table) of an existing form (callback of a hook\_menu entry).

The form\_id (container) :

```
  // Part of the existing form having a $form_id,
  // where I want to put form elements into a table :
  ...
  $data = mymodule_get_content_list();

  $form['mymodule_content_list'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $data,
  );

```

Table builder function :

```
function mymodule_content_list() {

  ... Running queries to get a $content_list

  $data = array();
  foreach($content_list as $content_data) {
    $operations = array(
      'update' => array(
        '#type' => 'submit',
        '#value' => 'Update',
        '#submit' => array('mymodule_page_edit'),
      ),
    );
    $content = array(
      '#type' => 'textfield',
      '#value' => $content_data->content,
    );
    $data[] = array(
      'content' => drupal_render($content),
      'operations' => drupal_render($operations),
    );
  }

  return $data;

}

```

With something similar to the above, I currently get the HTML of content textfields and submit buttons in place, but they aren't used as real form elements:

* When I click the submit above ('Update'), the submit function used is the first declared within the form container but not the declared array('mymodule\_page\_edit').
* Using a debugger, I found out that textfields declared in the table's rows aren't passed as $form\_state\['values'\] within the (wrong) submit function.

So the question is, how to insert form elements (fields and submits) into a drupal table, inside of an existing form (hook\_menu callback) ? Is it possible ?

# Answer
> 4 votes
Here is sample example where form and tables are used together.

**Step1:** Gather whole data, going to use in table.

```
$sample_data = array
(
  array('id' => 1, 'first_name' => 'jay', 'last_name' => 'chris'),
  array('id' => 2, 'first_name' => 'clo', 'last_name' => 'jason'),
  array('id' => 3, 'first_name' => 'len', 'last_name' => 'ken'),
);

```

**Step2:** Create table header.

```
$sample_header = array
(
  'first_name' => t('First Name'),
  'last_name' => t('Last Name'),
);

```

**Step3:** Create table rows and columns data.

```
$options = array();
foreach($sample_data as $data)
{
  $options[$data['id']] = array
  (
    'first_name' => $data['first_name'], // 'first_name' was the key used in the header
    'last_name' => $data['last_name'], // 'last_Name' was the key used in the header
  );
}

```

Your data should be something like this:

```
Array
(
  [1] => Array
  (
    [first_name] => jay
    [last_name] => chris
  )

  [2] => Array
  (
    [first_name] => clo
    [last_name] => jason
  )

  [3] => Array
  (
    [first_name] => len
    [last_name] => ken
  )
)

```

**Step4:** Use drupal function(tableselect) for table

```
$form['table'] = array
(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
);

```

**Here is complete form for you.**

```
function my_form($form, $form_state)
{
  $sample_data = array
  (
      array('id' => 1, 'first_name' => 'jay', 'last_name' => 'chris'),
      array('id' => 2, 'first_name' => 'clo', 'last_name' => 'jason'),
      array('id' => 3, 'first_name' => 'len', 'last_name' => 'ken'),
  );

  $sample_header = array
  (
    'first_name' => t('First Name'),
    'last_name' => t('Last Name'),
  );
  $options = array();
foreach($sample_data as $data)
{
  $options[$data['id']] = array
  (
    'first_name' => $data['first_name'], // 'first_name' was the key used in the header
    'last_name' => $data['last_name'], // 'last_Name' was the key used in the header
  );
}

  $form['table'] = array
  (
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
  );

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

```

There can be some TYPO mistake, so do change in code accordingly.

# Answer
> 1 votes
You are going about this in the wrong way.

The output of the form (if it needs to look in a specific way) should be handled by a theme function for the form.

You can specify which theme function should be used, by using

```
$form['#theme'] = 'my_theme_function';

```

The form callback should handle structuring the different elements.

In your theme function to can render each form item individually, and thus create a table which contains form elements.

See theme\_form for reference on how to create form theme functions and consult the Drupal FAPI for more info on `$form['#theme']`.

# Answer
> 0 votes
Drupal doesn't have universal tool for creating tables with inputs/selects/etc.

theme\_table is useful only when you want to view static information or links.

Some modules (core modules too) have their own table implementations (as block module), which can have inputs, but these method are individual, and supposed, that each table will be rendered with individual theming function.

Drupal also can't create ajaxed sort/pager links.

So.. I've spent a lot of time to create solution.

https://github.com/player259/ajax\_table

Not well documented, but there is a demo module. I'm using this module every time, when I need table element, just for sure that Forms API will work as expected.

---
Tags: 7, forms
---


# Question
Title: display the entities that are referencing the current entity with views
I have a content type "reservation" and another "room" this is a simple booking app that Im making from stracht "just for learning purposes"

Im using entity reference for make the reservations, so I can create a new reservation and reference the room it belongs to.

So I need to create a view into a block that displays all the reservetions for the current room.

So how to make that in views? display all the entities that are referencing a certain entity.

# Answer
You create a View that lists all reservations and then add entity\_reference\_field as the context.

If you use Panels, you should create a content pane and require a node id as context.

If you don't use panels, you should create a block and provide a default value to the context being the node id from the url. (When you insert the block on the node page, views will grab the node id from the url and use it in the query to display only reservations for that room).
> 1 votes

# Answer
Create a view of `room` and add a relationship of `Entity Reference: Referencing entity`, then you will get the referencing entity data.
> 0 votes

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


title: Import User ID with Drupal Feeds

text:
# Question
Title: Import User ID with Drupal Feeds
Is it somehow possible to import the user ID with feeds. The GUID field is not the ID field, as I just found out, but I need my user IDs with my imported users to stay the same.

# Answer
I don't think feeds supports that out of the box, but there's a patch for it that is reported to work.
> 0 votes

---
Tags: feeds
---


# Question
Title: Altering Webform email %value before sending email
I summon your wisdom on this day because I can't figure out how to **alter submitted Webform values** that are used in **email templates**.

Here's my situation:

I have a **"contact us" form** (set with Webform API) with first name, last name, email and message fields. Nothing spectacular. The submitted values are sent by email to the administrator.

In this *webform setting \> Email subject*, I have this template:

```
[NAMEOFMYSITE | question from %value[first_name] %value[last_name]

```

Everything works fine. But my problem appears when the user forgets to put an **uppercase** in last name or first name value. It doesn't look professional in the email subject. And I want to **force** these two values with an uppercase as first letter to get something like:

```
NAMEOFMYSITE | question from John Doe

```

And never:

```
NAMEOFMYSITE | question from john doe

```

I tried to **alter submitted values** because I thought template's `%value` were based on it:

```
function pwe_webform_form_alter(&$form, &$form_state, $form_id) {
  [...]
  $form['#submit'][] = 'contactus_webform_submit'; // callback function on submit
}

function contactus_webform_submit($form, &$form_state) {
  $form_state['values']['submitted']['last_name'] = ucfirst($form_state['values']['submitted']['last_name']);
  $form_state['values']['submitted']['first_name'] = ucfirst($form_state['values']['submitted']['first_name']);
}

```

But even if I succeed to modify them, the `%value` in email doesn't change.

Of course, I dpm `$form_state` tree to see where the submitted values appear in it and where the template's `%value` could find its origin. It appears on several levels:

* $form\_state\['input'\]\['submitted'\]\['last\_name'\]
* $form\_state\['values'\]\['submitted'\]\[2\]
* $form\_state\['values'\]\['submitted\_tree'\]\['last\_name'\]
* $form\_state\['complete form'\]\['submitted'\]\['last\_name'\]\['#value'\]
* $form\_state\['webform'\]\['component\_tree'\]\['children'\]\[2\]\['value'\] *(but always empty)*

I altered **every variable** but the email value **still the same**. I'm about to ask myself if it is actually based on one of those variables... If not, on what is it based? And how can I alter it?

Please excuse the looooong post but I wanted it to be very clear. I hope you will help anyway :-(

# Answer
> 4 votes
In `hook_form_alter()`, add a new submission handler before the other submission handlers.

```
function pwe_webform_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'YOUR_WEBFORM':
      array_unshift($form['#submit'],'pwe_webform_form_submit');
      break;
  }
}

function pwe_webform_form_submit($form, &$form_state) {
  $form_state['input']['submitted']['last_name'] = ucfirst($form_state['input']['submitted']['last_name']);
}

```

---
Tags: 7, webforms, emails, forms
---


# Question
Title: Unable to post message to wall on facebook using facebook rules module
I have following modules installed

1. FBOauth
2. Facebook Rules

I have installed its dependencies like Rules and Oauth library.

The settings implemented on the facebook app

Dashboard

TEST This app is public and available to all users **App ID** : 22321917809249
**App Secret** : ●●●●●●●●Show

In the below all the blurred value has been appropriately added.

Also in the status and review I have made following changes as shown in the image

In the facebook rules I have created a rule with following

**Events** **User logged in using Facebook connect.
User registered using Facebook connect, requires admin approval.
User registered using Facebook connect.
**

**Action**

**Post an update on user's facebook wall. Parameter: Message: Hello Facebook world!, Link to post: m2w.redcom.in**

The api and secret key has been added on the facebook configuration settings page and I am able to retrieve the facebook details of the user on the user details on the websites. How can I post to the user's facebook wall using the above rules configuration?

All while facebook is logged in and i try to use the fconnect feature, I get a message dialog box which has following text "This does not let app post to the facebook" How can I allow my app to post to the facebook. ??

Drupal Issue posted : https://www.drupal.org/node/2299375

# Answer
> 1 votes
The problem lies with proper permission. You need to have permission "publish\_actions" to post on someone's behalf. If you do need more permissions then follow the below link to get all the permissions provided via Facebook Graph API.

https://developers.facebook.com/docs/facebook-login/permissions/v2.0#reference-extended

---
Tags: 7, social-network
---


title: Where is template_preprocess() located

text:
# Question
Title: Where is template_preprocess() located
where is the `template_preprocess()` function located? It seems that my `markaspot` theme (`mas`) call this function but I can not find this funktion in a file.

Thanks for your help.

# Answer
> 2 votes
It's in

```
includes/theme.inc.

```

Docs are here.

Next time just put the name of the function in Google...the docs on Drupal.org will tell you what file any function is in.

---
Tags: files
---


# Question
Title: Migrating specific nodes from Drupal 6 to Drupal 7
I have an existing Drupal 6 site, and an updated version of the same site running on Drupal 7. Setting up the Drupal 7 site did take a lot longer than I planned, and the old Drupal 6 site accumulated some more content in the meantime. I now want to migrate some new nodes from the old site to the new one, but not all of them as many already exist on the new site in updated versions.

I did find the Migrate module, but from what I can tell this seems to be a framework, and not an out of the box solution.

Is there an easy way to migrate specific nodes, either hand-picked or based on selection criteria like node type and creation date, between two Drupal installations of different major versions?

# Answer
> 0 votes
The easiest way I know is export your nodes from Drupal 6 by using Node Export . Then you can import your node to Drupal 7 by Feeds module. This has update and replace exsisting nodes options. Just make sure you set one of the source as an "Unique" on Mapping setting, like "uid" or "title" of the node. Hope this help

# Answer
> 0 votes
Migrate module. We migrated an entire site using this module and migrating nodes was the easiest. The documentation is pretty well written. Let me know if you decide to go down that path. I could maybe help get you setup.

# Answer
> 0 votes
I think the answer is "no". But in the realm of non-easy ways, you might try

* depending on the number of the nodes in question, is recreating them by hand possible?
* if it's an option to re-run your original upgrade process on the new snapshot of the site, that might be the easiest way. If that might be destructive to things you've created on the D7 site, try diving into the Features module for how to move site-building elements between sites. It's work, but it builds character.
* I would investigate Node Export and Feeds next, as H-L suggested.
* Migrate and migrate\_d2d are very effective tools written for a developer audience. This will solve your problem very quickly, however if it's your first time using it, it will take a little while to get up to speed on the framework.

---
Tags: migrations
---


title: How to create sql alias in drupal 7

text:
# Question
Title: How to create sql alias in drupal 7
How do you achieve the highlighted 'node' alias when using the Drupal 7 database abstraction language?

This is the original query produced by the view

```
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, **'node' AS field_data_field_reference_code_node_entity_type, 'node' AS field_data_field_employer_node_entity_type, 'node' AS field_data_field_contract_type_node_entity_type, 'node' AS field_data_field_display_location_node_entity_type, 'node' AS field_data_field_salary_description_node_entity_type**
FROM
{node} node
INNER JOIN {field_data_field_locations} field_data_field_locations ON node.nid = field_data_field_locations.entity_id AND (field_data_field_locations.entity_type = 'node' AND field_data_field_locations.deleted = '0')
LEFT JOIN {workflow_node_history} workflow_node_current ON (  SELECT max(hid) FROM {workflow_node_history} where nid = node.nid and sid != old_sid ) = workflow_node_current.hid
WHERE (( (node.type IN  ('job')) AND (field_data_field_locations.field_locations_tid = '56') AND (workflow_node_current.sid =  '3') ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0;

```

Here my current code, which produces the query but cant recreate the aliases in bold with the addfield method. Tried to escape the quotes around 'node' but drupal stripes it out.

```
$result = db_select('node','node');

    $join = $result->innerJoin('field_data_field_locations','field_data_field_locations',"node.nid = field_data_field_locations.entity_id AND field_data_field_locations.entity_type = 'node' AND field_data_field_locations.deleted = '0'");

    $result->leftJoin('workflow_node_history','workflow_node_current',"(SELECT max(hid) FROM {workflow_node_history} where nid = node.nid and sid != old_sid ) = workflow_node_current.hid");

    $result->addField('','node')
    $result->addField('node','title','node_title');
    $result->addField('node','created','node_created');
    $result->addField('node','nid','nid');
    $result->condition('node.type',array('job'),'IN');
    $result->condition('field_data_field_locations.field_locations_tid','56','=');
    $result->condition('workflow_node_current.sid','3','=');
    $result->orderby('node.created','desc');

```

# Answer
Add an expression instead:

```
$result = db_select('node','node');

$join = $result->innerJoin('field_data_field_locations','field_data_field_locations',"node.nid = field_data_field_locations.entity_id AND field_data_field_locations.entity_type = 'node' AND field_data_field_locations.deleted = '0'");

$result->leftJoin('workflow_node_history','workflow_node_current',"(SELECT max(hid) FROM {workflow_node_history} where nid = node.nid and sid != old_sid ) = workflow_node_current.hid");

// EXPRESSION HERE
$result->addExpression("'node'", 'field_data_field_reference_code_node_entity_type');

$result->addField('node','title','node_title');
$result->addField('node','created','node_created');
$result->addField('node','nid','nid');
$result->condition('node.type',array('job'),'IN');
$result->condition('field_data_field_locations.field_locations_tid','56','=');
$result->condition('workflow_node_current.sid','3','=');
$result->orderby('node.created','desc');

```

Produces:

```
SELECT node.title AS node_title, node.created AS node_created, node.nid AS nid, 'node' AS field_data_field_reference_code_node_entity_type
FROM
{node} node
INNER JOIN {field_data_field_locations} field_data_field_locations ON node.nid = field_data_field_locations.entity_id AND field_data_field_locations.entity_type = 'node' AND field_data_field_locations.deleted = '0'
LEFT OUTER JOIN {workflow_node_history} workflow_node_current ON (SELECT max(hid) FROM {workflow_node_history} where nid = node.nid and sid != old_sid ) = workflow_node_current.hid
WHERE  (node.type IN  (:db_condition_placeholder_0)) AND (field_data_field_locations.field_locations_tid = :db_condition_placeholder_1) AND (workflow_node_current.sid = :db_condition_placeholder_2)
ORDER BY node.created desc

```
> 0 votes

# Answer
In this link you will see that field method doesn't support alias. Instead supports,

```
$query = db_select('node', 'n');

```

But to have alias for fields follow this link which will be,

```
$query->addField('n', 'name', 'label');
$query->addField('n', 'name', 'value');

```
> 1 votes

---
Tags: 7, database
---


title: Thousands separator (comma) in term id

text:
# Question
Title: Thousands separator (comma) in term id
I'm rewriting the results in a view. I've added taxonomy term ID field and hidden it from displaying.

This is the rewriting code:

```
<a href="/publications/working-area/[tid]">[name]</a>

```

This is the result generated:

```
<a href="/publications/working-area/1,007">Constitution</a>

```

The problem is the comma in \[tid\]. I want Drupal to not to insert comma there i.e.. instead of 1,007 I want 1007.

# Answer
Go to your view. and Click on Taxonomy term to configure the field. Make sure to select the **Thousand marker** as `<none>`.

Then you can use this as replacement pattern in your href path
> 4 votes

---
Tags: 7, views
---


title: Aegir redirect url to actual site

text:
# Question
Title: Aegir redirect url to actual site
I’d like to redirect the: `aegir-server.com/a-site-url.com` to `a-site-url.com` without hacking Aegir and based on a pattern so any future site will follow this type of redirect. Is it possible through Aegir?

(Aegir redirects the : aegir-server.com/node/site\_id/goto\_site to the site, but this is not what I need)

# Answer
The easiest way would be to edit the .htaccess file of your hostmaster platform and add something like

`RewriteRule ^(.*\.com) http://$1 [L,R=301]`

Note that you have to reload apache as Aegir integrates the htaccess file into the vhost config.
> 0 votes

---
Tags: redirection, aegir
---


# Question
Title: Put a field in views with the vocabulary of the taxonomy term from a contextual filter
I have a view which accepts taxonomy terms as contextual filters. Now, what I would like to have is to put the vocabulary of the term in a field. Relationships?...
On the nodes that arewhown by views there are two fields with taxonony terms, and the view can be sorted by both. I want to access the *very one* the view is filtered with.

# Answer
Add a `term relationship` based on the term field.

Then add a `taxonomy Vocabulary Name` Field using that relationship.
> 0 votes

# Answer
If you put a field in views with taxonomy vocabulary name then there is no need to use relationship. While creating a new view just select -

**Show -\> Taxonomy Terms**

But if you want to show other content fields with that view then use relationship -

**Taxonomy term: Content with term**
> 0 votes

---
Tags: views
---


title: drupal_goto in new tab

text:
# Question
Title: drupal_goto in new tab
**Shortly**: How can I open a drupal\_goto() result in a new tab?

**More details**:

I've got a list of news, made with Views, that can be imported from a RSS feed (*big custom module, very complicated, etc, etc*) or directly written by the site's editor.

When I click on a news, I access the node full view mode page and, if it is an imported news, I'm redirected to the source site with `drupal_goto(source)`.

**I want to redirect to the external source site in another tab.** And I can't figure it out. I'm not even sure if that's possible with only PHP.

Thanks in advance for any help.

# Answer
That isn't possible - `drupal_goto()` happens server-side, and you can only affect tabs/windows with client-side code.

You would need to stop using `drupal_goto()`, and instead insert some javascript into the page which opens the new URL in a new tab upon refresh.

Some (including myself) would also argue that you have no "right" to do this - let the *user* decide whether they want a new tab or not. Be careful of trying to force your will onto them. See Target Blank is Evil for a wonderfully opinionated bit of rhetoric on the matter.
> 7 votes

---
Tags: 7, views, navigation, redirection
---


# Question
Title: Do something in hook_node_load only when displaying node
Is there a way to run a specific block of instructions in hook\_node\_load only when the node is loaded do be displayed and not when it's loaded in the edit form?

The only way I can imagine is analyzing the url and if the pattern is node/%/edit don't execute the code.

I know I can also use hook\_node\_view, but in this case I have to add render arrays instead of simple values

# Answer
Yes, you'll need to examine the URL for this.

Loading a node is (correctly), completely de-coupled from displaying a node. `node_load()` doesn't know *what* you've loaded the node for; it doesn't care, its only responsibility is to prepare the node object.

So the context you're looking for doesn't conceptually exist when `hook_node_load()` is invoked, as that by definition has to happen before the object is passed to `node_view()`, and there's no way to signal your desired intent to `node_load()`
> 1 votes

---
Tags: 7, nodes, hooks
---


title: Insert a view with a context using php?

text:
# Question
Title: Insert a view with a context using php?
I know I can insert a view using the following code:

```
 <?php
    $view = views_get_view('VIEWNAME');
    print $view->preview('default');
 ?>

```

In my view I have a contextual filter of user: name

When I insert this view using the Display Suite module I have this option from Display Suite:

I was wondering if there is a way to pass this context to the view, like Display Suite does, using php code only.

# Answer
You can set the default value for the contextual filter through URL and then in your code use `$view->set_arguments()` to pass the argument.
> 0 votes

---
Tags: views
---


# Question
Title: Rules - New events inside code not shown in interface
I am trying to insert a new event inside an already existing module. The module is Nodeaccess https://www.drupal.org/project/nodeaccess it's used to grant users edit/delete permissions to single nodes.

inside sites/all/modules/nodeaccess i have made the file nodeaccess.rules.inc which contains this code:

```
/**
 * @file
 * Rules integration.
 */

/**
 * Implementation of hook_rules_event_info().
 */
function nodeaccess_rules_event_info() {
    return array(
        'nodeaccess_grant_permissions' => array(
            'label' => t('Permissions are granted to a user'),
            'group'=>t("NodeAccess"),
            'variables' => array(
                'granter' => array('type' => 'user', 'label' => t('The user who granted the permissions.')),
                'granted' => array('type' => 'user', 'label' => t('The user who got the new permissions.')),
                'node' => array('type' => 'node', 'label' => t('The node on which the permission has been granted.')),
            ),
        ),
    );
}

```

Looking at different guides on the web it looks like this is all you have to do to get a new event but in the events list i can't find it. I have tried:

* refreshing the cache
* disabling/enabling nodeaccess module then refreshing the cache (and rebuilding permissions as it was requested)
* disabling/enabling rules module then refreshing the cache
* adding the rule entry in a \*.rules.inc file i've seen it's being imported (namely the feeds.rules.inc file from the feeds module which already existed when i installed the rules module)

Nothing worked so far

EDIT: i have changed the function name and the entry name (both from "node\_access" to "nodeaccess" ) but it's still not showing. I have discovered that if i add an entry on a file i know it's being imported and keep the prefix of the entry, then it shows up

# Answer
> 0 votes
The problem is the function name. Since the module name is nodeaccess (and not node\_access), function name should be nodeaccess\_rules\_event\_info

However, it is not recommended to add anything to a contributed module (unless you are going to contribute back to the module's issue queue).

If this rule is specific your project, you can add it in your own custom module.

---
Tags: 7, rules
---


# Question
Title: Is there a function to get the system path for the current language?
If I'm using multiple languages on the site with path prefixing, is there a quick way to get a system path for the current language?

For example, if the current language is English, and I'm interested getting the English path for 'user/password', what function call (or small number of lines) will return 'en/user/password'?

The following doesn't seem to work; it returns nothing:

```
drupal_lookup_path('alias', 'user/password', $language->language);

```

# Answer
> 0 votes
The internal path is same for all languages,though you can set different alias for different languages. From your question it seems that you want to get the path with language prefix not the alias, if so then I don't think there is any function that will return the path with language prefix.

Since you can get the language using `$language->language` you can write a custom function as follows.

```
function custom_lookup_path($action, $path = '', $path_language = NULL){
   global $language;
   if(empty($path_language)){
      $path_language=$language->language;
   }
   if(!empty($language->prefix)){
      $path = $language->prefix.'/'.drupal_lookup_path($action, $path , $path_language);
   }
   else{
      $path = drupal_lookup_path($action, $path , $path_language);
   }
   return $path
}

```

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


# Question
Title: How to use module template to override a specific Views field and send the right variable?
I hope the title is ok. I've seen many discussion here about using custom templates in a module when using views, but i lack a piece of answer : how to use specific variables from an entity in that template ?

Backgound information about my problem : I'm making a module 'youtube2drupal', using a custom table 'youtube\_video', having some fields (one of them is 'vhash', the video hash in youtube). With this table i create an entity 'ytv'. I added this key to mymodule\_entity\_info() to use with Views : 'views controller class' =\> 'EntityDefaultViewsController', Then to test it i create a view displaying one video with all its informations =\> everything is ok.

Everything BUT, to display the video, i need a iframe and i cant't use the rewrite of the output for the 'vhash' field i added in the view field.

The code needs to be :

```
<iframe width="560" height="315" src="//www.youtube.com/embed/<?php print $vhash; ?>" frameborder="0" allowfullscreen></iframe>

```

In the suggested template for the view, there is one i can use : views-view-field--vhash.tpl.php

I don't want to override any theme : i'd like to have all the code in my module. So I created this file 'views-view-field--vhash.tpl.php' in my /templates dir in my module.

I looked for solutions to tell Drupal to use it:

First, I've checked this lead, with hook\_theme\_registry\_alter() https://swsblog.stanford.edu/blog/using-templates-custom-drupal-module

and i tried

```
function youtube2drupal_theme_registry_alter(&$theme_registry) {
  dpm($theme_registry);
  $module_path = drupal_get_path('module', 'youtube2drupal');
  $theme_registry['views_view_field__vhash']['theme path'] = $module_path . '/templates';
  $theme_registry['views_view_field__vhash']['template'] = 'views-view-field--vhash';
}

```

but the 'views\_view\_field\__vhash' key doesn't exists, so it seems this is not the right solution to register this template.

Then i saw this discussion https://stackoverflow.com/questions/5305114/drupal-7-how-to-load-a-template-file-from-a-module#answer-5307126

so i tried

```
function youtube2drupal_theme($existing, $type, $theme, $path){
  return array(
    'views_view_field__vhash' => array(
      'variables' => array('vhash' => NULL),
      'template' => 'views-view-field--vhash',
      'path' => drupal_get_path('module', 'youtube2drupal') . '/templates'
    )
  );
}
function youtube2drupal_page(){
  // some code to generate $vhash variable : this is where i'm stuck !
  return theme('views_view_field__vhash', array('vhash' => $vhash));
}

```

=\> This seems the right way to register correctly the template but i don't know how to set vhash variable in this context : i want to use something like `$myentity->vhash`. but i can't use `$myentity = entity_load('ytv', array($entity_id));` because $entity\_id is not defined in youtube2drupal\_page() context.

Am i on the right track using youtube2drupal\_theme() / youtube2drupal\_page() to register the template for the module ? If so how can i tell Drupal to use the right value of vhash for this entity i created ?

----- Edit ------- I tried the preprocess function : I changed :

```
function youtube2drupal_theme($existing, $type, $theme, $path){
  return array(
    'views_view_field__vhash' => array(
      'template' => 'templates/views-view-field--vhash',
      'file' => 'includes/youtube2drupal.theme.inc',
      'base hook' => 'views-view-field',
    )
  );
}

```

and added in the includes/youtube2drupal.theme.inc :

```
function youtube2drupal_preprocess_views_view_field__vhash(&$variables, $hook) {
  dpm($variables);
  $variables['vhash'] = $variables['view']->result[0]->youtube_video_vhash;
  //sets the right value into $vhash, but only for the first element
}

```

This doesn't "break" the site, but obviously the `$variables['view']->result[0]->youtube_video_vhash;` is valid only for the first element in the list. If i want to display 2 or more videos, the keys for $variables\['view'\]-\>result should be 1, 2, ...

So, how can i dynamically set this vhash variable with the correct value ? Is it possible that way ? Thanks in advance.

# Answer
> 0 votes
Try to get the value from `row` object instead of `view` object like `$variables['row']`

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


# Question
Title: Organic Groups Views contextual filter is not working
I am trying to make a view in which I have to show images from an image-field of an organic group content type. I have tried for many hours but I am unable to make it work. I am trying to explain the scenario:

I have a venue (organic group) content type. For each venue there is an image field which can hold multiple images. I want to show a list of images that belong to a specific venue. For that I have to make a view so that I can show a list of images belonging to that specific venue. I have used the following path string:

```
/group/%/images

```

Now what I want is that for example, I want to visit a "pizza-house" venue, then the path string of the view will be:

```
/group/pizza-house/images

```

Now on this page I only want to show images from multiple image-field that only belong to "pizza-house" venue (Venue content type contains that field). For achieving this, I have tried the following contextual filter and relationships as in shown the pictures but of no use :/ Please help me figure out what I am doing wrong? I am new to contextual filters and organic groups. Thanks in advance.

# Answer
I had a similar issue and it took me hours to finally find this solution: http://drupaleasy.com/blogs/ultimike/2013/05/sneaky-previously-undocumented-views-feature

I know it's for overriding the title, but it worked for me when I wanted to display a certain content type in a view for a specific group based on what page I was on. I fiddled for quite some time with relationships and different combos. But, all you need is the contextual filter: OG Membership: Group ID with a default value provided (current OG group from context) and specify validation criteria (OG GrouP).

Hope this helps!
> 0 votes

---
Tags: organic-groups, views
---


# Question
Title: How to add user role as a class while rendering a username
I'd like to style the username of certain roles differently (mainly admin roles) and I think the way to do it is to append the user roles in the class of the username.

I'd like your help with this because I've tried this but it doesn't work:

```
function THEME_username(&$vars) {
  foreach($vars['user']->roles as $role){
    $vars['classes_array'][] = 'role-' . drupal_html_class($role);
  }
}

```

# Answer
> 2 votes
You need to *preprocess* the theme function, and add to the attributes array or link options, depending on context. Currently you're overriding the theme function and reducing its output to an empty string.

```
function MYTHEME_preprocess_username(&$vars) {
  foreach($vars['account']->roles as $role) {
    if (isset($variables['link_path'])) {
      $vars['link_options']['attributes']['class'][] = 'role-' . drupal_html_class($role);
    }
    else {
      $vars['attributes_array']['class'][] = 'role-' . drupal_html_class($role);
    }
  }
}

```

# Answer
> 1 votes
Given the advice by Mołot, I've decided that this works best for me since I can hide the specific user roles a user has.

```
function MYTHEME_preprocess_username(&$vars) {
 $target = array('admin','admin 1','admin forum','admin shop');
  if(count(array_intersect((array)$vars['account']->roles, $target)) > 0) {
    if (isset($variables['link_path'])) {
      $vars['link_options']['attributes']['class'][] = 'role1';
    }
    else {
      $vars['attributes_array']['class'][] = 'role1';
    }
  }
 }

```

Clive has answered my question correctly and I'm leaving his answer as the accepted one, since it addressed my initial question.

---
Tags: 7, theming
---


# Question
Title: Is it possible to export/import content types from one site to another
is there a way to import/export content types between diff Drupal websites?, assuming they are the same versions of Drupal

# Answer
A few options:

* Features

The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
* Bundle Copy
> 0 votes

---
Tags: nodes, importing-exporting
---


# Question
Title: Facets blocks populated with incorrect field data and strange behavior
I'm building a product catalog with faceted search. I'm using Search API, Search API Database Search, and Display Suite.

I've created a search server as well as an index which indexes four fields that I'm interested in filtering by (artist, country, printing, subject).

My problem is that the facets set on the individual fields have erroneous data in them (data pulled in from other fields, splitting the names of artists, etc). Then when you click the facets, the contents of the facet change by removing or changing fields from the list of options in the individual facet block. Interestingly, in the artist facet clicking on an erroneous field (e.g. a brand in the print type facet) produces no results (yes is available as an option).

Part of this maybe my data quality in the db, I do have Artists' names as two words in a single field.

So, I'm curious why the facet options change when clicked, but much more so as to why my facets are messed up.

Thanks in advance.

# Answer
When preparing the data for the Search Page, make sure that the fields you index are indexed as strings and not full text. This is what caused the problem.
> 0 votes

---
Tags: database, search
---


# Question
Title: Prevent enter to submit form / disable enter
I am trying to prevent to submit the form when a user is pressing enter. I am trying to do so in a form that is also using ajax. I want to have the user click on submit after filling out all the necessary stuff and not have them accidentally press enter and have the form submitted.

I have the code below; the alertbox is popping up when pressing 's' for example. also when I press enter I can get a alertbox popping up. But it is not preventing to submit the form.

```
$("#edit-searchfield").keydown(function(e){
  var code = e.which; // recommended to use e.which, it's normalized across browsers
  if (code == 13) {
    e.preventDefault();
    return false;
  }
  if (code == 83 || code == 13 || code == 188 || code == 186) {
    alert("I am an alert box!");
  }
});

```

# Answer
> 1 votes
And the answer is :-)

```
$form['#attributes'] = array('onsubmit' => 'return false');

```

or alternatively (the above will disable submit all together)

```
  $('#edit-searchfield').keypress(function(event) {
   if (event.keyCode == '13') {
       event.preventDefault();
   }
});

```

# Answer
> 1 votes
Try jQuery's `submit()` event:

```
$('#my-form').submit(function(e) {
    if (/* the form is invalid */) {
      e.preventDefault();
    }
});

```

That's better than adding `onsubmit` to `$form['#attributes']`. It's considered bad practice to mix your HTML and JavaScript that way =)

# Answer
> 0 votes
Another alternate to achieve that is using the Hide submit button module

> Some users accidentally click the submit button more than once while waiting for their post to be saved. In some cases this may result duplicate postings or duplicate e-commerce orders.

---
Tags: 7, forms
---


# Question
Title: How do I get hex value for field categoryhex on creating category?
I want to create a new category to my Drupal site but I need to set an `categoryhex` but I don't know which value I need to set here.

Thanks for your help.

# Answer
> 0 votes
That hexadecimal value of the color. You can get the hex value of the color from here - http://www.w3schools.com/html/html\_colornames.asp http://www.color-hex.com/color-names.html

---
Tags: 7
---


# Question
Title: How to get the untranslate original string?
In a form, there a submit button:

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

```

In the form \_submit function:

```
  switch($form_state['values']['op']) {
    case 'Modify' :
      // ...
      break;

```

the `case 'Continue'` will not match if `Modify` is translated. How can I always get the original untranslated `Modify` string for the sake of string comparison?

# Answer
> 3 votes
If there are multiple submit buttons on the form, I always prefer to have different submit functions for them. In your case I'd go for something like :

```
  $form['previous'] = array(
    '#type' => 'submit',
    '#value' => t('Modify'),
    '#submit' => array('_my_function_to_go_to_previous_function'),
  );

```

and implement the logic inside the submit:

```
function _my_function_to_go_to_previous_function($form, &$form_state) {
  // Logic to go to previous step.
}

```

In this way you'll have more control over whatever you do. Works well with multistep forms. You can also implement separate `#validate` function per button too.
Note that the `$form_state` parameter is passed by reference, which would mean you don't have to return anything from the submit function. Just manipulate the values inside the variable as per requirement, and then call

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

```

inside the submit function, so that the form rebuilds itself with the new values.

# Answer
> 1 votes
You can get the value from `$form_state['triggering_element']['#id']` instead of `$form_state['values']['op']`

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


# Question
Title: Print taxonomy term description onto product page
I am currently running Drupal Commerce 7.

The products listed are all referenced to different designers through a "Designer" Taxonomy. Within the Taxonomy, the individual terms, i.e. the different designers have an added description. I would like to know if there is any way to print on the product page the description for the particular designer referenced by the page.

For instance I have a shoe. I have it designed by Mary under "Designer". I have also attached an example description for Mary: "Mary is a great designer". I would like to print this somehow onto the product page.

# Answer
> 0 votes
It depends a lot on how you're showing this page/information, most probably you're using Views lo list these products, so you can add a Relationship from the Product entity to the Taxonomy (from product variation or display, doesn't matter) to show the fields coming from your categories.

If it's in the product page, it might get trickier, I'd use Display Suite to show fields from other entities, Dynamic fields is an option included in DS and alows you to explore more information that is available for display contextually on your current entity view mode.

---
Tags: taxonomy-terms, commerce
---


title: Module Block destroys head

text:
# Question
Title: Module Block destroys head
I'm struggling with blocks and a custom module. What I've got so far is a module which generates a block with that code:

```
function commerce_bulk_invoice_block_info() {
    $blocks = array();
    $blocks['showinvoiceoptions'] = array(
        'info' => t('Define Invoice Options'),
    );
    return $blocks;
}
function commerce_bulk_invoice_block_view($block_name = '') {
    if ($block_name == 'showinvoiceoptions') {
        echo '<div id="invoice-block">';
        if(!isset($_SESSION['selected_entities'])) {
            echo 'select a product first';
        } else {
            echo '<h1>SESSION Variables:</h1>';
            echo '<pre>';
            print_r($_SESSION['selected_entities']);
            echo '</pre>';
        }
        echo '</div>';
    }
}

```

My problem is, the content generated by hook\_block\_view is not shown in the selected region but directly after the opening body tag. And it pulls the whole head-content into the body. Anyone knows a solution for that?

# Answer
> 2 votes
By the documentation, you should **`return`** content you want in block, not **`echo`** it.

```
$block['subject'] = t('Subject'); // String here
$block['content'] = t('Content'); // Array or string here
return $block;

```

---
Tags: blocks
---


# Question
Title: Programmatically insert field collection of Phone fields
I have a profile2 profile type. In profile type i have created the collection for storing the information of form fields.

I have used the phone module to create the phone number fields. This collection contains the two phone number fields, one for office and one for mobile.

So my scenario is give below

```
--Profile type

--- Field collection to store the phone numbers

---- Two fields to store  phone numbers
    1. field_office_phone
    2. field_office_mobile

```

Now i want to save the data of the field programmatically. I have used below snippet from here to create and save the field collection programmatically. In the given below code **company** is my profile2 profile bundle.

```
module_load_include('inc', 'field_collection', 'field_collection.pages');
  // Load the profile we're adding the field to
  $profile_entity = profile2_load_by_user($account, 'company');

  // Define the values of the new field
  $values = array();
  $values['field_name'] = 'field_contact_number'; // field collection name
  $values['field_office_phone'][LANGUAGE_NONE][0]['#value']['number'] = 1234;
  $values['field_office_mobile'][LANGUAGE_NONE][0]['#value']['number'] = 12374;

  // Create the field collection entry and associate it with the profile
  $field_entity = entity_create('field_collection_item', $values);
  $field_entity->setHostEntity('profile2', $profile_entity);
  $field_entity->save();

```

The above code snippet only creates field but it is not storign the values in the field. I am not getting the reason why it is not setting the values.

# Answer
> 2 votes
This code works fine for user entities under Drupal 7:

```
  $values['field_office_phone'][LANGUAGE_NONE][0]['number'] = '0412345678';
  $values['field_office_phone'][LANGUAGE_NONE][0]['country_codes'] = 'au';

```

Adapt countrycode to your user's country. I don't think I'm using Profile2 and there are multiple different modules that implement phone number fields. My server has cck\_phone-7.x-1.x-dev installed.

---
Tags: entities
---


# Question
Title: Adding Pagination to to custom form block results
I have created a custom block that has a form which has a list of result and I wanted to know how to add pagination to the results

Thanks for any help on this

Colin

# Answer
> 6 votes
```
    /**
 * Implements hook_block_info().
 */
function custommodule_block_info() {
    $blocks = array();
    $blocks['latest_news'] = array(
        'info' => t('Latest News'),
        'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

    /**
 * Implements hook_block_view().
 */
function custommodule_block_view($delta = '') {
    $block = array();
    switch ($delta) {

        case 'latest_news':
            $block['subject'] = t('');
            $block['content'] = latest_news();
            break;
    }
    return $block;
}

/*
 * Implementation of hook_theme
 * */

function custommodule_theme() {
    return array(

        'latest_news' => array('variables' => array('data' => array()),
        'template' => 'latest_news'),

    );
}

    function latest_news() {
     $query = db_select('node', 'node');
    $query = $query->fields('node', array('nid'))
            ->condition('node.status', 1) //Published.
            ->condition('node.type', 'auction_news');
    $query = $query->extend('PagerDefault');
    $result = $query->limit(20)->orderBy('node.created', 'DESC')->execute()->fetchAll(PDO::FETCH_ASSOC);
    $paging = theme('pager');

    return theme('latest_news',array('data' => $result,'paging'=>$paging));
}

```

In a tpl file latest\_news.tpl.php

```
 <ul>

    <?php
    foreach($data as $lat_news)
    {

       echo '<li>'.$lat_news->nid.'</li>';
    }
    ?>
    </ul>
    <div><?php echo $paging;?></div>

```

---
Tags: 7, forms, paging
---


title: Translate a form

text:
# Question
Title: Translate a form
I've installed i18n module for taxonomy translation,and I have set in translatable mode. What I need is to have a form with some checkboxes in a multilingual site.

I'm able to obtain that checkboxes options, and I can see in my site in spanish and in basque. The problem is that for example, in my spanish site if I select some of the options and save it, when I want to edit the values I'm able to see the selected options in the spanish site but not in the basque one.

What I do is to optain first the options this way:

```
$query = "SELECT name, tid FROM taxonomy_term_data WHERE vid=2 AND language = '$language_url';";
    $result = db_query($query);
    foreach ($result as $row2) {

    $options2[$row2->tid] = t($row2->name);
    }

```

Then obtain the selected values and set in the default value:

```
foreach ($node->field_municipio[LANGUAGE_NONE] as $delta => $value ) {

     $term2  = taxonomy_term_load($value['tid']);
     $datos[$term2->tid]=$term2->name;
    }

    $form['municipios'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Municipios'),
    '#options' => $options2,
    '#required' => TRUE,
    '#multiple'=>TRUE,
    '#default_value'=> array_keys($datos),
    /*'#prefix' => '<p>',
    '#suffix' => '<br></p>',*/
    );**

```

I suppose that I'm doing wrong doing a taxonomy\_term\_load, because I obtain only the selected options of the spanish site, but how can I know what is the translation of that value in basque??

I hope you can help me.

Thank you in advanced.

# Answer
I recommend you to use Entity Translation instead of i18n. With Entity Translation each entity has its translation attached to the entity while i18n tends to crate new entities that are related (for example, two nodes related, each one for each language). This makes harder to manage all the translations for a piece of content.

For translating the term label you may need the Title module, I don't remember well.
> 0 votes

---
Tags: taxonomy-terms, i18n-l10n, forms
---


# Question
Title: Commerce Search API with Custom field search
I have a Custom search form with multiple fields on my front page. After clicking on submit button, user would be routed to search result page. (Ideally, a Commerce search view). On search result page, all facets blocks are enabled.

Products are mapped with Commerce Stores (cmp\_store). I have used field collection for Store so Seller can add multiple stores. Each store has Zip code associated with it.

I am getting zip code in my search facets. But if User has not entered zip code then I want search result based on User's current location + 25 kms radius. Sorting should be location based.

I guess I have to alter the search query. Not sure how to alter query.

How can I do that ?

# Answer
> 0 votes
I have added related fields to the index configuration page under the "fields" tab. First have added the store then the zip code.

---
Tags: commerce, search
---


title: Access denied while deleting an entity

text:
# Question
Title: Access denied while deleting an entity
This is my Config entity:

```
 * @ConfigEntityType(
 *   id = "myentity",
 *   label = @Translation("My Entity"),
 *   controllers = {
 *     "storage" = "Drupal\Core\Config\Entity\ConfigEntityStorage",
 *     "list_builder" = "Drupal\mymodule\Controller\MyEntityListBuilder",
 *     "form" = {
 *       "default" = "Drupal\mymodule\Form\MyEntityForm",
 *       "delete" = "Drupal\mymodule\Form\MyEntityDeleteForm",
 *     },
 *   },
 *   admin_permission = "administer mymodule",
 *   config_prefix = "myentity",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "url" = "url",
 *     "status" = "status"
 *   },
 *   links = {
 *     "canonical" = "mymodule.myentity_info",
 *     "add-form" = "mymodule.myentity_add",
 *     "edit-form" = "mymodule.myentity_edit",
 *     "delete-form" = "mymodule.myentity_delete",
 *   }
 * )
 */

```

The `MyEntityDeleteForm`:

```
/**
 * @file
 * Contains \Drupal\mymodule\Form\MyEntityDeleteForm.
 */

namespace Drupal\mymodule\Form;

use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Url;

/**
 * Defines a confirmation form for deletion of a custom menu.
 */
class MyEntityDeleteForm extends EntityConfirmFormBase {

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return t('Are you sure you want to delete the myentity %title?', array('%title' => $this->entity->label()));
  }

  /**
   * {@inheritdoc}
   */
  public function submit(array $form, array &$form_state) {
    $this->entity->delete();
    drupal_set_message($this->t('The entity %title has been deleted.', array('%label' => $this->entity->label())));
    $form_state['redirect_route'] = $this->getCancelRoute();
  }

  public function getConfirmText() {
    return $this->t('Delete');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelRoute() {
    return $this->entity->urlInfo('canonical');
  }
}

```

The route defined in `routing.yml`:

```
mymodule.myentity_delete:
  path: '/admin/config/search/mymodule/myentity/{myentity}/delete'
  defaults:
    _entity_form: 'mymodule_myentity.delete'
  requirements:
    _entity_access: 'mymodule_myentity'

```

I'm getting this error while trying to delete the entity:

```
Notice: Undefined offset: 1 in Drupal\Core\Entity\EntityAccessCheck->access() (line 46 of core/lib/Drupal/Core/Entity/EntityAccessCheck.php).
Drupal\Core\Entity\EntityAccessCheck->access(Object, Object, Object)
call_user_func_array(Array, Array)
Drupal\Core\Access\AccessManager->performCheck('access_check.entity', Object, Object, Object)
Drupal\Core\Access\AccessManager->checkAll(Array, Object, Object, Object)
Drupal\Core\Access\AccessManager->check(Object, Object, Object)
Drupal\Core\EventSubscriber\AccessSubscriber->onKernelRequestAccessCheck(Object, 'kernel.request', Object)
call_user_func(Array, Object, 'kernel.request', Object)
Symfony\Component\EventDispatcher\EventDispatcher->doDispatch(Array, 'kernel.request', Object)
Symfony\Component\EventDispatcher\EventDispatcher->dispatch('kernel.request', Object)
Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.request', Object)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
Drupal\Core\HttpKernel->handle(Object, 1, 1)
Drupal\Core\DrupalKernel->handle(Object)

```

And this message on the page:

```
Access denied
You are not authorized to access this page.

```

# Answer
If you look at `EntityAccessCheck::access()` you'll see this:

```
$requirement = $route->getRequirement('_entity_access');
list($entity_type, $operation) = explode('.', $requirement);

```

The second line is causing the notice, and your access check to subsequently fail. Basically, the access method is expecting (requiring, in fact) your permission to contain an entity type and access operation, separated by a `.`.

If you take the node module's routing file as an example:

```
node.delete_confirm:
  path: '/node/{node}/delete'
  defaults:
    _entity_form: 'node.delete'
    _title: 'Delete'
  requirements:
    _entity_access: 'node.delete'
  options:
    _node_operation_route: TRUE

```

I would suggest you just need to change your route to match:

```
mymodule.myentity_delete:
  path: '/admin/config/search/mymodule/myentity/{myentity}/delete'
  defaults:
    _entity_form: 'mymodule_myentity.delete'
  requirements:
    _entity_access: 'mymodule_myentity.delete'

```
> 1 votes

---
Tags: entities, 8
---


title: Form and Textcontent in Block

text:
# Question
Title: Form and Textcontent in Block
I'm having problems with adding a form and text-content into a block. To get both, form and text, into my block, I use `render()` on my form, but I read, this isn't the best way to do, but don't found another way. Anyone knows how to get both into the content without using `render()`?

```
function commerce_bulk_invoice_block_view($block_name = '') {
    $block = array();
    if ($block_name == 'showinvoiceoptions') {
        $block['content'] = '<div id="invoice-block">';
        if(!isset($_SESSION['selected_entities'])) {
            $block['content'] .= 'select a product first';
        } else {
            $block['content'] .= '<h1>SESSION Variables:</h1>';
            foreach($entity_array as $book) {
                $block['content'] .= '<pre>';
                $block['content'] .= print_r( $book, true );
                $block['content'] .= '</pre>';
            }
        }
        $block['content'] .= '</div>';

        $form = drupal_get_form('commerce_bulk_invoice_form');
        $block['content'] .= render($form);
    }
    return $block;
}

```

# Answer
> 0 votes
Try the following code

```
function commerce_bulk_invoice_block_view($block_name = '') {
  $block = array();
  if ($block_name == 'showinvoiceoptions') {
    $content = '<div id="invoice-block">';
    if(!isset($_SESSION['selected_entities'])) {
        $content .= 'select a product first';
    } else {
        $content .= '<h1>SESSION Variables:</h1>';
        foreach($entity_array as $book) {
            $content .= '<pre>';
            $content .= print_r( $book, true );
            $content .= '</pre>';
        }
    }

    $content .= '</div>';

    $build['content']=array('#markup' => $content);
    $build['form']=drupal_get_form('commerce_bulk_invoice_form');

    $block['content'] = $build;
 }
 return $block;
}

```

---
Tags: 7, forms, blocks
---


# Question
Title: How to create menu and submenu using taxonomy collection in drupal commerce kickstart?
I am using Drupal Commerce Kickstart for ecoomerce site. I created menu using taxonomy **collection**. I want to create submenu also using taxonomy **collection**. Is it is possble? I want to menu like this Image.

I am creating taxonomy vocabulary as 'collection'.i created 'computers'. then i can add the products in computers. If i want to add the products in computers-\>printers. How can i create computers-\>printers using taxonmoy?

# Answer
There is module Taxonomy Menu. You should use this module.
> 0 votes

---
Tags: commerce, taxonomy-terms
---


title: Unable to submit rendered field

text:
# Question
Title: Unable to submit rendered field
I have a custom form with text field and a submit button.

```
$form['bid_amount'] = array(
  '#type' => 'textfield',
  '#title' => t("Your Bid"),
  '#prefix' => '<div id="test-ajax">',
  '#suffix' => '</div>',
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Calculate your bid'),
  "#ajax" => array(
  'callback' => 'custom_callback',
  'wrapper' => 'test-ajax',
  'method' => 'replace',
  'effect' => 'fade',
  ),
);
}

```

What I want to do is, when 'bid\_amount' is empty, and button is clicekd, 'bid\_amount' should be rendered again with a prefilled value. This is what I can do. But at this time, when again button is clicked, with FILLED field of 'bid\_amount', it shows up again with suggested value. Actuly it should be submitted this time.

Here is how I am rendering this ....

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

    $next_bid = 100;
    return array(
      '#type' => 'ajax',
      '#commands' => array(
        ajax_command_replace("#test-ajax", render($form['bid_amount'] = array(
              '#type' => 'textfield',
              '#title' => t("Your Bid"),
              '#value' => $next_bid,
              '#prefix' => '<div id="test-ajax">',
              '#suffix' => '</div>',
        ))),
      )
    );
}

```

# Answer
I was facing the same issue. I think the render function doesn't add "name" to the html so the form values are not submitted. I fixed this by adding them in the array

```
'#attributes' => array(
  'class' => array('edit-bid-amount'),
  'name' => 'bid_amount'
),

```

The function now is

```
function custom_callback(&$form, &$form_state) {
  $next_bid = 100;
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace(
        "#test-ajax", render($form['bid_amount'] = array(
          '#type' => 'textfield',
          '#title' => t("Your Bid"),
          '#value' => $next_bid,
          '#prefix' => '<div id="test-ajax">',
          '#attributes' => array(
            'class' => array('edit-bid-amount'),
            'name' => 'bid_amount'
          ),
          '#suffix' => '</div>',
          )
        )
      ),
    )
  );
}

```

Hth, Sadashiv
> 0 votes

---
Tags: ajax, theming
---


# Question
Title: Conversion tracking code immediately after body tag?
I'm fairly new to Drupal, so bare with me. I need to add some tracking code immediately after the body tag on the checkout complete page. I'm guessing I need to add it to the html.tpl.php or `$page_top` variables or maybe a checkout pane. My question is:

1. Which way is the best way to do it?
2. If I need to add it in the html.tpl.php, how would I do that for just the checkout complete page?
3. If I need to add it in the `$page_top` variable for only the checkout complete page, how would I do that?
4. If I need to do it in a checkout pane, how would I keeping in mind is needs to be immediately after the body tag?

Using the Drupal Commerce module.

# Answer
> 2 votes
You can do this in template.php by using theme\_preprocess\_html()

```
function mytheme_preprocess_html(&$vars) {
  $arg = arg();
  $vars['checkout_tracking_script'] = '';
  if (count($arg) == 3 && $arg[0] == 'checkout' && $arg[1] == 'complete' && is_numeric($arg[2])) {
    $vars['checkout_tracking_script'] = '<script>myScript</script>';
  }
}

```

Then in your html.tpl.php you can print your script like this.

```
<?php if ($checkout_tracking_script): ?>
  <?php print $checkout_tracking_script; ?>
<?php endif ?>

```

---
Tags: commerce
---


# Question
Title: How to use "db_query" instead of "db_select"?
I am using "db\_select" in a computed field to get an array of values from database (trough an entity reference field - multi value):

```
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$current_nid = $wrapper->nid->value();
$values_y = array();
/* First I get an array of referenced nodes IDs that are neccesary in second query*/
$child = db_select('field_data_field_plan_tpl_select_trainings', 'f')
  ->fields('f', array('field_plan_tpl_select_trainings_target_id'))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'skills_plan_tpl')
  ->condition('entity_id', $current_nid)
  ->execute();
$child_nid = array();
foreach ($child as $item_child){
   $child_nid[] = $item_child->field_plan_tpl_select_trainings_target_id;
}
/* Here I get an array of values from referenced nodes */
$week_no = db_select('field_data_field_skill_week_no_planned', 'f')
  ->fields('f', array('field_skill_week_no_planned_value'))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'skill')
  ->condition('entity_id', array($child_nid))
  ->execute();
$week_value = array();
foreach ($week_no as $item_week){
   $week_value[] = $item_week->field_skill_week_no_planned_value;
}

$values_y = array_filter($week_value);

```

I understand that "db\_query" is faster than "db\_select"; is it true and can it have a positive impact in my situation? How can this be translated into "db\_query"?

# Answer
db\_query can be used with an actual MySQL query - you just insert the MySQL query as you would in, say, PHPMyAdmin or some other UI for MySQL (or command line).

You can also substitute arguments into the query based on the second argument passed to the function, as such (found on Drupal.org as an example):

```
$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));

```

Here the $uid variable is being passed as an argument to the query. Theoretically you could also write this as such:

```
$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n WHERE n.uid = ' . $uid);

```

As Clive mentions in the comments though, this is just for illustrative purposes, as it does open you up to potential attack.
> 0 votes

---
Tags: database
---


# Question
Title: How to implement a secure video streaming website?
I want to create a secure Video streaming website where people need to pay to play videos and they should not be able to download directly the video. What are the possible solution to achieve this? I know there is a flowplayer secure streaming plugin http://flowplayer.org/plugins/streaming/secure.html but is this enough?

Thanks

# Answer
This is quite a complicated problem with a lot of possible approaches; a whole book could be written about it (your question is probably too broad).

That said, have you checked out Videola? Videola is a Drupal-based distribution for creating subscription-based websites. It's made by Lullabot, one of the leading Drupal companies, and they use it to power their learning network, Drupalize.me.
> 2 votes

# Answer
All of the solutions that I have seen so far recommended provide protection of the links to the resource, but nothing to prevent users from screen recording the video as it is played. For that you can add protection to the page displaying the video by using **Copysafe Web Protection**.

Copysafe Web provides an easy to use and economical solution that can be used in all popular Windows browsers, but if you want absolutely unexploitable protection for web media you can try the **ArtistScope Site Protection System** (ASPS). ASPS is most secure because it uses a custom web browser specially designed to protect web media instead of expose it. The ASPS site filter can be applied to any web site on Apache and Windows servers, including Wordpress, Joomla and Drupal portal solutions.
> 1 votes

# Answer
the security that in that article you posted is only "security by obscurity", because the shared secret needs to be passed to the client, who can easily decompile it from the swf file. The security flow is basically here. It's interesting why do the docs say that having that key hardcoded and compiled into the swf is safe. Having the key in his hands, nothing prevents him from compiling his own player.

I suggest you that you implement your own authentication mechanism based on Wowza Server Side API, for example you can create something similar to Wowza Wrench, which comes with pay per minute for Wowza by the way. If you want to prevent Wrench tokens from being compromised before usage, you need to use transport level security, e.g. use HTTPS for your website. They have a Drupal Wowza integration article there on the site.
> 0 votes

---
Tags: files
---


title: LEFT JOIN with db_select()

text:
# Question
Title: LEFT JOIN with db_select()
I'm trying to do a left join but it isn't working.

I have 2 tables:

```
TABLE profile
- uid
- pid

TABLE field_data_field_naam
- entity_id
- field_naam_value

```

I want to select the `field_naam_value` where `uid` is equal to .. and `pid` equal to `entity_id`. My normal query looks like this:

```
SELECT fdfm.field_naam_value, pf.uid
FROM field_data_field_naam fdfm
LEFT JOIN profile pf
ON fdfm.entity_id=pf.pid
WHERE pf.uid = 4

```

When I execute this on my database it works. Then I have this:

```
$naam = db_select('field_data_field_naam', 'fdfm')
     ->fields('fdfm', array('field_naam_value'));
$naam->leftJoin('profile', 'pf', 'fdfm.entity_id = pf.pid');
$naam->condition('uid', 4)
     ->execute();

```

And when I do the following:

```
foreach ($naam as $record) {
    die;
}

```

nothing happens... (he doesn't kill the app). Also tried to add `->fetchAll()` but no success.

# Answer
Use the below code for fetching values. It will give you `field_naam_value` field data.

```
$naam = db_select('profile', 'pf');
$naam->join('field_data_field_naam', 'fd', 'pf.pid = fd.entity_id');
$all_names = $naam->fields('fd', ['field_naam_value'])
  ->condition('pf.uid', 4, '=')
  ->execute()
  ->fetchAll();
foreach ($all_names as $record) {
  die;
}

```
> 13 votes

---
Tags: 7, database
---


# Question
Title: How to disallow some emails in Drupal 7?
Some temporary emails are frequently used by human spammers and I want to disallow them either from registration or posting.

I know that there is a similar question here but that one is for D6 and did not work for me. I'd like to do that in D7. Appreciate your help.

# Answer
> 1 votes
Use the User Restrictions module. This module allows you to block both emails and usernames based on certain patterns.

For example, to block mails from spammers.com create a user restriction with:

* Access type: Denied
* Rule type: Email
* Mask: %spammers.com

# Answer
> 1 votes
I think what you are looking for can be achieved with the "user restrictions" module.

But the "http:BL" module could also be interesting for you!

you should check them out! ;)

---
Tags: 7, users, emails, advertising
---


# Question
Title: notify after event in followed node by follower
I use the Flag module in Drupal 7, and created a flag (for nodes) with "follow" as name of the flag.

I want to add new event on the followed content by user, send notify for follower by php code or display counter of new event unread to user.

How can I do this?

# Answer
> 0 votes
If i understand you right, you want to do something after a user was flagged...

The flag module has a full Rules module integration. This module gives you the ability to react to specific events (like flagging a user) and do actions like showing a message, sending a email, or execute some custom php-code.

---
Tags: nodes, flags, notifications
---


# Question
Title: How To Pass Taxonomy Term (Name) to Filtered View (ID) - Drupal 7
I have a custom view (page) created using Views in Drupal 7.

It contains a taxonomy field and an (exposed) taxonomy filter. When viewing the custom page/view, it works exactly as needed and a user can select a taxonomy filter to limit results accordingly. For example, the default view is /books and the user, via the exposed filter can select **/books?book\_type\[\]=21** to show only the books that have taxonomy ID 21.

The problem I am experiencing is that I need a second custom view (essentially a series of thumbnails, each depicting a different 'book\_type') to link directly to the **/books?book\_type\[\]=21** URL path. Within this second view, I have added the appropriate taxonomy field and via the Rewrite Results option of the field, I have selected Output This Field as a Link and inserted **books?book\_type\[\]=\[field\_book\_taxonomy\]**, where \[field\_book\_taxonomy\] is the referenced taxonomy field.

When I view this thumbnail page, the link works, but the URL contains the taxonomy name rather than ID. So whilst I need **/books?book\_type\[\]=21**, the page receives **/books?book\_type\[\]=ficton**.

I have tried various Contextual Filters, including Term Name converted to ID, but the URL always passes name and the page therefore returns "An illegal choice has been detected".

Ideally I would like to retain the path **/books?book\_type\[\]=ficton** on the initial view and have this interpreted successfully by the actual filtered view.

Please can someone offer a pointer as to where I am going wrong with this?

Thank you.

# Answer
I don't think it is possible to pass term name,instead of term id, as value for exposed filter. But if you are fine with passing term id in your second view then while rewriting the output check the replacement patterns available there you will see the term id.

Like if your field name is **field\_book\_taxonomy** then in your replacement patterns you will see two patterns like **\[field\_book\_taxonomy\]** and **\[field\_book\_taxonomy-tid\]**, choose the later one.
> 0 votes

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


# Question
Title: Apply comments votes to parent node (with Rate module)
My site have a fivestar field in comments, where users gives their vote and the points are applied to the parent node. This is possible using Fivestar module, following this instructions: http://drupalclinic.blogspot.com.es/2011/09/add-fivestar-ratings-in-comments-and.html

Could the same be done with Rate module (https://www.drupal.org/project/rate) and without custom coding?

# Answer
No, it is not possible.

And also unlike **Fivestar** module, where the rating field can be made visible in node/comment form and node/comment display, the **Rate** module allows you to add the field only on node/comment display, not on form.
> 0 votes

---
Tags: 7, rating
---


# Question
Title: Is there a way module to tell if you're logged into Dev, Stage, or Production
Our deployment model has

1. Dev
2. Stage
3. Production
4. Failover (mysql replication and load balancer)

Our problem is that the server has failed over, we want to alert content editors that they're on the failover, or moreso, we'd like to ensure they're editing in the production areas and not on a development box.

Is there a way to distinguish the environment, after a user logs in? Is there a module by which color codes the admin bar depending on the server's host name?

# Answer
Try Environment Indicator, it does exactly what you want.

> This module will help you to keep sane while working on your different environments by adding a configurable color bar to each one of your environments.

It also integrates nicely with Admin Menu.
> 14 votes

# Answer
As mentioned in the 1st answer, environment\_indicator is the one you are looking for.

Well, we also use the same kind of development model and for ease of use if features module is used then you can have the settings written in a file. This makes the colour changing automated.

Follow the code below, this can be imported via Features module.

```
/**
 * Implements hook_default_environment_indicator_environment().
 */
function mymodule_default_environment_indicator_environment() {
  $export = array();

  $environment = new stdClass();
  $environment->disabled = FALSE; /* Edit this to true to make a default environment disabled initially */
  $environment->api_version = 1;
  $environment->machine = 'live';
  $environment->name = 'Live';
  $environment->regexurl = 'example.com';
  $environment->settings = array(
    'color' => '#bb0000',
    'text_color' => '#ffffff',
    'weight' => '',
    'position' => 'top',
    'fixed' => 0,
  );
  $export['live'] = $environment;

  $environment = new stdClass();
  $environment->disabled = FALSE; /* Edit this to true to make a default environment disabled initially */
  $environment->api_version = 1;
  $environment->machine = 'staging';
  $environment->name = 'Staging';
  $environment->regexurl = 'stage.example.com';
  $environment->settings = array(
    'color' => '#000099',
    'text_color' => '#ffffff',
    'weight' => '',
    'position' => 'top',
    'fixed' => 0,
  );
  $export['staging'] = $environment;

  $environment = new stdClass();
  $environment->disabled = FALSE; /* Edit this to true to make a default environment disabled initially */
  $environment->api_version = 1;
  $environment->machine = 'dev';
  $environment->name = 'Dev';
  $environment->regexurl = 'dev.example.com';
  $environment->settings = array(
    'color' => '#000066',
    'text_color' => '#ffffff',
    'weight' => '',
    'position' => 'top',
    'fixed' => 0,
  );
  $export['dev'] = $environment;

  return $export;
}

```
> 7 votes

---
Tags: 7
---


# Question
Title: Execute Drupal Feeds Import Programatically - Where to put code
I found this code for executing feeds importers programatically:

```
<?php

// Define the id (machine name) of the importer you want to use.
$importer_id = 'my_feeds_importer';

// Load the Feeds Source object.
$source = feeds_source($importer_id);

// Override configurations... (more on that in a moment)

// Execute the import.
$source->startImport();

?>

```

I'm just not sure where this code is supposed to go (I'm still pretty green when it comes to Drupal!).

# Answer
> 0 votes
I think you have found the code from this link. In this case you can mention this code in a custom function or hook\_cron or in a separate page. Totally depends upon you.

Follow Triggering the Feed Import module and Programmatically execute FEED import

---
Tags: feeds
---


# Question
Title: Resize Image for more than one Image Size profile automatically
Here is my problem.

I have field BigPicture in a my Product Content Type.

Is there a way that When I upload an image from BigPicture Field that the current picture automatically resize in more than one image profile.

Here is the desire Image Resize Workflow:

1- Upload the image

2- Automatically Resize and Crop the image in more than one size property (Thumb :120px X 120px, Big : 250px X 250px, ExtraBig 1024px X 760px)

3- The Final File Name for each image should be like MyImageName\_Thumb.jpg, MyImageName\_Big.jpg, MyImageName\_ExtraBig.jpg

I'am using Drupal 7

Thanks a lot

# Answer
> 1 votes
Image styles in Imagecache Actions should handle this for you. But as said above, it will do it on display, not on upload. It will scale/crop however you like (there are extra sub modules for this), and the styles will be sorted into folders by image style, but not rename them. But it will put them in folders like Thumb/MyImageName, Big/MyImageName, etc.

Imagecache actions does have a custom option, I'm not sure if it would let you rename the file:

> Custom Actions - Execute your own PHP/GD code in the middle of an imagecache generation process. Requires some familiarity with imageAPI internals.

---
Tags: rules, media
---


title: admin/content customizing

text:
# Question
Title: admin/content customizing
I need to add some new filters to the admin/content (or admin/content/file) page. Standardly, it offers me just type and status. Let's say, I would like to add the filter "name", that shows just the files of specified author. I am able to generate all the possible authors (their names) from SQL table, as well as showing them on the page (simple add it to `$form['filter']['filters']['status']['filters']` with hook\_form\_alter function).

But now I do not know, what to do next. The submit button calls some function to generate some filters (but then it seems pretty difficult to change everything).

Do you know any way to do that?

# Answer
Try Administration Views module. It comes with views based listing. Which can be easily modified based on our requirements.
> 0 votes

---
Tags: 7
---


# Question
Title: How can I set up an existing site from Pantheon on my computer?
I am a real newbie to all this so I appreciate all the help.

I am helping a company develop a Drupal website which already exists and is hosted on Pantheon. I have login access to the drupal site. How do I get the current codebase for the existing drupal site?

From what I understand, Pantheon automatically commits codechanges to the development section. However pantheon seems to use git so I downloaded git and then created an ssh key and pasted it into my account on pantheon. So I think I have created the connection between my laptop and pantheon.

So really all I think I'm missing is how to extract the codebase.

Thank you and let me know if I'm missing a whole bunch of other steps.

By the way do I have to use git? Or can I use github?

# Answer
> 1 votes
Uploading your key is the first step towards cloning your repository because this gives you access. The next step is to grab the git repository address from your site's dashboard. This is located in the "Connection Info" dropdown menu on the upper righthand side, or in the "Connection Mode" bar above your commit log. The info button provides the git commands you'll need to get started. Please note that you'll need to be in the Git mode in order to push your local commits to the Pantheon repository.

---
Tags: version-control
---


# Question
Title: Problem when downloading large files using Storage module
I'm using the Storage module to managed uploads on my website. I'm hosted on EC2, some content is sent to S3, and some stays on EC2.

Logged in users are able to transfer files to each other. One user uploads the file, and the other goes to download it.

The files that are causing problems are stocked on EC2.

A user is able to upload a large file (4 gb for example), to the server, but when someone tries to download the file, they get a file of 0b.

I checked via FTP and the file is there and complete (i downloaded it and opened it).

When moving the file to another directory (/default/files/file.zip), it works. If it is in the "/system/storage/serve/359/file.zip" it doesn't work.

--- EDIT ---

Forgot to mention that it DOES NOT happen with small files.

--- EDIT ---

Does anyone has any suggestion?

Thanks !

# Answer
> 0 votes
I would have preferred to put this into a comment, but I don't have enough rep points yet. :/

First, a few questions: What version of PHP are you using? Does the same thing happen with small files? Are you using symlinks? Do your server logs show anything suspicious?

I am trying to fix a similar problem on one of my sites. PHP 5.4 works fine, but 5.5 is choking when trying to interact with the file, which happens to be linked into a mounted filesystem. They are on different versions of Ubuntu as well, so I am currently trying to figure out if it is a Linux kernel bug, a PHP bug, or a PEBKAC error.

---
Tags: files
---


title: JQuery via the .info file isn't working

text:
# Question
Title: JQuery via the .info file isn't working
I'm using/experimenting with Zen on my drupal site, and have just inserted a js file named alert.js into my theme's js folder. The file has the following code:

```
  (function ($){
Drupal.behaviors.kiwiAlert = {
  attach: function(){
    alert('Hello World');
   }
 };
})(jQuery);

```

I followed up by making the necessary changes in my .info file, by inserting the following snippet:

```
 scripts[] = js/alert.js

```

Since my site is in development mode I've set the cache to be cleared/theme registry to be rebuilt upon each page load, but just in case I cleared my cache again. And nothing, the alert message doesn't show, why is this not working??

PS: I also tried the following code in the js file, in the same context, but to no avail :C

```
 alert("Hello World!!");

```

Any and all answers will be much appreciated :)

# Answer
> 1 votes
Answered in comments, but just moving the answer here for posterity's sake.

The theme was loading the .js file, but the permissions were restricted, so the server was returning a 403 error. Changing the permissions fixed the issue.

---
Tags: javascript, theming
---


title: Looking for Captcha field for webform

text:
# Question
Title: Looking for Captcha field for webform
I have tried: Mollom module and Captcha module to put a captcha in my webforms.

Had no problem at all -they work for non-admin users- but they don't fit all my needs because I need an actual field I can include in a form in a position I want (e.g. my webform has two columns and want to place that field inside of one of the columns, instead of adding it at the end). E.g.

```
++++++++++++++++++++++++++++++++++++++++++++++++++++
+ First name              + Car Model              +
++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Last Name               + Car Color              +
++++++++++++++++++++++++++++++++++++++++++++++++++++
+ City                    + I need captcha         +
+++++++++++++++++++++++++++ in this exact          +
+ Phone                   + line / cell            +
++++++++++++++++++++++++++++++++++++++++++++++++++++
+ T&C / ToU               +          Send          +
++++++++++++++++++++++++++++++++++++++++++++++++++++

```

But with those modules I get the captcha field as displayed:

```
++++++++++++++++++++++++++++++++++++++++++++++++++++
+ First name              + Car Model              +
++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Last Name               + Car Color              +
++++++++++++++++++++++++++++++++++++++++++++++++++++
+ City                    +          Send          +
++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Phone                   +                        +
+++++++++++++++++++++++++++                        +
+ T&C / ToU               +                        +
++++++++++++++++++++++++++++++++++++++++++++++++++++
+ I'm having the                                   +
+ captcha component at                             +
+ the end of the form                              +
++++++++++++++++++++++++++++++++++++++++++++++++++++

```

(which does not help since the "send" button is above the field and the field is not inside of any column).

What module could I install so I can create an explicit \[web\]form captcha field and place it where I want in the form layout?

# Answer
Maybe think about alternatives? We use BOTCHA module everywhere these days to combat spam submissions. Works much better than any captcha and is far less intrusive for real people. Just a thought.
> 1 votes

# Answer
I can think of a few ways to do this while still using the contrib catpcha or mollom modules.

First, you can use a hook\_form\_alter(), but you probably need to make sure that your module has a heavier weight than the captcha modules so that you can be sure to alter the form (and manipulate the `#weight` of the individual form elements) after all other modules have done their part.

A second, completely different way would be to create a custom theme function for this form.

I have done both approaches (depending on the needs of the project) and they both work.

As far as I am aware, there is no module that explicitly helps with the layout of captcha fields within a form.
> 0 votes

# Answer
Use hook\_form\_alter and form api weight attribute of form element to handle this situation.
> 0 votes

---
Tags: 7, webforms, captcha
---