# Question
Title: Drupal nested ajax call not working correctly
I got this nested ajax call issue,

```
/**
 * Problems
 * 1). When I click "Add one more" to add more file, I need to click the button
 *     Twice to get one 'Name'/file element available. I click once, no file
 *     field shows. Click again, one file field will show.
 * 2). When one file field shows, as long as I click 'upload' button of the 'managed_file'
 *     field, this file field will disappear immediately. I upload another file, this
 *     file will be fine. Then another uploaded file will disappear.
 * 3). When I click "submit" to submit the form, all previously disappeared file fields
 *     will show. Because, as you see, the submit function only rebuild the form.
 * 4). If container of multiple file fields are not triggered by ajax, i.e,
 *     $form['test']['names_fieldset'] is not triggered by "select" field, then
 *     tihs "Add one more" function works perfectly.
 *
 * So, why this happens with the ajax triggered container:)?
 */
function agl_jira_new_test_form($form, &$form_state) {
  $form['select'] = array(
    '#title' => 'select',
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('man', 'woman')),
    '#required' => TRUE,
    '#default_value' => isset($form_state['values']['select']) ? $form_state['values']['select'] : NULL,
    '#ajax' => array(
      'callback' => 'agl_jira_select_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  $form['test']['names_fieldset'] = array(
    '#markup' => '<div id="names-fieldset-wrapper"></div>',
  );
  if (isset($form_state['values']['select']) && $form_state['values']['select'] == 'man') {
    $form['test']['names_fieldset'] = array(
      '#type' => 'fieldset',
      '#prefix' => '<div id="names-fieldset-wrapper">',
      '#suffix' => '</div>',
      '#tree' => TRUE,
    );
    $form['test']['names_fieldset']['text'] = array(
      '#title' => t('name'),
      '#type' => 'textfield',
    );
    $form['test']['names_fieldset']['attachment'] = array(
      '#title' => t('File'),
      '#type' => 'fieldset',
      '#prefix' => '<div id="agl-jira-file-attach-wrapper">',
      '#suffix' => '</div>',
    );
    if (!isset($form_state['num_names'])) {
      $form_state['num_names'] = 1;
    }
    for ($i = 0; $i < $form_state['num_names']; $i++) {
      $form['test']['names_fieldset']['attachment']['name'][$i] = array(
        '#type' => 'managed_file',
        '#title' => t('Name'),
      );
    }
    $form['test']['names_fieldset']['add_name'] = array(
      '#type' => 'submit',
      '#value' => t('Add one more'),
      '#limit_validation_errors' => array(),
      '#submit' => array('agl_jira_example_add_more_add_one'),
      '#ajax' => array(
        'callback' => 'agl_jira_example_add_more_callback',
        'wrapper' => 'agl-jira-file-attach-wrapper',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'submit',
  );
  return $form;
}

function agl_jira_select_callback($form, $form_state) {
  return $form['test']['names_fieldset'];
}

function agl_jira_new_test_form_submit($form, &$form_state) {
  //dsm('form has been submitted!');
  // do something.
  $form_state['rebuild'] = TRUE;
}

function agl_jira_example_add_more_add_one($form, &$form_state) {
 // dsm('submitted');
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

function agl_jira_example_add_more_callback($form, $form_state) {
  return $form['test']['names_fieldset']['attachment'];
}

```

Any help will be appreciated.

# Answer
> 1 votes
Correct one, just copy and paste it:

```
function agl_jira_new_test_form($form, &$form_state) {
  $form['#tree'] = TRUE;
  $form['select'] = array(
    '#title' => 'select',
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('man', 'woman')),
    '#required' => TRUE,
    '#default_value' => isset($form_state['values']['select']) ? $form_state['values']['select'] : 'man',
    '#ajax' => array(
      'callback' => 'agl_jira_select_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  $form['test']['names_fieldset'] = array(
    '#type' => 'fieldset',
    '#prefix' => '<div id="names-fieldset-wrapper">',
    '#suffix' => '</div>',
    '#tree' => TRUE,
  );
  if (isset($form_state['values']['select']) && $form_state['values']['select'] == 'man') {
    $form['test']['names_fieldset']['text'] = array(
      '#title' => t('name'),
      '#type' => 'textfield',
    );
    $form['test']['names_fieldset']['attachment'] = array(
      '#title' => t('File'),
      '#type' => 'fieldset',
      '#prefix' => '<div id="agl-jira-file-attach-wrapper">',
      '#suffix' => '</div>',
      '#tree' => TRUE,
    );
    if (!isset($form_state['num_names'])) {
      $form_state['num_names'] = 1;
    }
    for ($i = 0; $i < $form_state['num_names']; $i++) {
      $form['test']['names_fieldset']['attachment'][$i] = array(
        '#type' => 'managed_file',
        '#title' => t('Name'),
      );
    }
    $form['test']['names_fieldset']['add_name'] = array(
      '#type' => 'submit',
      '#value' => t('Add one more'),
      '#submit' => array('agl_jira_example_add_more_add_one'),
      '#ajax' => array(
        'callback' => 'agl_jira_example_add_more_callback',
        'wrapper' => 'agl-jira-file-attach-wrapper',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'submit',
  );
  return $form;
}

function agl_jira_select_callback($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  return $form['test']['names_fieldset'];
}

function agl_jira_example_add_more_callback($form, &$form_state) {
  return $form['test']['names_fieldset']['attachment'];
}

function agl_jira_example_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

function agl_jira_new_test_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

```

removed `$form['test']['names_fieldset'] = array(
 '#markup' => '

',
 );`, added reference to the form\_state in `agl_jira_example_add_more_callback`..

# Answer
> 1 votes
Okay, answering my own question here. The problem is when I use "limit\_validation\_error", I need include the first level fields data, i.e.,

```
$form['test']['names_fieldset']['add_name'] = array(
  '#type' => 'submit',
  '#value' => t('Add one more'),
  '#limit_validation_errors' => array('select'),
  '#submit' => array('agl_jira_example_add_more_add_one'),
  '#ajax' => array(
    'callback' => 'agl_jira_example_add_more_callback',
    'wrapper' => 'agl-jira-file-attach-wrapper',
  ),
);

```

---
Tags: ajax
---


# Question
Title: alias the path of single - node views (pagination on single nodes)
I would like to effectively replace the nodes with views that would show the "full content" of a node with items to display set to 1. (Each paged page of the view would thus include only one node and the pager - effectivly i'm trying to use views' pager for nodes).
Now, what I am missing is the possibility of having aliases of the paths that include given nodes. I would like the pages to have paths like site.com/myview/nodetitle, not site.com/myview/1.
The aim is to replace the links to nodes in a context of a given view by links to single - node views, thus obtaining views pagination on node-alike. So the "title" field would be linked to, say, site.com/myview/nodetitle, wichh would be the single - node - position in a that has the same cireteria etc as the one I am coming from, but with full node view *and* a views pager. I am trying to replicte the features from views-navigation. Is there any way to achieve that?
EDIT: i do not want to use contextual filters, as I do want the view to include many nodes, with 1 node showing per page

# Answer
I would not use views at all. Pathauto will help you with the aliasing. So, on hook\_init you can set the pathauto pattern for that node type to be 'myview/\[node:title\]'. Such as this:

```
function myMod_init() {
  variable_set('pathauto_node_yournode_pattern', 'myview/[node:title]');
}

```

For the pagination, I'm not sure what your use case is like. If you could have the nids gathered via a db\_query and passed to your 'page callback' function, you could construct your own "next" and "previous" buttons containing the correct href. You will find function such as drupal\_get\_path\_alias() or url() to be very useful here.

If you wanted a pagination with proper numbering, you can look into EFQ. It has pager as a public method. Although, that will probably give you query like url such as ?page=1, etc. and not the nice alias pathauto had created for you.

All in all, more information about your usecase will be useful. But this method will give you a lot more flexibilities than using views IMO.
> 1 votes

---
Tags: views, paging
---


# Question
Title: How do I render multiple form fields select boxes in a single row
I am trying to render three dropdown boxes to be on the same line using a tpl file. Here is the snippit of code I am trying to work with:

```
$form_stuff = array();
$form_stuff[]=$form['field_list_1'];
$form_stuff[]=$form['field_list_2'];
$form_stuff[]=$form['field_list_3'];
print drupal_render($form_stuff);

```

I have also tried:

`print drupal_render($form['field_list_1'] . $form['field_list_2'] . $form['field_list_3']);`

Both will render each field element on a separate line.

This gets me a little closer but the dropdown renders on top of the label. It there a way to insert a `<br>` after the label renders or some sort of `style=display:block`?

```
print '<table><tr>';
print '<td>' . drupal_render($form['field_list_1']) . '</td>';
print '<td>' . drupal_render($form['field_list_2']) . '</td>';
print '<td>' . drupal_render($form['field_list_3']) . '</td>';
print '</tr></table>';

```

Thanks

# Answer
> 0 votes
In this, there is nothing to do with the coding part. When we add a field it adds lot of wrapper div tags around it. And div tags has the by default property to take the next line in the page.

Just write some css for these divs.

```
<style>
    div.class1(display:inline-block;width:150px;float:left)
    div.class2(display:inline-block;width:150px;float:left)
    div.class3(display:inline-block;width:150px;float:left)
</style>

```

Hope it will work for you.

---
Tags: theming, forms
---


# Question
Title: Problem assigning group members membership types other than default
core 7.29 og 7.x-2.x-dev, also tested 7x-2.7

So, I'm going a little crazy trying to get users assigned a membership type other than default in an og.

I can create a new membership type no problem, and add fields. What I can't do for the life of me is find how to assign users to that membership type. The node 1 video made it seem like it shows automatically when adding/editing a user in a group (#overlay=group/node/1/admin/people/add-user), as roles do, but no dice. I realize that video is 2 years old, but it is the most helpful thing I can find on the subject.

Any thoughts/help?

Thanks,

Dan

# Answer
You may want to use the rules module to accomplish that. It's pretty powerful and if you haven't used it before make sure to add it to one if your most favorite modules list. Here's some good advice that'll get you going https://forums.acquia.com/acquia-products-and-services/dev-desktop/auto-assign-og-groups-user-roles
> 0 votes

---
Tags: 7, organic-groups
---


# Question
Title: How to allow users to edit a specific field of content?
I have a taxonomy list connected with a content type. I want to give all authenticated users to access the content edit page but only see and access the taxonomy field section so users can participate in making the site more organized and accurate.

Is there a way to only show 1 field to users and allow them to edit just that one field? If so, how do i show a link on the content page to the edit page? (example: "Click here to edit/add tags" - This link would then go to the /node/2343/edit link)

My idea comes from many video sharing sites where people can add/edit "categories" or "tags" if the user has permission to do so. These sites usually have a little "+" symbol next to the categories which then opens the category check list for that piece of content for editing.

# Answer
You can set permissions for fields who can edit or not Please have a look into this module

Field Permissions

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
> 1 votes

# Answer
Using hook form alter will allow you to do this.

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  // Pick which content type you want to tinker with.
  if ($form_id == 'your_custom_contenttype'){
    global $user;
// only hide fields when editing the node
if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) != 'edit' {

 // Check if the user has the 'authenticated' role.
      if (in_array('authenticated', $user->roles)) {
      // Now it's time to hide all the fields you don't need
      $form['title']['#access'] = FALSE;
      $form['body']['#access'] = FALSE;
      $form['field_name_1']['#access'] = FALSE;
      $form['field_name_2']['#access'] = FALSE;
      $form['field_name_3']['#access'] = FALSE;
      //etc
    }
  }
}
}

```
> 0 votes

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


# Question
Title: How to add relationship in view for custom entity
I have an entity that references `node` and `user` via `nid` and `uid` fields.

I have created an entity around my schema and would like to use it in views. I can create a view based on a new entity that shows fields from the entity.

Now I want to add relationships to `node` and `user` so I could pull fields from them. So I want to show fields from related user and node, not my entity bundles.

What's the right way to do this?

# Answer
> 8 votes
two solutions:

1)using relation ,relation end field,relation UI

2)using `hook_views_data_alter` example from commerce module:

```
function hook_views_data_alter(&$data) {
  // Expose the uid as a relationship to users.
  $data['users']['uc_orders'] = array(
    'title' => t('Orders'),
    'help' => t('Relate a user to the orders they have placed. This relationship will create one record for each order placed by the user.'),
    'relationship' => array(
      'base' => 'uc_orders',
      'base field' => 'uid',
      'relationship field' => 'uid',
      'handler' => 'views_handler_relationship',
      'label' => t('orders'),
    ),
  );
}

```

# Answer
> 10 votes
Entity API supports this out of the box, but you will have to let it know which entity your data represents. If Entity API encounters a field containing numeric data it will by default assign it the type 'integer'. Just change the type to the right entity type and you can define the relations in Views:

```
<?php
  /**
   * Implements hook_entity_property_info_alter().
   */
  function my_entity_entity_property_info_alter(&$info) {
    $info['my_entity']['properties']['nid']['type'] = 'node';
    $info['my_entity']['properties']['uid']['type'] = 'user';
    $info['my_entity']['properties']['tid']['type'] = 'taxonomy_term';
  }
?>

```

---
Tags: entities, views
---


# Question
Title: zoom and centre gmap output based on results (views+gmap+location modules)
I've got several nodes with location information attached. I am using the Gmap output form views to show the results on a map. Drupal is so great sometimes, I'm literally shocked at how little time it took to get that solution up and running!

At the moment the map is using the default centring and zoom no matter what the results are. I'm pretty sure I have just missed an option or setting somewhere, but can someone point me in the right direction to re centre and zoom based on the pins from the results?

I've had a search on here and Google and can't see this question having been asked. Probably because an available option is staring me right in the face!

Thanks

# Answer
I just noticed someone talking about the macro behaviour for autozoom. I added behavior=+autozoom to my \[gmap\] macro in the Gmap views settings and the few tests I have done so far suggest it works
> 12 votes

# Answer
The answer left by author of the post is wrong, he created a bicycle instead of using default function that allows to do it in a simple way.

Right way it is to use `gmap_simple_map` function(gmap.module in D7) and pass arguments into the function.

An example:

```
gmap_simple_map($latitude, $longtitude, $markername, $info, $zoom, $width, $height, $autoshow, $map);

gmap_simple_map('37.275376', '12.87876', '', '', 5, '500px', '200px', false, array());

```

P.S.: To use default saved marker you have to left `$markername` empty, set width and height like in css. Oops, be careful with css styles, dont set `display: none` for gmap block, it can cause the block empty or the grey map.
> 0 votes

---
Tags: views, google-maps, location
---


title: Drupal Services 3 Login and CSRF

text:
# Question
Title: Drupal Services 3 Login and CSRF
I'm working on a Phonegap app (JS) anndn I'm confused how to pass along the CSRF token with my requests. Would I need to call user/login.json first and then store the token? For future requests how do I pull the token?

```
$('#page_dashboard').live('pageshow',function(){
  try {
    // Obtain session token.
    $.ajax({
        url:"http://" + website + "/?q=my_services/user/token.json",
        type:"post",
        dataType:"text",
        error:function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
        },
        success: function (token) {
        // Call system connect with session token.
        $.ajax({
      url:"http://" + website + "/?q=my_services/system/connect.json",
      type: "post",
      dataType: "json",
      beforeSend: function (request) {
        request.setRequestHeader("X-CSRF-Token", token);
      },
      error: function (jqXHR, textStatus, errorThrown) {
        alert(errorThrown);
      },
      success: function (data) {
        var drupal_user = data.user;
        if (drupal_user.uid == 0) { // user is not logged in, show the login button, hide the logout button
            $('#button_login').show();
            $('#button_logout').hide();
            $('#button_create').hide();
        }
        else { // user is logged in, hide the login button, show the logout button
            document.getElementById("welcome").innerHTML = "<center>Welcome " + drupal_user.name + "</center>";
            $('#button_login').hide();
            $('#button_logout').show();
            $('#button_create').show();
        }
      }
    });
        }
    });
  }
 catch (error) { alert("page_dashboard - " + error); }
});

```

# Answer
> 8 votes
I've been surprised by the lack of documentation and general information about Drupal RESTful services.

The best resources out there are from Tyler Frankenstein, the creator and maintainer of Drupalgap. Much thanks goes to Tyler as I started with his article here. Unfortunately, the documentation is rather old and no longer works with the current version of Services.

I highly recommend Drupalgap to any newbies that are looking to put a simple site on an Android/IOS app. It's a great tool that is well-maintained and constantly growing.

That being said....Drupalgap is great but ultimately I want the ability to expand beyond a framework requirement (i.e. Drupal). Understanding how JavaScript interacts with RESTful services is key to that point. After much effort I finally scraped together data from different sources and came up with a solution. Keep in mind that this worked for me. I'm sure there are better ways to do this but I only know this one.

**Creating a PhoneGap app that Connects with Drupal 7 & Services 3.5+**

My Environment:

```
Ubuntu 14.04
Cordova 3.5
Android SDK Manager 23
Apache 2.4.7
Drupal 7.28
Services 7.x-3.7
JQuery 1.11.1
jQuery Mobile 1.4.3

```

**1) Setup your environment**

Install Apache, Drupal, Phonegap, etc. I installed drupal to a sub-directory (localhost/drupal). Remember to setup your Services endpoint and enable resources for it. I use cordova to build the scaffolding for my Phonegap app:

```
 cordova create MyApp
 cd MyApp
 cordova platform add android
 cordova build

```

I have a symbolic link from my phonegap www folder to my apache root so I can test my mobile app on a browser before deploying.

**2) Enable CORS for testing**

Testing locally is a big requirement as the JavaScript console gives a developer so much more insight into what is actually happening with the code. Enabling CoRS was a requirement to get testing working. Getting CORS to function proper was a pain. Keep in mind that I'm testing from a local server (localhost) and CORS is configured to match, update your configuration accordingly:

```
1. Enable mod-headers,mod-setenvif
2. Add:
    Header add Access-Control-Allow-Origin "*"
   to the Apache Directory Directives (example.conf)
3. Add:
    SetEnvIf Origin "^(https?://localhost|https://[a-z]+\.my\.base\.domain)$" ORIGIN_SUB_DOMAIN=$1
    Header set Access-Control-Allow-Origin: "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
    Header set Access-Control-Allow-Methods "GET, PUT, POST, OPTIONS"
    Header set Access-Control-Allow-Credentials "true"
    Header set Access-Control-Allow-Headers "Authorization, Origin, Content-Type, X-CSRF-Token"
   to the .htaccess file at the root of your Drupal installation
4. Reload/restart apache

```

**3) Create jQuery Mobile app** I followed Tyler's initial instructions and used jQuery Mobile to develop my application. The JavaScript was taken from a post in the Services issue queue here. This is a VERY basic app - just takes a login and outputs your username...but once you understand how the token is passed you can extend this to do ANY request.

Here's my index.html file:

```
<!DOCTYPE html>
<html>
    <head>
    <title>Hello World</title>
        <script src="js/jquery.min.js"></script>
        <link rel="stylesheet" href="css/jquery.mobile.css" />
        <script src="js/jquery.mobile.js"></script>
    </head>
    <body>
        <div data-role="page" id="page_dashboard"><!-- page -->
            <script type="text/javascript" charset="utf-8" src="script.js"></script>
            <div data-role="header"><h1>Home</h1></div>
            <div data-role="content"><!-- content -->
                <h2 align="center">Shopping List App</h2>
                <p id="welcome"></p>
            </div>
            <div>
                <label for="page_login_username">My Name</label>
                <input type="text" id="page_login_username" />
            </div>
            <div>
                <label for="page_login_name">Username</label>
                <input type="text" id="page_login_name" />
            </div>
            <div>
                <label for="page_login_pass">Password</label>
                <input type="password" id="page_login_pass" />
            </div>
            <input type="text" id="page_login_token" />
            <input type="hidden" id="page_login_session_ID" />
            <input type="hidden" id="page_login_session_name" />
            <fieldset>
                <div><button type="button" data-theme="b" id="page_login_submit">Login</button></div>
            </fieldset>
  </div>
        </div> <!-- end page -->
    </body>
</html>

```

Here's my script.js file:

```
$(document).ready(function(){

function setToken(){

// Get a Token from the site
$.ajax({
url: "http://localhost/drupal/my_services/user/token",
type: 'POST',
dataType: 'json',
//crossDomain: true,
error: function(XMLHttpRequest, textStatus, errorThrown) {
// Error getting Token
console.log('Get Token Failed');
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
// Set the Token Value in a textfield
$("#page_login_token").val( data.token );
}
}); // End Ajax
}

function doLogin( tokenid ){
var tokenValue = $(tokenid).val();
$.ajax({
url: "http://localhost/drupal/my_services/user/login",
type: 'POST',
dataType: 'json',
crossDomain: true,
data: {"username":$("#page_login_name").val(),"password":$("#page_login_pass").val()},

beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", tokenValue);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function( userdata ){
$("#page_login_session_ID").val( userdata.sessid );
$("#page_login_session_name").val( userdata.session_name );
$("#page_login_username").val("Welkom SUPER" + userdata.user.name +"You are my Hero!");

// Get and Set a new Token after Login!!!
setToken();

}
});
}

function doLogout( tokenid, session_id, session_name ){

$.ajax({
url: "http://localhost/drupal/my_services/user/logout",
type: 'POST',
dataType: 'json',
crossDomain: true,
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", jQuery("#page_login_token").val());
},

error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
$("#page_login_session_ID").val("");
$("#page_login_session_name").val("");
$("#page_login_username").html("");
$("#page_login_token").val("");
}

});

}

function testConnect( tokenid ){
var tokenValue = $(tokenid).val();
var gorge = tokenValue.substring(14);
$.ajax({
url: "http://localhost/drupal/my_services/system/connect",
type: 'POST',
dataType: 'json',
crossDomain: true,
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", tokenValue);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//alert( 'Error with Connect.json' );
alert( gorge );
console.log( 'Error with Connect.json' );
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function( data ){
console.log( data );
alert( data );
}
});
}

$(document).on("click", "#page_login_submit", function () {
    //alert("Goodbye!");
    setToken();
    //testConnect( "#page_login_token" );
    doLogin( "#page_login_token" );
});

});// End document ready

```

**4) Test with Poster and Chrome**

Firefox was a bit of a disappointment in the testing arena; except for Poster. This allows you to test Drupal Services directly by using Get/Post. Very handy for testing. Chrome developer tools came in very handy - they were the first to tell me what was actually wrong with my CORS configuration.

**I hope this helps you!** Feel free to add any comments/advice. I can update this in time and make it better.

---
Tags: javascript, services
---


# Question
Title: How to debug missing default value of managed file?
I have a form with images. It also contains title and alt for 3 languages, so when I select them in one query, I get the same managed file fid 3 times. But that's not the problem.

Relevant part of code is:

```
kpr($image_has_language);
$first_language = reset($image_has_language);
$form['image'][$i] = array (
   '#type' => 'fieldset',
   '#collapsible' => FALSE,
   'ImageFile' => array(
     '#type' => 'managed_file',
     '#default_value' => (integer)$first_language['ImageFile'],
     '#title' => t("Image"),
     '#title_display' => 'invisible',
     // '#description' => t('Allowed extensions: gif png jpg jpeg.'),
     '#upload_validators' => array(
       'file_validate_extensions' => array('gif png jpg jpeg'),
       'file_validate_size' => array(variable_get('something_image_size', 5 * 1024 * 1024)),
     ),
     '#upload_location' => 'public://something/image',
     '#theme' => 'preview_upload',
   ),
   'id_image' => array(
     '#type' => 'value',
     '#value' => $clone?'new':$first_language['idImage'],
   )
 );
 kpr($form['image'][$i]);

```

Below results of that `kpr`s:

As you can see, all is perfectly well. File is on disk, file preview work, in database it is marked as permanent and as used.

When I call `var_dump` on `$form_state['values']['image'][0]` in validation function, without changing file on the form, I get:

```
  array(3) {
    ["ImageFile"]=>
    int(0)
    ["id_image"]=>
    string(3) "599"
  }

```

Values in `$_POST` are OK:

```
  ["image"]=>
  array(4) {
    [0]=>
    array(2) {
      ["ImageFile"]=>
      array(1) {
        ["fid"]=>
        string(4) "3696"
      }

```

**If I change file**, it works as expected:

```
  array(3) {
    ["ImageFile"]=>
    string(4) "3698"
    ["id_image"]=>
    string(3) "599"
  }

```

and in `$_POST`:

```
  ["image"]=>
  array(4) {
    [0]=>
    array(2) {
      ["ImageFile"]=>
      array(1) {
        ["fid"]=>
        string(4) "3698"
      }

```

How can I identify where my value gets removed? I also have another image on that form, single one (so without `foreach`), and it works OK.

# Answer
First of all can you try to remove the fieldset to a different $form\[\] array key? Is it really necessary to make it nested like this?

I think if you want to know if the file is added or removed then you can check in the following way.

```
$total_image_count = $form_state['storage']['image_elements']; // The number of image uploaded elements; just as example.
for($i = 0; $i < $total_image_count; $i++) {
  if ($form_state['values']['image'][$i] != 0) {
    // File is not deleted.
  } elseif ($form_state['values']['image'][$i] == 0) {
    //File is deleted.
  }
}

```

However, check with this and let me know.
> 1 votes

# Answer
There is no need to debug anything. It seems it was just an effect of Regression: Files or images attached to certain core and non-core entities are lost when the entity is edited and saved

Solution is to downgrade, or wait.
> 1 votes

---
Tags: forms, files
---


title: Calendar Pop Up - Extend year range

text:
# Question
Title: Calendar Pop Up - Extend year range
A little bit of introduction: I have a specific content type with the name "Database" where i can add content and with the views module and Search API, the user is able to search on my site for that content.

When I was creating the fields for the content type i noticed there were no fields for "date". So I installed Date module that allows me to have a **Popup Calendar**. On "MORE SETTINGS AND VALUES" i managed to extend the year range for 10 years. So, when i am adding content i'm able to choose from 2004 to 2022. So far so good!

In the view I created, i added some filters to make it easy for the users to search in the database. One of them is "Search by date" and I was able to display the same popup Calendar. **My problem is**: the year range is not the same. It is only 2011 - 2017 and i have no idea how to change that. Since is the same from the previous configuration it should work...

Sorry for the confusing explanation, i don't know how else to put this.

Hope you guys can help me! Thank you!

# Answer
The "Search by Date" Views field should be configuration (clickable) in the Views Administration and in its settings allow you to select the Year range, or the granularity of the date fields and their format.
> 0 votes

# Answer
Problem solved!

I don't know if it is the right way to do it.

I changed line 329 of the data\_popup.module file and replaced the "year\_range" to this: $year\_range = '-10:+10';

At least is working!

But, if you have any other suggestions please feel free to give them.

Thank you :)
> 0 votes

---
Tags: views, search, datetime
---


# Question
Title: How to ignore specific Drupal release in update notifications?
I'm using Drupal 7.28 and getting this message:

> There is a security update available for your version of Drupal. To ensure the security of your server, you should update immediately! See the available updates page for more information and to install your missing updates.

Sadly, there is a critical bug in 7.29 that makes this particular release totally not workable for me. No way I'm installing it, it's that simple. I'll either apply some of 7.29 patches manually, or wait for 7.30. Thus, **I don't want to be bothered with release I know I will not install**. How can I make my Drupal ignore it? **I do want to be notified when 7.30 is ready**, so simply turning off all messages about updates is not an answer I'm looking for.

# Answer
Note: this is definitely **not recommended**. Hiding security updates is bad for all the obvious reasons (it's clear you know that, but for the sake of others who see this...).

As a technical exercise, I can't see why something like this wouldn't work (un-tested):

```
function MYMODULE_update_projects_alter(&$projects) {
  $projects['system']['info']['version'] = '7.29';
}

```

That should basically trick Drupal into thinking core is already at 7.29, so you shouldn't get any warnings. Plus you should also receive update notices for 7.30.
> 2 votes

---
Tags: 7, updating
---


# Question
Title: What is the Views 3 equivalent of the MySQL Limit 1 in order to return just the latest record
I want to display data from the latest activity record for each contact in a report created using views 3 / Drupal 7

In MySQL I'd use sorts and limit to give me the result I want (the following is not the full query, which of course would have joins)...

```
SELECT column_name FROM table_name
ORDER BY column_name DESC
LIMIT 1;

```

What is the equivalent in Views 3? I know how to sort, but how do I limit?

I don't think that limiting the results on a page is the answer - I'm quite happy with a table with 200 rows, it is just that I want only one row for each contact displaying the data from just the latest activity record associated with that contact.

Any clues anyone?

# Answer
> 0 votes
To get the query in your question you would use a pager:

* Select 'Use pager' in the admin UI
* Select 'Display a specified number of items'
* Click 'Apply'
* Enter '1' for "Items per page" on the settings screen.
* Save

I suspect you might be talking more about grouping, though, and that the SQL you've got isn't representative of the query you actually want to run.

If that's the case, you should be able to accomplish what you need buy turning on aggregation, and then setting appropriate values for each field's grouping options.

---
Tags: views
---


# Question
Title: How to set same filter value to be searched to the different filters on the same page?
I am using 3 exposed filter on same page for video, audio and album search, what I want is when I enter filter criteria for one filter all filters should take same filter criteria. Is there anyone who is having an idea to do this?

# Answer
You should enter the same identifier for all views, if you want to use one exposed value for all views in current page.
> 0 votes

---
Tags: views
---


title: List main menu links

text:
# Question
Title: List main menu links
I need a list of main menu item links to display on a page (sort of a sitemap). How would I accomplish this in Drupal 7?

# Answer
> 0 votes
```
   $menu = menu_navigation_links('main-menu');
   print theme('links__menu_main_page', array('links' => $menu));

```

Write This code where you want to display menu.

Or you can assign menu block to a region and can call that region like this

```
print render($page['menu_block']);

```

# Answer
> 1 votes
Go to `admin/structure/block` and configure the Main Menu block

You want to go further you can Install Menu block module

> So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
>
> Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!

---
Tags: navigation
---


# Question
Title: How to intetrupt a form submission in drupal
I have made a custom module where I create one page. In that page I load the existing form for creating a new content and also add a password field. In my loaded form I have an email field. I want before submitting the form to check if there exists a user with the username the value found in the email field and the password offered by the password field. Here I have 3 scenarios:

1. if the user does not exist I take the email and password and create an account then create the content
2. if the user exists and the password is correct , I create the content
3. if the user exists but the password is incorrect I stop the form submission

My problem is I don't know how to stop the form submission ( I am refering to scenario number 3). Any suggestions are most aprerciated

Here are the callback for the page function:

```
function add_new_article_simple_page() {
  module_load_include('inc', 'node', 'node.pages');
  $node_form = new stdClass;
  $node_form->type = 'announcement';
  $node_form->language = LANGUAGE_NONE;
  $form = drupal_get_form('announcement_node_form', $node_form);
  return $form;
}

```

the alter function to insert the password field :

```
function add_new_article_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='announcement_node_form')
  {
    $form['#after_build'][] = 'add_new_article_after_build';
    $form['account_password'] = array(
        '#title' => 'Parola',
        '#type' => 'password',
        '#required' => TRUE,
    );
    $form['#submit'][] = 'add_new_article_form_submit';

    return $form;
  }
}

```

and the form submit function

```
function add_new_article_form_submit($form, &$form_state){
  $email=$form_state['values']['field_email']['und'][0]['value'];
  $password=$form_state['values']['account_password'];
  //check if the email even exists
  if(!db_query("SELECT COUNT(*) FROM {users} WHERE name = '".$email."';")->fetchField())
  //create the new account
  {
    $edit = array(
        'name' => $email,
        'pass' => $password,
        'mail' => $email,
        'init' => $email,
        'roles' => array('4' => 'standard user'),
        'status' => 0,
        'access' => REQUEST_TIME,
    );
    $loc_var=user_save(drupal_anonymous_user(), $edit);
    $GLOBALS['new_user']=$loc_var->uid;
  }
  else
  {
    //check if username + password are valid combination
    if($uid = user_authenticate($email,$password))
        //log in user after account creation
    else
        //this is where I want to interrupt the submission of the form
        form_set_error('account_password', 'Parola nu este buna pentru acest email.');
  }
}

```

When i test the 3rd scenario: The content is created , the page jumps to that content page and that is where the error message appears

I have followed a suggestion to try hook\_form\_alter, so I wrote a simple validation function which should always give an error. The problem is that the content is still submited and saved. It doesn't seem to even call hook\_form\_validate .. Here is the function :

```
function add_new_article_form_validate($form, &$form_state)
{
    $email=$form_state['values']['field_email']['und'][0]['value'];
    $password=$form_state['values']['account_password'];
    form_set_error('account_password',t('The form is being validated.'.$email.' and '.$password));
}

```

Thank you, Cristi

# Answer
Try adding the validate function as you have added the submit function:

```
function add_new_article_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='announcement_node_form')
  {
    $form['#after_build'][] = 'add_new_article_after_build';
    $form['account_password'] = array(
        '#title' => 'Parola',
        '#type' => 'password',
        '#required' => TRUE,
    );

    $form["#validate"][] = 'add_new_article_form_validate';
    $form['#submit'][] = 'add_new_article_form_submit';

    return $form;
  }
}

```
> 3 votes

# Answer
Cristi,

I am not properly getting the point why you used the HOOK\_form\_alter to alter the custom form `add_new_article_simple_page`. However, I think the simple process of using the Form API is as follows,

1. Create a form as `my_custom_form()`.
2. Create validation function as `my_custom_form_validate($form, &$form_state)`.
3. Create a submit function `my_custom_form_submit($form, &$form_state)`.

In your validation function you should only check for the 3rd condition of yours and then set `form_set_error('field_name', t("Password doesn't match"));`

In your submit function you just apply the other business logic for #1 & #2 to create content or users.
> 0 votes

# Answer
You could use hook\_validate, or, if you want to validate some data before you actually click submit, you could use the Drupal form api's #ajax.

```
/**
 * Implementation of hook_form().
 */
function poll_form(&$node, $form_state) {
  $form['choice_wrapper']['poll_more'] = array(
    '#type' => 'submit',
    '#value' => t('More choices'),
    '#description' => t("If the amount of boxes above isn't enough, click here to add more choices."),
    '#weight' => 1,
    '#submit' => array('poll_more_choices_submit'), // If no javascript action.
    '#ajax' => array(
      'callback' => 'poll_choice_js',
      'wrapper' => 'poll-choices',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );
}

/**
 * Menu callback for AJAX additions. Render the new poll choices.
 */
function poll_choice_js($form, $form_state) {
  return $form['choice_wrapper']['choice'];
}

```

Here is the documentation for #ajax.
> 0 votes

---
Tags: 7, forms, hooks, users
---


# Question
Title: How to set relationship between custom tables in views?
I'm creating a module that retrieves Youtube data (video and playlists) from Youtube feeds

I've created cutom tables :

* youtube\_video (with fields : vid, vtitle, description...)
* youtube\_playlist (with fields : pid, ptitle, description...)
* youtube\_video\_playlist (with fields: vid, pid, weight)

**I'd like to have a view that displays all videos from a playlist (filtered with a contextual filter)**. I'm using Views 7.x-3.8 and Drupal 7. It seems that what i need here requires quite some custom coding, but i'm fairly new to Views programming...

How can i set relationships so that i can access to all the fields i need ( youtube\_video.vtitle, youtube\_playlist.ptitle, youtube\_playlist.vid) to construct my query ?

I've looked at the example in the view api with hook\_views\_data() to add a custom table (youtube\_playlist) in Views to put in relation with (youtube\_video), but here, i'm using a third table (the relation table youtube\_video\_playlist).

So in "sql terms" how can i have :

```
SELECT v.vtitle, v.vid
FROM youtube_video AS v
JOIN youtube_video_playlist AS vp
    ON vp.vid = v.vid
JOIN youtube_playlist AS p
    ON p.pid = vp.pid
WHERE p.pid = contextual_value_of_playlist_pid

```

So in fact, since i'm learning, in this particular case :

* Using all the hooks, classes in the Views API, how can i achieve my goal (hooks / classes to use) ?
* is it useful (= optimized) to go all the way in using the views api or could i set this custom request above directly in the code ?

I've also created entities from these 2 main tables (youtube\_video and youtube\_playlist), in order to display them "easily" in views. But is this (creating entities from tables) mandatory to my purpose (displaying videos from some playlist) ?

---

@Andy : Thank you for this specific help : I didn't find it in the "regular" documentation, but in this advanced help, there's an explanation for the indirect joins. That said, i didn't manage to display my fields :

I tried first the example in the documentation and it works as expected,i've got a group showing in the different section of views (add field, add filter, add sort...), but when i try to adapt the code in the advanced help, with the left table, nothing is displayed :

```
function mymodule_map_views_data() {
  //The group name
  $data['youtube_playlist']['table']['group'] = t('Youtube playlist');
  $data['youtube_video']['table']['group'] = t('Youtube video');
  //The base table
  $data['youtube_video']['table']['base'] = array(
    'field' => 'vid',
    'title' => t('youtube video'),
    'help' => t('youtube video should be related to youtube playlist.'),
    'weight' => -10,
    'defaults' => array(
      'field' => 'vtitle',
    ),
  );
  //The join
  $data['youtube_playlist']['table']['join']['youtube_video'] = array(
    'left_table' => 'youtube_video_playlist',
    'left_field' => 'pid',
    'field' => 'pid',
  );
  // Allow this field to be used as a contextual filter.
  $data['youtube_playlist']['pid'] = array(
    'title' => t('playlist id'),
    'help' => t('playlist id'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'argument' => array(
      'handler' => 'views_handler_argument',
      'name field' => 'title',
    ),
  );
  $data['youtube_video_playlist']['table']['join']['youtube_video'] = array(
    'left_field' => 'vid',
    'field' => 'vid',
  );
  //the fields description
  $data['youtube_playlist']['ptitle'] = array(
    'title' => t('youtube playlist title'),
    'help' => t('youtube playlist title.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  //the fields description
  $data['youtube_playlist']['description'] = array(
    'title' => t('youtube playlist description'),
    'help' => t('youtube playlist description.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  $data['youtube_video']['vtitle'] = array(
    'title' => t('youtube video title'),
    'help' => t('youtube video title.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  $data['youtube_video']['vhash'] = array(
    'title' => t('youtube video vhash'),
    'help' => t('youtube video vhash.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  return $data;
}

```

I think i'm confused with the left table / base table and which one should be fully described.

I also add the scheme, just in case :

```
function MYMODULE_schema() {
  $schema['youtube_playlist'] = array(
    'description' => t('List of youtube playlists from a channel'),
    'fields' => array(
      'pid' => array(
        'description' => t('Unique key for playlist'),
        'type' => 'serial',
        'size' => 'medium',
        'unsigned' => true,
        'not null' => true,
      ),
      'ptitle' => array(
        'description' => t('video title'),
        'type' => 'varchar',
        'length' => '255',
        'not null' => true,
      ),
      ...
    ),
    'primary key' => array('pid'),
  );
  $schema['youtube_video_playlist'] = array(
    'description' => t('Video and playlist'),
    'fields' => array(
      'vid' => array(
        'description' => t('Primary Key: Identifier for a Youtube video'),
        'type' => 'int',
        'size' => 'medium',
        'unsigned' => true,
        'not null' => true,
      ),
      'pid' => array(
        'description' => t('Unique key for playlist'),
        'type' => 'int',
        'size' => 'medium',
        'unsigned' => true,
        'not null' => true,
      ),
      'position' => array(
        'description' => t('Position of the video in the playlist'),
        'type' => 'int',
        'size' => 'small',
        'unsigned' => true,
        'not null' => true,
      ),
    ),
    'primary key' => array('vid', 'pid'),
  );
  $schema['youtube_video'] = array(
    'description' => t('Informations on video from Youtube'),
    'fields' => array(
      'vid' => array(
        'description' => t('Unique key for video'),
        'type' => 'serial',
        'size' => 'medium',
        'unsigned' => true,
        'not null' => true,
      ),
      'vtitle' => array(
        'description' => t('video title'),
        'type' => 'varchar',
        'length' => '255',
        'not null' => true,
      ),
    ),
    ...
    'placeid' => array(
        'description' => t('id for the place'),
        'type' => 'int',
        'size' => 'medium',
        'unsigned' => true,
    ),
    'primary key' => array('vid'),
    'foreign keys' => array(
      'placeid' => array(
        'table' => 'youtube_places',
        'columns' => array('placeid' => 'placeid'),
      ),
    ),
  );
  return $schema;
}

```

# Answer
The best place to find documentation for these things is actually the code in the views module.

If you look at `node_views_data` function you can see an example of creating a relationship from a node's author (uid) to the user table.

```
function node_views_data() {
  ..
  // uid field
  $data['node']['uid'] = array(
    'title' => t('Author uid'),
    'help' => t('The user authoring the content. If you need more fields than the uid add the content: author relationship'),
    'relationship' => array(
      'title' => t('Author'),
      'help' => t('Relate content to the user who created it.'),
      'handler' => 'views_handler_relationship',
      'base' => 'users',
      'field' => 'uid',
      'label' => t('author'),
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_user_name',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_numeric',
    ),
    'field' => array(
      'handler' => 'views_handler_field_user',
    ),
  );
  ..
}

```

The interesting part here is the `'relationship'` part. Basically you define the table (base) that you are joining and the column (field) you are joining on. In your case where you are joining to another FK, you can use the built in handler from views.

So in code you would need to do something like this:

```
$data['youtube_video']['vid'] = array(
  'relationship' => array(
    'handler' => 'views_handler_relationship',
    'base' => 'youtube_video_playlist',
    'field' => 'vid',
    ..
  ),
  ...
);

$data['youtube_video_playlist']['pid'] = array(
  'relationship' => array(
    'handler' => 'views_handler_relationship',
    'base' => 'youtube_playlist',
    'field' => 'pid',
    ..
  ),
  ...
);

```

In the Views UI you would create two relationships.
> 3 votes

# Answer
If you wanted to use a join rather than a relationship you need something like this:

```
$data['youtube_playlist']['table']['join']['youtube_video'] = array(
  'left_table' => 'youtube_video_playlist',
  'left_field' => 'pid',
  'field' => 'pid',
);

$data['youtube_playlist']['pid'] = array(
  ...
  // Allow this field to be used as a contextual filter.
  'argument' => array(
    'handler' => 'views_handler_argument',
    'name field' => 'ptitle',
  ),
);

$data['youtube_video_playlist']['table']['join']['youtube_video'] = array(
  'left_field' => 'vid',
  'field' => 'vid',
);

```

Relationships are more flexible, this approach is appropriate if the tables are always joined in this way.
> 2 votes

---
Tags: views
---


# Question
Title: How to get node ID from drupal 7 when i know title (title shouldnt be duplicated) Drupal
My module is creating node with title "123title", after this i want to create next node, with entity reference field whose have to contain id of node with title "123tile" whose i created before. –

# Answer
As suggested by Mołot you can do this with EntityFieldQuery.

```
// Initialize EntityFieldQuery.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');

$query->propertyCondition('title', "My title", "=");

// Execute query and collect results
$result = $query->execute();

$nids = array();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
}

```

In the example $nids will be an array with all node ids that have the title "My title". Entity field query really helps you when the query gets more complicated. You don't have to do joins for example yourself but can instead do something like `$query->fieldCondition('field_news_types', 'value', 'spotlight', '=')` which using db\_select would require joins on tables.
> 3 votes

# Answer
```
$title='put title here';
$node_id = db_select('node', 'n')
  ->fields('n',array('nid'))
  ->condition('title',$title,'=')
  ->execute()
  ->fetchField();

```

Now $node\_id contains node id that you want.
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: How to disable a module dependents module? Not the module but the feature
Hello I have the module **BEF better exposed filters** installed and enabled and together with it is the *BEF Test Content* module (**feature of BEF better exposed filters moduke**).

I just enable the features so **BEF Test Content** for making tests and now when I want to disable it shows on the screen like red and when i try to disable and save configuration... i can not...

also i tried through drush by using:

```
drush dis better_exposed_filters

```

**but logically it says that it will disable the BEF Test Content module extension but also it will disable together with the BEF Better exposed filters too...**

is there a way to disable only the dependent module? how about with drush?

thanks!

# Answer
If you mean

> Can I disable/uninstall the BEF module without first disabling/uninstalling the BEF Test Content module (or any other modules that depend on it)

Then no, that's not possible.

"Dependency" means that one module cannot function without the other. In this case, the BEF Test Content module will be unable to function unless the BEF module is also installed and enabled.

Drupal understands this constraint, and makes sure the you can't break your site by removing functionality from one module that is required by another.

If you mean

> Can I disable/uninstall the BEF Test Content module without disabling/uninstalling the BEF module

Then yes, you can either disable/uninstall it through the UI as normal, or use Drush. BEF doesn't have a dependency on BEF Test Content, so Drupal won't stop you from removing it.

The only caveat to that is if there are *other* constraints introduced by the BEF Test Content module. For example, if it provides a field type which is in use, the module cannot be disabled until the field is detached from all entities. But the admin UI will tell you explicitly if that's the case
> 1 votes

---
Tags: 7, drush, views
---


# Question
Title: Access callback for user/%user/edit menu item not working
I have two roles, client & student. Students can edit their profiles, clients cannot. I thought the easiest way to solve this would be to add a permission as per below:

```
function si_permission() {
  return array(
    'edit account' => array(
    'title' => t('Edit account'),
    'description' => t('Allow users to edit their account')
  )
}

```

I then altered the menu item and changed the access callback to my new permission:

```
function si_dashboard_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = user_access('edit account');
}

```

I then set the permission appropriately in permissions settings, but it does not work. It always appears to be false, so the menu item access is always disabled. I have even debugged 'user\_access('edit account')' whilst logged in as the appropriate user and it returns TRUE, so I know the permission is working.

All caches cleared, menus rebuilt using developer tools. Any ideas?

# Answer
Ok, it appears I have to set the access as per following:

```
function si_dashboard_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'user_access';
  $items['user/%user/edit']['access arguments'] = array('edit account');
}

```
> 1 votes

---
Tags: routes, users
---


# Question
Title: How to use hook_menu to add an item to the secondary links?
Adding an item to the primary links is easy:

```
function hook_menu()
{
    $items = array();
    $items['bla'] = array(
        'title' => 'bla',
        'page callback' => 'mymod_blah',
        'expanded' => TRUE,
    );
    return $items;
}

```

This adds it to the primary links. How do I add it to the secondary links?

# Answer
You can use `menu_name` to specify the menu of the items you are adding:

See the hook\_menu docs for more info.

For example, to add the item to the main menu:

```
function hook_menu()
{
    $items = array();
    $items['bla'] = array(
        'title' => 'bla',
        'page callback' => 'mymod_blah',
        'expanded' => TRUE,
        'menu_name' => 'main-menu',
    );
    return $items;
}

```
> 1 votes

---
Tags: routes, hooks
---


title: Content type provide to menu link

text:
# Question
Title: Content type provide to menu link
I'm using Drupal 7 and different content types.

I've got 'News' content type and want this be like a blog. So, provide News content type to menu link.

Click Content Type and after menu settings, selected parent item main menu but not seen on frontpage.

How can i provide News content type to menu link?

# Answer
> 1 votes
Have a look on the Menu Position module. This allows you to map a specific content type to a menu item without generating "hard linked" menu entries.

# Answer
> 1 votes
What about using views for this? So you generate a new view with content type news, set to only show published, order by news date field (From your news content type) and this will do you a nice list, with paging etc available from the view config.

EDIT - I notice this is a little late now, but might help others who want the question answered.

---
Tags: 7, routes, nodes
---


# Question
Title: Printer - PDF format: How can I change the header info and add page count on the footer?
I like this Printer module on my Drupal 7 site. But, when it generates PDF, it contained breadcrumb and no page-count on the footer. Is there a way to add name of "Content type" and node "Title", instead of breadcrumb? I also would like to have the page-count number on the footer on every page. Is there a file that I can modify?

PS: I'm using mPDF third-party tool

# Answer
The Print module uses a separate template for the print, email, and PDF versions of a page. You would need to implement a `hook_preprocess_print()` to set up some addtional variables, and then duplicate print.tpl.php into your theme and use your new variables (and/or change the markup in the template). The default template file is rather well documented, and explains what is possible.
> 3 votes

# Answer
You can write CSS to hide the breadcrumb and other unwanted content to print.

```
@media print
{
.breadcrumb{display:none;}
}

```

Put other unwanted content class in @media print.
> 1 votes

---
Tags: theming, files
---


title: Solr search, number of results

text:
# Question
Title: Solr search, number of results
I'm trying to find a way to display the number of resuts in a solr search. I need to display it in search-results template.

Thanks for any hint

# Answer
The link given is a nice one to deal with the default search result number count. In Apache Solr you can use the following code to get the total number of documents returned in the search result.

```
if (apachesolr_has_searched() && ($response = apachesolr_static_response_cache())) {
  $returned_doc_num = $response->response->numFound;
}

```
> 0 votes

---
Tags: theming, search
---


# Question
Title: Workbench: How can I reorder display of Workbench Tabs?
I'm running Workbench, workbench access, workbench moderation and workbench media on Drupal 7. I added a new state "Needs publish" for "Waiting to be published", which is under "**Configuration \> Workbench \> Workbench Moderation \> States tab**". Also, I cloned the "Needs review page" view for "Needs publish page"(just changing the filter "Workbench Moderation: State" to "Needs Pulish"). However, the new tab I have for "Needs publish" is in between "My Drafts" and "Needs Review".

Question: How can I move the new tab "Needs Publish" after "Needs review"?

--- Added screenshot on July 23, 2014 at 1:49pm

# Answer
> 0 votes
under the view `Table Display` Settings. You should be able to assign placement of the columns there.

See the `Format` \> `Table` \> `Settings` at the left:

Then assign fields to certain columns here. The ordering of these columns by default is the ordering of the `Fields` defined in the View.

---
Tags: workbench
---


# Question
Title: When Num of Values is "Unlimited", create begins with two instances
I've created a custom module for a field in drupal that has two fields, Position and Affiliation. I add the field to my test content, and set Num of Values to "Unlimited".

**The Problem:**

When I go to create a new instance of `test` content, instead of seeing one instance of my field and the "Add another item" button, it starts with two (see image) and the "Add another item" button.

If I set the Num of Values to 1, I only get one. If I click "add another item", it only adds one. I'm looking at my code, and for the life of me cannot figure out where the problem can be. I assume it's something in the widgit.

```
function pos_aff_select_field_widget_info() {
    return array(
        'pos_aff_select_widget_default' => array(
            'label' => t('Affiliation and Position default widget'),
            'description' => t('Drop Down Menu for Affiliation and Position'),
            'field types' => array('pos_aff_select'),
            'behaviors' => array(
                'multiple values' => FIELD_BEHAVIOR_DEFAULT,
                'default value' => FIELD_BEHAVIOR_DEFAULT,
            ),
        ),
    );
}

function pos_aff_select_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element){
    $base = $element;

    if($instance['widget']['type']  == 'pos_aff_select_widget_default') {
        $element['position'] = array(
            '#type' => 'select',
            '#title' => t('Position'),
            '#default_value' => isset($items[$delta]['position']) ? $items[$delta]['position'] : NULL,
            '#options' => pos_aff_select_query("ibs_position"),
        );

        $element['affiliation'] = array(
            '#type' => 'select',
            '#title' => t('Affiliation'),
            '#default_value' => isset($items[$delta]['affiliation']) ? $items[$delta]['affiliation'] : NULL,
            '#options' => pos_aff_select_query("ibs_affiliation"),
        );
    }
    return $element;
}

```

Does anyone have any clue what is going wrong?

# Answer
I'll post my work around just in case anyone else has the same problem. But after fiddling around with it, I found out that if you have default values set, then it will set the first instance of the field to the default values and the second instance of the field to blank (I tested this by switching my `select` to `textfield` and if defaults were blank then I got only one instance of the field, if I put any text into the default, then I got two). Because my fields uses a `select` form then I, by default, had set my field values to something, thus, I had default values, thus, it showed the behavior I mentioned.

I set `'default value' => FIELD_BEHAVIOR_NONE,` in the `hook_field_widget_info` and the field only produced one instance. Ridiculous.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to redirect to a certain page after logout from any link
Does anyone know how to redirect to a certain page like **mysite.com/message-board-page/23** from any link, for example from **mysite.com/node/add/message-board/23** or **mysite.com/message-board-page/23**

Currently I am doing like this, but it just works for any link that has $arg = 3

$arg = arg(3); .... href="/user/logout?destination=message-board-page/'.$arg.'"

Any help would be appreciated!

# Answer
If i am correct you want the user to to redirect to a certain page say test-page-3 from any page or url after logout. Enable the Trigger Module. In configuration go to Actions, -- there in Create an advanced action Select Redirect to URL and press Create. Then label it as you want it and in URL add the page URL you want the user to redirect. Then go to Structures and Select Triggers, here select USER Tab in Top Right corner. Then in Trigger: After a user has logged out , Select the action the action u have created.

Hope that helps and tick if u find it useful.
> 1 votes

# Answer
```
<?php

  case 'user_block':
    global $user;
    $arg = arg();
    $ca = count($arg);

    $dest = '';
    if (($ca>=2) && ($arg[$ca-2] == 'message-board-page') && is_numeric($arg[$ca-1])) {
      // We have page, that URL end like next: message-board-page/XXX
      $dest = '?destination=message-board-page/' . $arg[$ca-1];
    }

    if (!$user->uid) { // Checking that user is guest like this more simpler.
      $block['content'] = '
        <div class="block-content">
          <div id="login">
            <a href="/user/login"> Login </a>
          </div>
        </div>';
    }
    else {
      $block['content'] = '
        <div class="block-content">
          <div id="logout">
            <a href="/user/logout' . $dest . '"> Logout </a>
          </div>
        </div>';
    }
    break;

```
> 0 votes

---
Tags: redirection
---


# Question
Title: Can't correctly reference bundle in EntityFieldQuery, field_get_items
I'm using EntityFieldQuery in an attempt to query for specific field values (dates in an event db) then perform some analysis on them.

I've gotten far enough to correctly query and return specific nodes as a result but am getting stuck on field\_get\_items - I can't get the actual field values out. It appears I am not passing the necessary parameters of the bundle to the function.

Where am I going wrong?

Drupal throws this error on the last line of code starting w $output "EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7734 of /home4/xxxxx/public\_html/xxxxxx/xxxxxx/includes/common.inc)."

Here's my code:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_date', 'value', 'NULL', '!=');
$result = $query->execute();

if (isset($result['node'])) {
  $stories = $result['node'];

  // Get all fields attached to a given node type
  $fields = field_info_instances('node', 'event');

  // Get id of body field
  $field_id = $fields['field_date']['field_id'];

   //echo $field_id... testing, works;

  // Attach a field of selected id only to get value for it
echo field_view_field('node', $stories, 'field_date');

  //Get values of our node field
  $output = field_get_items('node', $stories, 'field_date');
}

```

I get an error on the last step

# Answer
A couple of things...first one is you haven't loaded the nodes. If you change

```
$stories = $result['node'];

```

to

```
$stories = node_load_multiple(array_keys($result['node']));

```

You'll have the fully loaded node objects available.

The other two things are both related; `field_view_field()` and `field_view_value()` both accept a single entity; currently you're trying to pass an array, which it won't like.

A simple loop will fix that:

```
foreach ($stories as $story) {
  $output[] = field_view_field('node', $story, 'field_date');
}

```

And similar for `field_get_items()`.
> 2 votes

# Answer
If you want to use my sandbox you can use EFQE to directly get field data.

```
$query = new EntityFieldQueryExtra();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->propertyCondition('status', 1)
  // Use inner join so the != NULL condition can be skipped.
  //->fieldCondition('field_date', 'value', 'NULL', '!=');
  ->getFieldValue('field_date', 'value', 'INNER');
$result = $query->executeEntityBuild();

if (isset($result['nodes'])) {
  $nodes = $result['nodes'];
  foreach ($nodes as $node) {
    echo $node->field_date['und'][0]['value'];
  }
}

```

No entity load was done in the above query. By using executeEntityBuild it will format the results to look like it was loaded via entity load and its placed under 'nodes'. 'node' will contain the data direct from the query. If you use $query-\>execute then 'nodes' will not be built.
> 0 votes

---
Tags: database
---


# Question
Title: Programmatically building a Quicktabs instance
What I need to do is merge the usermenu ( user tasks ) with a Quicktabs menu I have on the same page.

So what I'm trying to do at the minute is to programmatically build a Quicktabs instance.

Based on the infomation at https://www.drupal.org/node/2119625 I have created a module 'userquicktabs' heres the .module . Ive enabled the module, and I take it after this I should be able to see a new instance with the others instances I've created in the Quicktabs UI. Do I need to make a block for the instance?

```
<?php

function userquicktabs() {
$tabs = array(
$tabs[] = array(
  'title'   => t('Node 1'),
  'type'    => 'node',
  'nid'     => '1',
  'weight'  => 0,
),
$tabs[] = array(
  'title'   => t('Node 2'),
  'type'    => 'node',
  'nid'     => '2',
  'weight'  => 1,
),
);

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

$quicktabs_name = 'newinstance';

 print drupal_render(quicktabs_build_quicktabs($quicktabs_name, $quicktabs_options, $tabs));

}

```

# Answer
Yes, programmatically created instances are not registered with those created trough the UI, but at least they are more flexible.
> 0 votes

---
Tags: blocks
---


# Question
Title: Administrator role can't edit html source in tinymce
I have created and administrator role that has full HTML editing capabilities when creating a node. The issue I am having is that when they click on the button to edit html source button (in tinymce) the resulting dialog doesn't show any source. As user 1, this works with no issues. I thought this was a permission issue of some sort but I can't find where this would be set. This is on a Drupal 6 install. Can anyone tell me what I need to do (and where to go) to fix this?

Thanks.

# Answer
> 0 votes
I found out the issue is that the person logging in as an administrator was using Internet Explorer 11. Once they changed browsers to either Firefox or Chrome, everything worked as it should. Microsoft should really get out of the browser business.

---
Tags: 6
---


# Question
Title: HTML markup is still stripped out, even if I am using the mimemail-message.tpl.php template
I'm having an issue where confirmation emails from Ubercart seem to have HTML markup removed. In my setup somehow the HTML markup in the Ubercart email template is being stripped when it reaches the mimemail template. A view of the source for emails sent shows that the HTML markup Mimemail puts into the message is there. It's just everything coming from Ubercart that is stripped out.

The line 35 of the mimemail-message.tpl.php template file is the following one

```
<?php print $body ?>

```

This is where the problem lies. All the HTML markup above and below this makes it into the email. However, the HTML markup that should be in the `$body` variable is stripped out.

Is there something I could be missing in my settings?

# Answer
> 0 votes
I added the htmlmail module and this fixed the problem.

---
Tags: 6, ubercart, mimemail
---


# Question
Title: Is there a way to create a Text Format on install of a Drupal Module? And enable a Filter for my module?
I want to do a custom filter that replaces certain text with HTML. Essentially shortcodes as done by Wordpress.

Unfortunately, the Filtered HTML Text Format strips most HTML.

So I created my own Text Format manually and enabled only my own Filter.

Is there a way to do this programmatically in the module.install file?

# Answer
Using Features you can export your Text Formats in code and have it automatically configured.

You can configure the filter used for a text format and their order. You can also configure the HTML filter used in the default Filtered HTML text format to allow more HTML elements. So by either allowing the HTML element produced by your filter, and by moving your filter after the HTML filter, you can get your custom filter to work.
> 1 votes

# Answer
If you plan on releasing this module for anyone to use, I would not be 'overriding' any currently set/activated formats, as this will cause problems for existing data/nodes/etc. You should simply provide the functionality, and let people activate it as need be. If there are node bodies saved with 'filtered\_html' and you disable 'filtered\_html', these nodes will not display correctly, and you will make a lot of people unhappy. As such, Drupal probably doesn't provide functions/hooks for doing this (so you can't cause damage to existing data).

If this is just for your own website, you can do anything you want with the right code and manual database changes. I would question the effectiveness of having code doing it, compared to just setting it once manually in the admin.

You can create a filter on install, if that is what you want. See filter\_format\_save and an example of how to use it in filter.install
> 0 votes

---
Tags: input-formats
---


# Question
Title: Mapping split taxonomy terms to new vocabs in nodes in migrate_d2d
I have a use case in a D6-\>D7 migration (using migrate\_d2d), where I need to split terms from a large vocabulary into two new vocabularies in the D7 site. I achieved the splitting into two new vocabularies just fine in the taxonomy migration (see here for details on how), but the problem is getting the new mapping to work during the blog node migration so that the nodes are attached to the proper vocabulary field in the destination node.

So here's the setup:

**D6**

* People and Organizations (vid 4)

**D7**

* People and Organizations (field\_people\_organizations, vid 9)
* Journalists (field\_journalists, vid 5) Non-Journalists
* Non-Journalists (field\_non\_journalists, vid 7)

In my blog node class constructor, I've added this:

```
$this->addFieldMapping('field_people_organizations', 4)
  ->sourceMigration('PeopleOrganizations');
$this->addFieldMapping('field_people_organizations:source_type')->defaultValue('tid');
$this->addFieldMapping('field_journalists', 4)
  ->sourceMigration('PeopleOrganizations');
$this->addFieldMapping('field_journalists:source_type')->defaultValue('tid');
$this->addFieldMapping('field_non_journalists', 4)
  ->sourceMigration('PeopleOrganizations');
$this->addFieldMapping('field_non_journalists:source_type')->defaultValue('tid');

```

However, what this does is just populate all three taxonomy reference fields with all terms from the People and Organizations field in the source. For instance, if the D6 People and Organizations field has Term A, Term B, and Term C, and in D7, Term B should be in Journalists and Term C should be in Non\_Journalists, I get all three terms in each term reference field instead of Term A in field\_people\_organizations, Term B in field\_journalists, and Term C in field\_non\_journalists.

I did a query that joined the D6 db with the D7 db using the migrate\_map\_peopleorganizations table in the D7 site, and the terms themselves are correctly populated in the D7 tables, so I know that's not the issue. I suppose I could do some wrangling in prepare() to move the terms to the appropriate field in the blog node, but it seems there should be an easier way to map to the new vocabulary. I'm guessing I would create a field on the fly and map to it in prepareRow(), but I'm not sure what I would put in that field, since the second parameter in addFieldMapping() for taxonomy terms is the source vocabulary, and there is no source vocabulary for the new ones.

Thanks.

# Answer
> 0 votes
As a possibility I mentioned above, I did some wrangling in the prepare() method to move the terms from field\_people\_organizations to field\_journalists and field\_non\_journalists.

```
  function prepare($entity, stdClass $row) {
    // Turn off pathauto generation for the node so we end
    // up with only one alias record.
    $entity->path['pathauto'] = 0;

    // Need to manually move any items that should be in the Journalists and Non-Journalists
    // vocabularies there from People and Organizations, since migration mapping doesn't
    // seem to be working.

    // First, see if the nb_migrate_users array is already cached.
    $nb_migrate_journalists = & drupal_static(__FUNCTION__);
    if (!isset($nb_migrate_journalists)) {
      if ($cache = cache_get('nb_migrate_journalists')) {
        $nb_migrate_journalists = $cache->data;
      }
      // Not cached, so we need to generate it this time through.
      else {
        //Get new tids for terms mapped in migrate_map_jounralists.
        $query = db_select('nb_migrate_journalists', 'nmj');
        $query->fields('nmj', array('journalists', 'non_journalists'));
        $query->innerJoin('migrate_map_peopleorganizations', 'mmp', 'nmj.tid = mmp.sourceid1');
        $query->addField('mmp', 'destid1');
        $result = $query->execute();

        foreach ($result as $record) {
          // Use the target vid for the vocab; 5 = Journalists, 7 = Non-Journalists.
          if ($record->journalists == 'x') {
            $nb_migrate_journalists[$record->destid1] = 5;
          }
          elseif ($record->non_journalists == 'x') {
            $nb_migrate_journalists[$record->destid1] = 7;
          }
        }
        // Cache the array.
        cache_set('nb_migrate_journalists', $nb_migrate_journalists, 'cache');
      }
    }
    // Move terms in array based on values in field_people_organizations and $nb_migrate_journalists.
    if (isset($entity->field_people_organizations[LANGUAGE_NONE][0])) {
      foreach ($entity->field_people_organizations[LANGUAGE_NONE] as $key => $term) {
        if (in_array((int)$term['tid'], array_keys($nb_migrate_journalists))) {
          if ($nb_migrate_journalists[$term['tid']] == 5) {
            $entity->field_journalists[LANGUAGE_NONE][] = array('tid' => $term['tid']);
          }
          elseif ($nb_migrate_journalists[$term['tid']] == 7) {
            $entity->field_non_journalists[LANGUAGE_NONE][] = array('tid' => $term['tid']);
          }
          // Remove term from field_people_organizations.
          unset($entity->field_people_organizations[LANGUAGE_NONE][$key]);
        }
      }
    }
  }

```

I still think there is probably a better way to do this within the class constructor, so if at some point in the future you read this and know that answer, please add it here.

Thanks.

---
Tags: taxonomy-terms, migrations
---


# Question
Title: Rules: after saving new content and after updating existing content both triggered on node create
I define two rules that should send an email once new node has been created. And second rule once user updated his content.

The problem I am having here is that both rules trigger in one time when your create a new node.

I found the same issue has been asked in anther question but not very clear and i am not able to understand enter link description here

But I am not able to understand.

Thanks for the help.

# Answer
This is very easy to accomplish, you have a few attributes of the node to compare and check in order to decide which trigger to be true/false.

Method 1: Put the following PHP code into your both conditions (create & update) by selecting execute PHP code

CREATE

```
if($node->created == $node->changed) {
   return true;
} else {
   return false;
}

```

UPDATE

```
if($node->created != $node->changed) {
    return true;
} else {
   return false;
}

```

Method 2:

UPDATE:

```
if($node->is_new) {
     return false;
} else {
     return true;
}

```

OR

```
if(!empty($node->nid)) {
    return true;
} else {
    return false;
}

```

I have not checked the Method 2 but, method 1 is easier and should definitely work out for you.

Don't forget to Accept this answer solve your problem.

Cheers.

Raf.
> 2 votes

---
Tags: nodes, rules, updating
---


# Question
Title: How can i hard-wire a link, in blocks, using $base_url or something similar?
I'm trying, unsuccessfully so far, to create a block that is simple hard-wired link. but i need to use $base\_url or something equivalent (like base\_url(); ?) but i guess adding php is not allowed.

i tried a few different things in the block body. for example…

```
<a href="<?php print $base_url . '/archive/program-archive-2012--2013' ?>"> Archives</a>

```

how i can achieve this, without using a full, or literal URL?

# Answer
> 1 votes
Hard wired to what?

Personally I like to hard wire my URLs the the root of the site. If my site is always a full domain name as `wwww.mysite.com` The url would be:

```
<a href='/archive/program-archive-2012--2013'> Archives</a>

```

This is relative to the root of the website. Which makes sense to me. You can move your site to a new domain, `www.mysite2.com`, and this *Path* will still work.

If you move your site to a sub-directory later then .htacess `BaseRewrite` rules can still allow this to work.

I find trying to make a url work for any combination of directory prefixes or a subsite in a folder, etc .... to much of a pain to deal with.

---
Tags: blocks
---


title: Create bulk nodes - PDOException

text:
# Question
Title: Create bulk nodes - PDOException
**Problem**

I'm trying to create multiple nodes at once using a CSV file for the data. However my script only creates the first 25 before it throws the following error. Any ideas what might be happening?

> PDOException: in drupal\_write\_record() (line 7166 of C:\XAMPP\htdocs\drupalie\includes\common.inc).

**Set-Up**

I have a custom form which creates the nodes on submit. The form just has a submit button.

This is the submit handler. I only have one column in my CSV sheet so I don't actually use the delimiter. First I generate an array with each node name.

```
  if (($handle = fopen("sites/all/modules/custom/generatenodes/nodes_database_import.csv", "r")) !== FALSE) {
    //open the CSV file
    $length = 1000;
    $delimiter = "|";
    //set the length and delimiter.
    while (!feof($handle)) {
      //$line is an array of the csv elements
      $node_name_array[] = fgetcsv($handle, $length, $delimiter);
    }

    fclose($handle);
  }

```

The array looks like this:

I then create the nodes:

```
global $user;
foreach ($node_name_array as $nodename) {
  if($nodename == FALSE) {
    return;
  }

    $values = array(
      'type' => 'school',
      'uid' => $user->uid,
      'status' => 1,
      'comment' => 0,
      'promote' => 0,
    );
    $entity = entity_create('node', $values);

    $ewrapper = entity_metadata_wrapper('node', $entity);

    $ewrapper->title->set($nodename['0']);
    $ewrapper->field_country->set($schoolname['0']);
     $ewrapper->save(true);
    entity_save('node', $entity);
}

```

But it breaks after the first 25 or so. What have I missed?

**EDIT--**

So I found the cause. It's to do with the values in my CSV file. Sometimes it likes them othertimes it doesn't. If I replace these values then it works up to the next broken value.

The first problem was a value with an accented e inside. Removing the accent fixed it.

Unfortunately the next two which broke it are not so obvious:

* Putian Cambridge English
* Zhangzhou Bilingual Middle School

Yet the following values work:

* Quanzhou Foreign Language Middle School
* International College of Xiamen University

I've only pasted in clean values, but something is breaking it. Any ideas?

Trying to navigate to the content page after causes MySQL to break. Here's the error log:

https://www.dropbox.com/s/jji3cw559filq03/mysqlcrash\_log.txt

# Answer
You should be using migrate for this: https://www.drupal.org/project/migrate, it covers many of the pitfalls you are currently encountering when creating or importing content from a CSV, database or XML file. Don't recreate the wheel when someone has already created it for you.

It's not like the feeds module or other "import" type modules, it's an entirely code based OOP solution. You just extend the main migration class and map your data. It comes with a number of built in PHP functions to process the data further and it literally covers almost every scenario you could possibly encounter when mass creating or transferring content.

As someone who's been down this path many times, it will save you a lot of time and hair pulling. I recommend looking at the code examples migrate provides.
> 0 votes

---
Tags: 7, nodes, database
---


title: Show sub menu via hook_menu

text:
# Question
Title: Show sub menu via hook_menu
Sorry for asking such a question, but I'm still new in Drupal. I want to show sub menu via main menu.

```
Ex:
- Top menu
1) Home
  a. Report
  b. Comment
2) Shopping
  a. Audi
  b. Honda

```

In this case, I would like to see 'a. Audi, b. Honda', or go back Home and see 'a. Report, b. Comment'. What should my module's hook\_menu implementation look like ?

# Answer
> 0 votes
You can simply achieve that by using the Superfish module.

> Superfish integrates jQuery Superfish plugin with your Drupal menus.

Image from Superfish module page

There is another module called Nice Menus

> Nice Menus enables drop-down/right/left expandable menus. It uses only CSS for most browsers, with minimal Javascript for IE6. (Version 2 uses the Superfish jQuery plugin for all browsers, with an option to disable JS, and falls back to CSS-only for browsers that can handle it.)

---
Tags: 7, routes
---


# Question
Title: How to Get data of Content type in a custom view
I have a content type "tasks", I created a custom view.i want to show all data of content type "tasks" in that custom view.

# Answer
This question seems to be answered already at How do I programmatically create a view?. In case you need the reference here is another link http://www.packtpub.com/article/creating-views-3-programmatically Hope this helps you.
> 0 votes

# Answer
I believe you are looking for this module: https://www.drupal.org/project/viewsnodefield
> 0 votes

# Answer
Just to be clear do you want to the data in View using some custom code, if not u can just go to Structure and then click Views. Then click add a new View. Add a name and select your custom content. In Display format under create a Page,, select Unformatted list of type Field from the the 2nd selection and then press Continue & Edit at Bottom. Here In Fields section click Add and add all the field relevant to your Content type.

Thanks hope that helps you. Click it if the answer is relevant to you.
> 0 votes

---
Tags: views
---


title: Custom theme function not being called?

text:
# Question
Title: Custom theme function not being called?
I'm building a Drupal 7 module to create a bespoke field type. I've implemented all the required hooks. My `hook_field_formatter_view()` function looks like this:

```
function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'default':
      foreach ($items as $delta => $item) {
                $element[$delta] = array(
                  '#theme' => 'test',
                  '#item' => $item,
                );
      }
      break;
  }

  return $element;
}

```

I've then defined the `theme()` function below:

```
function theme_test($variables) {
    return '<h1>Hello World</h1>';
}

```

But when I view the page nothing is output. If I look at the recent log entries I see this message:

`Theme key 'test' not found.`

If I change my MYMODULE\_field\_formatter\_view render array '#theme' value to a built in theme function like 'item\_list' it works. But for some reason my custom theme function is not being picked up.

I've rebuilt the theme registry hundreds of times as well as cleared the caches.

# Answer
> 12 votes
You probably have not defined your theme hook in `hook_theme()`.

The Using the theme layer section of the Development handbook has an in-depth discussion about this.

# Answer
> 10 votes
You need to define the theme function in `hook_theme` and then clear the cache.

```
 function MYMODULE_theme() {
   return array(
     'test' => array (
       'render element' => 'element',
     ),
   );
 }

```

# Answer
> 2 votes
I was facing the same issue where my custom theme function was never being called in my template, even though it was registered. When I switched to another theme, it worked.

My solution was re-naming theme into 'something\_theme', because I made a stupid mistake and already had module named 'something'.

**Module and theme should never have the same name**, because it leads into collision which causes unexpected behavior and hook overriding.

---
Tags: 7, theming, hooks, entities
---


title: Drush Hangs on wget but wget Works

text:
# Question
Title: Drush Hangs on wget but wget Works
Every drush command I run hangs on wget. However, if I run wget outside of drush, it works just fine. I am behind an http proxy and suspect that's factoring into the problem. I don't understand why wget isn't looking at my http\_proxy environment variable when run through drush.

# Answer
> 0 votes
Might this help... http://www.xandermar.com/blog/may-20-2014/using-drush-proxy ?

(sorry, I know this is more of a comment, but I don't have the points!)

If not, have you run the drush commend in verbose mode to get more info?

---
Tags: drush, proxies
---


# Question
Title: Resetting outputted HTML markup to default?
I am trying to fix a site, which I did not build nor 'break'.

On a clean install of Drupal, the markup for a node's textfield, set to display inline, looks like this:

```
<div class="field field-name-field-foo field-type-text field-label-inline clearfix">
  <div class="field-label">Foo: </div>
  <div class="field-items">
    <div class="field-item even">Bar</div>
  </div>
</div>

```

On my problem site it looks liike this:

```
<span class="field-label">Foo: </span>
<div class="field field-name-field-foo field-type-text field-label-inline inline">Bar</div>

```

I have turned off the custom theme and I have disabled the Display Suite module, cleared all caches - no change.

Are there any other obvious places I could look to find what is changing the outputted markup?

There are 250 modules enabled, so turning things off one by one is not really an option.

Thanks.

# Answer
> 0 votes
Yes, it was the configuration of the fences module. I needed to cancel the override in the first section. Navigate to Fences configuration to change the settings.

---
Tags: theming
---


# Question
Title: How to pass an extra argument to an entity form?
Suppose, I've two entities:

```
entityA
entityB

```

A user creates an `entityA` and has the option of creating multiple types of `entityB` referenced from a single `entityA`. For example, a parent-child relationship. Parent being `entityA` and child being `entityB`.

In the module, I want the users to select an `entityA` object, go to a new page page for creating `entityB`. So, at this point, (add-form of `entityB`) I should have the data of that particular `entityA` object that the user clicked on.

So, far I'm able to get "all" the data of `entityA` on the `add-form of entityB`, which is of no help as I'm unable to get the specific `id` of `entityA`.

The relevant code are:

**routing.yml**

```
mymodule.entityB_add:
  path: '/admin/config/mymodule/{entityA}/entityB/add'
  defaults:
    _entity_form: 'mymodule_entityA_entityB.default'
    _title: 'EntityB'
  requirements:
    _entity_create_access: 'mymodule_entityA'

```

When, I'm shown the form addition page of `entityB` (type: .`./../testentitya/entityA/add`), how do I pass the `entityA` object to the form and what will be the structure of entityB's config schema?

# Answer
> 2 votes
Have a look at https://www.drupal.org/node/2310425

This should explaine everything needed.

Here is an example how it would look like:

```
mymodule.entityB_add:
  path: '/admin/config/mymodule/{entityA}/{entityB}/add'
  defaults:
    _entity_form: 'mymodule_entityA_entityB.default'
    _title: 'EntityB'
  requirements:
    _entity_create_access: 'mymodule_entityA'
  options:
    parameters:
      entityA:
        type: entity:entity_type_a
      entityB:
        type: entity:entity_type_b

```

# Answer
> 2 votes
Regarding the references: config entities are simple beasts. Entity references are only supported on content entities; however you are on the way of building it out yourself tailored for your needs. So, just store a string with the id of configA and that's about it. What you do with a string is your call.

---
Tags: entities, 8, database
---


# Question
Title: Blocks are invisible after hosting drupal7
I am facing with a problem in drupal7, I am new to drupal7 too. When I run my website in localhost everything fine, blocks and menu are visible. But after I host my website in GoDaddy, that blocks and menu are invisible, where they gone. I am also hoping someone can help me to solve this problem. Thanks.

This is the image when I call this website in localhost. We can see block and menu.

This is the image when I call after hosting this website.

# Answer
> 0 votes
Sometime the issue occurs when we migrate the site. Just follow through these steps:-

1) Check the block section of the local and live site 2) Check all blocks from the local and live 3) Now assign the blocks to the same regions in live as it is in the local setup 4) Check blocks are visible on the given region on the page or not.

Edit the blocks to set their display settings.

# Answer
> 0 votes
You configured the block in your localsite so the data is stored in your local database. Please take dump from your local site the import the dump into your server database.

---
Tags: routes, blocks
---


title: Error in db_query statement - d7

text:
# Question
Title: Error in db_query statement - d7
The below query is giving error:

PDOException: SQLSTATE\[HY093\]: Invalid parameter number: no parameters were bound in webform\_options\_submit()

What am I missing? Any suggestions/ideas will be helpful.

And, How should I use the LIKE command in this query?

```
  $args = array(':entities' => $_REQUEST['entities'], ':countries'=>$_REQUEST['countries']);
  $query = db_query("SELECT field_entity_value,field_country_value, filename
                   FROM field_data_field_entity,field_data_field_country , field_revision_field_file_upload, file_managed
                   WHERE ( field_data_field_entity.field_entity_value LIKE :entities
                   AND field_data_field_country.field_country_value= :countries )
                   AND field_data_field_entity.entity_id = field_revision_field_file_upload.entity_id
                   AND field_data_field_country.entity_id= field_data_field_entity.entity_id
                   AND field_revision_field_file_upload.field_file_upload_fid=file_managed.fid", $args);
  $results = $query->execute();

```

# Answer
Try it without the $query-\>execute(); as according to the docs for db\_query the function already executes the query and returns a result.

Try this:

```
$args = array(':entities' => $_REQUEST['entities'], ':countries'=>$_REQUEST['countries']);
$result = db_query("SELECT field_entity_value,field_country_value, filename
                   FROM field_data_field_entity,field_data_field_country , field_revision_field_file_upload, file_managed
                   WHERE ( field_data_field_entity.field_entity_value LIKE :entities
                   AND field_data_field_country.field_country_value= :countries )
                   AND field_data_field_entity.entity_id = field_revision_field_file_upload.entity_id
                   AND field_data_field_country.entity_id= field_data_field_entity.entity_id
                   AND field_revision_field_file_upload.field_file_upload_fid=file_managed.fid", $args);

```

I would say the error is from trying to execute a result.
> 3 votes

---
Tags: 7, database
---


# Question
Title: How can I find webform e-mail submission values keys?
I created a Webform and now I want to send an email on submit to the customer. But I'm not understanding how to take the submission values one by one and use it in the email body.

The submission tokens description says:

> %value\[key\] - A value without additional formatting. Elements may be accessed such as %value\[fieldset\_a\]\[key\_b\]. Do not include quotes.

What kind of key the `%value` array have got? How can I find they?

# Answer
Here is the answer.

Lets say I've 4 fields in Webform

`Label` \- `Field Key`

```
First Name - first_name

Last Name - last_name

Phone Number - phone_number

Message - message

```

Here is the way to access them in *template* field

For example if you want to display name as the combination of *First Name and Last Name*

```
Name:  %value[first_name] %value[last_name]

```

Then this appears in mail like

```
Name: Krishna Mohan

```

If you want to access a individual *field value with Label*

For example Phone number

```
%email[phone_number]

```

This appears in mail like

```
Phone Number - 555-555-5225

```

I've tested this and works great! Hope this helps
> 7 votes

---
Tags: 7, webforms, tokens
---