title: node_data_field not working on 6

text:
# Question
Title: node_data_field not working on 6
I have this structure:

```
<div class="FloatLeft RightText">: '.$data->node_data_field_story_text_html_field_kampanya_adi_value.'</div>
    <div class="clear"></div>
    </div>
    <div class="InfoTextItems">
    <div class="FloatLeft LeftText">Ajans</div>
    <div class="FloatLeft RightText">: '.$data->node_data_field_story_text_html_field_ajans_value.'</div>
    <div class="clear"></div>
    </div>
    <div class="InfoTextItems">
    <div class="FloatLeft LeftText">Reklamveren</div>
    <div class="FloatLeft RightText">: '.$data->node_data_field_story_text_html_field_reklamveren_value.'</div>
    <div class="clear"></div>
    </div>
    <div class="InfoTextItems">
    <div class="FloatLeft LeftText">Ödül</div>
    <div class="FloatLeft RightText">: '.$data->node_data_field_story_text_html_field_odul_value.'</div>

```

It's working. And 4 other field:

```
field_one
field_two
field_three
field_four

```

When I change this field to other, not working. Like this:

```
<div class="FloatLeft RightText">: '.$data->node_data_field_story_text_html_field_one_value.'</div>

```

And not working on my page.

How can I fix it?

# Answer
> 0 votes
It looks like you're in the context of a views template. If so, you need to check that you have added the mentioned fields to the views config using the UI. Are you using Views Custom Field? If that's the case, check the field type that you're trying to render. The ending part is different for the different field types:

* text fields: \_value
* files / images: \_fid / \_list / \_data
* node / user references: \_nid

So for example, if `field_one` is a file field, you could output the filepath by following the solution described here: https://drupal.org/node/1502064

Depending on the field type, you may need to prepare the variable in order to render it properly. Some problem descriptions and solutions can also be found in this thread: https://drupal.org/node/467190

Pay particular attention to these comments:

To see what kind of information is accessible in your context, you can use several methods of examining the `$data` variable as Thomas4019 already mentioned. E.g.:

* `<?php print_r($data); ?>`
* `<?php var_dump($data); ?>`
* `<?php dpm($data); ?>` This requires the devel module being enabled

# Answer
> 0 votes
I imagine $data-\>node\_data\_field\_story\_text\_html\_field\_one\_value is not being set.

Try running dpm($data) if you have the devel module enabled which will show you all the object members set.

Also you should check your php error logs and Drupal watchdog for any errors to see if they provide a clue as to why it doesn't work

# Answer
> 0 votes
If you are testing it as an anonymous user or user other than super admin, then please check the permission of the fields and if you have set the value in the above said field or not. May be the variable you are using to access the field value is not correct so check by printing $data variable.

```
   print_r($data);

```

---
Tags: entities
---


title: Show taxonomy only when logged in

text:
# Question
Title: Show taxonomy only when logged in
I have a content type with two taxonomy terms: "Intern" and "Non-Intern" I want the items with "Intern" to only be visible when logged in. How do I achieve that?

# Answer
> 1 votes
You can use Taxonomy access module to access control for user `role`.

> * Automatically controls access to nodes (based on their taxonomy terms).
> * Configuration page for each user role.
> * Three node access permission types: View, Update, Delete.
> * Two term access types: View tag, Add tag.

---
Tags: taxonomy-terms, users
---


# Question
Title: Generate h1 et h2 inside link with theme function
I am trying to modify a module.

I have two variables: let say **$date = "mydate"** and **$title = "mytitle"**

I have for the moment a theming function that creates a link by doing something like this:

```
$vars['row_dates'][$i] = l( $date, '', array('fragment' => $vars['timelinr_dates_id'] . '_' . $i, 'external' => TRUE));

```

which output a result like: mydate

I would like now to output something like:

```
<a href="...">
    <h2>mydate</h2>
    <h1>mytitle</h1>
</a>

```

the problem is that if I do:

```
$date = "<h2>mydate</h2>";
$title = "<h1>mytitle</h1>"

```

then the markups are outputed like text Is there a way to acheive it ?

# Answer
> 0 votes
You need to set the html-Option of l() to true:

```
l( $date, '', array(
  'fragment' => $vars['timelinr_dates_id'] . '_' . $i,
  'external' => TRUE,
  'html' => TRUE
));

```

Otherwise all html-tags get escaped by l().

---
Tags: 7, theming
---


# Question
Title: How to set which node a module loads on?
I have a module that works on the hook\_user (updates) it pushes details to another DB. I only want this module to load on the admin user edit screen where you can assign roles to a user. Currently I have a message that either says because you are role X you are allowed to send data, else sorry you do not have the rights to send data. However these messages display on every page in my drupal 6 website. I was wondering how I can limit this module to just the admin user edit screen, that would help a lot.

# Answer
Check the current user having admin role, if you are using drupal superadmin, then check current logedin user's id equals 1.

```
<?php
  function custommodule1_user($op, &$edit, &$account, $category = NULL) {
    global $user;
    if($op == 'update') {
      if (in_array("administrator", $user->roles) || $user->uid == 1) {
          // Show message that only for admin.
          // Do whatever you want do for admin.
          drupal_set_message('You are Administrator you are allowed to send data');
      }
      else {
          // Show message for author users.
          drupal_set_message('Sorry you do not have the rights to send data');
      }
    }
  }
?>

```
> 0 votes

---
Tags: 6
---


# Question
Title: PECL uploadprogress installed - but no progress bar, just spinning gif
Pretty much same question as this. I've set everything up - can confirm pecl uploadprogress is on, and activated from the status reports page.

But how do I see this for uploading files? I've recently enabled the handy drag and drop upload module from here \- which supports the progress bar, but whenever I upload something it's just a spinning gif. I can't find where to alter the progress indicator as mentioned in the answer in the first link above - can anyone point me in the direction?

cheers

# Answer
Managed to solve this by changing the widget type of the field - back to normal 'File'. Then if you go to the manage field display for this, you should now have an option to set the progress indicator to either 'Throbber' or 'Progress Bar'. If you select progress bar, then flip the widget type back to drag n drop module - it seems to do the trick. Cheers
> 2 votes

---
Tags: files
---


# Question
Title: Multistep ajax form, rebuild form and replace contents with the current step
I have a multistep form. In the first step i have an AJAX submit callback that updates my &$step in $form\_state and should return the next step of the form in the same page (replace contents of the form with the form elements in the second step) e.g.

```
  <?php

  funtion my_form_builder($form, &$form_state) {
     if (empty($form_state['step'])) {
      $form_state['step'] = 'step_1';
     }
     $step = & $form_state['step'];
     // build step 1
     if ($step == 'step_1') {
       $form['first_submit'] = array(
         '#type' => 'submit',
         '#ajax' => array(
           'callback' => 'form_first_submit',
          ),
         '#executes_submit_callback' => TRUE,
       );
     }
     // build step 2
     if ($step == 'step_2') {
       $form['elem_2'] = array(...)
       $form['elem_2_1'] = array(...)
     }
     return $form;
  }

  function form_first_submit($form, &$form_state) {
     $current_step = & $form_state['step'];
     // store values...
     // move on to the next step
     $current_step = 'step_2';

  $form = drupal_rebuild_form('my_form_builder', $form_state, $form);
  $commands[] = ajax_command_replace('#main-content', render($content));
  // return  ajax
  return array(
   '#type' => 'ajax',
   '#commands' => $commands,
  );
  }

```

So, naturally after the first submit, i should be able to rebuild my form and return to the #main-content the form elements defined for step 2. Why this doesn't work?I see the code passes on the right places and rebuilds and prepares the form for rendering.

I tried with drupal\_build, drupal\_retrieve\_form and im getting nowhere.

If i `drupal_get_form('another_form_id')` it will work as expected.

Where is my error?

# Answer
You dont' have to call drupal\_get\_form explicitly, instead mark form to rebuild.

In your ajax powerd element define two attributes: #submit, and #ajax.

#submit references the function that makes the action related to the submission (in your case changing the step value to 2 in form state). Also, set $form\_state\['rebuild'\] to TRUE.

#ajax, where you set the ajax parameters and the PHP function that will return the result form the built form (in this case, the rebuilt one). When this fucntion is called form is build (or rebuilt) and you only have to return the form part you need.

Take into account that in the #ajax attribute you can set the HTMl element that will be replaced by the answer, so you don't need to use ajax commands.

```
<?php

  funtion my_form_builder($form, &$form_state) {
     if (empty($form_state['step'])) {
      $form_state['step'] = 'step_1';
     }
     $step = & $form_state['step'];
     // build step 1
     if ($step == 'step_1') {
       $form['first_submit'] = array(
         '#type' => 'submit',
         '#ajax' => array(
           'callback' => 'form_first_ajax_callback',
          ),
         '#executes_submit_callback' => TRUE,
         '#submit' => array('my_form_builder_callback'),
       );
     }
     // build step 2
     if ($step == 'step_2') {
       $form['elem_2'] = array(...)
       $form['elem_2_1'] = array(...)
     }
     return $form;
  }

  function my_form_builder_callback($form, &$form_state) {
     $current_step = & $form_state['step'];
     // store values...
     // move on to the next step
     $current_step = 'step_2';
     $form_state['rebuild'] = TRUE;
  }

  function form_first_ajax_callback($form, &$form_state) {

  $commands[] = ajax_command_replace('#main-content', render(form['element_to_return']));
  return array(
   '#type' => 'ajax',
   '#commands' => $commands,
  );
  }

```

Example uses the ajax commands aproach.

Check the Form API internal workflow illustration.
> 2 votes

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


# Question
Title: Superfish menu - how to remove parent sign: "PARENT_LINK >>"?
I built my main menu (horizontal) using superfish module.

All the parent links in the menu (that has drop down menu with childs) has a sign. For example it looks like that: "PARENT\_LINK \>\>"

I really tried to find a solution through CSS files, but couldn't solve it.

How can I remove the "\>\>" sign?

# Answer
> 2 votes
In your superfish block settings there should be a setting that reads "AUTO-ARROWS:" with a dropdown.

Set that to no (and save) and you shouldn't have any arrows anymore.

---
Tags: routes, theming, navigation
---


# Question
Title: How to export field collection with Drupal 7 views data export plugin?
The Views Data Export plugin appears to work perfectly with the data that I have, though I have a field called "Items Bought" consisting of fields ("Item Bought" and "Cost"). For each content type of type "ShoppingRecord" a user could have one or more "Items Bought" field collections (i.e. Bannana $2, Apple $5).

When I add the field to my "page". I noticed that when I create a view with the "Data Export" and use CSV as the option, I am getting blanks for all the rows in the "Items Bought" column. Is there some way to get the plugin to recognize field collections and maybe export them all into the same field in the CSV? All the other fields that are not field collections appear to export properly.

# Answer
If you only need the first result you can add a relationship in the view. Search for the name of the field collection. Once you add this relationship you should be able to access the field collection items and add them to your output.

If you want all the values you need to search add the field collection to your view rather than the fields directly. You then have the options of how to display the results but these options are limited.
> 2 votes

---
Tags: importing-exporting
---


# Question
Title: Is it possible to use drush to save a theme setting?
I need to set a theme setting via a scripting mechanism (specifically phing). Is it possible to use drush to set a very specific theme setting, without passing JSON?

```
drush vset {theme_setting} {specific_theme_setting}

```

I can use `drush vget theme_{custom_theme}_settings --filter=json` and get the JSON string, but I can't (at least I'm not aware of a way) set a specific key item of that array...?

# Answer
Drush does not have any facilities for manipulating elements of arrays in the variable table; however, you can use `drush php-eval` to call `variable_get()` `variable_set()`, and include a bit of php to manipulate the json yourself.

It would also be pretty easy to make your own Drush command to manipulate the items you'd like to set regularly. See the drushify tool for a fast way to get started.
> 2 votes

---
Tags: drush
---


# Question
Title: Weekly Gym schedule / irregular recurring Events / D7
I've been searching and trying for weeks now, but could not find a way to properly display a gym's schedule. Here is the setup:

* atm there are 3 gym branches with their own unique schedule (but using one pool of classes)
* each gym got its own node showing a schedule table/calendar
* classes recur irregular e.g. Gym-1: "Zumba" each Mo 8-9am and Fr 6-7pm (but Gym-2 with different times)
* tables only need to be editable by admins; no user interaction
* table granularity should be 15 or 30 minutes (but only showing rows with at least one item)
* also, on the front page there will be a block, showing the next class for each gym (day and time)

So I created one node for each class (e.g. "Bodypump", "Zumba",..) and added all kind of fields but can not work out how to show them in 3 independent schedules. I think it has to be 3 views but unsuccesfully tried TableField, multi-value date Fields with FullCalendar, Taxonomy,... Is it actually possible to do this with existing modules? Pushing me in the right direction would be highly appreciated!

Note: I am not capable of programming my own modules, but at least i would know how things stand when this is becoming necessary. Also I am not a Drupal pro and might have missed the obvious.. Thank you!

# Answer
Try this:

1. Create content types gym1, gym2, gym3... \> add suitable fields to them eg. Title and time(name the time field to field\_gym1\_calendar, reason for this -- see part five).
2. Create content: EXAMPLE: "content type: gym 3 --\> Title: bodypump, Time: 10/10/2013 14:00-14:30". You can also add a taxonomy "bodypump, zumba, etc..." and add a 'Term Reference'-field to your content type (This way admin doesn't have to type 'bodypump' or 'zumba' every time he's adding stuff to calendar, just select the right one from dropdown-box)
3. Install "Date Tools" and "Date"- modules
4. Go to Views \> look for button "+ Add view from template" On top of the page.
5. Search for the NAME of the TIME field you added to CONTENT TYPE gym1. Should look something like this: "A calendar view of the 'field\_gym1\_calendar' field in the 'node' base table."
6. Name this view to 'Gym 1 calendar'- for example.
7. If you have content in "gym1/......." It should be listed in "Preview" Below

Play around with "+ Add view from template" button, it creates a calendar view of any node type with -date / time- field in it (I think)

All this works in a commerce\_kickstart install I'm currently f\*cking with.. All the modules you need are listed in my comment... don't know. Have fun :)
> 0 votes

---
Tags: datetime, theming, javascript
---


# Question
Title: Drupal7 provoking ajax error in Views (installed in sub folder)
I have installed drupal 7 in a subdirectory of my domain. The subdirectory is masked as explained on the following site: http://kahthong.com/2011/05/how-serve-drupal-sub-directory-web-root-0

Now, this works pretty well EXCEPT when an AJAX query is done by the drupal backend. This will always produce an error. One example is in the Views-UI module: when I try to edit some setting in a view, an error like the follow will pop up:

```
An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: ***mydomain****/en/admin/structure/views/ajax/display/store/page/row_options
StatusText: error
ResponseText:
ReadyState: 0

```

My guess is that the URL rewriting specified in the .htaccess is not being applied. Therefore my two questions:

* ***Why does the URL rewrite not work for AJAX queries***
* ***How can I fix this?***

# Answer
I have found that my problem is distinct: the AJAX request has included the www in front of my domain meanwhile I have set the default without www.

So I had to change in settings.php the base\_url FROM 'http://www.mydomain.com' TO 'http://mydomain.com'

Cheers
> 1 votes

---
Tags: views, ajax
---


# Question
Title: How to build a webform with a slider field
The Webform module itself doesn't (yet?) support the html5 `<input type="range">` element, which isn't really cross-browser compatible yet anyway. I suppose right now (2013) we're stuck using a Javascript solution, and the most popular solution in the Drupal world seems to be the JQuery UI slider component, via the sliderfield module. However, the module page and issue queue makes no mention of integration with Webform.

I'm wondering if there is a module I've somehow overlooked that does offer slider/range widgets for Drupal Webforms, and if not, what is the most recommendable way to implement one, that could be shared and or turned into a module.

# Answer
You will actually need to create a custom module to create a new webform component. This link contains more information on how to get it done http://jamestombs.co.uk/2012-09-24/create-new-webform-element-drupal-7
> 1 votes

---
Tags: webforms, javascript
---


title: Drupal 6 Search Redirect

text:
# Question
Title: Drupal 6 Search Redirect
I would like to modify the search box to point to a custom search function. So far, I have modified template.php to detect when the search box is being called from a specific module and I reset some variables.

```
function my_theme_preprocess_search_block_form(&$vars, $hook) {
    $uri = request_uri();
    if (preg_match("/\/my_module/", $uri)) {
        unset($vars["form"]["search_block_form"]["#title"]);
        $vars["form"]["search_block_form"]["#title"] = t("SOME SEARCH MESSAGE");
        $vars["form"]["search_block_form"]["#value"] = t("SOME SEARCH TERM");
    }
}

```

That works fine. But now what I want to do is have that form submit to some module of my own creation. Oddly, this isn't as obvious. Do I need to modify something in modules/search/ ? If so, what?

# Answer
The way to alter the action handler for the search form is to add a submit handler, as outlined here: https://stackoverflow.com/questions/6444769/altering-search-form-action-not-working-for-custom-search-module-drupal-6. You can call your function in the submit handler or redirect to it from the submit handler.

```
/**
* Implementation of hook_form_alter()
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'search_block_form') {
    $form['#submit'][] = 'mymodule_form_submit';
  }
}

/**
 * Process a block search form submission.
 */
function mymodule_form_submit($form, &$form_state) {
  // The search form relies on control of the redirect destination for its
  // functionality, so we override any static destination set in the request,
  // for example by drupal_access_denied() or drupal_not_found()
  // (see http://drupal.org/node/292565).
  if (isset($_GET['destination'])) {
    unset($_GET['destination']);
  }

  // Check to see if the form was submitted empty.
  // If it is empty, display an error message.
  // (This method is used instead of setting #required to TRUE for this field
  // because that results in a confusing error message.  It would say a plain
  // "field is required" because the search keywords field has no title.
  // The error message would also complain about a missing #title field.)
  if ($form_state['values']['search_block_form'] == '') {
    form_set_error('keys', t('Please enter some keywords.'));
  }

  $form_id = $form['form_id']['#value'];
  $form_state['redirect'] = 'search/mymodule/'. trim($form_state['values'][$form_id]);
  }

```
> 0 votes

---
Tags: 6, search
---


# Question
Title: How do you keep production site in synch with development site?
I've got a Drupal development site where I test everything (modules, configurations etc.) before implementing on the production site. As it is right now, I need to write everything I do on paper and carry out the same steps on the production site.

How do you keep production sites in synch with development sites? Is there any handy modules out there for this purpose? To what extent can Drush help me out on this?

# Answer
> 8 votes
There are a number of approaches to synchronizing configuration between environments.

A few popular ones for Drupal 7 are:

1. https://drupal.org/project/features (recommended)
2. https://drupal.org/project/strongarm
3. https://drupal.org/project/configuration

For example with drush and features you can revert a component to the code definition with

```
drush fr my_feature

```

For more info on drush and features https://drupal.org/node/960926

In Drupal 8, exporting configuration has become much easier:

> With Drupal 8 you can deploy a configuration from one environment to another. This capability replaces the need for various contributed modules such as Features, Strongarm and Context. https://drupal.org/documentation/administer/config

# Answer
> 1 votes
David's answer is good. In addition, you might also want to take a look at Drush CTools Export Bonus. It uses the same underlying technology as features, but is designed with configuration management in mind rather than collections of features. It supports block configuration.

Also, if you want to script simple block configuration operations (e.g. turning on devel blocks on a development machine), drush\_extras now supplies some simple block manipulation commands.

---
Tags: 7, configuration
---


title: Hide Superfish menu on selected pages

text:
# Question
Title: Hide Superfish menu on selected pages
I have installed Danland Theme and it is cool. I want the superfish menu to be appeared on few pages, not all the pages. For example if I type a wrong URL address in the address bar, it says Page not found and it still gives that Superfish menu there on the page.

I have some pages, where I don't want that superfish menu to be appeared.

Can anyone help?

# Answer
> 0 votes
Goto /admin/structure/block/ configure your superfish menu block

Scroll down to the bottom and locate "Show block on specific pages"

select this option " Only the listed pages "

and define the paths of the pages on which you want superfish menu to appear.

---
Tags: theming, navigation
---


# Question
Title: Why is the Media module ignoring view_mode display settings?
I'm using the Media module 7.x-2.

I've added an image field to a content type, and I've enabled the Media CKEditor/Wysiwyg plug in and filter.
I've added fields to the image media/file type and set these up to display for the 'large' view mode setting.
When using the field, the image is displayed along with the other fields, as normal, but when I've inserted the image via Wysiwyg, only the image comes through; the fields are not displayed.

Why is this happening?

# Answer
This is currently not supported in Media module. There is work being done though. Checkout this issue. https://drupal.org/node/1792738
> 1 votes

---
Tags: media
---


title: Node Export and VBO

text:
# Question
Title: Node Export and VBO
In an effort to mass export all my nodes, I installed Node Export and VBO. The NE project page claims that it supports VBO, but I can't seem to edit the prepackaged VBO view and add the Node Export operator. Am I missing something in terms of configuration?

I've done due diligence with searching for a potential solution, but am still looking for one.

Node Export 7.x-3.0 VBO 7.x-3.1

# Answer
> 4 votes
A few steps to check:

* in `admin/config/content/node_export`, in `Format to use when exporting a node` check "Drupal var export"
* in `admin/structure/views`, you should have a view named "Content". Edit it, and click on "Bulk operations: Content" in the Fields zone
* in the lightbox, check `Node export (Drupal var export) (node_export_drupal_action)`

# Answer
> 4 votes
Even if "`Drupal var export`" is initially preselected in "node\_export" configuration (`admin/config/content/node_export`), "Node export (Drupal var export)" option do not appear in "Selected Bulk operations" of view Edit interface.

Just save "node\_export" settings (even if no updates made) to force Drupal variables to be saved, and `Node Export` option will appear.

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


# Question
Title: Pulling Possible Select Values From A Field (Drupal 7)
I have been looking if there is a function that return all the possible values for a field. I have a select field that is a Node Ref. So, function list\_allowed\_values() is out of the question. Because, list\_allowed\_values() is not compatible with Node Ref. Does anyone know a function to get all the possible Node Ref for a field?

Or do have to code my own function? Thanks, Nate

# Answer
> -1 votes
Ok, I did some digger on google. ychaugule made a nice function for this problem. Here is the post. Also, reference to the information here:

"But the above code will only work for select list, not for node reference or other types of references. \_field\_allowed\_values() function is a custom function which returns allowed values of reference type field. The function returns allowed values for node reference and term reference field and can be extended to get allowed values of other reference fields as well. - See more at: http://yogeshchaugule.com/blog/2013/get-allowed-values-select-list-field#sthash.xnf89Cgn.dpuf"

```
<?php
function _field_allowed_values($field_name) {
      // retrieve field configurations from DB.
  $allowed_values = array();
  $query = db_select('field_config');
  $query->condition('field_name',$field_name)
  ->fields('field_config',array('type', 'data'));

  $result = $query->execute()->fetchAssoc();

// Allowed references type
  $ref_type = array(
    'node_reference',
    'taxonomy_term_reference',
    );

  $field_config = unserialize($result['data']);
  if (in_array($result['type'], $ref_type)) {
    if ($result['type'] == 'node_reference') {
      $node_types = array_filter($field_config['settings']['referenceable_types']);

      $query = db_select('node');
      $query->condition('type', $node_types, 'in')
      ->condition('status', 1)
      ->fields('node', array('nid', 'title'));
      $allowed_values = $query->execute()->fetchAllKeyed(0, 1);
    }
    elseif ($result['type'] == 'taxonomy_term_reference') {
      $allowed_values = taxonomy_allowed_values($field_config);
    }
  }
  else {
    $allowed_values_raw = unserialize($result['data']);
    $allowed_values = (!empty($allowed_values_raw['settings']['allowed_values']) ? $allowed_values_raw['settings']['allowed_values'] : array());
  }
  return

  $allowed_values;
}

$field = _field_allowed_values('FIELD_NAME');

```

---
Tags: 7, entities
---


# Question
Title: Email without body being sent to newly added users
In "admin\>config\>people\>account-settings" for "Who can register accounts?" settings I have selected:

* Visitors, but administrator approval is required.
* Require e-mail verification when a visitor creates an account.

I have even enabled notifications for sending emails to newly added users from the options available at the bottom of the same page and I am using the default subject and body for the mail.

I have got an very unusual problem that my newly added user receives a mail from my site without any body. Though the subject of the mail is same but the body of the mail doesn't shows up; all I can see in email's body are just three dots (...). Please help.

# Answer
> 0 votes
Do you have any module that alters mail before being sent? If so, can you check if they are causing the problem.

Can you check for other mails as well, sent by Drupal. Do they generate the same issue?

Apart from that, please check the mail headers once, that might give you some hint.

If you get anything, Post it here, I will be happy to help ....

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


# Question
Title: Figuring out a conditional statement for a specific page
I have a view which is modified by a views template page - this is in Drupal 6.

I'm trying to figure out a condition to affect the layout. Currently, the element seems to be generated in page.tpl.php, which is fine, but I want to add a condition for this specific page, in order to add an id to this element.

For other pages, I've used the node id to do this, as such:

```
else if ($node->nid == '250' || $node->nid == '429' || $node->nid == '555' || $node->nid == '378') {print '<h1'. ($tabs ? ' class="with-tabs"' : '') .' id="medspecheader">'. $title .'</h1>';}

```

But I'm not sure how to do this with the view page. Is there a machine name that I can use, or something to affect the layout?

# Answer
If you are asking how to modify the default `page.tpl.php` to do something different when a specific path is called, you could just copy `page.tpl.php` to `page-PATH.tpl.php`, eg, `page-PATH-THAT-VIEWS-USES.tpl.php` and then anything inside this new template would be used just for the page displayed at that path.

In your example code, as an example, you could copy `page.tpl.php` to `page-node-250.tpl.php` or `page-node-429.tpl.php` etc and then you wouldn't need any `if`s in them with respect to the `id="medspecheader"` as these templates would only be used when looking at those nodes.

Just realize that the path used is the drupal system path, not any alias, but Views does create such a path for any Views that utilize a Page Display.

Lots more information about template suggestions for Drupal 6 can be found here.

If these don't work for your specific needs, you can also create more templates suggestions for Drupal to use via a `hook_preprocess_page()` call in your module or theme.

For example, if you wanted the page to display differently whenever a specific node type is being displayed, and you didn't want to hard code in all of the specific node nids, you could do something like this in your theme...

```
function YOURTHEME_preprocess_page(&$variables) {

  if (isset($variables['node']) && $variables['node']->type=='med_special') {
    $variables['template_files'][]='page-cck-' . str_replace('_','-', $variables['node']->type);
  }

  // any other page preprocessing goes here

}

```

Now, whenever page displaying a node of type `med_special` is called up, Drupal will look for a `page-cck-med-special.tpl.php` file in your theme to display it.
> 0 votes

---
Tags: views
---


# Question
Title: How to wrap content around a display suite region?
I'm using the nifty Display Suite module to create a custom layout for an event page. I'm using the stacked fluid 2 column layout with the Body field on the left and the image and event fields in the left column.

I would like the body (left region) to wrap around the image and date fields (right region). I''ve been unable to figure out to to accomplish this.

http://ctu.robohobo.net/node/17

How would I make that happen?

Drupal: 7.19 Display Suite: 7.x-2.0

# Answer
To solve this issue you need to reorder your html by flipping columns in your custom layout

If you inspect your html you'll see that group-left renders first then group-right

```
<div class="group-left">content</div>

<section class="group-right">image and location </section>

```

So you need to have the following structure:

```
<div class="group-left">image and location </div>

<section class="group-right">content</section>

```

Then add the following style to your css file

```
.ds-2col-stacked > .group-left {
  float: right;
  width: auto;
}

.ds-2col-stacked > .group-right {
  float: none;
  width: auto;
}

```
> 1 votes

# Answer
Try to change structure of template file of display suite module file named ds-2col.tpl.php in :

**your project \> sites \> all \> ds \> layouts \> ds\_2col \> ds-2col.tpl.php**
> 0 votes

---
Tags: theming, location, display-suite
---


# Question
Title: how to change the widget of view's exposed filter form?
I have an exposed filter form, and its default widgets are textfields. I'd like to change them to selects based on values from database. I have tried `hook_form_alter` and `hook_form_views_exposed_form_alter`, but get an error:

```
An illegal choice has been detected. Please contact the site administrator.

```

The code I used to change the widget is like this and I've tried `#validate` option.

```
$form['field_address_province'] = array(
        '#type' => 'select',
        '#options' => $province_options,
        '#validate' => true,
        '#description' => 'Select address',
    );

```

Edit:

Sorry for the lack of infomation. The `$province_options` is an array like

```
Array
(
    [0] => Please Select
    [6] => Area1
    [7] => Area2
    [2] => Area3
)

```

# Answer
> 2 votes
i tested this kind of thing and found that when you try to switch a exposed widget field you need to provide an array with the empty first key, if it is checkboxes or radios; if new widget will be a select then you need to provide an array with the 'All' first key. E.g.:

```
//Suppose that you have a default input widget which you want to change to select widget.
//We will get the values which we want our new select widget will get as options:
$opts = array(
  'first_key' => 'First value',
  'sec_key' => 'Second value',
);

// Then we will add required 'All' first key:
$options = array('All' => 'Choose a value') + $opts;

// Then we will create our new select widget
$form['YOUR_FIELD_NAME'] = array(
     '#type' => 'select',
     '#title' => t('MY TITLE'),
     '#options' => $options,
   );

```

---
Tags: views
---


title: How can I download a distribution?

text:
# Question
Title: How can I download a distribution?
Am I right in thinking that the Drupal distributions that I can download from http://drupal.org/project/distributions are a standard Drupal core download with a load of other stuff added at /profiles?

Anyone know if there are any plans to create a dev branch of distributions that would automatically update the core version that the distribution is running on? Currently it seems that the distribution runs on whatever core version its developer has chosen.

And how can I use distributions with Drush? Is there an equivalent to `drush dl drupal` that will download a specific distribution?

And, finally, is there any difference between an install profile and a distribution?

# Answer
A distribution is a collection of Drupal modules configured to perform a certain function. An installation profile is a script that will configure Drupal at install time. A distribution always has an installation profile in it, but not every installation profile will be a distribution. An installation profile can be distributed without the modules it uses; in that instance, you can use `drush make` to download them, as installation profiles include a make file.

Drush dl will download distributions as well as Drupal core and contrib modules (e.g. `drush dl commerce_kickstart`). Distributions are updated whenever the developer chooses to update them; of course, you can always run `drush pm-update` on your copy of your distribution, but there are testing concerns -- occasionally, updates will break things. This is no different with distributions than your own Drupal install, but in the case of a distribution, presumably the dev will test and fix problems before rolling out an updated release.
> 6 votes

# Answer
To install a distribution with Drush you have to :

1. Download the distribution from drupal.org :

`drush dl distribution_i_want`
2. Install the distribution you want

`cd directory_created_by_drush_dl`

`drush site-install distribution_i_want --account-name=admin --account-pass=password --db-url=mysql://mysqldatabaseuser:mysqldatabasepassword@localhost/mysqldatabase`

Notice : when you download look at the name of the distributions it could be a different name than the project like `distribution_i_want`
> 3 votes

---
Tags: drush, distributions
---


# Question
Title: MailChimp campaign not showing up in Drupal 7
I set up the MailChimp (https://drupal.org/project/mailchimp) module by following the readme file. I've enabled all the Mailchimp modules and added the API key to my drupal instance. I've created and Sent one campaign through MailChimp however, when I go to /admin/config/services/mailchimp/campaigns the page is blank. I've cleared the cache but the page is still blank. I was expecting to see the campaign I sent earlier but it is not there.

What am I doing wrong or missing?

# Answer
You need to have libraries 2.0 module installed and download a special mailchimp API library. https://drupal.org/documentation/modules/mailchimp
> 2 votes

# Answer
I think you use mcc module for create mailchimp for node. when you disable this module its show list of all campaign which you created.

you can also use mailchimp function for getting list of campaign:

$campaigns = mailchimp\_campaign\_load\_multiple();
> 2 votes

---
Tags: emails
---


title: Views table with two columns

text:
# Question
Title: Views table with two columns
I have 3 fields.

I've set them with view table, set their labels and they are displaying in this order:

field1 label field2 label field3 label

field1 value field2 value field3 value

They are in three columns.

How can I set them in this order like on the screenshot?

# Answer
You can use Views Flipped Table module.

> This module provides a views table style with rows and columns flipped. This is useful for views showing few entities with many fields, such as product comparison.
> 4 votes

# Answer
I think Views Flipped Table will help you.
> 4 votes

---
Tags: views, theming
---


# Question
Title: How to make Drupal upload pasted links to .doc files from the internet
Let's say I have a Drupal website and I want there a function that would work like this: Paste an URL to a .doc file, so on submit Drupal downloads that file, uploads to its local server and generates a link to download from the website.

I was wondering if this needs custom coding or can this be achieve with a module?

# Answer
> 1 votes
Can be achieved with Filefield Sources module.

> FileField Sources is an extension to the FileField module. The FileField module lets you upload files from your computer through a CCK field. The FileField Sources module expands on this ability by allowing you to select new or existing files through additional means, including:
>
> * Re-use files by an auto-complete textfield
> * Attach server-side files uploaded via FTP
> * **Transfer files from a remote server (cURL required)**
> * Paste a file directly from the clipboard (Drupal 7 only)
> * Select existing files through the IMCE file browser

---
Tags: 7, files
---


# Question
Title: Custom ckeditor.styles.js possible to specify for any/all elements?
In the ckeditor.styles.js can you leave the element blank or specify multiple elements in a single line? Ex. if the class .red could apply to any element, do I actually have to write out a line for every possible element?

```
{ name : 'Red' , element : 'p', attributes  : { 'class' : 'red' } },
{ name : 'Red' , element : 'h1', attributes  : { 'class' : 'red' } },
{ name : 'Red' , element : 'h2', attributes  : { 'class' : 'red' } },

```

etc...

Or is there an easier way?

# Answer
> 5 votes
I also searched for a way to specify multiple elements for one style - and it doesn't seem to be documented anywhere. I was successful with specifying multiple elements as an array:

```
{ name: 'Red', element : ['h1', 'h2', 'p'], attributes: { 'class': 'red' } }

```

This works for me in CKEditor 4.2.1.

---
Tags: wysiwyg
---


# Question
Title: Create hierarchical taxonomy url alias with token term:parents using a field other than term:name
Sorry, the title is a bit of a mouthful but I will attempt to clarify.

I have a question about pathauto tokens to create a URL alias for a nested/hierarchical taxonomy.

Specifically, I have a taxonomy called Category, which is `n` layers deep; e.g:

> Category level 01 \> Category level 02 \> Category level 03

And so on. The question appears to have been asked many times before and there are a number of good solutions, including the following pattern:

> \[term:parents:join:/\]/\[term:name\]

This yields the following url alias for the above example:

> category-level-01/category-level-02/category-level-03

Pretty straightforward. This would be perfect except in my example the taxonomy terms are in Chinese.

I need English in the path aliases, so I have set up a new field in my taxonomy called 'Name English'. This gives me the following replacement pattern:

> \[term:parents:join:/\]/\[term:field\_name\_english\]

Which is almost perfect, but the parents default to using the `name` field, and there does not seem to be an easy way of overriding this. I cannot use the parent taxonomy terms with delta because it's not dynamic; e.g:

> \[term:parents-all:1:field\_name\_english\]/\[term:field\_name\_english\]

Some taxonomy depths will be deeper than others.

---

So, in summary, I need to somehow specify an alternate term field to name for the `[term:parents]` token. To do this I assume I will need to do one of the following:

1. Create a custom token
2. Override the current `[term:parents]` token

Can anyone advise on this? Thanks a million.

# Answer
## Option 1

You could copy the token created by the taxonomy module for \[term:parents:join:/\] and recreate it in your own module, using your field as a substitute for title.

This would require some familiarity with the token system. There is also a module entitled 'Custom Token' that might be worth a look, though I have not used it.

## Option 2

One divergent way I could suggest to get around this is to use drupal's title field to store your english language title, and another field to store the chinese title (\*field\_chinese\_title\*).

You could then preprocess the node title within your theme/module to replace $variables\['title'\] with \*field\_chinese\_title\*. You might also have to do this for menu entries and search results, and you would also have to remember to use \*field\_chinese\_title\* for views fields etc.

*YOURTHEME/template.php:*

```
<?php
function YOURTHEME_process_page(&$variables) {
  if (isset($variables['node']->field_chinese_title['und'][0]['value'])) {
    $variables['title'] = $variables['node']->field_chinese_title['und'][0]['value'];
  }
}

function YOURTHEME_preprocess_search_result(&$variables) {
  // use chinese version of title for search results
  if (isset($variables['result']['node']->field_chinese_title)) {
    $variables['title'] = $variables['result']['node']->field_chinese_title['und'][0]['value']);
  }
}

```

I admit I have little experience of multi language sites, and I do realise that this method might look a little crude, but I have used a variation (with autonodetitle) to differentiate the titles used by menu entries and nodes (so that menu entries can optionally be more concise) and it works beautifully. For my use case, I later found a module for that...
> 1 votes

---
Tags: 7, taxonomy-terms, tokens, path-aliases
---


# Question
Title: oderid sort not work correclty in number more than 1000 in commerce_orders views
I look at the `commerce_orders` views, and I see some strange there, when I set sort record according by orderID it not work correctly for number more than 1000 ,it seems that only 3 first digit consider in sort, Is this a bug in views? appreciate any help

and query is :

```
SELECT commerce_order.order_number AS commerce_order_order_number, commerce_order.order_id AS order_id, commerce_order.uid AS commerce_order_uid, commerce_order.created AS commerce_order_created, commerce_customer_profile_field_data_commerce_customer_billing.profile_id AS commerce_customer_profile_field_data_commerce_customer_billi, users_commerce_order.name AS users_commerce_order_name, users_commerce_order.uid AS users_commerce_order_uid, commerce_order.status AS commerce_order_status, 'commerce_customer_profile' AS field_data_commerce_customer_address_commerce_customer_profi, 'commerce_order' AS field_data_commerce_order_total_commerce_order_entity_type
FROM
{commerce_order} commerce_order
LEFT JOIN {users} users_commerce_order ON commerce_order.uid = users_commerce_order.uid
LEFT JOIN {field_data_commerce_customer_billing} field_data_commerce_customer_billing ON commerce_order.order_id = field_data_commerce_customer_billing.entity_id AND (field_data_commerce_customer_billing.entity_type = 'commerce_order' AND field_data_commerce_customer_billing.deleted = '0')
LEFT JOIN {commerce_customer_profile} commerce_customer_profile_field_data_commerce_customer_billing ON field_data_commerce_customer_billing.commerce_customer_billing_profile_id = commerce_customer_profile_field_data_commerce_customer_billing.profile_id
WHERE (( (commerce_order.status NOT IN  ('cart', 'checkout_checkout', 'checkout_shipping', 'checkout_review', 'checkout_payment', 'checkout_complete')) ))
ORDER BY commerce_order_order_number DESC
LIMIT 50 OFFSET 0

```

# Answer
As you can see in `commerce_order_schema`, order number is not a number, it's a string:

```
'order_number' => array(
    'description' => 'The order number displayed to the customer.',
    'type' => 'varchar',
    'length' => 255,
    'not null' => FALSE,
  ),

```

This means that your view **works as designed**, sorting this text field that accidentally contains numbers alphabetically. Which, again accidentally, gave you *illusion* of numeric sort when numbers was in \[100-999\] range.

If you need something that's guaranteed to be numeric and ordered the way orders was placed, use either `order_id` (`'type' => 'serial'`) or `created` (`'type' => 'int'`).
> 3 votes

---
Tags: views
---


# Question
Title: How to embedding Comment form for each individual item in drupal's view?
In my current project I want to embedding comment form for individual item in views but I did not get any settings/ configurations for the same in view. I tried to override template for the same using

```
print drupal_get_form('comment_form', array('nid' => $nid));

```

code but I got an error, so please suggest my any idea or any module using that I can show comment form in views.

Error: The website encountered an unexpected error. Please try again later.

# Answer
> 4 votes
In Drupal 7, function comment\_form() is expecting an object parameter instead of array. This code should work for you:

```
$comment = new stdClass;
$comment->nid = $nid;
$form = drupal_get_form('comment_form', $comment);
print render($form);

```

# Answer
> 1 votes
You can do that in the view itself,, When you create a node view for example you choose teaser .. then in the teaser settings check "Display comments"

This will show the comments with the field after each node entry

# Answer
> 0 votes
I added a Global: PHP field and inside it I put in the output code field the following snippet:

```
<?php
$comment_form = drupal_get_form('comment_node_NODETYPE_form', (object) array('nid' => $data->nid));
print drupal_render($comment_form);
?>

```

---
Tags: views, comments
---


# Question
Title: Filtering among Exposed Filters : Parent/Child relationship between two Exposed Filter in Drupal View
I wanted to make a page with `exposed filter` search app in Drupal for a list of people.

I started by creating content type `Bio` and populated it as following:-

Then, I continued making a view with exposed filters of the fields of content type `Bio`. With the help of `Better Exposed Filters`, I am showing both Filters through Checkboxes through AJAX, as below:-

Now, until now, it's working fine. when I select a region or/and any city, the content updates according to that.

What I am hoping to create is a dependency between the `region` and `city`. All I want is that when I select any region in the `Filter by Region`, the lower filter values in the `Filter by City` automatically adjust and show me only the cities for which the `region field` in `Bio` is the selected city.

As an example, If a user selects `EMEA`, the `city` exposed filters should only show European cities.

I have been stuck in this for hours now. I have tried various solutions (`View Dependent Filters`and `Filter Fields`) but to no avail.

I'll be therefore very thankful for any help whatsoever.

# Answer
Look at my currently developing site's exposed filter(where 'Бренд' and 'Модель' fields): Link

If you want to achive this kind of functionality then you can achieve it like this. First you need to alter exposed filter function:

```
function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form['#id'] == 'views-exposed-form-VIEWS_NAME_VIEWS_DISPLAY') {
    if(!empty($form_state['values'])) {
      $form_state['input'] = array_merge($form_state['input'],$form_state['values']);
    }

    // Marks
    $mark_childs = populate_terms_by_vocab('transport_models', TRUE, FALSE);
    $form['field_adv_mark_tid']['#options'] = array('All' => t('--Выберите')) + $mark_childs;
    $form['field_adv_mark_tid']['#ajax'] = array(
      'callback' => 'adv_mark_callback',
      'wrapper' => 'model-wrapper',
      'effect' => 'none',
      'progress' => array(
        'type' => 'throbber',
        'message' => '',
      ),
    );
    // marks end

    // Models begin
    $selectedMark = isset($form_state['input']['field_adv_mark_tid']) ? $form_state['input']['field_adv_mark_tid'] : NULL;

    if($selectedMark != NULL || $selectedMark != FALSE) {
      $model_childs = populate_terms_by_vocab('transport_models', FALSE, $selectedMark);
    }
    elseif($selectedMark == NULL || $selectedMark == FALSE) {
      $model_childs = array();
    }

    $form['field_adv_model_tid']['#options'] = array('All' => t('--Выберите')) + $model_childs;
    $form['field_adv_model_tid']['#prefix'] = '<div id="model-wrapper">';
    $form['field_adv_model_tid']['#suffix'] = '</div>';
    // models end
  }
}

// This is an Ajax callback for $form['field_adv_mark_tid']['#ajax']
function adv_mark_callback($form, $form_state) {
  return $form['field_adv_model_tid'];
}

// This is a helper function which returns terms (suitable for form selectlist, checkboxes or radios..)
function populate_terms_by_vocab($vocabulary_machine_name, $only_parents = TRUE, $parent = FALSE) {
  $vocab = taxonomy_vocabulary_machine_name_load($vocabulary_machine_name);
  $terms = array();
  if($parent == FALSE) {
    $terms = taxonomy_get_tree($vocab->vid, 0, NULL, FALSE);
  }
  elseif($parent == TRUE) {
    $terms = taxonomy_get_tree($vocab->vid, $parent, NULL, FALSE);
  }

  $child_terms = array();
  foreach($terms as $key => $value) {
    if($only_parents && $terms[$key]->parents[0] == 0) {
      $child_terms[$terms[$key]->tid] = $terms[$key]->name;
    }
    elseif($only_parents == FALSE && $terms[$key]->parents[0] != 0) {
      $child_terms[$terms[$key]->tid] = $terms[$key]->name;
    }
  }

  return $child_terms;
}

```

I thinks the logic is the same.. In my case, I am adding to my entity type the two same term reference fields, and on content creation form I am displaying them as different parent field and child field (with pre-render function). By that, first field is holding the top level terms, the second field is holding child terms. And by views ui I am exposing them separately. And, that piece of code is displaying them as I want..
> 2 votes

# Answer
Simple Hierarchical Select module seems to do what you are trying to achieve.

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy. The widget is available in node forms and as Views exposed filter.
>
> * add a new filter using the field set-up as "Simple hierarchical select" or use "Content: Has taxonomy terms (with depth; Simple hierarchical select)" as a new filter
> * use "Simple hierarchical select" as selection type
> * select "Expose this filter to visitors, to allow them to change it"
> 0 votes

---
Tags: ajax, views
---


title: Creation of entity with image field

text:
# Question
Title: Creation of entity with image field
I would like to generate an entity that contains image generated by another module file in drupal 7. This is my code :

```
//appel de la variable user
global $user;

//recuperation de lapercu
$apercu = $_SESSION['image_generate'];
//creation de lobject file
$file_apercu = new StdClass();
$file_apercu->uid = $user->uid;
$file_apercu->uri = $apercu;
$file_apercu->filemime = file_get_mimetype($file_apercu->uri);
$file_apercu->status = 1;
//sauvegarde en base
$file_apercu = file_save($file_apercu);
$file_apercu = (array) $file_apercu;
$file_apercu = array($file_apercu);

//recuperation du pdf
$pdf = $_SESSION['pdf']->uri;
//creation de lobject file
$file_pdf = new StdClass();
$file_pdf->uid = $user->uid;
$file_pdf->uri = $pdf;
$file_pdf->filemime = file_get_mimetype($file_pdf->uri);
$file_pdf->status = 1;
//sauvegarde en base
$file_pdf = file_save($file_pdf);
$file_pdf = (array) $file_pdf;
$file_pdf = array($file_pdf);

//recuperation du numero de commande
$form_panier = $_SESSION['form_state_panier'];
$sql = db_query('SELECT MAX("order_id")
                FROM commerce_order
                WHERE uid = '.$user->uid.'')->fetchAssoc();

//creation de lentity
$values = array(
            'type' => 'commandeflyer',
            'uid' => intval($user->uid),
            'status' => 1,
            'comment' => 0,
            'promote' => 0,
        );

$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('commandeflyer'.$sql['MAX("order_id")']);
$ewrapper->field_flyer_image_commande->set($file_apercu);
$ewrapper->field_pdf->set($file_pdf);
$ewrapper->field_numcommande->set(intval($sql['MAX("order_id")']));
$ewrapper->save(true);
entity_save('node', $entity);

```

When I run this code I get this error :

```
EntityMetadataWrapperException : Invalid data value given. Be sure it matches the required data type and format. dans EntityMetadataWrapper->set() (ligne 122 dans /var/www/commerce_kickstart-7.x-2.9/profiles/commerce_kickstart/modules/contrib/entity/includes/entity.wrapper.inc).

```

But my type correspond : pdf for pdf and jpg for image. Thank you for help.

# Answer
> 1 votes
Solution found :

```
//appel de la variable user
global $user;

//recuperation de lapercu
$apercu = $_SESSION['image_generate'];
//creation de lobject file
$file_apercu = new StdClass();
$file_apercu->uid = $user->uid;
$file_apercu->uri = $apercu;
$file_apercu->filename = basename($file_apercu->uri);
$file_apercu->filemime = file_get_mimetype($file_apercu->uri);
$file_apercu->status = 1;
//sauvegarde en base
$file_apercu = file_save($file_apercu);

//recuperation du pdf
$pdf = $_SESSION['pdf']->uri;
//creation de lobject file
$file_pdf = new StdClass();
$file_pdf->uid = $user->uid;
$file_pdf->uri = $pdf;
$file_pdf->filename = basename($file_pdf->uri);
$file_pdf->filemime = file_get_mimetype($file_pdf->uri);
$file_pdf->status = 1;
//sauvegarde en base
$file_pdf = file_save($file_pdf);

//recuperation du numero de commande
$form_panier = $_SESSION['form_state_panier'];
$sql = db_query('SELECT MAX("order_id")
                FROM commerce_order
                WHERE uid = '.$user->uid.'')->fetchAssoc();

//creation de lentity
$values = array(
            'type' => 'commandeflyer',
            'uid' => intval($user->uid),
            'status' => 1,
            'comment' => 0,
            'promote' => 0,
        );

//creation dentity sans limage et le pdf
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('commandeflyer'.$sql['MAX("order_id")']);
$ewrapper->field_numcommande->set(intval($sql['MAX("order_id")']));
$ewrapper->save(true);
entity_save('node', $entity);

//chargement de lentity
$commandeflyer = node_load($nid = $entity->nid, $vid = NULL, $reset = FALSE);

//ajout image
$commandeflyer->field_flyer_image_commande[LANGUAGE_NONE][] = array(
    'fid' => $file_apercu->fid,
    'uid' => $file_apercu->uid,
    'uri' => $file_apercu->uri,
    'filename' => $file_apercu->filename,
    'filemime' => $file_apercu->filemime,
    'status' => $file_apercu->status
    );

//ajout pdf
$commandeflyer->field_pdf[LANGUAGE_NONE][] = array(
    'fid' => $file_pdf->fid,
    'display' => '1',
    'uid' => $file_pdf->uid,
    'uri' => $file_pdf->uri,
    'filename' => $file_pdf->filename,
    'filemime' => $file_pdf->filemime,
    'status' => $file_pdf->status
    );

//save entity
node_save($commandeflyer);

```

---
Tags: 7, files, entities
---


title: Adding a body ID to a view page

text:
# Question
Title: Adding a body ID to a view page
I would like to add a body id to a view page in Drupal 6 - would I modify template.php? I'm trying to figure out where to make the correct modification

# Answer
You can do this in a couple ways.

Easiest, if you have only one Views page that needs this, you could go into your theme's directory and copy `page.tpl.php` to `page-PATHTOVIEWPAGE.tpl.php` and then inside there, put in the id, eg,

```
<body id="ID" ... >

```

Just change any `/`s in your path to this page to `-`s in the template name and you should be all set. Take a peek at Drupal 6 Template Suggestions for more info.

Now, if you are going to want to do this in multiple pages or need it to be more extensible, then, yes, you will most probably want to add in a `preprocess_page()` hook in `template.php` as well as another custom `page.tpl.php` template file.

What you could do would be to copy `page.tpl.php` inside your theme to, let's say `page-with-body-id.tpl.php`. Then, inside there, you could put something like this:

```
<body id="<?php print $body_id; ?>" ... >

```

Then, inside `template.php` you would add in a `preprocess_page()` hook, eg, something like this:

```
function YOURTHEME_preprocess_page(&$variables) {

   $whereami=$_GET['q'];  // eg, www.yourhost.com/WHEREAMI

   switch ($whereami) {

     case 'events':
     case 'news':
     case 'press':

       $variables['body_id']=$whereami;
       $variables['template_files'][]='page-with-body-id'; // and use this new template

       break;

    }

    // any other page preprocessing goes here

 }

```

Just make sure you don't create a page template that would match an existing path on your system. I doubt `www.yoursite.com/with/body/id` exists but you never know :)

Otherwise, another good place to look for info is here: Overriding Theme Templates in Drupal 6.

Also, if you can use a body class instead of an id, this is even simpler:

```
function YOURTHEME_preprocess_page(&$variables) {

   $whereami=$_GET['q'];  // eg, www.yourhost.com/WHEREAMI

   switch ($whereami) {

     case 'events':
     case 'news':
     case 'press':

       if (empty($variables['body_classes'])) {
         $variables['body_classes']='view-' . $whereami;
       } else {
         $variables['body_classes'].=' view-' . $whereami;
       }

       break;

    }

    // any other page preprocessing goes here

 }

```

which will add `view-WHEREAMI` to the list of classes for the body in (most) default page templates.

RE: How do I do an if conditional based on a view in template.php, you can also do something like this in the appropriate spot:

```
$mgi=menu_get_item();

if ($mgi['page_callback']=='views_page' && $mgi['page_arguments'][0]=='WHATVIEWYOUARELOOKINGFOR') {

  // you are on the views page you are looking for

}

```
> 3 votes

---
Tags: views
---


# Question
Title: How to migrate D6 node reference to D7 organic group membership?
I have created migrations for most of my D6 site to a new D7 site. In the D6 site I have users with profile nodes. Those profile nodes are linked to another type of node via node reference. In D7 the other node will be an organic group.

I would like to be able to transfer the node reference relationship in D6 to organic group membership in D7. Has anyone done this?

Thanks in advance for any help given.

# Answer
I ended up using the advanced method as described in the semi-official documentation (https://drupal.org/node/2023273). It all came down to modifying the query to get the nid and new group nid.

```
class MemberCompanyMembershipMigration extends DrupalMigration {
    /**
     * Construct a migration.
     *
     * @param array $args
     *   Constructor arguments passed at migration-registration time.
     */
    public function __construct($args) {

        parent::__construct($args);

        // Set the fields we want; document in the UI.

        $this->sourceFields += array(
                'nid' => t('Group node ID.'),
                'is_active' => t('User status in the group.'),
                'is_admin' => t('Group admin or not.'),
                'uid' => t('User ID.'),
        );
        $this->sourceOptions['map_joinable'] = FALSE;
        // Set the query as the migration source.
        $this->source = new MigrateSourceSQL(
                $this->query(), $this->sourceFields, NULL, $this->sourceOptions
        );
        // Map source rows to destination rows with uid+gid.
        $this->map = new MigrateSQLMap($this->machineName,
                array(
                        'field_contact_member_company_nid' => array(
                                'type' => 'int',
                                'not null' => TRUE,
                                'description' => 'ID of the group.',
                        ),
                        'uid' => array(
                                'type' => 'int',
                                'not null' => TRUE,
                                'description' => 'ID of the user.',
                        ),
                ),
                MigrateDestinationOGMembership::getKeySchema()
        );
        // Destination is group membership.
        $this->destination = new MigrateDestinationOGMembership();
        // Field mappings.
        $this->addFieldMapping('group_type')
        ->defaultValue('node');
        $this->addFieldMapping('entity_type')
        ->defaultValue('user');
        // Let the user migration map the uids.
        $this->addFieldMapping('etid', 'uid')
        ->sourceMigration('ClickUser');
        $this->addFieldMapping('state', 'is_active');
        $this->addFieldMapping('is_admin', 'is_admin');
        // Group migration maps the gid via the OG Node migration.
        $this->addFieldMapping('gid', 'field_contact_member_company_nid')
        ->sourceMigration('MemberCompany');
        // Minimal source config means we just set a default
        // instead of looking for roles to map.
        $this->addFieldMapping('group_roles')
        ->defaultValue(array(OG_ADMINISTRATOR_ROLE));
        // Accept defaults for these destination fields.
        $no_input = array(
                'created',
        );
        $this->addUnmigratedDestinations($no_input, t('Do Not Migrate'));
    }
    /**
     * Query for the source group data.
     *
     * @return QueryConditionInterface
     *   Provides a connection and query for getting OGMembership records.
     */
    protected function query() {
        $query = Database::getConnection('click2', $this->sourceConnection)
        ->select('content_type_contact_content','p')
        ->fields('p', array('field_contact_member_company_nid'));
        $query->join('node','n','n.vid = p.vid');
        $query->addField('n', 'uid');
        $query->isNotNull('field_contact_member_company_nid');
        return $query;
    }
    public function prepareRow($row) {
        if (parent::prepareRow($row) === FALSE) {
            return FALSE;
        }
    }
}

```
> 0 votes

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


# Question
Title: Issues with namespaces and Migrate module migrating XML content
In the Migrate module I noticed that one reason I could not import an XML file was because it contained namespaces. Removing namespaces from the XML file and Migrate class allowed me to import the content without issue.

In trying to fix this issue I came across this post which brought me to this patch for the xml.inc file (used to import xml sources) in the Migrate module. Unfortunately it was for an outdated version of the module so I had to manually apply it.

The patch does not seem to work as I still get this error when attempting to migrate (the same error I was getting before applying the patch):

> Migration failed with source plugin exception: Passed variable is not an array or object, using empty array instead

I think I have tracked down where the issue is appearing in the xml.inc code, as this function, &xml, does not output $this-\>currentXml which should be a simplexml\_load\_file:

```
/**
   * Load and return the xml from currentUrl.
   *
   * @return SimpleXMLElement
   */
  public function &xml() {
    if (!empty($this->currentUrl)) {
      dpm('start grab url/xml');
      dpm($this->currentUrl);//it is grabbing this url ok
      $this->currentXml = simplexml_load_file($this->currentUrl);
      dpm($this->currentXML);//it is not loading the file properly it seems
      dpm('end grab url/xml');
      if (!$this->currentXml) {
        Migration::displayMessage(t(
          'Loading of !currentUrl failed:',
          array('!currentUrl' => $this->currentUrl)
        ));
        foreach (libxml_get_errors() as $error) {
          Migration::displayMessage(self::parseLibXMLError($error));
        }
      }
      else {
        dpm('register namespace');
        dpm($this->registerNamespaces($this->currentXml)); // this then fails
                                                           // to load since
                                                           // $this->currentXml
                                                           // is not populated,
                                                           // which is most
                                                           // likely generating the error
        dpm('endr egister namespace');
      }
    }
    return $this->currentXml;
  }

```

Here is the output when migration is run:

Is there something that would be stopping a simple php function such as simplexml\_load\_file to run here? Or could this possibly not even be the issue? There is currently an open issue with the Migrate module for this issue, though there is not much activity on it.

# Answer
> 2 votes
A few things had to be changed.

```
public function &xml() {
    if (!empty($this->currentUrl)) {

      // $this->currentXml = simplexml_load_file($this->currentUrl);

      // simplexml_load_file wasn't explicit enough, change to file_get_contents
      // then explicitly call it a new SimpleXmlElement.

      $xml = file_get_contents($this->currentUrl);
      $this->currentXml = new SimpleXmlElement($xml);

      if (!$this->currentXml) {
        Migration::displayMessage(t(
          'Loading of !currentUrl failed:',
          array('!currentUrl' => $this->currentUrl)
        ));
        foreach (libxml_get_errors() as $error) {
          Migration::displayMessage(self::parseLibXMLError($error));
        }
      }
      else {
        $this->registerNamespaces($this->currentXml);
      }
    }

    return $this->currentXml;
  }

```

However, the major issue was this function in xml.inc:

```
protected function getElementValue($itemXML, $xpath) {
    $value = NULL;
    if ($itemXML) {
      $result = $itemXML->xpath($xpath);
      if ($result)
        $value = (string)$result[0];
    }
    return $value;
  }

```

The if($itemXML) needs to be changed to if($itemXML-\>asXML()), like so:

```
protected function getElementValue($itemXML, $xpath) {
    $value = NULL;
    if ($itemXML->asXML()) {
      $result = $itemXML->xpath($xpath);
      if ($result)
        $value = (string)$result[0];
    }
    return $value;
  }

```

After applying the patch manually and changing the simplexml\_load\_file and the if statement in the above functions, the import works successfully with namespaces.

I re-rolled the patch mentioned earlier with my changes: https://drupal.org/comment/8260027#comment-8260027

---
Tags: migrations, feeds, 8
---


# Question
Title: Force existing users to complete profile after adding required fields
I inherited a Drupal (D7) site with existing users. Now I want to add new fields to the user profile, but they will be required.

New users will have to fill out these fields when registering. Existing users will have to fill out these fields when trying to save their profile.

But what I would want is for existing users to be redirected to their profile page after logging in. Of course, I would also like to display a message on that page that they need to complete their profile with this new information.

Is this possible in Drupal?

# Answer
Peter,

there are two modules for such thing:

1. complete\_profile
2. pfff

But.. I want to try your rules solution because the modules above don't work with hybridauth :(.

If you don't use hybridauth you'd better try complete\_profile. It doesn't allow user to go to another pages if required fields are empty.
> 1 votes

# Answer
I fixed this with the Rules Module.

First, I set the necessary fields in the user profile as required. That fixes it for new users that want to register.

Then, a little more complex, I used the Rules module for the existing user, with the following setup:

* Event: user has logged in
* Actions:
    + page redirect (to `user/[account:uid]/edit`)
    + show a message on the site (to clarify why the user was sent here)
* Conditions:
    + One OR group with the following conditions:
    + Data value is empty (with `site:current-user:field-lastname`)
    + Data value is empty (with `site:current-user:field-firstname`)
    + etc.

This works perfectly. The only minor point is that when I add a required field, I also have to add a condition to the OR group manually.
> 3 votes

# Answer
You can do it of course. But for that you have to create your own module with the hook\_user\_login. You can also give a look at the documentation that has a simple example to redirect user to his profile page to fill data.
> 1 votes

---
Tags: entities, users
---


# Question
Title: How do I do an if conditional based on a view in template.php
Related to this question: Adding a body ID to a view page

How do I add a conditional based on whether a page is a view or not? I'm not sure how to test for whether a page is a view.

# Answer
> 0 votes
You can call menu\_get\_item() and it will return an array containing a lot of information about the path you are on.

Inside that, you can look for

```
[page_callback] => views_page
[page_arguments] => Array (
  [0] => arg0
  [1] => arg1
)

```

or similar, and then based upon that, figure out what View you are looking at.

FYI: It might not be obvious from the documentation, but if you call it without arguments, it returns the information about the path/page you are currently on.

---
Tags: views
---


# Question
Title: After importing a content type from Features, What's the correct way to manage it?
I've taken control of a project recently, and I see a workflow I've not used before.

The original developer would create content types on his dev machine; use Features to export the content type's code, and upload that as a module (with related functionality) to the production server. Enabling it, the content type is created.

Now that the content type is created, I'd like to add / adjust / delete field configurations. What's the correct workflow to work with the content type from that point? Once the content type is created, is it part of the db as if I had created it normally through the UI? Can I safely delete the Feature generated content type code? Can I manage fields through the UI, or would I have to fiddle with the Feature generated code?

Thanks!

# Answer
> 5 votes
1. Once the content type is created, is it part of the db as if I had created it normally through the UI?
**Yes**
2. Can I safely delete the Feature generated content type code?
**No**\- See this Q/A for a more complete answer.
3. Can I manage fields through the UI...
**Yes** \- once you have the content type set the way you want it, you should regenerate the feature module so that you have an up-to-date representation of your content type in code.
4. ...or would I have to fiddle with the Feature generated code?
**Definitely no**

## What's the correct workflow to work with the content type from that point?

*First, make sure you have a clean starting point by ensuring that all of your features in all of your environments have the "Default" status (this just means that the loaded database configuration of the Feature matches the configuration defined in code in the Features module).*

1. Make changes to the content type through the UI on dev as you normally would.
2. Once the content type has been modified to your liking, Recreate the Feature by clicking on the "Recreate button". That will generate a tar file. Extract that file in the same directory as the existing Feature module - overwriting the previous version.
3. Revisit the Features page on dev. The feature that was previously overridden should now be "default".
4. Assuming you are using git or subversion or similar, commit the changes to the Feature module and pull them to staging. (If you're not using source control, just FTP the changes to the Staging server).
5. Visit the Features page on staging. The Feature in question should now have a status of overridden. Click on the "Overridden" link, tick the checkboxes on the resulting page and click "Revert". This will update the database settings to match what is defined in the new Features module. The status of the Feature should now be "Default". (Note: sometimes the Features module automatically pulls in the new settings when you visit the Features page, but honestly, I'm not sure what triggers that or when - perhaps someone can add to that).
6. If all goes well on staging, repeat the same steps on prod.

# Answer
> 1 votes
When working with features you want to continue with the dev box to prod workflow. With features you're creating modules, so all the config code lives within your exported feature.

Here's a drupal.org link to updating features - https://drupal.org/node/582680

You'll make changes on your dev box, then update your feature and move that to your production site.

You shouldn't delete the content type code in the feature.

You can fiddle with the UI to update fields within the feature just make sure you rebuild on your dev box.

The purpose of features is to allow you to quickly move configurations from site to site, and if you are using something like Git provide version control in case you need to move backwards.

---
Tags: 7, nodes, features
---


title: Template reused on repeated node

text:
# Question
Title: Template reused on repeated node
I have a node repeated on the page, once for styled dropdown menu through submenuesmall view and once as node when that submenu is selected. Submenu is styled with node--view--submenuesmall.tpl.php that is OK. But same template is used for node later instead of normal node.tpl.php

If I omit that node from submenuesmall normal node.tpl.php is used.

Is that standard behaviour and how can I fix it or did I do something wrong. All modules are up to date.

# Answer
I believe, you can handle this in template.php of your theme, using the hook - `hook_preprocess_page` OR `hook_preprocess_node`.

Here you can change the Template file which is going to be used for that particular node, but you will have to identify at what time which TPL is to be used.
> 0 votes

# Answer
Solution acording to @Vaibhav tip...

```
// node__view__submenuessmall is used in view
// for creating block menues with images
// when same node is used in menue and on page
// wrong theme_hook_suggestion is used on page

function cuter_preprocess_node(&$variables){
 if(array_key_exists('theme_hook_suggestions',$variables))
  {
    $lastVar = count($variables['theme_hook_suggestions'])-1;
    if($variables['theme_hook_suggestions'][$lastVar]=='node__view__submenussmall')
    {
      //dpr($variables['theme_hook_suggestions'][$lastVar]);
      $variables['theme_hook_suggestions'][$lastVar]='foobar';
      //dpr($variables['theme_hook_suggestions'][$lastVar]);
    }
  }
}

```
> 1 votes

---
Tags: views, nodes, theming
---


title: Link webform to a specific node

text:
# Question
Title: Link webform to a specific node
Use-case-scenario: There are multiple content types. There is the webform module. Context and Views are used.

Requirement: Display specific webform below specific node. The content editor should be able to choose specific form for specific node.

My first idea is: -\>start with adding a node/entity reference field (lets call it "webform\_node\_url")in the webform, so that a webform is related with a specific node. -\>create a view that renders all webforms that have "webform\_node\_url" -\>Embedding this view in the context.

But the problem I have is, I cant find entity/reference functionality for the webform. Do you have any ideas and/or suggestions.

# Answer
> 2 votes
I think you should be able to do this fairly easily, without even involving views or contexts!

Here's how you can do it:

1. Just like you said, you can create a new **Entity Reference** field that will point to the relevant webform. I'd make this field an **Autocomplete (Tags style)** field:
2. When you're setting up your field, make sure to select that it should only pull from your Webform content type:
3. When you've created the new field, make sure you hit the 'Manage Display' settings on the content type that includes this webform reference. Here's where the real magic is going to happen: you can have this new referenced entity (which is your webform) be displayed not as a link, but as a rendered entity. Which means you can just automatically display the webform under or above your node, or whereever you choose to output it. In my case, I made it the very last field (so it displays under my node), and here are the exact settings:

Now test: If you go to create a new content type, you should be able to just start typing in the title of the webform you want to attach (such as "Contact Us"), and all the matching webforms will pop up - just choose the right one, save, and it should appear under your node.

Voila!

Let us know if it works for you.

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


title: How to add SSL site seal in drupal?

text:
# Question
Title: How to add SSL site seal in drupal?
I have got site seal from positive ssl but cant figure out where to insert it. Their support option says inset the code in the html body tag. Its very vague for drupal, at least for me to understand because i dont have much knowledge of the drupal internal structure. Can anyone help please?

# Answer
You can just insert it in a Block. just goto Structure \> Block \> Add Block and enable full html input and just copy and pate. Then just assign that block to where you want it to show up.
> 2 votes

---
Tags: ssl
---


title: Associate an image with each checkbox

text:
# Question
Title: Associate an image with each checkbox
I'd like to have a graphics-oriented Webform, wherein the user will select from check boxes that have a specific image associated with each. For instance, I might have a row of checkboxes with a color swatch above each one, like this:

\[red jpg color swatch\] \[blue jpg color swatch\] \[green jpg color swatch\] \[checkbox\].................\[checkbox\]..................\[checkbox\]

How can I accomplish that using the Webform module?

Thanks!

# Answer
> 0 votes
I used this CSS technique to make checkboxes larger and add background images unique to each checkbox. Sample LESS Code:

```
#edit-field-vegetables {

  input[type='checkbox'] {
    -webkit-appearance:none;
    width:70px;
    height:70px;
    background: url('../img/vegetables_icons_long.png') no-repeat;
  }
  input[type='checkbox']:checked {
    opacity: 0.5;
  }

  .form-type-checkbox{
    display: block;
    width:110px; height:110px;
    position: relative;
    float:left;
    input.form-checkbox{
      float:right;
      position: absolute;
      top:40px;
    }
  }

  .form-item-field-vegetables-und-orange input {
    background-position: 0 -753px;
  }
  .form-item-field-vegetables-und-banana input{
    background-position: 0 -1415px;
  }
  .form-item-field-vegetables-und-apple input{
    background-position: 0 -80px;
  }
}

```

This works on chrome. Look at the discussion linked above to see how to make it cross-browser.

---
Tags: 7, webforms
---


# Question
Title: Execute pending queues using batch? Possible?
I have implemented the Queue API inside `hook_cron`, to do certain update operations on a site:

```
function HOOK_cron() {
  $interval = variable_get('variable_val', 60 * 60 * 24);
  if (time() >= variable_get('cron_next_execution', 0)) {
    variable_set('cron_next_execution', time() + $interval);
    $queue = 'MODULE_queue';
    $queue = DrupalQueue::get($queue);
    $query = db_query('SELECT nid FROM {node} WHERE type=:type', array(':type' => 'profile'))->fetchAll();
    foreach ($query as $node_obj) {
      $node = node_load($node_obj->nid);
      $queue->createItem($node);
    }
  }
}

```

where `MODULE_queue` is name of the queue, who's worker callback does some task on the nodes.

At any moment of time I would like the administrators to be able to run the updates manually using batch. I would like something like this

* Check if there is anything pending in a queue at the moment Admin chooses to manually update, and execute them in batch.
* If not just run a manual batch update.

So, I'm stuck at the part where I need to run the queue inside batch. I am not sure if this even is possible. Any pointers would be highly appreciated.

# Answer
> 2 votes
Check: https://drupal.org/project/queue\_ui

> Process queue with Batch API

---
Tags: 7, cron
---


# Question
Title: suggestions needed to define a class for field per entity/node
Im not sure the best way to go about this, and not so much a big programmer...

I would like to let the node creator decide whether the image in the image field should be top, left, or right. So i simply want to add class to the image div somehow.

So there should be a way to grab that info, maybe a "list" field?

Now, how to get that info over the image field?

Im thinking something like a field template for the image field (using media module)... or maybe something i heard about preprocessing in template.php?

pointer and tips appreciated!

# Answer
> 0 votes
You are looking for Image Class module - either use it directly, or use it's code - it is open source after all.

> Extends the Image formatter by adding an option to add an element class.

---
Tags: entities, theming
---


# Question
Title: Node's Preview when using Views module to render Node
I have been using Views module to render Node's Full content (using unformatted list of fields!). Seems that was not such a good idea.

Now when I preview the Node, I see the Teaser and Full content Entity view modes (instead a View with fields). So the actual problem is these teasers and Full content are not themed the way my View is.

Is there any workaroud except rebuilding the whole thing in Display Suite module?

THX!

# Answer
> 0 votes
The solution was to rebuild the whole thing in Display Suite module. Views (when using Unformatted List of Fields) cannot render teaser and Full content in node's preview!

---
Tags: views, nodes, display-suite, entities
---


title: Attaching multiple webforms to a node

text:
# Question
Title: Attaching multiple webforms to a node
I need not one, but three different webforms for my content type. So far I've seen that the webform module allows for only one webform per node. Any suggestions?

EDIT:

To clarify why I can't use the easy solution using blocks - I need to have each instance of the webform prepopulated with the node title (the node the webform is attached to) and I also need it to open in a lightbox. For making that work with one webform I used this solution, however, adding more webforms to the mix makes it more complicated.

# Answer
Webform allow embed form as block, so you can build 3 webforms, then show one in main content, and other 2 as blocks...
> 2 votes

---
Tags: 7, webforms
---


# Question
Title: Get future node id (nid) of nodes being programmatically created (future node)
I want to create multiple nodes using one form, but I'd like to have connection between them stored in Entity Reference, so I need to know their nids. But they aren't created yet, so they hasn't nids.

Question: Is there a way to predict future nodes nids and preserve them for a while or do something similar to deal with task above?

# Answer
> 3 votes
Unfortunately, there's no a clean way to do that!

# Answer
> 1 votes
Create all nodes with pseudo-random values. Receive all nids. They are reserved now.

After that, within the submit handler, update all node objects.

# Answer
> 1 votes
The `nid` is available after `node_save($node);`

You can access is from the same function that does the `node_save`

e.g:

```
global $user;

$entity = array(
  'type' => 'article',
  'title' => 'Example node',
  'uid' => $user->uid,
  'created' => REQUEST_TIME
);

// Uses Entity API module
$node = entity_create('node', $entity);

// Node object is passed by reference and has nid property after save.
node_save($node);

drupal_set_message(t('Node %title nid is %nid', array('%title' => $node->title, '%nid' => $node->nid)));

```

# Answer
> 0 votes
I had a similiar requirment but I dont know how helpful it will be, Check out this question

You may be able to use `$last_id = db_last_insert_id($table, $field);`

# Answer
> 0 votes
My idea is to create dummy field with some unique token same for all node types that I need to connect. After submission (creation of multiple nodes) I'll check nodes WHERE token is equal and I'll try to set them Entity relation somehow.

My first thought after getting 'no a clean way to do that' answer.

# Answer
> -3 votes
If you insert a new node say node/71 then next node will always be node/72
NIDs are auto incremented in mysql tables. To get the NID of recently inserted node you can do this query.
`SELECT MAX(nid) FROM {node}`
You can increment it by 1 to predict next node nid.

---
Tags: 7, nodes
---


title: Drush DB connection on MAMP

text:
# Question
Title: Drush DB connection on MAMP
I have a slight issue in connecting Drush to my MAMP localhost DB. Already tried multiple solutions like changing host from localhost to 127.0.0.1, and editing MAMP files like this suggestion.

It seems my socket location is slightly different from most examples I see on the web, being var/mysql/mysql.sock rather than tmp/mysql.sock. I installed via homebrew, if that's helpful.

Super new to drush, and command line in general, so any help much appreciated. All file transfers (like dl) work fine, just anything DB related throwing an error. Thanks!

```
    PDO::__construct(): [2002] No such file or directory (trying to connect  [warning]
via unix:///var/mysql/mysql.sock) environment.inc:523
Command pm-enable needs a higher bootstrap level to run - you will need  [error]
to invoke drush from a more functional Drupal environment to run this
command.
The drush command 'en views' could not be executed.                      [error]
Drush was not able to start (bootstrap) the Drupal database.             [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be wrong or
the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version        :  7.24
 Site URI              :  http://default
 Database driver       :  mysql
 Database username     :  root
 Database name         :  DB_name
 Default theme         :  garland
 Administration        :  garland
 theme
 PHP executable        :  /usr/bin/php
 PHP configuration     :
 PHP OS                :  Darwin
 Drush version         :  6.1.0
 Drush configuration   :
 Drush alias files     :  /Users/UserName/.drush/pantheon.alias
                          es.drushrc.php
 Drupal root           :  /Applications/MAMP/htdocs/landmark/landmark-l
                          earning
 Site path             :  sites/default
 File directory path   :  sites/default/files

```

# Answer
OK, finally got it working:

```
sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

```

Thanks to Remy for putting me on the right track, and This drupal.org post.

Seems it was that I needed to make a directory first... Rookie move.
> 6 votes

---
Tags: drush
---


title: Field with author link in node

text:
# Question
Title: Field with author link in node
i am building a website where many users will be able to add specific content. I want each content-node to have a link to the the authors profile page. I am using profile2 for users profiles and the alias of link in the node must be the "Company Name" field and not the username.

How can i achieve this?

Thank you!

# Answer
Why don't you just use Views, and place that view towards the bottom of the article or that content type?

The views will be based on a user relationship with the node uid (the author's user id).

All those fields you require you can add to the user profile (admin/config/people/accounts/fields) - Company Name, Byline etc etc? And then display them via views.
> 1 votes

# Answer
create a template file for your content type, in your theme folder. it should be something like `node--node_type.tpl.php` . In that file you should have access to all the node's fields.

You can start by using the default `node.tpl.php` as an example. More about templates you can find here.

**EDIT:**

in your default `node.tpl.php` you could find something like this:

```
// this is taken from the omega theme
<?php if ($display_submitted): ?>
  <footer class="submitted"><?php print $date; ?> -- <?php print $name; ?></footer>
<?php endif; ?>

```

so instead of `print $name` you could do something like `print l('your custom field value', 'user/' . $node->uid)`
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to control from a module the block visibility of a block implemented by another module?
The default options in the administrative page for block visibility (e.g. `admin/build/block/configure/block/3`) are not enough for my needs.

For security reasons, I do not wish to use the PHP option (`Show if the following PHP code returns TRUE (PHP-mode, experts only).`). I plan to turn off all PHP configuration throughout the site.

The only route that remains available is to create a module that will control the visibility of certain blocks on specific pages. I am an experienced module developer but I do not know how to implement this specific thing.

What API exist that I could use? Apparently it's possible in Drupal 7. What alternatives do exist in Drupal 6?

**Edit:**
I actually easily found the answer to my original question. Now, I want to be able to control from my module the visibility of a block implemented by another module. My specific use case is thus: core's aggregator.module create feed blocks, but I want each feed block to be displayed on pages of certain types authored by specific users who are associated with specific feeds. I could re-implement the whole aggregator\_block() or... I could let the aggregator.module do its job and simply control the visibility of the block that it produces. Is it possible?

# Answer
> 1 votes
You can call the aggregator's (or an other module's) block routines by doing something like this in your module...

```
$foo=module_invoke('aggregator', 'block', 'view', 'BLOCK_DELTA');
$content.=$foo['content'];

```

...with the resulting `$content` containing the html of the block in question.

So, it would be fairly trivial to include something like the above in your custom module's block view hook instead of copying all of the aggregator module's code into your module.

More information on `module_invoke()` here.

Just an FYI: Using the `visibility` key set to PHP in `hook_block()` actually requires the `<?php ... ?>` brackets with the whole shabang being passed through `eval()` so IMHO I don't think it is all that much safer than using the Block UI's PHP option.

# Answer
> 0 votes
***Edit:*** *this answers the original question, but not the follow up.*

I should have looked closer before asking.

Apparently, it's also possible in D6: https://api.drupal.org/api/drupal/developer!hooks!core.php/function/hook\_block/6

'visibility' = 2: Use custom PHP code to determine visibility. 'pages' gives the PHP code to use. 'pages' = custom PHP code when 'visibility' is set to 2.

I had seen that question but I thought it only applied to D7. Can't set PHP block visibility programatically

I'll try that!

---
Tags: 6, blocks
---


# Question
Title: Why does hook_menu add my menu items multiple times?
I'm using a hook\_menu to add some custom menu items to my user menu. One is a link to an external page, one is a duplicate of the "node/add/discussion" page.

I'd expect these menu links to be added to my user menu once and only once. Instead, these links get added to my user menu once for every time I clear cache.

```
function MYMODULE_menu() {
    $items['external'] = array(
        'title' => 'External',
        'link_path' => 'http://www.example.com',
        'type' => MENU_NORMAL_ITEM,
        'menu_name' => 'user-menu'
    );
    $items['have_a_chat'] = array(
        'title' => 'Have a chat',
        'link_path' => 'node/add/discussion',
        'type' => MENU_NORMAL_ITEM,
        'access_callback' => 'user_is_logged_in',
        'menu_name' => 'user-menu'
    );
    return $items;
}

```

Exported from the database (`SELECT * FROM menu_links WHERE menu_name = 'user-menu';`) the menu looks like:

```
"menu_name","mlid","plid","link_path","router_path","link_title","options","module","hidden","external","has_children","expanded","weight","depth","customized","p1","p2","p3","p4","p5","p6","p7","p8","p9","updated"
"user-menu","2","0","user","user","User account","a:1:{s:5:""alter"";b:1;}","system","0","0","1","0","-10","1","0","2","0","0","0","0","0","0","0","0","0"
"user-menu","10","2","user/register","user/register","Create new account","a:0:{}","system","0","0","0","0","0","2","0","2","10","0","0","0","0","0","0","0","0"
"user-menu","14","0","user/login","user/login","Log in","a:0:{}","system","0","0","0","0","0","1","0","14","0","0","0","0","0","0","0","0","0"
"user-menu","15","0","user/logout","user/logout","Log out","a:0:{}","system","0","0","0","0","10","1","0","15","0","0","0","0","0","0","0","0","0"
"user-menu","20","2","user/password","user/password","Request new password","a:0:{}","system","-1","0","0","0","0","2","0","2","20","0","0","0","0","0","0","0","0"
"user-menu","336","0","profile-main","profile-main",,"a:0:{}","system","0","0","0","0","0","1","0","336","0","0","0","0","0","0","0","0","0"
"user-menu","1071","0","http://www.example.com",,"External","a:0:{}","system","0","1","0","0","0","1","0","1071","0","0","0","0","0","0","0","0","0"
"user-menu","1072","0","node/add/discussion","node/add/discussion","Have a chat","a:0:{}","system","0","0","0","0","0","1","0","1072","0","0","0","0","0","0","0","0","0"
"user-menu","1074","0","http://www.example.com",,"External","a:0:{}","system","0","1","0","0","0","1","0","1074","0","0","0","0","0","0","0","0","0"
"user-menu","1075","0","node/add/discussion","node/add/discussion","Have a chat","a:0:{}","system","0","0","0","0","0","1","0","1075","0","0","0","0","0","0","0","0","0"
"user-menu","1076","0","http://www.example.com",,"External","a:0:{}","system","0","1","0","0","0","1","0","1076","0","0","0","0","0","0","0","0","0"
"user-menu","1077","0","node/add/discussion","node/add/discussion","Have a chat","a:0:{}","system","0","0","0","0","0","1","0","1077","0","0","0","0","0","0","0","0","0"
"user-menu","1078","0","http://www.example.com",,"External","a:0:{}","system","0","1","0","0","0","1","0","1078","0","0","0","0","0","0","0","0","0"
"user-menu","1079","0","node/add/discussion","node/add/discussion","Have a chat","a:0:{}","system","0","0","0","0","0","1","0","1079","0","0","0","0","0","0","0","0","0"

```

My Drupal version is 7.23.

One odd thing I notice is that "module" is listed as "system" despite the fact that I'm adding these links in a custom module.

How do I fix my code so that these menu links only get added once?

# Answer
> 0 votes
This was a problem with link\_path as hinted at by @xurshid29 and @ARUN.

link\_path "works" in that it inserts a link with the given path into the menu, but it also has the odd side effect of inserting multiple links into the menu - one for each cache clear - despite each link having the same key in $items. It's also undocumented, so I have no idea where I picked it up from.

Removing the link\_path argument and replacing it with "page callback" fixes the problem of multiple links being inserted.

"Have a chat" was fixed to explicitly callback the "add discussion form":

```
$items['have_a_chat'] = array(
    'title' => 'Have a chat',
    'page callback' => 'node_add',
    'page arguments' => array('discussion'),
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('create discussion content'),
    'menu_name' => 'user-menu'
);

```

And "external" was fixed to `page callback` a function that then calls `drupal_goto`.

---
Tags: routes
---