# Question
Title: Prefix html before radiobutton (input field)
I'm looking to insert some extra html before an input radio button. This is my html now:

```
<div id="edit-field-geslacht-und" class="form-radios">
    <div class="form-item form-type-radio form-item-field-geslacht-und">
        <input type="radio" id="edit-field-geslacht-und-female" name="field_geslacht[und]" value="female" class="form-radio">
        <label class="option" for="edit-field-geslacht-und-female">Female</label>
    </div>
    <div class="form-item form-type-radio form-item-field-geslacht-und">
        <input type="radio" id="edit-field-geslacht-und-male" name="field_geslacht[und]" value="male" checked="checked" class="form-radio">
        <label class="option" for="edit-field-geslacht-und-male">Male</label>
    </div>
    <div class="form-item form-type-radio form-item-field-geslacht-und">
        <input type="radio" id="edit-field-geslacht-und-other" name="field_geslacht[und]" value="other" class="form-radio">
        <label class="option" for="edit-field-geslacht-und-other">Other (transgender...)</label>
    </div>
</div>

```

Now I would like to add the following html before every radio input:

```
<span class="radio" style="background-position: 0px -28px;"></span>

```

But how can I do this?

**UPDATE**:

I've tried to do it with theme\_form\_element function and now have this:

```
function theme_form_element($variables)
{
    if($variables['element']['#type'] == 'radio')
    {
        dump($variables);
    }
}

```

My dump shows me this array:

```
array (size=1)
  'element' =>
    array (size=27)
      '#type' => string 'radio' (length=5)
      '#title' => string 'Female' (length=6)
      '#return_value' => string 'female' (length=6)
      '#default_value' => string 'male' (length=4)
      '#attributes' =>
        array (size=0)
          empty
      '#parents' =>
        array (size=2)
          0 => string 'field_geslacht' (length=14)
          1 => string 'und' (length=3)
      '#id' => string 'edit-field-geslacht-und-female' (length=30)
      '#ajax' => null
      '#weight' => float 0.001
      '#input' => boolean true
      '#process' =>
        array (size=1)
          0 => string 'ajax_process_form' (length=17)
      '#theme' => string 'radio' (length=5)
      '#theme_wrappers' =>
        array (size=1)
          0 => string 'form_element' (length=12)
      '#title_display' => string 'after' (length=5)
      '#pre_render' =>
        array (size=1)
          0 => string 'ctools_dependent_pre_render' (length=27)
      '#after_build' =>
        array (size=1)
          0 => string 'conditional_fields_element_after_build' (length=38)
      '#defaults_loaded' => boolean true
      '#tree' => boolean true
      '#array_parents' =>
        array (size=3)
          0 => string 'field_geslacht' (length=14)
          1 => string 'und' (length=3)
          2 => string 'female' (length=6)
      '#processed' => boolean true
      '#required' => boolean false
      '#name' => string 'field_geslacht[und]' (length=19)
      '#value' => string 'male' (length=4)
      '#ajax_processed' => boolean false
      '#sorted' => boolean true
      '#after_build_done' => boolean true
      '#children' => string '<input type="radio" id="edit-field-geslacht-und-female" name="field_geslacht[und]" value="female" class="form-radio" />' (length=119)

```

I've tried to change the `#children` variable and add my html before it. But when I do that no element on my page is showing ... .

# Answer
> 1 votes
You can override the theme\_radio function in your own theme :

```
function mytheme_radio($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'radio';
  element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

  if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-radio'));

  if ($its_my_field) {
     return '<span class="radio" style="background-position: 0px -28px;"></span><input' . drupal_attributes($element['#attributes']) . ' />';
  }
  else {
     return '</span><input' . drupal_attributes($element['#attributes']) . ' />';
  }

```

Maybe try with the more generic function theme\_form\_element.

Make sure to add conditions to only affect the form or the element you need like in the example written above.

# Answer
> 0 votes
You can use jQuery selector -

```
    <html>
    <head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
    jQuery(document).ready(function() {
jQuery( "input[type=radio]" ).before( '<span class="radio" style="background-position: 0px -28px;"></span>' );
});
</script></head>
<body>
<div id="edit-field-geslacht-und" class="form-radios">
    <div class="form-item form-type-radio form-item-field-geslacht-und">
        <input type="radio" id="edit-field-geslacht-und-female" name="field_geslacht[und]" value="female" class="form-radio">
        <label class="option" for="edit-field-geslacht-und-female">Female</label>
    </div>
    <div class="form-item form-type-radio form-item-field-geslacht-und">
        <input type="radio" id="edit-field-geslacht-und-male" name="field_geslacht[und]" value="male" checked="checked" class="form-radio">
        <label class="option" for="edit-field-geslacht-und-male">Male</label>
    </div>
    <div class="form-item form-type-radio form-item-field-geslacht-und">
        <input type="radio" id="edit-field-geslacht-und-other" name="field_geslacht[und]" value="other" class="form-radio">
        <label class="option" for="edit-field-geslacht-und-other">Other (transgender...)</label>
    </div>
</div>
</body>

</html>

```

---
Tags: 7, forms, input-formats
---


# Question
Title: Is there a number field with + and - feature?
I am working with Form API to create a customized form shown in a block. Most of the fields are textfields.

I need a +/- feature for a numeric textfield, i.e.:

Is there an existing field like the above I can use?

# Answer
Try the Stepper Field module

> The Stepper Field module is based in a plugin for jQuery UI called jQuery.ui.Spinner and provides a new steps widget that can be added to any Integer field.

Here is the image
> 1 votes

# Answer
There is SpinInt module for this

> Spinint provides a simple up down arrow widget for integer number fields.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: jQuery ui buttonset is not a function in Drupal 7
Like the title of this post suggests, I'm trying to add a fancy jQuery ui buttonset to my custom Drupal 7 module. But I'm getting the error message "TypeError: jQuery(...).buttonset is not a function" in Firebug. How can this be fixed? Do I need to update Drupal's internal jQuery ui version or something? Or maybe I need to add the buttonset widget manually?

Thanks for the help.

HTML:

```
<div id="edit-service-amount" class="form-radios">
<div class="form-item form-type-radio form-item-service-amount">
<input id="edit-service-amount-0" class="form-radio" type="radio" value="0" name="service_amount">
<label class="option" for="edit-service-amount-0">Enkel </label>
</div>
<div class="form-item form-type-radio form-item-service-amount">
<input id="edit-service-amount-1" class="form-radio" type="radio" checked="checked" value="1" name="service_amount">
<label class="option" for="edit-service-amount-1">Dubbel </label>
</div>
</div>

```

JS:

```
jQuery(document).ready(function() {
 jQuery('.form-item-service-amount').buttonset();
}

```

# Answer
> 0 votes
You're probably just missing the UI button library (libraries are added when they're needed rather than every js file being included for every page).

To fix, add this in your page callback:

```
drupal_add_library('system', 'ui.button');

```

To ensure your JS code is invoked after AJAX calls, you just need to wrap it in a Drupal behaviour:

```
(function($) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      $('.form-item-service-amount', context).once('mymodule').buttonset();
    }
  };
})(jQuery);

```

There's no need to use `ready()` in this context, Drupal will fire `attachBehaviors()` on document load, and when ajax calls occur, and your module's attach function will be called each time.

`once()` just makes sure the buttonset is only applied to an individual element once only, to avoid reattaching behaviours to elements that have already had it.

---
Tags: javascript
---


# Question
Title: How to completely disable 'further instructions sent to email' message after sign up
How to completely turn off/remove message 'Further instructions have been sent to your e-mail address.' that appears after registration? I'm using logintobogan module and I can see some customization than can be made to registration confirmation page, but none of these settings direct this particular message. It appears every time, also if I use redirection to completely custom thank you page?

Any idea?

# Answer
You can use rules redirect the user to a pre-defined URL upon registration. This should over-ride whatever default behaviors you are seeing now...

* Back up your database.
* Enable Rules
* Navigate to admin/configuration/workflow/rules
* Add new Rule

```
Event: 'After saving a new user account'
Action: 'Page Redirect' (optionally 'force redirect')

```
> 0 votes

---
Tags: users
---


title: Select list with input fields

text:
# Question
Title: Select list with input fields
I would like to have the following field widgets:

I would like to give the user the possibility to give in 4 nicknames and select the default one that will be shown to other users.

Is there a module for this or something I can work with?

I've searched google but with no success ... .

# Answer
Try the Double field module.

> Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can split your fields up into two separate parts.

I used it for one of my project and works well.
> 1 votes

---
Tags: entities
---


# Question
Title: Can I render the same block twice on a page?
I want to have `<?php print render ($page['homepage_video'])?>` two different places on the page. By default it can only be done once, but is there a workaround for that?

# Answer
> 1 votes
If what @Chapabu said doesnt work for you, if you have *any* hand-coded module on your site you can use hook\_page\_alter to copy the render array information for the block in question and set it into another region of the page.

This is more of a 1-off solution. But, I try to stay away from extra modules todo 1 thing on a site. Especially if you're somewhat comfortable coding a solution.

Here is a small example using hook\_page\_build (which runs at the beginning of page builds, hook page\_alter runs at the end):

```
/**
 * implementation of hook_page_build().
 *
 * Depending on the path or NID or whatever, we want to
 * embed additional blocks and stuff into the page.
 *
 * I could use Context or the BlocksUI for this but I
 * give clients "Basic Page" for all of these urls and I'm
 * merely appending additional data on those pages.
 */
function ccs_core_page_build(&$page) {
  _page_build_section_header_image($page);
  _page_build_embed_course_views($page);
  _page_build_embed_faculty_views($page);
  _page_build_embed_distinguished_alumni_view($page);
}

function _page_build_embed_distinguished_alumni_view(&$page) {
  if (drupal_get_path_alias() == 'people-contacts/distinguished-alumni') {
    $view = views_get_view('distinguished_alumni_listing');
    $display = 'blocks';
    $view->set_display($display);
    $output = $view->preview($display);
  }
  if (isset($output)) {
    $page['content']['system_main']['distinguished_alumni_listing_view'] = array(
        '#weight' => 99,
        '#markup' => $output,
    );
  }
}

```

# Answer
> 1 votes
Just copy $page\['homepage\_video'\] variable before it will be rendered and then render both.

```
<?php $homepage_video = $page['homepage_video']; ?>
<?php print render ($page['homepage_video'])?>
<?php print render ($homepage_video)?>

```

# Answer
> 0 votes
Multiblock should be able to help, however I've not used it in templates, only through the UI (with Context).

> Drupal's block module is limited by the fact that a block can only have one instance. Each block has a 1:1 relationship with its region, weight, visibility (and other) settings. This means that it is impossible to have blocks in multiple regions or to have blocks that have different settings on different pages. MultiBlock module solves this problem by allowing you to create multiple Block Instances of already existing blocks.

# Answer
> 0 votes
Try display Suite Module and place your block in a block field with a different name then place it in the desired region..

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


# Question
Title: Get custom fields from users table in global user object
I've altered users table and added two new fields directly using MySQL workbench

1. first\_name
2. last\_name

If we add new fields by config \> people \> site information \> manage fields, it does not allow adding drop-down list. So, directly added using MySQL workbench.

Now I was able to alter user\_register\_form and added above two fields with validation. At the time of creating new user, the values of first\_name and last\_name gets stored in users table.

Now, how to get those two fields when user logs in?

i've used below code to print user object

```
global $user;
$user_full = user_load($user->uid);
print_r($user_full);

```

Any help would be appreciated, thanks !!

# Answer
> 1 votes
You can implement the hook\_user\_load() for this purpose

I have altered the user table with field "**fname**" , Now you can load this in user object with the help of **hook\_user\_load()** func.

```
function testing_custom_user_load($users) {
  foreach ($users as $record) {
     foreach ($users as $record) {

        $result = db_query("SELECT fname FROM {users} WHERE uid IN ($record->uid)")->fetchAssoc();

        $users[$record->uid]->extra =$result['fname'];
     }
  }

}

```

Just put this code snippet in any of your custom module file.

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


# Question
Title: media_gallery images are not opening with proper size
I have set up a media\_gallery with colorbox in http://www.mountvilleresorts.com/. The gallery is working fine, but gallery images are shown very small.

After opening the images again, they are shown in the right size.

What is wrong with galleries that shows the images with a wrong size?

# Answer
> 0 votes
For the images to be of same size on every refreshing of page:-

1. you need to define the image style as per your requirement by Configuration \> Media: Image Styles
2. Add the new style by giving it a name
3. Add the effect you want to give
4. Click on Add button and add the corresponding properties.
5. Update the style
6. Finally when uploading the images,choose the image style for the image ,this would result in the constant size of the image throughout instead of the variable size of the image.

# Answer
> 0 votes
Have a look at your JS and CSS aggregation settings in admin/config/development/performance of your config pages. Try turning off all aggregation, clear all caches and see what happens - see if that improves the situation.

Another thing to try would be to try different themes as I know of a case in the past where there have been conflicts (not that common). The specific example I remember is mapping with bootstrap theme.

# Answer
> 0 votes
Please try any other jquery plugin to show the images.For e.g . Lightbox2,fancy-box etc.

Also set the image style in media page for this gallery .

---
Tags: javascript, media
---


# Question
Title: Help me with my page, when open this page shows me this:
PDOException: SQLSTATE\[HY000\]: General error: 145 Table './mapibrasil/watchdog' is marked as crashed and should be repaired: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9); Array ( \[:db\_insert\_placeholder\_0\] =\> 0 \[:db\_insert\_placeholder\_1\] =\> file \[:db\_insert\_placeholder\_2\] =\> The file permissions could not be set on %uri. \[:db\_insert\_placeholder\_3\] =\> a:1:{s:4:"%uri";s:18:"public://languages";} \[:db\_insert\_placeholder\_4\] =\> 3 \[:db\_insert\_placeholder\_5\] =\> \[:db\_insert\_placeholder\_6\] =\> http://brasil.machupicchu.biz/ \[:db\_insert\_placeholder\_7\] =\> \[:db\_insert\_placeholder\_8\] =\> 190.237.102.164 \[:db\_insert\_placeholder\_9\] =\> 1403795901 ) em dblog\_watchdog() (linha 160 de /srv/www/machupicchu.biz/public\_html/modules/dblog/dblog.module).

# Answer
> 0 votes
Not a drupal question, but you need to repair your table in the MYSQL database, if you can access the db server via command line:

```
REPAIR TABLE <table name>;

```

Otherwise, tools like phpmyadmin have repair tools, check this tutorial: http://www.siteground.com/tutorials/phpmyadmin/phpmyadmin\_optimize\_database.htm

---
Tags: 7, database
---


title: Replacing logo.png in a subtheme

text:
# Question
Title: Replacing logo.png in a subtheme
So, I created a subtheme, and added a random logo.png (found a random icon online, and renamed it). It worked, of course. Then I got the .png that I actually wanted to use... and the site won't update. I replaced the old logo.png file in the root of the subtheme's folder. The old file doesn't exist anywhere (as far as I know), but it's still showing it over the new logo.png

* I've tried clearing the cache probably 30 or 40 times.
* I've tried clearing my browsers cache, and using different browsers and computers just to make sure it wasn't some local cache
* When I upload a custom logo.png through the theme's administration page, it works, but when I go back to the "default", it goes back to the old one. (I'd like this icon to be the default, not to have to choose a custom one.)

I'm not sure what else to try.

# Answer
Does your subtheme heritate from another theme? Maybe you can paste your logo in the super theme folder too to erase its default logo as well.

edit: Even if I think that it's not a good thing to change Drupal core or contrib modules/themes directly in the files.
> 1 votes

# Answer
Turns out the color module was caching the image. Kind of?

The path to the image that the user was seeing was "site.com/sites/default/color/nameoftheme-randomaplhanums/logo.png." It didn't matter what I replaced the "site.com/sites/all/themes/nameoftheme/logo.png" file with, it was still using the other one. So, I just replaced it.

I'm not sure how to avoid that from happening (maybe uninstalling color? I dunno.) But replacing the image worked. Seeing as how you're not going to constantly changing the default logo that a theme is packaged with that often, I guess it's a viable solution
> 0 votes

---
Tags: 7
---


# Question
Title: Why direction nav transition not working on Flexslider module?
I am using the following modules: Flexslider module (version flexslider 2.2), FlexSlider Views Slideshow Module and Views, in Drupal 7.

I build the slideshow, and define the Direction Nav (prev / next).

when I looked at the demo of the flexslider, I saw that these is a transition to the arrows when they are appearing and disappearing- it looks they are coming from the sides when I hover, and they going out when I stop hover.

unfortunately, I don't see any transition on my slider, and the the arrow just appear and disappear.

When I checked, I notice that the problem is that when I stop hovering, and then immediately hover again, I see that the transition is in fact happening, but it's only visible if I hover immediately again.

Does someone know what is the problem and can you help me solve this issue?

here is the direction nav code:

```
/* FlexSlider Default Theme
*********************************/
.flexslider { margin: 0 0 60px; background: #fff; border: 4px solid #fff; position: relative; -webkit-border-radius: 4px; -moz-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: 0 1px 4px rgba(0,0,0,.2); -moz-box-shadow: 0 1px 4px rgba(0,0,0,.2); -o-box-shadow: 0 1px 4px rgba(0,0,0,.2); box-shadow: 0 1px 4px rgba(0,0,0,.2); zoom: 1; }
.flex-viewport { max-height: 2000px; -webkit-transition: all 1s ease; -moz-transition: all 1s ease; -o-transition: all 1s ease; transition: all 1s ease; }
.loading .flex-viewport { max-height: 300px; }
.flexslider .slides { zoom: 1; }
.carousel li { margin-right: 5px; }

/* Direction Nav */
    .flex-direction-nav {*height: 0;}
    .flex-direction-nav a  { display: block; width: 40px; height: 40px; margin: -20px 0 0; position: absolute; top: 50%; z-index: 10; overflow: hidden; opacity: 0; cursor: pointer; color: rgba(0,0,0,0.8); text-shadow: 1px 1px 0 rgba(255,255,255,0.3); -webkit-transition: all .3s ease; -moz-transition: all .3s ease; transition: all .3s ease; }
    .flex-direction-nav .flex-prev { left: -50px; }
    .flex-direction-nav .flex-next { right: -50px; text-align: right; }
    .flexslider:hover .flex-prev { opacity: 0.7; left: 10px; }
    .flexslider:hover .flex-next { opacity: 0.7; right: 10px; }
    .flexslider:hover .flex-next:hover, .flexslider:hover .flex-prev:hover { opacity: 1; }
    .flex-direction-nav .flex-disabled { opacity: 0!important; filter:alpha(opacity=0); cursor: default; }
    .flex-direction-nav a:before  { font-family: "flexslider-icon"; font-size: 40px; display: inline-block; content: '\f001'; }
    .flex-direction-nav a.flex-next:before  { content: '\f002'; }

```

# Answer
I see the same issue sometimes. When I look at my local direction anchors, they are display:none by default, but the WooThemes example they are display:block. Also, obviously, the opacity and left/right css3 transitions don't work.

In Chrome you can test the :hover selector on the .flexslider element.

I have seen this work properly in some sites.

It looks like there's a responsive breakpoint at 860px that you need to consider, so I placed these styles at min-width:861px. If you make these styles the default, the arrows will always be visible under 860px. This is why I put the styles at 861 and above.

Anyway, my approach to 'fixing' this was to simply reinforce the display, opacity, left/right, and transition settings in my theme CSS. Not sure if all of this is necessary, but it does work :)

```
/** Media Queries: min 861 only Flexslider
------------------------------*/
@media (min-width: 861px) {
    .flex-direction-nav .flex-prev {
        -webkit-transition-property:left, opacity;
        -moz-transition-property:left, opacity;
        -o-transition-property:left, opacity;
        transition-property:left, opacity;
        -webkit-transition-duration:0.3s;
        -moz-transition-duration:0.3s;
        -o-transition-duration:0.3s;
        transition-duration:0.3s
    }
    .flex-direction-nav .flex-next {
        -webkit-transition-property:right, opacity;
        -moz-transition-property:right, opacity;
        -o-transition-property:right, opacity;
        transition-property:right, opacity;
        -webkit-transition-duration:0.3s;
        -moz-transition-duration:0.3s;
        -o-transition-duration:0.3s;
        transition-duration:0.3s
    }
    div.flexslider .flex-direction-nav a {
        display:block
    }
}

```
> 1 votes

---
Tags: javascript
---


# Question
Title: Show fields of content type B while keeping filter criteria as content type = A in view
I am creating a website in drupal.

I have two content types first is Article and second is Author

Article contains following fields: Title, Body, Author-name, Language

Author has following fields: Name, Year, Info

Now In a view I want to show the Article name, its author-name and the year of that author!

How can I do this? Thanks

# Answer
You need Entity Reference, In your **Article** content type, create the author field as an entity reference field and refer it to the **Author** content type. After that you can create a view and add a relationship of **Entity Reference** and you will get the related fields. For further read, refer here
> 1 votes

---
Tags: views
---


# Question
Title: Need Help passing field data from one content type to another
I am working on an Equipment Checkout system using Drupal 7, MERCI, views, panels, rules, and many other modules. I am working for a community college in Oregon. I am upgrading features on an already running system that was built by myself with the help of a few other people last year. The system is offline for the summer.

Before I jump into the nuts and bolts of the question let me give you a little information on our workflow.

When the Student want to checkout equipment (cameras, microphones, whatever) we first open up the students customer account. This is a content type called customer, that has various fields containing data about the student, name, email, L# etc. We do this to verify the identity of the student as well as to make sure that they can actually check out the equipment they are requesting.

After we have verified the students credentials. We then create a new reservation, that is also a content type. Then we input the student information into the reservation.

So what I want to do: Have a button or link on the customer page that will capture the customer data, create a reservation, and then put the data in the appropriate place.

I have done some searching looking for answers and this seems to be a common problem, but the specifics always seem to throw me off. I've tried a few modules to attempt this, autofill and prepopulate but with no success.

This is the first of many features that I am trying to implement over the next 3 months, any help would be greatly appreciated.

Thank You

# Answer
I don't have enough reputation to comment. I would approach this with an entity reference field, a block, and rules.

Your reservation content type should have an entity reference field for the 'customer' record.

A block would have the button to click. It goes on your customer record page. You might need a module like Rules Link to trigger rules.

Set up rules so that when you click this button it:

* creates a new entity (a node of type reservation)
* populates the user reference field with the customer node you are looking at
* saves the new node
* opens the edit screen on the new node so more work can be done

It will take some playing around play around with rules to get it right.
> 0 votes

---
Tags: views
---


# Question
Title: How do I intercept a press on "Save" and get the nid?
I want to get hold of the `nid` of the newly created node whenever a new node or comment is created by a user by pressing "Save" (and only when the user press "Save" - not when the node is created or saved by other means).

I've tried to create a custom submit handler to intercept the save by means of a custom submit handler:

```
$form['#submit'][] = 'mymodule_node_submit';

```

This handler intercepts the press on the "Save" button, but it is invoked too early. The `nid` of the node it is not yet available inside the submit handler.

What is the correct way of getting the `nid` whenever a new node is created by an interactive user?

I know there is a similar question here: Get node id of saved node \- but the accepted solution (use `hook_node_update()`) is not correct. `hook_node_update()` will also intercept calls when nodes are created programatically (for instance by the **Feeds** module), when there is no real user involved.

# Answer
If you read through `node_form()` you will see that the **Submit** button has its own submit handler:

```
$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
  '#value' => t('Save'),
  '#weight' => 5,
  '#submit' => array('node_form_submit'),
);

```

so you need to add your own submit handler to this

```
function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  $form['actions']['submit']['#submit'][] = 'MYMODULE_node_form_submit';
}

```

Then inside that `$form_state['nid']` or `$form_state['node']` should have what you need.
> 2 votes

# Answer
You can use `hook_node_submit($node, $form, &$form_state)` and check `$node->op == 'Save'`.

```
This hook is invoked when a node form is submitted with either the "Save" or
"Preview" button, after form values have been copied to the form state's node
object, but before the node is saved or previewed.

```

**Update:** You can use `hook_node_insert()` itself, if you check the `$node` object it will contain `$node->op` only when creating through UI, it won't be present when creating through code.
> 1 votes

---
Tags: 7, hooks
---


title: Get only one field from profile

text:
# Question
Title: Get only one field from profile
I have a profile field called "myutr" that I need to pass to the browser, for ALL pages, via js

```
drupal_add_js(....)

```

I know that $user does not contain profile fields so to get the value of this field I need to load it via

```
$account = user_load($user);
drupal_add_js($account->myutr); //I know that is not the correct code

```

But in a big site with more and more page views call user\_load only for a field is for me a bad perfomance practice. So: is there a possibility to load only this field via drupal standard api ? Or I need to call db\_query(....) ?

Thanks.

# Answer
> 1 votes
Have a look at this article, I've used the method in the past.

http://timonweb.com/working-with-drupal-fields-getting-single-field-values-for-display-and-manipulaton

# Answer
> 0 votes
Entity Queries will probably work!

Taken from this answer: How to get users (entities) for a certain field value?

Just add in the condition for the current userid.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_birthday', 'value', $birthday);

$result = $query->execute();
$users_ids = array_keys($result['user']);

```

---
Tags: 7, users, performance
---


# Question
Title: Pre populate a text field when creating node
Say I'm creating content into a text field. Instead of inserting text by typing into text field, how could select text from a drop down list to pre populate the text field?

# Answer
I would suggest you create a content type called "Text Templates". Then add a reference to this content type in the content type that you are using.

In hook\_node\_submit you can get the value from the body fields of the Text Template node using the node-reference and then pre-populate in your current node.

If you want the body to be filled during the node edition then you will have to write an ajax call to fetch the body based on the drop-down value and fill it in the body.
> 1 votes

# Answer
Have a look at this module and see if it does what you need

https://www.drupal.org/project/prepopulate
> 1 votes

---
Tags: nodes
---


title: SSL setup on BOA 2.2.5

text:
# Question
Title: SSL setup on BOA 2.2.5
I am trying to use https for my website hosted using BOA 2.2.5, I am following this documentation:

http://community.aegirproject.org/content/content/administrator/post-install-configuration/using-ssl

The problem is after following the steps for Configure Your Aegir Server, I can't find the directory that it said would be created:

/var/aegir/config/ssl.d

/var/aegir/config/server\_master/ssl.d

# Answer
> 0 votes
We don't recommend the built-in Aegir SSL feature (yet), as explained in BOA docs.

Anyway, on BOA/Octopus, the directory you are looking for is located in the /data/disk/USER/config/ tree.

---
Tags: aegir
---


# Question
Title: Use Rules to give users a discount on their order after a few days (Commerce)
I want to create a series of rules that will discount user's carts in specific time intervals after their cart has been created. I can think of two way to do this. I realize that I will most likely need the rules\_scheduler module as well. This site is built using Commerce.

My first idea was to create discount codes for each discount level (5OFF for 5% off, 10OFF for 10% off, etc.) that will only be enabled for that specific user during each respective timeframe. This would require these codes to be both enabled and disabled in order to transition properly. However, from what I currently understand, these discount codes are global. So this method would not work. My second idea will still read the order created date. Two days after that, the rule will multiply their oder by .95. After five days that amount will change to .9. continuing as necessary.

Essentially: 1) User creates an account and adds products to his cart. 2) After 2 days pass, they will be given 5% off of this order. 3) After 5 days pass, they will be given 10% off of this order. and so on.

My question is has anybody has tackled this issue before? I would like to receive some insight or advice on how to best accomplish this type of functionality . So far, I have been unsuccessful in figuring out how to make an order creation be the event to react on for this/these rules. I also have not used rules scheduler yet, but I do not foresee that being too difficult to configure. Thanks!

# Answer
> 0 votes
I haven't done anything date related, but I have made some rules to apply discount based on various specifications. You should checkout the Commerce Discount module, it integrates in with rules.

So you would just need to create a rule to add a scheduler item for each of the time periods that you are interested in when the user adds an item to their cart, or whatever event you need.

Then when each scheduled item goes off, you would have a rule to apply a discount to their order, and do whatever else you want (maybe notify them by email).

Then a final rule that would delete any additional scheduled items once the order is marked at complete.

You should be able to accomplish all this with a few rules.

---
Tags: rules, commerce
---


title: Theming a PDF file

text:
# Question
Title: Theming a PDF file
I would like to theme the PDF generated through the Print module. I have created a view for displaying the fields of my choice in PDF.

Can anyone help me out on how to theme the PDF?

# Answer
Create your own template file:

print\[--html|--mail|--pdf\]\[--node--node-type\].tpl.php

Look inside the modules directory and you will see the template files, say print.tpl.php. Copy these and modify as needed.
> 2 votes

# Answer
You should use Views PDF module

> With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the administration interface. Therefore a new display called "PDF" is added.
> 2 votes

# Answer
You could use the FillPDF module and plug your data into a pre-designed fillable PDF.

> Most PDF modules generate PDFs from scratch; FillPDF is not one of those modules. Instead, it lets you fill in existing editable PDFs with data from your Drupal site. Editable PDFs are those forms that let you type into them
> 1 votes

# Answer
I did the same thing recently: I had a view on my nodes page that outputs fields, including fields from a referenced node, but of course this was not included in the default PDF file output by the Print module.

What I did was:

* Making a custom template as Chadpeppers explained. The filename should have a name like print\[--html|--mail|--pdf\]\[--node--node-type\].tpl.php; in my case, it was print--pdf--node--job.tpl.php.
* Embedding the view I needed in the template, using the current node ID as argument.

```
 $view = views_get_view('VIEW_NAME');
 $view->set_arguments(array($node->nid));
 $view->execute();

```

I now have a view object with all the results I expected.
> 1 votes

# Answer
I agree with @Rupesh. You should use the Views PDF module. First create the view, add the fields you need, take full advantage of theming, then add a PDF display, which this module provides. This is easier than theming the print module IMO.
> 1 votes

---
Tags: theming, files
---


# Question
Title: AJAX added form element disappears after failed validation?
I have a form field which uses the #ajax element. When a user interacts with this field a function is called and a new form element is added to the form and then the new form is displayed to the user.

However, if validation fails the added element disappears? Of course, I want it to remain.

How do I solve this problem?

# Answer
Generally it's not good to create the elements in the ajax callback. What I usually do is add the form elements to the main form, but wrap them in the if statement, and then in the ajax callback just refresh the container of that element or the whole form if it's small.

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

  $form['nominee'] => array(
    '#type' => 'checkbox',
    '#title' => t('I am nominating someone else'),
    '#ajax' => array(
      'callback' => 'return_nominee_email_element',
      'wrapper' => 'nominee-email-wrapper',
      'progress' => array('type' => 'none'),
    ),
  ),

  if(isset($form_state['values']) && $form_state['values']['contact_details']['nominee'] == TRUE) {
    $form['nominee_email'] = array(
      '#type' => 'textfield',
      '#title' => t('Email'),
      '#required' => TRUE,
      '#prefix' => '<div id="nominee-email-wrapper">',
      '#suffix' => '</div>',
    );
  } else {
    $form['nominee_email'] = array(
      '#prefix' => '<div id="nominee-email-wrapper">',
      '#suffix' => '</div>',
    );
  }

 return $form;
}

function return_nominee_email_element($form, &$form_state) {
  return $form;
}

```

See if something like that works for you.
> 1 votes

# Answer
The mistake I made was assuming that $form\_state\['values'\] always contains all the values the user has input so far. It doesn't, but $form\_state\['input'\] appears to. So, if you want to render a form element according to the current state of the form: test the contents of $form\_state\['input'\], not $form\_state\['values'\]. If the form is rebuilt (due to an custom ajax callback, or file upload, for example) $form\_state\['values'\] will change and can't be relied upon.

Edit: Be careful using `$form_state['input']` as it contains untrustworthy, raw input from the user.
> 0 votes

---
Tags: forms
---


# Question
Title: Add a custom line item type with custom fields when my module is active
I'm developing a module that adds on to Drupal Commerce that requires a custom line item type (LIT) along with additional fields on the LIT. With this hook I can add the LIT.

```
function package_designer_commerce_line_item_type_info_alter(&$line_item_types) {
     $lineItemType = array
    (
        'name' => "new product line item type",
        'description' => "A customized product line item type",
        'product' => true,
        'add_form_submit_value' => "Add product",
        'base' => "commerce_product_line_item"
    );
    $line_item_types['new_product_line_item_type'] = $lineItemType;

}

```

And it appears in the LIT list under the configuration menu. But when I click on Manage Fields it doesn't have the same list of as the regular commerce line item type, which is what I thought the `base` entry was meant to do. That is secondary though to my actual problem.

I want my LIT to have a specific field attached to it without having to provide instructions on how to go through the admin interface and create it. This might mean that instead of using that hook I need to use the `.install` file but I'm new to Drupal and would like to start with the recommended method instead of developing bad habits.

*Update*

It turns out `base` doesn't do what I thought it did. It only sets the line item up for using the default callbacks that start with 'commerce\_product\_line\_item\_type'. To actually make my LIT have the same base fields as the commerce product one I need to add this to my module

```
function package_designer_enable() {
    commerce_product_line_item_configuration(array('type'=>'new_product_line_item_type'));
}

```

# Answer
As stated by @pcambra, the hook to define custom line items is hook\_commerce\_line\_item\_type\_info.

The `base` key is used to build the name of some callback functions. If not specified, it defaults to the line item type name.

One of the possible callbacks is "configuration", and it is invoked when the line item is first detected by Commerce. In this callback is where you should create the fields/instances related to your line item type. Commerce already does it in commerce\_product\_reference module. See commerce\_product\_reference\_commerce\_line\_item\_type\_info and commerce\_product\_line\_item\_configuration for reference.

Also, you can consult this blog post for some tricks to ease the creation of fields/instances.
> 1 votes

# Answer
That would work in the case that your line item type is a "product" one, you can check how Commerce Shipping does this in case it weren't product types.

Instead of using hook\_commerce\_line\_item\_type\_info\_alter, you should be using hook\_commerce\_line\_item\_type\_info to define your line item type.

Alternatively, you can use Commerce Customizable Products module if you don't want to code yours.

For creating fields into Line item types or any entity, check Commerce discount or Commerce recurring framework.

Commerce recurring uses an hook\_enable approach (link), making sure that a field is not created if it previously existed whereas Commerce discount uses a similar approach but in hook\_flush\_caches() (link)
> 0 votes

---
Tags: commerce, entities
---


# Question
Title: If logged in, My Account/Log Out are missing, how can i fix?
I have a Drupal Commerce website in development and there is a problem with the User Login block.

If logged in, it is missing the 'My Account / Log Out' links. But if logged out, is shows the standard links, 'Username/Pass fields, Create New Account, Request New Password' links.

I have no idea how to fix. can someone please clue me in where to start? This was a PSD to Drupal job so maybe the problem lies in one of the Template files? like Regions.tpl ?

On a standard Drupal install this hasn't been an issue.

# Answer
> 0 votes
The user login block doesn't include "My Account" and "Log Out" links.

`user_block_view` \> `user_login_block`

However, you can add the "User menu" to that region instead

*Admin \> Structure \> Blocks \> "User Menu"*

It contains "My Account" and "Log Out" links.

---
Tags: blocks, users
---


title: Create a robust permission control

text:
# Question
Title: Create a robust permission control
I am building a system in Drupal and here is one question that is blowing my mind for more than a month and I hope you guys can help me.

My user access control inside the system must work like this:

1) I have a role called partners and I have lots of permissions assigned to this role partners.

2) I have a role called clients and again, I have a bunch of permissions assigned to this role.

3) The users with a partner role can create users with role partner AND client. The users with role client can create users with role client.

So far it is simple!

4) A user with role partner can create users with role partner and client BUT they can also say that the new partner or client created MUST NOT access some specific areas. So for example: A partner is allowed to see users, create users and create clients. When the ¨partner master¨ is creating a new partner user, he can say that this new user can only see users and create users but not create partners.

Do you know any module to solve this problem? I have already tried user\_permission and subrole, none of them fit :(

Hope you can help, thanks!

BTW, I am using Drupal 7

# Answer
> 0 votes
Have you checked out the role delegation module? Sounds to me like your already using it but I may be wrong. It allows users with certain roles to act like the administrator. You can limit which roles can be granted.

---
Tags: users
---


# Question
Title: Using a backup file to transfer a site to new directory
I am working on a project on a sub-domain of my site that when it is ready I want to move it to my client's site. I was wondering if I can do this by creating a back-up file using 'Backup and Migrate' and installing Drupal on their site and loading this back-up file to move all my work there. Is this possible or is there a better way?

All the best!

# Answer
This will depend a little on which version of Backup and Migrate you are using.

Older versions only backed up the database, so you would also need to copy over the public and private files to the new site, along with the rest of the code.

Newer versions can backup files, but I don't have any direct experience with doing this. It advertises that it can do either the public files, or the entire site.

Just keep in mind that Backup and Migrate will by default exclude the data from certain tables, mainly the cache files, logs, and the search index. Rebuilding the search index can be a very expensive (and lengthly) process on a big site. This is configurable, though.

There are other options, too, such as drush.
> 0 votes

---
Tags: backups
---


# Question
Title: Getting current tid on taxomony/term/{id} without using arg()
From a page based on a url of `taxonomy/term/##`, how do I properly get the tid (the numeric value in the URL) *without* using `args()`? Is using args() a decent way of doing this?

# Answer
> 4 votes
From where this page is coming, from core taxonomy or views?.

By default the taxonomy module provide the `taxonomy/term/##` callback and views module also provide a default view with the path `taxonomy/term/##`.

If you haven't enabled the **Taxonomy term** view then this page will be the default taxonomy core page, in that case you can use `menu_get_object('taxonomy_term', 2)` to get the loaded term.

For `arg()`, the document says

> Avoid use of this function where possible, as resulting code is hard to read. In menu callback functions, attempt to use named arguments. See the explanation in menu.inc for how to construct callbacks that take arguments. When attempting to use this function to load an element from the current path, e.g. loading the node on a node page, use menu\_get\_object() instead.

---
Tags: taxonomy-terms
---


# Question
Title: How to comment on image in colorbox (modal form)?
I have created view to display images and also user to display it in popup using Colorbox trigger in view.

I want to allow users to comment on each individual image in modal form only. Just like Facebook. I have printed the comment form on popup but it is coming with preview button which redirects user to the photo's node page. And allow there to POST comment which I don't want.

What I want is user should be able to comment in popup with post button and the comment should be posted in modal form only (Should be visible in modal and node page as well). Is there any module to workout this?

# Answer
Inline Ajax Comments should do the trick for you.

> Inline Ajax Comments is a views handler that allows you to add a field to a view to allow users to view and post comments on nodes in a view. This is a basic version of what you see with commenting in social networking sites like Facebook.

Ajax Comments comments can also be considered.
> 0 votes

---
Tags: views, comments, javascript
---


# Question
Title: How to restyle GeoField's proximity filter controls?
**Background**
I am using the modules: geocoder geofield addressfield geophp ip\_geoloc libraries to create a store locator view. The user can search the available stores using an exposed GeoField proximity filter.

**Question**
How can I restyle the GeoField's proximity filter controls? I would like to change the edit box for distance to a select with fixed values, and hide the distance units select defaulting it to miles.

# Answer
> 4 votes
I had a similar issue with editing the exposed form. Form alter is not the right way to go though. You'll need to use element info alter. Take a look at this custom module I threw together for editing the geofield proximity search. You can see what I did, and add/modify functionalities for your needs (although I think i did exactly what you wanted).

# Answer
> 2 votes
Something like

```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
   if (($form_id == 'views_exposed_form') &&  ($form['#id'] == 'views-exposed-form-your-view')) {
    $form['proximity']['default_radius']['#type'] = 'select';
    $form['proximity']['default_radius']['#options'] = array(10, 20, 30);
    $form['proximity']['radius_unit']['#type'] = 'item';
  }
}

```

---
Tags: 7, views, location
---


title: OG assign existing content to group

text:
# Question
Title: OG assign existing content to group
I'm adding OG to and existing site with hundreds of existing nodes. I'm looking for a way to assign existing content to groups. Sort of OG after-the-fact. Does anyone have any recommendations?

# Answer
> 0 votes
You can use the og\_group provided by the OG module.

```
  // The id of the group to which you need to assign the nodes
  $gid = 123;

  // The node which should be added to a group.
  $node = node_load(1);

  $values = array(
    'entity_type' => 'node',
    'entity' => $node,
    'state' => OG_STATE_ACTIVE,
  );

  //Add the current node to the group using the funciton provided by OG
  $result = og_group('node', $gid, $values);

```

---
Tags: organic-groups
---


# Question
Title: disable the preview and delete buttons on node edit form
I want to disable the preview and delete buttons on node edit form.I have used the following code.But it is not working. where am i wrong with this?

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
// Check for a particular content type's node form.
  if ($form_id == 'node-gallery-item-node-form') {
    drupal_set_message("Formid");

    unset ($form['edit-preview']);
    unset ($form['edit-delete']);

  }
}

```

# Answer
> 1 votes
Since you are not checking for any particular condition in your code, I would suggest that you remove the preview option from the content type settings.

```
admin/structure/types/manage/[you_content_type]

```

Regarding the delete button if you can do it using permissions, you should always do it using permissions. If you do not want to revoke the permission but just want to hide for a particular screen then use

```
$form['actions']['delete']['#access'] = FALSE;

```

# Answer
> 0 votes
For disabling preview you can go through your content-type edit page under submission form setting tab.Here you can disable Preview before submitting option. For delete you can go through permission and uncheck delete permission for your specific content-type.

---
Tags: forms
---


title: How to set url alias as article title?

text:
# Question
Title: How to set url alias as article title?
I'm getting url alias for all articles like mysite.com/node/14 but I wanted to set the url as aritcle titles like this: mysite.com/article-title

So, How to set all url alias as per the articles title?

# Answer
Use Pathauto module.

> The Pathauto module automatically generates URL/path aliases for various kinds of content
> (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias.
> This allows you to have URL aliases like /category/my-node-title instead of /node/123.
> The aliases are based upon a "pattern" system that uses tokens which the administrator can
> change.
> 4 votes

---
Tags: 7
---


title: hooks inside template.php

text:
# Question
Title: hooks inside template.php
Everytime I use drupal hooks I always take the custom module route and call the hooks from there. I'm basically talking about all the hooks in drupal -- hook\_form\_alter(), hook\_page\_alter(), hook\_menu, hook\_user(), hook\_nodeapi(), hook\_init, etc. etc. etc. etc.

On the other hand, I have never actually delve into writing hooks inside my template.php so I was wondering:
\- If this is possible?
\- Is it going to work exactly the same as it does when called in a module?
\- Are all drupal functions available as well through template.php?
\- Are there any notable differences in code implementation?
\- In which scenario I would choose custom module over theme.php?

Please note any D6 and D7 difference.

Please advice. Thank you.

# Answer
Some hooks you can call inside template.php, but not all hooks - it really depends on what you're doing. If you keep it mostly theming related (altering data output, adding CSS, form alters, etc), you should be okay. A hook like hook\_search\_api\_query\_alter wouldn't work.
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: Can someone explain how Text Formats work with CKEditor profiles? Very confused
sorry if this is a silly question, but I'm stuck. I'm trying to figure out the relationship between profiles configured in CKEditor and those configured in Config\>Text Formats.

Some context: In CK editor (Config \> CKEditor), I set up three text editor formats: \- "Admin": Full editor for admin \- "Editor": Filtered-but-robust text editor for editors and bloggers \- "User": Filtered-but-VERY-simple text editor for everyone else.

In CKEditor, I don't see a way to assign these profile to different roles.

When I head over to Config \> Text Formats, I DO see the ability to assign them to roles, and some configuration options.

Can someone explain the relationship (if any) or what I am missing?

Thanks in advance!

# Answer
> 1 votes
The text formats have to do with how the text is being processed as you can have functions that process icon labels, tokens, video snippets, etc. Sometimes you don't want certain roles to have access to these properties.

For example, I wouldn't want to give a normal user access to add certain HTML tags or YouTube video tags, but I would want to give that access to a content editor.

With CKEditor, you can then assign a CKEditor profile with a certain set of buttons to each text format. For example, I would give a CKEditor profile with a lot of buttons and functionality to an admin or content editor, so I would pair that with the Full HTML text format, but I want to slim down the CKEditor profile for a regular user, so I would pair that with the Basic HTML text format (if I created one).

---
Tags: wysiwyg
---


# Question
Title: Custom simpltest does not run successfully
I have written an automated test to create a node of a specific content type.

Here is the code:

```
class GlueTestingBuySystemTestCase extends DrupalWebTestCase {

  protected $privileged_user;

  public static function getInfo() {
    return array(
      'name' => 'Buying system',
      'description' => 'Buying system test',
      'group' => 'GLUE',
    );
  }

  public function setUp() {
    $this->profile = 'testing';
    // Enable any modules required for the test. This should be an array of
    // module names.
    parent::setUp(array('glue_testing'));

    // Create and log in our privileged user.
    $this->privileged_user = $this->drupalCreateUser(array(
      'administer nodes',
      ));
    $this->drupalLogin($this->privileged_user);
  }

  public function testBuyingSystem() {
    $edit = array();
    $edit['title'] = $this->randomName(8);
    $this->drupalPost('node/add/test', $edit, t('Save'));
    $this->assertText(t('Test Node Type @title has been created.', array('@title' => $edit['title'])));
  }

}

```

It does appear in the group "GLUE" but when I run the test it gives me the errors:

```
Failed to set field title to lLzjWnd0
Found the Save button
Found the requested form fields at node/add/test
"Testing Node Type lLzjWnd0 has been created." found

```

And does not create any node nor created the user. Any one who have idea that what is wrong in my code?

# Answer
> 0 votes
afaik there's any content-type in the testing site. You need to create it first. For example date module creates one in DateFieldBasic::setUp (surely there're more examples in core, but I've got that one at hand).

---
Tags: 7, testing
---


# Question
Title: Commerce Extra Pane wont drag in checkout UI
I have created a Drupal Commerce pane using the Commerce Extra Panes module. I created a group and field and they show up on the UI. However, its listed in the Disabled section. I tried to drag it into the Checkout pane and when I save it reverts back to the Disabled section.

When I look in the database it does list it correctly in the Checkout pane, but it doesn't actually appear on any page pane.

What is happening here and what can I do to debug more?

# Answer
It looks a bit odd, but the only thing I can come up without more information is that you might have the node disabled in the commerce extra panes tab:

If that's not the case, try also to disable the js in the checkout configuration form, click on "show row weights" so you can select the page for each pane without dragging and dropping.
> 0 votes

---
Tags: commerce
---


title: Unique profiles for each user role

text:
# Question
Title: Unique profiles for each user role
I have 3 different roles: Patient, Operator, Nurse. I have one registration form for all my users with basic information (applied via 'Account Settings'). I've been messing around with Profile2 to give each of roles a unique profile.

My problem is that I can't seem to stop Patients from having an Operator Profile and Nurses from having a Patient Profile. Is there a way for me to make the profiles unique to the roles?

I've also considered doing it exclusively in 'Account Settings' and restricting fields using Field Permissions?

I would like to do this so that alternations to the profiles is quick and easy to do.

# Answer
Restricting fields using field permissions would probably be the easiest way to do it; I've had to do something similar with Profile2 in the past and it involves overriding the access callback for profile pages, and checking that the user has a certain role.

Here's some sample code if you want to try it that way:

```
function MYMODULE_menu_alter(&$items) {
  // Ensure that category profiles are only visible if the user has the correct role
  $items['user/%user_category/edit/parent']['access callback'] = 'zylo_user_category_access';
  $items['user/%user_category/edit/tutor']['access callback'] = 'zylo_user_category_access';
  $items['user/%user_category/edit/school_staff']['access callback'] = 'zylo_user_category_access';
}

function MYMODULE_category_access($account, $type_name) {
  // First make sure the user has normal access to the page
  if (profile2_category_access($account, $type_name)) {
    // Check that the user has the correct role
    return in_array(str_replace('_', ' ', $type_name), $account->roles);
  }

  return FALSE;
}

```

It isn't the prettiest but it does get the job done
> 3 votes

# Answer
The best solution so far is Managing account registration for multiple user types and you can see the result here: Profile2 Registration Path.

> This module enables administrators to set unique registration paths per Profile2 profile type.
> 0 votes

---
Tags: 7, users
---


title: Views - sorting multiple date fields

text:
# Question
Title: Views - sorting multiple date fields
I have two content types Tweet and Instagram. Both content types includes a Date field. The information in the Date fields is imported by a json parser module.

I am displaying both content types in a view titled "homeview". All works well as expected. Both date fields use the same date format d/m/Y.

I am trying to sort both types of content chronologically in a descending order based on the date field. In other words, I would like to see this:

* Twitter post - date: 26/06/2014
* Instagram post - date: 25/06/2014
* Twitter post - date: 24/06/2014
* Instagram post - date: 23/06/2014

But was I see is this:

* Twitter post - date: 26/06/2014
* Twitter post - date: 24/06/2014
* Instagram post - date: 25/06/2014
* Instagram post - date: 23/06/2014

I found a tip how to address the issue and I created my custom module:

```
        <?php

    /**
     * @file
     *
     */

    function mysortmodule_views_query_alter(&$view, &$query) {
      // this is the name of our View and Display
      if ($view->name == 'homeview' && $view->current_display == 'page') {
        // override the ordering
        // this is because the two different date fields are one or the other
        // but not both fields, so we coalesce.
        $query->orderby = array(
          array(
            'field' => 'COALESCE( field_twitter_created_value, field_instagram_date_value )',
            'direction' => 'DESC',
          )
        );
      }
    }

```

Unfortunately, it doesn't to be working.

Could anyone please give me tips how to sort view using two different date fields? Here's my "homeview" export code:

```
        $view = new view();
    $view->name = 'homeview';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'node';
    $view->human_name = 'homeview';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['title'] = 'HomeView';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['access']['type'] = 'perm';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['pager']['type'] = 'infinite_scroll';
    $handler->display->display_options['pager']['options']['items_per_page'] = '5';
    $handler->display->display_options['pager']['options']['offset'] = '0';
    $handler->display->display_options['pager']['options']['id'] = '0';
    $handler->display->display_options['pager']['options']['quantity'] = '0';
    $handler->display->display_options['style_plugin'] = 'masonry_views_grid';
    $handler->display->display_options['style_options']['masonry_animated'] = TRUE;
    $handler->display->display_options['style_options']['masonry_resizable'] = TRUE;
    $handler->display->display_options['style_options']['masonry_center'] = FALSE;
    $handler->display->display_options['style_options']['masonry_rtl'] = FALSE;
    $handler->display->display_options['row_plugin'] = 'fields';
    /* Field: Content: Title */
    $handler->display->display_options['fields']['title']['id'] = 'title';
    $handler->display->display_options['fields']['title']['table'] = 'node';
    $handler->display->display_options['fields']['title']['field'] = 'title';
    $handler->display->display_options['fields']['title']['exclude'] = TRUE;
    $handler->display->display_options['fields']['title']['link_to_node'] = FALSE;
    /* Field: Content: Type */
    $handler->display->display_options['fields']['type']['id'] = 'type';
    $handler->display->display_options['fields']['type']['table'] = 'node';
    $handler->display->display_options['fields']['type']['field'] = 'type';
    $handler->display->display_options['fields']['type']['label'] = '';
    $handler->display->display_options['fields']['type']['element_label_colon'] = FALSE;
    /* Field: Content: Post date */
    $handler->display->display_options['fields']['created']['id'] = 'created';
    $handler->display->display_options['fields']['created']['table'] = 'node';
    $handler->display->display_options['fields']['created']['field'] = 'created';
    $handler->display->display_options['fields']['created']['label'] = 'Drupal';
    $handler->display->display_options['fields']['created']['exclude'] = TRUE;
    $handler->display->display_options['fields']['created']['date_format'] = 'universal_date';
    $handler->display->display_options['fields']['created']['second_date_format'] = 'long';
    /* Field: Content: Created */
    $handler->display->display_options['fields']['field_twitter_created']['id'] = 'field_twitter_created';
    $handler->display->display_options['fields']['field_twitter_created']['table'] = 'field_data_field_twitter_created';
    $handler->display->display_options['fields']['field_twitter_created']['field'] = 'field_twitter_created';
    $handler->display->display_options['fields']['field_twitter_created']['label'] = '';
    $handler->display->display_options['fields']['field_twitter_created']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['field_twitter_created']['hide_empty'] = TRUE;
    $handler->display->display_options['fields']['field_twitter_created']['settings'] = array(
      'format_type' => 'universal_date',
      'fromto' => 'both',
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_to' => '',
    );
    /* Field: Content: Date */
    $handler->display->display_options['fields']['field_instagram_date']['id'] = 'field_instagram_date';
    $handler->display->display_options['fields']['field_instagram_date']['table'] = 'field_data_field_instagram_date';
    $handler->display->display_options['fields']['field_instagram_date']['field'] = 'field_instagram_date';
    $handler->display->display_options['fields']['field_instagram_date']['label'] = '';
    $handler->display->display_options['fields']['field_instagram_date']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['field_instagram_date']['hide_empty'] = TRUE;
    $handler->display->display_options['fields']['field_instagram_date']['settings'] = array(
      'format_type' => 'universal_date',
      'fromto' => 'both',
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_to' => '',
    );
    /* Field: Content: Link */
    $handler->display->display_options['fields']['view_node']['id'] = 'view_node';
    $handler->display->display_options['fields']['view_node']['table'] = 'views_entity_node';
    $handler->display->display_options['fields']['view_node']['field'] = 'view_node';
    $handler->display->display_options['fields']['view_node']['label'] = '';
    $handler->display->display_options['fields']['view_node']['exclude'] = TRUE;
    $handler->display->display_options['fields']['view_node']['element_label_colon'] = FALSE;
    /* Field: Content: Link */
    $handler->display->display_options['fields']['field_instagram_link']['id'] = 'field_instagram_link';
    $handler->display->display_options['fields']['field_instagram_link']['table'] = 'field_data_field_instagram_link';
    $handler->display->display_options['fields']['field_instagram_link']['field'] = 'field_instagram_link';
    $handler->display->display_options['fields']['field_instagram_link']['label'] = '';
    $handler->display->display_options['fields']['field_instagram_link']['exclude'] = TRUE;
    $handler->display->display_options['fields']['field_instagram_link']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['field_instagram_link']['click_sort_column'] = 'url';
    /* Field: Content: Image */
    $handler->display->display_options['fields']['field_instagram_image']['id'] = 'field_instagram_image';
    $handler->display->display_options['fields']['field_instagram_image']['table'] = 'field_data_field_instagram_image';
    $handler->display->display_options['fields']['field_instagram_image']['field'] = 'field_instagram_image';
    $handler->display->display_options['fields']['field_instagram_image']['label'] = '';
    $handler->display->display_options['fields']['field_instagram_image']['alter']['alter_text'] = TRUE;
    $handler->display->display_options['fields']['field_instagram_image']['alter']['make_link'] = TRUE;
    $handler->display->display_options['fields']['field_instagram_image']['alter']['path'] = '[field_instagram_link]';
    $handler->display->display_options['fields']['field_instagram_image']['alter']['external'] = TRUE;
    $handler->display->display_options['fields']['field_instagram_image']['alter']['target'] = '_blank';
    $handler->display->display_options['fields']['field_instagram_image']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['field_instagram_image']['click_sort_column'] = 'fid';
    $handler->display->display_options['fields']['field_instagram_image']['settings'] = array(
      'image_style' => 'thumbnail',
      'image_link' => '',
    );
    /* Field: Content: Twitter Text */
    $handler->display->display_options['fields']['field_twitter_text']['id'] = 'field_twitter_text';
    $handler->display->display_options['fields']['field_twitter_text']['table'] = 'field_data_field_twitter_text';
    $handler->display->display_options['fields']['field_twitter_text']['field'] = 'field_twitter_text';
    $handler->display->display_options['fields']['field_twitter_text']['label'] = '';
    $handler->display->display_options['fields']['field_twitter_text']['alter']['alter_text'] = TRUE;
    $handler->display->display_options['fields']['field_twitter_text']['alter']['text'] = '<a href="https://twitter.com/MusicMusiqueNB/status/[title]" target="_blank">[field_twitter_text]</a>';
    $handler->display->display_options['fields']['field_twitter_text']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['field_twitter_text']['hide_empty'] = TRUE;
    /* Sort criterion: Content: Created (field_twitter_created) */
    $handler->display->display_options['sorts']['field_twitter_created_value']['id'] = 'field_twitter_created_value';
    $handler->display->display_options['sorts']['field_twitter_created_value']['table'] = 'field_data_field_twitter_created';
    $handler->display->display_options['sorts']['field_twitter_created_value']['field'] = 'field_twitter_created_value';
    $handler->display->display_options['sorts']['field_twitter_created_value']['order'] = 'DESC';
    /* Sort criterion: Content: Date (field_instagram_date) */
    $handler->display->display_options['sorts']['field_instagram_date_value']['id'] = 'field_instagram_date_value';
    $handler->display->display_options['sorts']['field_instagram_date_value']['table'] = 'field_data_field_instagram_date';
    $handler->display->display_options['sorts']['field_instagram_date_value']['field'] = 'field_instagram_date_value';
    $handler->display->display_options['sorts']['field_instagram_date_value']['order'] = 'DESC';
    /* Filter criterion: Content: Published */
    $handler->display->display_options['filters']['status']['id'] = 'status';
    $handler->display->display_options['filters']['status']['table'] = 'node';
    $handler->display->display_options['filters']['status']['field'] = 'status';
    $handler->display->display_options['filters']['status']['value'] = '1';
    $handler->display->display_options['filters']['status']['group'] = 1;
    $handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
    /* Filter criterion: Content: Type */
    $handler->display->display_options['filters']['type']['id'] = 'type';
    $handler->display->display_options['filters']['type']['table'] = 'node';
    $handler->display->display_options['filters']['type']['field'] = 'type';
    $handler->display->display_options['filters']['type']['value'] = array(
      'instagram' => 'instagram',
      'tweet' => 'tweet',
    );

    /* Display: Page */
    $handler = $view->new_display('page', 'Page', 'page');
    $handler->display->display_options['path'] = 'homeview';

    /* Display: Block */
    $handler = $view->new_display('block', 'Block', 'block');
    $handler->display->display_options['defaults']['pager'] = FALSE;
    $handler->display->display_options['pager']['type'] = 'some';
    $handler->display->display_options['pager']['options']['items_per_page'] = '5';

```

# Answer
If they share the same date field, you should just sort by that field descending and it should work perfectly. If not, I think you should be able to add both to the sort one after the other and it should work. But try to have them use the same field, it will make life simpler.
> 0 votes

# Answer
You can use Views PHP module for this purpose. The module allows you to code your own condition or expression for a field in a view.

Here are the steps 1)Enable the module 2)Add the date fields to the fields section and exclude them from display incase they should not be displayed 3)add the field "Global: PHP" to sort condition and use the following code in the PHP field.

```
$date1 = $data->field_field_date_1;
$date2 = $data->field_field_date_2;
if(!empty($date1)){
   return $date1;
}else{
  return $date2;
}

```

4) Replace "field\_field\_date\_1" and "field\_field\_date\_2" with the appropriate field names.

Please note that using the PHP code in sort and filter conditions might have a performance impact. So this option needs to be used carefully.
> 0 votes

---
Tags: datetime, views
---


# Question
Title: On quantity change, create individual line items of the same item in Drupal Commerce cart
Here is a more detailed explanation:

In Drupal Commerce cart, when a customer sets the quantity of a product from 1 to 5 for example, on 'Update Cart', we'll need 5 individual line items of the same product with quantity 1 each.

I've gotten this far on solving the problem but I'm not sure how to continue:

```
<?php
/**
 * Implements hook_entity_update
 */
function mymodule_entity_update($entity, $type){
  if ($type == 'commerce_line_item'){
    $original = intval($entity->original->quantity);
    $updated = intval($entity->quantity);

    if ($original != $updated){
        $new_product = $entity;
        // Create as many individual line items of the same product as needed, save them and add them to the order
    }
  }
}

```

I've tried to use `commerce_line_item_save()` to save `$new_product`, which is in this code snippet should be a clone of the line item. I've tried it with increasing the line item id and save it that way but I just got DB errors.

How can I make this happen in a nice way? Thank you!

# Answer
It would be possible to create a new views handler based on `commerce_line_item_handler_field_edit_quantity` that worked the way you want, but IMHO it would be weird from a UX POV to enter 5 into the quantity textfield of 1 line item, submit, and then see 5 distinct line items with quantity 1.

A simple alternative would be to modify the cart view to have something like an *Add 1 more* button:

1. Remove the quantity field;
2. Add a relationship to the product;
3. Add the product's add to cart form as a field;
4. Configure the field to not combine products (and you can also modify the text here, eg *Add 1 more*).

I haven't tested this, but I think it should work.
> 1 votes

---
Tags: 7, commerce
---


title: DrupalGap BarcodeScanner Integration

text:
# Question
Title: DrupalGap BarcodeScanner Integration
Does anybody have experience integrating external libraries with Drupalgap (in particular the BarcodeScanner)? I've been able to get BarcodeScanner working with Phonegap relatively easily but Drupalgap's architecture is more complicated and requires using a function to acces. Any help would be great!

Here's the BarcodeScanner info:

https://github.com/cfjedimaster/Cordova-Examples

I created a project from scratch using Cordova, added the plugin according to the readme, and then copied the contents of www from the repo to my project. This works great standalone. How do I add this button to Drupalgap so I can scan barcodes from within the app?

# Answer
After setting up the plugin in phonegap simply add this to a page:

```
var html = theme('button_link', { text: 'Start Scan', path: null, attributes: { onclick: "startScan()" } });
$('#my_container').html(html).trigger('create');

```

Thanks to TylerFrankenstein for this one.
> 1 votes

---
Tags: javascript
---


# Question
Title: Two sort criteria. How to display first those with a specific List (float) selection
i have a View that provides a list of products(content type Product). This view has two sort criteria. The one is the "SKU" and the second is "New product". The "New product" is a List(float) field and the available options are N/A, Yes and No.

The view must show first the new products and then all the rest. New products are considered those that they have selected the option "Yes".

Is this possible? Any idea?

Thank

# Answer
You can do it using views\_query\_alter. Find out what are the key values being stored from your list and then use them accordingly in the code below.

```
function yourmodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'shop' && $view->current_display == 'page') {
     $query->orderby[0] = array(
           'field' => 'CASE table.type WHEN '1' THEN 1 WHEN '0' THEN 2 WHEN
            ELSE 3 END');
  }
}

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to link the parent of a Nice Menu to nowhere?
In order to make a Nice Menu, I created a menu like this:

```
My Menu
   - First link
   - Second link
   - Third link

```

The menu works perfectly fine, but I also had to fill in a link for the 'My Menu' (I've set it to the frontpage). However, I'd like the parent link to be linked to nowhere. How can I do that?

This is the relevant code for the menu's parent:

```
<div id="block-nice-menus-2">
 <ul id="nice-menu-2">
  <li class="menu__item">
   <a class="menu__link menu__link" href="/mysite/">
    My Menu
   </a>
  </li>
 </ul>
</div>

```

---

**Note:** At first, I couldn't get the code from the accepted answer working, because I forgot to load my theme's `MYTHEME.js` file. After reading this, I learned that one can do that by adding `scripts[] = MYTHEME.js` to the `MYTHEME.info` file.

# Answer
I already tried to suggest you something on your same question here: https://stackoverflow.com/questions/24431641/how-to-remove-a-link-but-keep-its-mouseover-effect/24447807#24447807

Edit: And I'm gonna write it down here as well.

I had to do this trick several times before. I just did a little javascript like :

```
$('MYLINKSELECTOR').click(function() {
    return false;
}).mouseover(function() {
    $(this).css('cursor', 'default');
}).attr('href', '#');

```

It will disable the destination href and set a default cursor but keep the hover effect.

Edit: I use this script in `MYTHEME/js/scripts.js` and to give you an example of a selector (I use Superfish, not Nice Menu), here is my full code:

```
Drupal.behaviors.pweMegaMenu = {
attach: function(context, settings) {
  // Parents links shouldn't be clickabled
  $('#menu-695-2 > a, #menu-695-2 li#menu-884-2 > a, #menu-695-2 li#menu-866-2 > a').click(function() {
    return false;
  }).mouseover(function() {
    $(this).css('cursor', 'default');
  }).attr('href', '#');
}

```
> 1 votes

# Answer
Yes you can do that using the Special menu items module:

> Special menu items is a Drupal module that provides placeholder and separator menu items.
>
> A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it
> 2 votes

# Answer
```
Drupal.behaviors.MY_MODULE_NAME = {
  attach: function(context, settings) {

    $('#nice-menu-2 ' +
    'li > ' +
    'a:not(.MYSITE-processed)').attr('href', '#')
                                   .addClass('MYSITE-processed');

  }
};

```

Should do the trick for you.

If it doesn't then try javascript debugging with firebug. To understand more about behaviors, check Better understanding of Drupal behaviors.
> 1 votes

---
Tags: 7, routes, navigation
---


# Question
Title: file_save_data() cannot save to private://
I have to write a custom module extension, that saves entityform submission after hitting submit button to a PDF file in the `private://pdf/<file_name>` uri.

At first step it generates the PDF file to a temp directory via TCPDF and then I try to use `file_save_data` to save it to private directory and upload the file data to the db.

When I upload the file to the public directory, there are no problems, but when I set the uri to `private://<pathname/filename>` it sends me an error message:

> "The data could not be saved, because the destination is invalid. More information is available in the system log".

In the system log:

> "The data could not be saved because the destination private://pdf/employee\_aontest\_richie\_2014-06-03\_00\_00\_00\_59.pdf is invalid. This may be caused by improper use of file\_save\_data() or a missing stream wrapper."

The code, that should save the whole thing is this:

```
$title = $node->title; // TCPDF doesn't let you have spaces or colons in your file name
$title_exploded = explode(' ', $title);
$title_imploded = implode('_', $title_exploded);
$imp_exploded = explode(':', $title_imploded);
$imp_exp_imploded = implode('_', $imp_exploded);
$real_title = drupal_strtolower($imp_exp_imploded);
//end of title generation
$save_path = 'private://pdf/'.$real_title.'.pdf';
$handle = fopen($full_path_tcpdf_output, 'r');
$file = file_save_data($handle, $save_path);
fclose($handle);
unlink($full_path_tcpdf_output);

```

I think the file saving procedure should work this way as it works if I save to public.

I appreciate any further advices.

# Answer
Check two things:

* The private flesystem is configured: look in /admin/config/media/file-system.
* The destination directory (private://pdf) is created. The exact path of private:// depends on where have tou configured the private filesystem.
> 1 votes

# Answer
You can use **file\_save\_upload()** function of drupal to save pdf file ,i used this function in my site and saved in private:// , and pdf file is uploaded easily their, Code that i have used in my site:-

// In form put this code

```
    $form['uploadrecord'] = array(
        '#type'=>'file',
        '#title'=>'Upload Pdf',
        '#attributes'=>array('class'=>array('upload_file')),
     );

```

// at form submit put this code

```
$validators=array();

      $file_upload_record = file_save_upload('uploadrecord',$validators, 'private://pdf/'.$real_title.'.pdf');

```

and checkout the permissions of pdf directory too.may this code will work for you.
> 0 votes

---
Tags: files
---


# Question
Title: Show message at every page regardless page content
I need to show some message for user for every page at my site.

I've tried Rules action "Content is viewed" and I see message, but only when some node is displayed.
I **don't see** message when I open User page, or page with Taxonomy term, or some View page without nodes as content.

How can I show message at every page of my site regardless page content? (Rules or Hooks or ...?)

# Answer
> 1 votes
Why not to write it directly in the template? Or create a Block which you show in the header? or do you need to use the `drupal_set_message()` Message?

You can use "Drupal is initializing" event at Rules.

# Answer
> 0 votes
Implement `hook_init()` and set the message using `drupal_set_message()`. But as @lance asked, why can't you put it in to template?

Note : make sure you set `$repeat = FALSE` while using `drupal_set_message()`

# Answer
> 0 votes
You can easily do this by simply write

```
drupal_set_message('Message That You want To display');

```

this into your activated theme **page.tpl.php** .That message will be shown for every page.

---
Tags: 7, rules
---


title: Fields capabilities

text:
# Question
Title: Fields capabilities
I am trying to enable a field in one of my content-types to be a sort of selection within a selection and I need some help doing so. Basically, I would like to have a field where the user selects from a more encompassing list (e.g., buildings) from which she is then presented with a more narrow list (perhaps room number, following the example). Is this possible to do with fields in Drupal? I understand that I could simply make two fields but I think it'd be much nicer to have this list within a list. Again, I'd appreciate any help.

Thanks!

# Answer
If your list is coming from `Taxonomy` then you can use Hierarchical Select module.
> 1 votes

---
Tags: entities, nodes
---


title: Finding menu item ID

text:
# Question
Title: Finding menu item ID
How to find a menu item pointing to the specific node?

On node creation I want to create a main\_menu link for the node. With menu\_rules it is relatively easy. The problem arises when the parent element can differ.

```
main_menu
Groups
-[GROUPS]
--[GROUP_CONTENT]

main_menu
...
Groups
-A
--a1
--a2
-B
--b1
-C
...

```

In the above case adding a new group D is easy - I simply add a menu item to 'Groups', but what if I would like to add a3? I know the name of A and I know what it is linking to (a node representing a group) but I don't know its randomly generated menu ID (for example \[menu-1082\]).

How do I find that Id?

# Answer
> 5 votes
I'm almost new user of Drupal, but I encountered the same problem because I write myself my modules. My need is to create a node and to insert it as submenu of a main menu Item. I solved my problem in this way:

I wrote this function

```
function mymodule_get_plid($menu_name , $name) {
    $menu = menu_tree_all_data($menu_name);
    foreach ($menu as $item => $menuitem) {
        if ($name == $menuitem['link']['link_title']) {
            return $menuitem['link']['mlid'];
            break;
        }
    }
    return false;
}

```

where $menuname is a string like 'main-menu', $name is the menu item for which I'm searching for it's Id. Function return Id if it find $name, false otherwise.

Now to complete node creation i wrote this.

```
$node = new stdClass();
$node->title = "YOUR TITLE";
$node->type = "page";  // Creating a node of Basic page type
node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
$node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
$node->uid = $account->uid;
$node->status = 1; //(1 or 0): published or not
$node->promote = 0; //(1 or 0): promoted to front page
$node->comment = 0; // 0 = comments disabled, 1 = read only, 2 = read/write

$node->menu['enabled'] = TRUE;
$node->menu['menu_name'] = 'main-menu';
$node->menu['plid'] = mymodule_get_plid('main-menu' , 'Inquiries');
$node->menu['link_title'] = 'MY SUBMENU NAME';
$node->menu['description'] = ''; // Needed even if empty to avoid notices.  /*

$node = node_submit($node); // Prepare node for saving
node_save($node);

```

Now all behaves well, "MY SUBMENU NAME" is created as a new node and appended as sub menuitem of the 'Inquiries' menu Item of the main menu.

# Answer
> 3 votes
Edit that menu item in your menu admin page, the id is in the URL of the menu item edit page. In most of cases you'll also find the ID of your menu item as a class of the `<a>` link.

EDIT :

You can either use menu\_get\_item if you know the path of A, or a db\_select on the `menu_links` table filtering on the path.

# Answer
> 1 votes
To get the ID I query the db using the bellow function. As an argument it takes node id of the content and it returns id of the menu item for the parent group.

```
function mymodule_get_fathers_menu_item($nid){
    $node = node_load($nid);
    $fathers_gid = mymodule_get_father($node);
    $fathers_nid = mymodule_get_nid_from_gid($fathers_gid);
    $father_node_link = "node/".$fathers_nid;

    $query = db_select('menu_links');
    $query->addfield('menu_links','mlid','mlid');
    $query->condition('link_path', $father_node_link,'=');

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

    //drupal_set_message($result['mlid']);

    return ("main-menu:".$result['mlid']) ;
}

```

I then use "Create a menu item for node" action from menu\_rules module with the parent parameter as PHP code.

```
return windbench_get_fathers_menu_item( $value );

```

and data selector set for node:nid.

My code does not work on node creation (probably something to do with when the og data are saved) so I trigger it on node edit (after publishing).

---
Tags: 7, routes, navigation
---


# Question
Title: Links in second language not working when logged out
I have inherited a Drupal web site with a lot of modules installed. Part of these modules have been setup to allow for translation of web site elements between English and French.

The site is configured to use paths prefix (mywebsite.com/fr) to indicate items from another language.

When I am logged in as administrator, I can access mywebsite.com/fr and see the french version of the homepage. When I am logged out, trying to get to the same address just redirects me to the english root (mywebsite.com).

Any ideas on where there may be a setting that would only allow logged in users to see translated content?

# Answer
After much searching, I have code in the site's theme folder, within template.php, that made a call to the drupal\_goto function if the connected user was not logged in, for all page requests where the language is set to french.

A search for $base\_url led me to find this. Although now seeing that the redirection function in drupal is drupal\_goto, I could have found this a lot quicker with a search for that call.
> 1 votes

---
Tags: users, i18n-l10n
---


title: Site emails state incorrect domain name

text:
# Question
Title: Site emails state incorrect domain name
I have a couple of drupal sites running from the same host, using apache vhosts to do domain name forwarding.

I have many domains/url's dns entries pointing to this server's ip address, some of which are not currently live websites (they fail/default over to my main website).

When a user registers on one of the sites, or the site sends me an email alert, it includes a link at the bottom of the email where I can click and view the user account, etc.

The problem is, it seems the domain/url in the link changes randomly, and is not always the domain/url of the actual site it's from. They are all domains I own and are pointing at the box, so it's like drupal does a DNS lookup on itself, then uses one of the returned domains to include in the email instead of the sitename set in the settings.

How can I fix this so emails will include a link to the proper domain they originated from?

# Answer
> 1 votes
Go to:

> admin\>configuration\>people\>account settings

Scroll down and you will see 8 email options for account activities such as account activation, password recovery, etc..

The Default token inside these emails is **\[site:name\]** which I presume is what's giving you trouble? Or do you have it set to **\[site:url\]**?

Regardless possible next steps:

>

# Answer
> 0 votes
Are the e-mails being queued to get sent during a cron run instead of going out immediately? I had this problem before while using a multi-site set up. If e-mails are queued, they will be sent from whichever site runs the cron job. So they'll be addressed from that site instead of the site that put it in the queue.

---
Tags: users, emails
---


# Question
Title: How to flag a product variation on a commerce website?
My products have multiple variations as enitities (size, color etc). I want to display a flag link on a product display page. When a visitor uses it, I want them to be able to flag the selected variation, not the node. Is it possible? Here is a related discussion on drupal.org: http://drupal.org/node/1050872

# Answer
> 3 votes
I wrote a way to use Flag for product variations here: http://drupal.org/node/1911568

Here is my solution:

1. Add a flag "add to wishlist" for commerce\_product entity type.
2. Install computed field module.
3. Add a computed field to the product (not the display content type)
4. In Display Code (PHP) area of the field:

$entity\_id = array\_shift(entity\_extract\_ids($entity\_type,$entity)); $display\_output = flag\_create\_link('add\_to\_wishlist', $entity\_id);

(Computed Code (PHP) part can be left empty, we dont want to store anything in database) 5. Go to Manage Display of the product and set the newly created computed field's format: "unsanitized" and make sure it is visible. 6. Go to Manage Display of the product display content type (not the product) and use your product's wishlist computed field there.

Now you can create a view to display a user's products in his wishlist. It is straitforward. You just add any field, add a relation: your flag and tweak the view as you like. You can also use view's menu system to create tabs on the user profile: http://drupal.org/node/326580

# Answer
> 0 votes
In case anyone comes here looking for a solution, I have created a module that will do this without needing you to do any custom coding.

Have a look at Commerce Product Reference Flag.

---
Tags: 7, commerce, entities, flags
---


# Question
Title: Using Rules after importing an item using Feeds to set a custom field value
I need a bit of help with Feeds and Rules. I have a Feed Importer that uses XPATH to parse websites for Titles and creates nodes in a custom content type. I've added a field (Field\_Source) to the content type. What I'd like to do is create a rule to copy the Feed URL value into the Field\_Source. I have a new rule that acts on After importing Feed but I'm not able to get access to the fields in the Node.

If I change the Event to Before saving an item imported by Feeds, I can get access to the node:field\_source but not the Feeds URL.

SOLVED: It was much easier than this: I just added a relationship in Views to the Feed Item and was able to use the source URL.

# Answer
I'd recommend using Feeds Tamper. do do what you want...i.e. map the pertinent section from your source "Feed URL" to your 'field\_source' and then use feeds tamper to shape it up as you like...
> 0 votes

---
Tags: rules, feeds
---