# Question
Title: Errors when Taxonomy is chosen in node's Term Reference field
I have created a vocabulary called "Recipes" with several terms underneath (Appetizers, Dinner, etc). I also have a content type called "Recipe" with a Term Reference field for the Recipes vocabulary.

When a term (let's say Appetizers) does not yet have a node referencing it via that Term Reference field, the term's page shows up fine (albeit without any node content). However, when I choose one of those terms on a Recipe node via that Term Reference field, the term's page shows three error messages and various elements of the page (such as the footer and the nav bar) are not displayed. The errors are:

> Notice: Undefined property: stdClass::$type in \_node\_extract\_type() (line 379 of /home/mysite/public\_html/modules/node/node.module).
>
> Notice: Undefined property: stdClass::$nid in node\_build\_content() (line 1417 of /home/mysite/public\_html/modules/node/node.module).
>
> EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7721 of /home/mysite/public\_html/includes/common.inc).

I upgraded from 7.24 to 7.26, but that did not fix the issue. Google has not been particularly helpful. Does anyone here have any feedback on what might cause this issue? FYI, I also added a Term Reference field for the built-in "Tags" vocabulary, and the same issues occurred.

# Answer
This **EntityMalformedException: Missing bundle property on entity of type node** errors seems to rear its ugly head in a lot of different contexts.

In my case it was a configuration of the view that showed the related nodes that had a couple of filters set wrong.

I had a relationship to related articles, but then in the filter section, Relationship was set to "Do not use a relationship" instead of using the related article. Setting the correct setting on the filter fixed the issue.
> 0 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: How to render ctools_custom_content_type_edit_form with ctools_modal_form_wrapper()
I have a scenario where I would like to reload/re-render the ctools\_custom\_content\_type\_edit\_form after closing another ctools modal. To do so, I've bound an ajax object to the .close element within the open modal that will fire an ajax callback to open the ctools\_custom\_content\_type\_edit\_form again.

My ajax callback looks like this, where the parent form is an argument in the menu callback. In this particular scenario, that form id is ctools\_custom\_content\_type\_edit\_form.

The form is rendered, but it seems to be missing fields: Administrative Title, Title, Body. Any help would be appreciated. Let me know if you need more information.

```
function mymodule_parent_modal_callback($js, $parent_form_id) {
  // Convert parent form id
  $parent_form_id = str_replace ('-', '_', $parent_form_id);
  $path = '' . drupal_get_path('module', 'wysifield');

  if ($js) {
    ctools_include('modal');
    ctools_include('ajax');
  }
  else {
    // Someone navigated to the AJAX endpoint.
    drupal_access_denied();
  }

  $form_state = array(
    'ajax' => TRUE,
    'title' => t('Parent Modal Form'),
  );

  $commands = ctools_modal_form_wrapper($parent_form_id, $form_state);

  // If form has been submitted, execute other ajax commands.
  if (!empty($form_state['executed'])) {
    // Add the responder javascript, required by ctools
    ctools_add_js('ajax-responder');

    // Create ajax command array, dismiss the modal window.
    $commands = array();
    $commands[] = ctools_modal_command_dismiss();
  }

  print ajax_render($commands);
  drupal_exit();

}

```

# Answer
> 0 votes
Look at `if ($settings['custom_type'] == 'fixed')` condition in `ctools_custom_content_type_edit_form()`. Problem in it I think. Also, look at `ctools_custom_content_type_get_conf()` and do all needed to this function return `$settings['custom_type']` equal to 'fixed'. Maybe this will fix problem, change this value before `ctools_modal_form_wrapper()` like this: `$form_state['subtype']['name'] = 'custom';`

---
Tags: 7, ajax, panels, chaos-tool-suite, javascript
---


# Question
Title: How can I add user information to orders administration pages?
I'm using Commerce User Profile Pane to capture Drupal Users profile fields *directly* in the Commerce checkout pages : as I have several custom customer fields (birthday, passport number...), I found this more accurate than storing this data in Billing information.

How can I display the collected informations along with the billing information data (name, address), in the order view page : `admin/commerce/orders/%`, and in the quick edit view ?

I can't find any view or .tpl for such task.

# Answer
> 0 votes
As per Andy's advices about Drupal Theming, I used devel\_themer, and could find immediately the correct template : `commerce_backoffice/theme/commerce-order--backoffice.tpl.php`.

---
Tags: users, commerce
---


title: Submenus do not work on some pages

text:
# Question
Title: Submenus do not work on some pages
For some reason, sub-menus do not work on all pages on my site. Here is one (basic page) that shows the submenus

and here is a screenshot where it doesn't even though the mouse is hovering over the Home menu item.

The links are enabled in Main Menu and I tried toggling "Show as expanded" on and off but neither one makes a difference. The background image is hidden by a display:none css style in the second image/page. If I go to the Contact page, which looks similar to the first image the submenu does not show up on there either. The Contact page was created using the webform module.

Any help figuring this out would be much appreciated.

Thanks,

Kamal

UPDATE: I noticed that on the pages where the submenu works, the following code is generated for the menu.

```
<ul class=" eh-hmenu "><li class="first last expanded active-trail active"><a class="active-trail" href="/">Home</a><ul class="menu eh-hmenu-right-to-left active"><li class="first last leaf active-trail active"><a class="active-trail active" href="/host">Host A 51@EarthHour Event</a></li>

```

Whereas on the pages where it doesn't work, I only see

```
<ul class=" eh-hmenu "><li class="first last collapsed active"><a class="active" href="/">Home</a></li>

```

# Answer
Which page are you on when it does not show and is that page in the menu? Also Are you using a block for the menu or printing it in the theme template file? That could be the cause. I'd recommend switching to a block if that's the case and make sure the expanded check-box is checked.
> 1 votes

# Answer
Have you tried the Nice Menus module?

> 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.)

---

Though it just might be a CSS error. if your submenu is `position: absolute`, check if its container is `position:relative`.

Also, if you added a `z-index` style in your css, it needs either `position:relative` or `position: absolute` to work properly.
> 1 votes

# Answer
Are you sure that you have the menu set to appear on all pages, including the subpages and not just the parent pages?
> 1 votes

# Answer
**You would do the following:**

Ensure that all the menu items in their settings have checked "showed as expanded".

In the CSS for the menu (as from ignoredbydinosaurs.com's example), ensured that your menu ul styling is in principle like the following:

```
ul {
  float: left;
  margin: 0;
  padding: 0;
}
ul li {
  position: relative;
  float: left;
  list-style: none;
  list-style-image: none; /* DRUPAL!! */
  padding: .5em 1em;
  margin: 0;
}
ul li ul {
  display: none;
  position: absolute;
  width: 10em;
  left: 0;
  top: 1em;
}
ul li:hover ul {
  display: block;
}

```

The display`:none;` `position:absolute` and `position:relative;` are what are at work here. and You will notice that this is from their example. Ensure that the CSS document is properly linked to your page and I believe that this will work.

here is a tutorial that helps with menus in drupal: http://www.ignoredbydinosaurs.com/2014/02/building-a-drop-down-menu-from-scratch . Also there was a discussion that addressed many of these problems where I also responded: https://www.drupal.org/documentation/modules/menu#comment-9014221. I responded to a problem in this discussion relating to dropdown menus.
> 0 votes

---
Tags: routes, navigation
---


# Question
Title: Add class to views row instead of replace system classes
I have this code:

```
function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (!empty($row->field_field_image)) {
      $vars['classes_array'][$id] = 'has_field';
    }
    else {
      $vars['classes_array'][$id] = 'has_no_field';
    }
  }
}

```

It works, but replaces all system original classes.

How to just add class? I tried with `$vars['classes_array'][$id][]` but I'm getting: Fatal error: \[\] operator not supported for strings

# Answer
Your question is simply a PHP programming question, and not entirely Drupal related. But here goes:

```
function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (!empty($row->field_field_image)) {
      $old_class_values = $vars['classes_array'][$id];
      $vars['classes_array'][$id] = $old_class_values . ' has_field';
    }
    else {
      $vars['classes_array'][$id] = $old_class_values . ' has_no_field';
    }
  }
}

```
> 1 votes

---
Tags: 7, views
---


title: AJAX change field is required

text:
# Question
Title: AJAX change field is required
I have simple form, two fields one is checkbox and second is text. When checkbox is checked. Text field is required, and when checkbox is unchecked textfield shouldn't be required...

To perform this need with AJAX, i have my working example like below:

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

      $form['ask_required'] = array(
        '#type' => 'checkbox',

        '#title' => t('required'),
        '#default_value' => "",
           '#ajax' => array(
            'callback' => 'ajax_required_callback',
            'wrapper' => 'replace_reqired_div',
        ),
    );

       if (!empty($form_state['values']['ask_required']) && $form_state['values']['ask_required']) {
    $form['vin'] = array(
        '#type' => 'textfield',
    '#required' => TRUE,
        '#title' => t('VIN'),
        '#default_value' => "",
          '#prefix' => '<div id="replace_reqired_div">',
        '#suffix' => '</div>',
    );

  }else{

       $form['vin'] = array(
        '#type' => 'textfield',

        '#title' => t('VIN'),
        '#default_value' => "",
          '#prefix' => '<div id="replace_reqired_div">',
        '#suffix' => '</div>',
    );
  }

    $form['next'] = array(
        '#type' => 'submit',
        '#value' => 'Dalej >>',
        '#submit' => array('mail_form_submit'),

    );
    //    dpm($form);
    return $form;

}

function ajax_required_callback($form, $form_state) {

     return $form['vin'];
}

```

Is there any more elegant way e.g. to change attributes of field not whole VIN field?

Second thing is that when i place above code in ...form\_alter, its not working..., there are fields there is ajax callback but required star is not changed

```
function module_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'user_register_form') {

        $form['account']['name']['#description'] = t('');
        $form['account']['mail']['#description'] = t('');

        $form['ask_required'] = array(
            '#type' => 'checkbox',
            '#title' => t('required'),
            '#default_value' => "",
            '#ajax' => array(
                'callback' => 'ajax_required_callback',
                'wrapper' => 'replace_reqired_div',
            ),
        );

        if (!empty($form_state['values']['ask_required']) && $form_state['values']['ask_required']) {
            $form['vin'] = array(
                '#type' => 'textfield',
                '#required' => TRUE,
                '#title' => t('VIN'),
                '#default_value' => "",
                '#prefix' => '<div id="replace_reqired_div">',
                '#suffix' => '</div>',
            );
        } else {

            $form['vin'] = array(
                '#type' => 'textfield',
                '#title' => t('VIN'),
                '#default_value' => "",
                '#prefix' => '<div id="replace_reqired_div">',
                '#suffix' => '</div>',
            );
        }
    }
}

```

why?

# Answer
You can use Form API #states attribute. This will allow you to trigger something based on another fields information. Below should be a working example.

```
$form['vin'] = array(
  '#type' => 'textfield',
  '#title' => t('VIN'),
  '#default_value' => '',
  '#states' => array(
    'required' => array(
      ':input[name="ask_required"]' => array('checked' => TRUE),
    ),
  ),
);

```
> 2 votes

---
Tags: ajax
---


# Question
Title: Drupal 6 - How to programatically create a content type
I am creating a module to display a dashboard that shows various stats. One section will be for adding announcements. My thought is that the best way to do this would be to create a custom content type and then pull in the latest announcements from the announcement content type submissions.

My question is how can I create that content type programatically with the proper fields? Where can I go to add those announcements once the type is created? And how can I pull the latest announcements to display on the page?

I'm new to Drupal, so I'm struggling at the moment to learn the proper way to do things.

# Answer
> 0 votes
You can use the Features module to export out the content type and the fields associated with it. Once you have done this you will have a .tar or .zip file of the export code in a functional module.

From here you are able to move that directory into your sites/all/modules directory and have a fully functional module.

Do remember to remove your content type and fields, before installing the module on your site. The new module will recreate them for you.

---
Tags: nodes
---


# Question
Title: Ajust the position of autocomplete fields
I working with the theme base bootstrap and my problem is that in autocomplete fields it's a bit offside of position, see the screenshot.

How fix this ? I need this more to the left and below the textfield.

Greetings.

# Answer
This should be a CSS positioning issue, whether it is caused by padding, margining, position, top, left, right, or bottom.

You should be able to use firebug or another developer tool like it to find what CSS is causing this and remove that CSS if it's your own CSS. Otherwise if the CSS is provided by contrib then you can use a more specific CSS selector and override the values.
> 0 votes

---
Tags: 7, theming, ajax
---


# Question
Title: Can Nivo Slider change slides without any effects?
I am trying to make the Nivo Slider module slide in between pictures without any effects. Is this possible from the Drupal admin section? Do I need to dive into code to do this?

Thanks!

# Answer
If you select fade and make the fade occur in 1ms, then it will appear to change slides without any effects.
> 0 votes

---
Tags: media, javascript
---


# Question
Title: Distinguishing form being built for rendering versus submission
Is there a way to distinguish, inside a form function, that the form is being built to be rendered on the page, as opposed to being re-built as a result of submission?

I would like to use `drupal_set_message()` inside the form function, but only while it's being built for rendering.

# Answer
Take a look at the $form\_state elements. You'll want to look at 'submitted', 'rebuild', 'cache', 'programmed', etc... depending on your use-case. You can get a good idea of those elements and what they mean in drupal\_build\_form. I typically use $form\_state\['submitted'\].
> -1 votes

---
Tags: 7, forms
---


title: "Add More" button to form

text:
# Question
Title: "Add More" button to form
I'm trying to add an "add more" field to a form in my custom module. I've been looking at the examples module, with no luck.

Here's what I have so far:

```
$form['#tree'] = TRUE;
  $form['names_fieldset'] = array(
  '#type' => 'fieldset',
  '#title' => t('People coming to the picnic'),
  // Set up the wrapper so that AJAX will be able to replace the fieldset.
  '#prefix' => '<div id="names-fieldset-wrapper">',
  '#suffix' => '</div>',
);

if (empty($form_state['num_names'])) {
  $form_state['num_names'] = 1;
}

for ($i = 0; $i < $form_state['num_names']; $i++) {
  $form['names_fieldset']['name'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
  );
}

$form['names_fieldset']['add_name'] = array(
  '#type' => 'submit',
  '#value' => t('Add one more'),
  '#submit' => array('spower_add_more_add_one'),
  // See the examples in ajax_example.module for more details on the
  // properties of #ajax.
  '#ajax' => array(
    'callback' => 'spower_add_more_callback',
    'wrapper' => 'names-fieldset-wrapper',
  ),
);

if ($form_state['num_names'] > 1) {
  $form['names_fieldset']['remove_name'] = array(
    '#type' => 'submit',
    '#value' => t('Remove one'),
    '#submit' => array('spower_add_more_remove_one'),
    '#ajax' => array(
      'callback' => 'spower_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
}

```

```
function spower_theme($existing, $type, $theme, $path) {
  $base = array(
    'render element' => 'form',
  );

  return array(
    'spower_my_form' => $base + array(
      'template' => 'spower',
    ),
  );
}

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

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function spower_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function spower_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
  }
  $form_state['rebuild'] = TRUE;
}

```

The problem is that when I click "add more", the entire form is submitted.

If the above isn't clear, I've added the module at http://pastebin.com/Hn7bkM2v and the spower\_elements.inc at http://pastebin.com/CwHW5mSm.

Thanks for the help.

# Answer
> 2 votes
It's a well known problem of Drupal 7 - every form button is rendered with `type="submit"`.

What you need to do, is to add `prevent="click submit mousedown"` to your button, to prevent actual submission. Maybe only one of those 3 is really needed, but this combination gave me pretty consistent results.

OK, but the above only prevents form from actual saving data. It still gets validated, and that's not exactly what you want, right? I already got answer on how to omit form's validation at AJAX button click.

Other approach would be to either add custom form element, let's call it real\_button, a copy of button but with `type="button"`, or to change type on document ready using jQuery.

# Answer
> 0 votes
I struggled for 2 hours and I figured it out. In my case, in the place of modulename (e.g. godown) in the code snippet it actally had to be the form name (e.g. godown\_item\_form).

All along the way, I was replacing the modulename in the code with godown (my module's name), but when I replaced it with godown\_item\_form (my form's name) it started working like a charm.

# Answer
> 0 votes
**IMPORTANT** note to everyone using this with a "Number of values" setting greater than one (read: If the user can add additional copies of the entire field type via the "Add another item" button.).

For over an hour now I have been struggling trying to fix a problem: After the AJAX callback triggered, an incorrect `$delta` value was used every time during the ajax form rebuilding process. To be more precise, it always used the `$delta` value referencing to the very last item in the list, regardless of whether I pressed the button of the first, second or last item.

The ridiculously simple solution to this involves to quick steps:

1. Append the `$delta` value to the ajax wrapper.
(This is optional really, and just to produce for correct markup, otherwise you would have multiple wrappers with the very same ID. Drupal's AJAX is still smart enough to target the correct wrapper regardless of the multiple ID copies.)

```
$form['names_fieldset'] = array(
  '#type' => 'fieldset',
  '#title' => t('People coming to the picnic'),
  // Set up the wrapper so that AJAX will be able to replace the fieldset.
  '#prefix' => '<div id="names-fieldset-wrapper-'.$delta.'">',
  '#suffix' => '</div>',
);

```
2. Include the `$delta` value in the `#name` element of the "add one more" ajax button.
this makes sure the system can distinguish between the "add one more" button of each item.

```
$form['names_fieldset']['add_name'] = array(
  '#type' => 'submit',
  '#value' => t('Add one more'),
  '#name' => 'add-name-'.$delta, // <-- most important bit
  '#submit' => array('spower_add_more_add_one'),
  // See the examples in ajax_example.module for more details on the
  // properties of #ajax.
  '#ajax' => array(
    'callback' => 'spower_add_more_callback',
    'wrapper' => 'names-fieldset-wrapper-'.$delta, // <-- accompany the name wrapper IDs
  ),
);

```

Additionally, if you followed step 1 above, you will also need to update the `wrapper` attribute as seen in this code.
And obviously the same will need to be done to the "remove one" button.

Again, the most important step is adding the unique `#name` attribute for all buttons for all items. Once I have added that, everything started working flawlessly here, as the correct `$delta` value is now being used after the callback function.

Hope this helps should anyone else ever run into this problem too.

---
Tags: forms
---


title: Contextual Filters

text:
# Question
Title: Contextual Filters
I have set up a Views Block for an events listing. I have set up a taxonomy vocabulary for Groups and have an extensive list under that. I have set up a Content Type for Events that has a field for the taxonomy list of events. What I need to do is when a visitor goes to that specific Group's page, there will be a listing of events specific to that group.

I have filtered the View by Content Type = Events. I can't wrap my head around how I will only show on each group page events under that group. Is this using Contextual Filters? Thanks!

# Answer
> 2 votes
To answer your question: Yes, I believe this is achievable using contextual filters.

To be more specific: I believe you'll be able to find a contextual filter "Content: Has taxonomy term ID". It's hard to be able to give you the information on what should go in here without knowing how the pages are constructed. But, for example, if you had pages that had the taxonomy term ID (for the Groups vocabulary) in the url, you could select:

Provide default value \> Taxonomy term ID from URL. **You may have to use "Raw value from URL" and select 2 under path component because of how your urls are constructed**

There's also "Specify validation criteria".

Select "Taxonomy term" from that and you can limit it by vocabulary or even convert taxonomy term names into IDs.

To use a taxonomy term name from the url under "Filter value type" select "Term name" or "Term name converted to Term id" (note, it is much safer to use taxonomy term ids in the url as terms with the same name can not be distinguished). If you are using term names make sure you check "Transform dashes in URL to spaces in term name filter values"

Hope that answers your question :)

---
Tags: views
---


# Question
Title: hook_field_extra_fields: hidden by default
When implementing hook\_field\_extra\_fields(), can I make the extra field hidden by default?

Sometimes it is friendlier to offer the extra fields as an option, instead of displaying it immediately after a module is enabled.

# Answer
In `_field_info_prepare_extra_fields()` the extra fields are set to visible by default, but the extra field settings are stored in the field\_bundle\_settings variable which you can change in your module's `hook_install()` like:

```
$entity_type = 'node';
$bundle = 'article';
$field_name = 'my_extra_field';
$view_mode = 'teaser';

$field_bundle_setting = variable_get('field_bundle_settings', array());
$field_bundle_setting[$entity_type][$bundle]['extra_fields']['display'][$field_name][$view_mode]['visible'] = FALSE;
variable_set('field_bundle_settings', $field_bundle_setting);

```
> 5 votes

# Answer
\_field\_extra\_fields\_pre\_render(), the pre-render callback used by field\_attach\_form() and field\_attach\_view(), contains the following code:

```
  elseif (isset($elements['#view_mode'])) {
    $view_mode = $elements['#view_mode'];
    $extra_fields = field_extra_fields_get_display($entity_type, $bundle, $view_mode);
    foreach ($extra_fields as $name => $settings) {
      if (isset($elements[$name])) {
        $elements[$name]['#weight'] = $settings['weight'];
        // Visibility: make sure we do not accidentally show a hidden element.
        $elements[$name]['#access'] = isset($elements[$name]['#access']) ? ($elements[$name]['#access'] && $settings['visible']) : $settings['visible'];
      }
    }
  }

```

Implementing hook\_field\_extra\_fields\_display\_alter(), you can alter the visibility setting, but that would make the field not visible all the time the form is displayed. If you want not to show the field when the form is first loaded, and show it when, for example, another form field is selected or its value is changed, then you need to use some JavaScript code.

```
function mymodule_field_extra_fields_display_alter(&$displays, $context) {
  if ($context['entity_type'] == 'taxonomy_term' && $context['view_mode'] == 'full') {
    $displays['description']['visible'] = FALSE;
  }
}

```
> 3 votes

# Answer
There is a patch to add this ability to drupal core.

If you want to see this go in please review it and give feedback.

http://drupal.org/node/1256368#comment-7201552
> 2 votes

# Answer
In the install hook of your module you can make a call to a function similiar this one and it will bulk hide your extra fields by default.

```
/**
 * Sets default visibility of extra fields in all active view modes on entity bundles.
 *
 * This will not overwrite visibility that already exists in the variable.
 *
 * @param  array $extra_field_names An array of extra fields
 * @param  string $entity_type       The name of the entity type. Defaults to 'node'.
 * @param  array $bundles           An array of bundle objects or names.
 */
function my_module_hide_extra_fields($extra_field_names, $entity_type = 'node', $bundles = NULL) {
  $entity_info = entity_get_info($entity_type);
  if ($bundles === NULL) {
    $bundles = array_keys($entity_info['bundles']);
  }

  foreach ($bundles as $bundle) {
    if (!is_string($bundle)) {
      $bundle = $bundle->type;
    }
    $settings = field_bundle_settings($entity_type, $bundle);

    $active_modes = array('default');
    foreach ($settings['view_modes'] as $mode => $mode_settings) {
      if ($mode_settings['custom_settings']) {
        $active_modes[] = $mode;
      }
    }
    foreach ($extra_field_names as $field_name) {
      foreach ($active_modes as $mode) {
        if (empty($settings['extra_fields']['display'][$field_name][$mode])
          || !array_key_exists('visible', $settings['extra_fields']['display'][$field_name][$mode])) {
          $settings['extra_fields']['display'][$field_name][$mode]['visible'] = FALSE;
          $settings['extra_fields']['display'][$field_name][$mode] += array(
            'weight' => 0,
          );
        }
      }
    }
    field_bundle_settings($entity_type, $bundle, $settings);
  }
}

```
> 2 votes

# Answer
So much simpler example. For Drupal 7 Create example\_module.install under the example\_module directory

```
/**
 * hook_install
 */

function example_module_install() {
  $field_machine_name = 'new_extra_field';
  $entity_types = array('node', 'taxonomy_term', 'user');
  foreach ($entity_types as $type) {
    $info = entity_get_info($type);
    $settings = field_bundle_settings($type, $bundle);
    $view_modes = array_merge(array('default'), array_keys($info['view modes']));
    foreach($view_modes as $view_mode) {
      $settings['extra_fields']['display'][$field_machine_name][$view_mode] = array(
        'visible' => FALSE,
        'weight'  => 0,
      );
    }
    field_bundle_settings($type, $bundle, $settings);
  }
}

```

Documentation for hook\_install https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_install/7

In your example\_module.module file add

```
 /**
  * Implementation of hook_field_extra_fields
  *
  */
 function example_module_field_extra_fields() {
   $extra = array();
   $field_machine_name = 'new_extra_field';
   $entity_types = array('node', 'taxonomy_term', 'user');
   foreach ($entity_types as $type) {
     $info = entity_get_info($type);
     foreach(array_keys($info["bundles"]) as $bundle) {
       $extra[$type][$bundle]['display'][$field_machine_name] = array(
         'label' => t('New extra field that will show up in manage display'),
         'description' => 'A description for the extra field',
         'weight' => 5,
        );
     }
   }
   return $extra;
 }

```

Documentation for hook\_field\_extra\_fields https://api.drupal.org/api/drupal/modules%21field%21field.api.php/function/hook\_field\_extra\_fields/7
> -1 votes

---
Tags: 7, entities
---


title: theme contact form block

text:
# Question
Title: theme contact form block
I am using contact\_form\_blocks-7.x-1.x-dev module. Using this module I have embedd contact us form in my website. For themeing I have created file named **block--contact.tpl.php**. Cleared cache, but it doesnt result anything.
How should I theme this contact us form?

# Answer
> 0 votes
For themeing contact form we can use the FORM\_ID which is contact\_site\_form. The code snippet will be as follows

```
function myTheme_theme() {
  return array(
'contact_site_form' => array(
'render element' => 'form',
'template' => 'contact-site-form',
'path' => drupal_get_path('theme', 'myTheme').'/templates',
),
  );
}
function myTheme_preprocess_contact_site_form(&$vars) {
$vars['contact'] = drupal_render_children($vars['form']);

}

```

That should get you the ability to create a template file called contact-site-form.tpl.php.

# Answer
> -1 votes
If you want to theme contact form then you can do it using `hook_form_alter()`.

Use `hook_form_alter(&$form, &$form_state, $form_id)` in your theme's template.php and alter the form the way you want to theme it.

---
Tags: theming
---


# Question
Title: Can I Run custom callback in site maitenance mode
In drupal site maintenance mode all custom menu callback is not working. it redirect into site maintenance page. But user/login is working. I need to create menu like user/login. please help me.

# Answer
If you want to test few menu item when Drupal site is in maintenance mode. You can use Maintenance Exempt module.

From this module's page:

> Drupal allows you to set your site into maintenance mode in order to deploy code and database upgrades safely. However, access to the site during maintenance mode is by default controlled by a permission, which is generally only given to administrative users. It's not possible to test the site as a regular anonymous or authenticated user without giving all anonymous/authenticated users the "Use the site in maintenance mode" permission, so you generally have to test those things on the fly after moving the site back to "live" mode.
>
> Until now, that is! This D7+ module (the necessary hook doesn't exist in D6 and below) allows specific people to perform the necessary testing on the site with all role combinations without opening the site up to all of your visitors.
> 2 votes

# Answer
Hi MutantMahesh & TBI Infotech

I got the answer,

The user module implements that hook (user\_menu\_site\_status\_alter()) to make sure the site is always online for the user, user/login, user/password and user/reset/\* paths. It should be simple enough to use the logic from that function to implement it for your custom path, e.g.

```
function MYMODULE_menu_site_status_alter(&$menu_site_status, $path) {
  if ($menu_site_status == MENU_SITE_OFFLINE && $path == 'my-path') {
    $menu_site_status = MENU_SITE_ONLINE;
  }
}

```

Just let you know..
> 1 votes

# Answer
**Site maintenance** is meant to work like this that no operation can be performed on site when it is in `maintenance mode` . The only user login page is accessible so the user with permission to edit the site can login.

Normally if you log in with `admin` user, you can access each and every part of the site. With admin credentials you custom callback functions will work too.

But if you are trying to access these pages with `anonymous user` or `user with no permissions` to edit content. Then you will automatically get redirected to the maintenance page.

Just try it with admin login.

Hope it will help you.
> 0 votes

---
Tags: routes, maintenance-mode
---


# Question
Title: Use an image instead of a menu link in Drupal 7
I have a menu in my page that I have created. I have a link called 'Home', and I want an image to be there for only this link. I saw many modules for Drupal 6. Is there any hook or module in Drupal 7 to do this?

# Answer
I am answering my own question, as I googled and found something, mixed it and carved my own way to do it.

```
function mytheme_menu_link(array $variables) {
  global $base_path;
  $element = $variables['element'];
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  if($element['#title'] == 'Home') {
    $element['#localized_options']['html'] = TRUE;
    $get = '<img src="' . $base_path . drupal_get_path('theme', 'arras') . '/linkback.png" style="vertical-align: middle;" alt="' . $element['#title'] . '" title="' . $element['#title'] . '" />';
    $output1 = l($get,$element['#href'], $element['#localized_options']);
    return '<li' . drupal_attributes($element['#attributes']) . '>' .$output1    . "</li>\n";
  } else {
    return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . "</li>\n";
  }
}

```
> 3 votes

# Answer
To tweak the answer of Hacker:

If you use fontawesome you could use these nice icons. Then you don´t need to worry about image upload...

The code in yout tempate.php could look like this:

```
function THEME_menu_link(array $variables) {
  global $base_path;
  $element = $variables['element'];
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  if($element['#title'] == 'Home') {

$element['#localized_options']['html'] = TRUE;
$get = '<i class="fa fa-home fa-lg"></i>';
$output1 = l($get,$element['#href'], $element['#localized_options']);
return '<li' . drupal_attributes($element['#attributes']) . '>' .$output1    . "</li>\n";
  } else {
return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . "</li>\n";
  }
}

```

See The Icon library of fontawsome for more examples for the classname (fa fa-home fa-lg)
> 1 votes

---
Tags: theming
---


# Question
Title: Drupal 7 hook_validate not called with custom form template
I received a pretty strange problem trying to customize custom form's template. So while form's template stay untouched (drupal core's form template was used) validation works just fine, but when I add some specific templates to my theme, validation just not working at all. Submitting a form just doesn't gives anything - MYMODULEFORM\_form\_validate and MYMODULEFORM\_form\_submit hooks are not called after form been submitted.

```
function MYTHEME_theme ()
{
    $items['MYMODULEFORM_1_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'MYTHEME') . '/templates',
        'template' => 'template_1_filename',
    );
    $items['MYMODULEFORM_2_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'MYTHEME') . '/templates',
        'template' => 'template_2_filename',
    );
    $items['MYMODULEFORM_3_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'MYTHEME') . '/templates',
        'template' => 'template_3_filename',
    );

    return $items;
}

```

When I print out $form variable inside the template file *#validate* and *#submit* elements are present and correct. Do you have any ideas what can cause this problem I just stucked at this. Thank you!

# Answer
> 0 votes
**SOLUTION:** Was only needed to add `print drupal_render_children($form);` at the bottom of the template file.

---
Tags: forms, theming
---


title: Add number of items as a class to menus

text:
# Question
Title: Add number of items as a class to menus
I would like to add a class to menu that shows how many items are in that particular level. I.E.

```
<ul class="menu count-5">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

```

What's the best way to do this?

I've looked at theme\_menu\_tree but the tree is already rendered html by that point so there is no easy way to count the number of items.

# Answer
It really feels like there should be a better way to do this (but I can't find one at the moment, `theme_menu_link()` isn't context-aware of its parent menu); however this will work:

```
function MYMODULE_menu_tree(&$variables) {
  // Load the current HTML into a DOMDocument to count the links
  $doc = new DOMDocument;
  $doc->loadHTML('<ul class="identifiable-string">' . $variables['tree'] . '</ul>');

  // XPath query to find only top-level <li>s
  $xpath = new DOMXPath($doc);
  $lis = $xpath->query('//ul[@class="identifiable-string"]/li');

  // Get the count based on the number of elements returned
  $count = 0;
  if ($lis) {
    foreach ($lis as $li) {
      $count++;
    }
  }

  return '<ul class="menu count-' . $count . '">' . $variables['tree'] . '</ul>';
}

```

It seems like a huge amount of effort (not to mention processor power) for not much reward, but if you're struggling then this method will definitely work.
> 2 votes

# Answer
If you are willing to do that with jQuery.

```
var num_links = jQuery('.menu > li').length;
jQuery('.menu').addClass('count-'+num_links);

```
> 1 votes

# Answer
The API function you want is theme\_menu\_link(). The information about each menu link's child menu items is available in this function. You will need to count the child menu items and use that count as part of your class. However, the array that holds the child menu items also holds other information.

The following implementation of theme\_menu\_link() worked for me with a quick, superficial test:

```
function THEMENAME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
    $count = 0;
    foreach($element['#below'] as $key=>$item) {
      //the child menu items' keys are their mlid, which is numeric
      //most other items in this array will not have numeric keys
      if(is_numeric($key)) {
        $count ++;
      }
    }
    $element['#attributes']['class'][] = 'count-'.$count;
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```
> 0 votes

# Answer
You can still use theme\_menu\_tree(), just explode the tree into an array.

Something like this should work:

```
function THEMENAME_menu_tree($variables) {
$menu_items = explode('</li>', trim($variables['tree']));
$count = count($menu_items);

  return '<ul class="menu count-'.$count.'">' . $variables['tree'] . '</ul>';
}

```
> 0 votes

# Answer
As pointed out here:

https://stackoverflow.com/questions/7176013/how-can-count-the-children-of-drupals-main-menu

it is possible to use menu\_tree\_page\_data.

You could thus use this in combination with `theme_menu_tree`, for instance:

```
function MYMODULE_menu_tree(&$variables) {
  $count = count(menu_tree_page_data('main-menu'));
  return '<ul class="menu count-' . $count . '">' . $variables['tree'] . '</ul>';
}

```

Please note that this will trigger for every single menu that displays in your page and it will always return the number of items of the menu 'main-menu'.

If you want to tailor it to a specific menu, you'd have to implement `THEMENAME_menu_tree__MENU_NAME()` in order to override the function for a specific menu.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Rules - After updating / saving user not working
I'm using Rules module to execute a python script after a user has been created / updated. This python script retrieves information of users from the database and feeds a datapushing / realtime data engine.

Everything works perfect, BUT, the script is executing before saving.

**Update regarding 'script is executing before saving'**

When I get the information from the DB with the python script is the one I have before saving, the only workaround is saving twice. One to make changes, to second one to 'really' update. I've noticed this because I need to save twice to get real information.

I found this issue: http://drupal.org/node/430274

I thought on running the script in Drupal's User Core but good practices kind of don't let me do it ( for now :) )

**Update**

I created a Module with this Info

```
<?php
// $Id: infographic.module

/**
* @file
* Custom functions for this site.
*/
function infographic_user_insert(&$edit, $account, $category) {
    exec('python GenerateInfographic.py');
}

function infographic_user_update(&$edit, $account, $category) {
    exec('python GenerateInfographic.py');
}

```

Any Suggestion!?

Thanks!

# Answer
You can use `hook_user_insert` and `hook_user_update` to execute your script, which is called after the user has been saved to the database.

Hooks should be implemented in a module. If you are new to module development, the Drupal documentation describes this very well: http://drupal.org/documentation
> 1 votes

# Answer
At least in D7, it worked for me calling

```
user_save($account);

```

at first. this it is if u need it changed in the own custom php rules code. I try to debug a message before/after that line of a load user and it seemed to work.

Actually, it didn't because i needed it changed because i was calling a script and in the script was getting the bad one, and i didn't have access to change that script.

So finally what it worked for me was calling the script in background:

```
$comando='php -f /var/www/moodle/auth/drupalservices/auth_drupalservices_sync_users.php '.$idUser.' >/var/tmp_files/output.txt &';
exec($comando);

```

and in the script putting a little sleep so i was sure was already changed in the other side :)

```
sleep(3);

```
> 0 votes

---
Tags: rules
---


# Question
Title: Views Rewrite Results Shows "Delete Comment" shows as text to anonymous users
I'm using a views to show my comments. I've Rewrite Results and add a delete comment field.

When users login they can click on the link and delete the comment

But when a user is logout any user can see \[delete\_comment\] token

How do I hide the \[delete\_comment\]token from anonymous users please?

# Answer
> 0 votes
set the permissions for anonymous users that they can't see or delete the comment.

---
Tags: views, comments
---


# Question
Title: Don't let user register without role/profile2 profile?
I created a site for a client that lets users register an account of either one out of two roles, which then is linked to one of two profile2 types.

Therefore my client wanta no other being able to register without one of these roles/profiles so i did a 301 direct from $site/user/register to in .htacces. It works, as I see it, but somehow users/bots seem to be able to get passed this and register accounts without a role anyway.

Any ideas how to secure this in a better way than currently?

Daniel

# Answer
Best way to close all ways of creating users without that profile is adding a custom validation function for the user\_register form.

In that validate handler just make sure that the form values are right and a user with a profile2 node will be created when form is processed (submit handlers are executed).

Use a form alter to add your validate.

This way you enforce the creation of valid user only where all user creation happen, the the user register form (except admins).
> 0 votes

---
Tags: users
---


title: Dependent Selects to feed on taxonomies

text:
# Question
Title: Dependent Selects to feed on taxonomies
I'm trying to create a module that generates a block with Dependent Selects to feed on taxonomies, I mean the first would be the term father Select first level and then display a Select with the children of that term and so on, this is the code that I have so far:

`/**
 * Implements hook_block_view().
 */
 function bloque_busqueda_block_view($delta = '') {
 switch($delta) {
 case 'bloque_busqueda' :
 $block['subject'] = t('Criterio de busqueda');
 $block['content'] = bloque_busqueda_block_content();
 return $block;
 break;
 }
 }`

````
function bloque_busqueda_block_content() {
    return drupal_get_form('ajax_dependent_dropdown');
}

function ajax_dependent_dropdown($form, &$form_state) {
    $options_first = _ajax_get_first_options();
    $selected = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : key($options_first);

    $form["dropdown_first"] = array('#type' => 'select', '#title' => 'Seccion', '#options' => $options_first, '#ajax' => array('callback' => 'ajax_dependent_dropdown_first_callback', 'wrapper' => 'dropdown-second-replace', ), );

    $form["dropdown_next"] = array('#type' => 'select', '#title' => $options_first[$selected] . ' ' . t('Subseccion'), '#prefix' => '

```

', '#suffix' => '
', '#options' => _ajax_get_next_options($selected), );

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

    return $form;
}

function ajax_dependent_dropdown_first_callback($form, $form_state) {
    return $form["dropdown_next"];
}

/**
 * Retorna el tid de la taxonomía actual.
 */
function current_tid() {
    $term = taxonomy_term_load(arg(2));
    return $term -> tid;
}

/**
 * Mide la profundidad de la taxonomía.
 */
function term_depth($tid) {
    $tid = db_query("SELECT tid FROM {taxonomy_term_hierarchy} WHERE parent = :parent", array(':parent' => $tid)) -> fetchField();
    if ($tid == 0) {
        return 1;
    } else {
        return 1 + term_depth($tid);
    }
}

function _ajax_get_first_options() {
    $terms = taxonomy_get_children(current_tid());
    foreach ($terms as $term) {
        $options[$term -> tid] = $term -> name;
    }
    return $options;
}

function _ajax_get_next_options($key = '') {
    $options = array();
    $tid = arg(2);
    $tree = taxonomy_get_tree($vid = 2, $tid);

    foreach ($tree as $term) {
        if ($term -> depth == 0) {
            $parent = $term -> tid;
        } else {
            if ($term -> depth > 1) {
                $options[$parent][$term -> tid] = str_repeat('-', $term -> depth) . ' ' . $term -> name;
            } else {
                $options[$parent][$term -> tid] = $term -> name;
            }
        }
    }

    if (isset($options[$key])) {
        return $options[$key];
    } else {
        return array();
    }

}

````

Thanks

# Answer
you can use hierarchical\_select module for this .
> 0 votes

---
Tags: forms
---


title: Drupal 7 view's operator "Is one of"

text:
# Question
Title: Drupal 7 view's operator "Is one of"
In Drupal 5 there was a possibility to filter our content type's NIDs using "is one of" operator. So I have a view where I only used one filter like

```
Node: Node ID -> Is One Of -> <?php return callback_function() ?>

```

This *callback\_function()* returns an array of NIDs and my view works just perfect. While moving project to Drupal 7 I discovered that there is no more such operator. Does anybody knows any possibility to use this good old "Is One Of" operator? Thank you!

# Answer
> 1 votes
Solution was to use *View PHP* module and *Global: PHP* field in filters.

---
Tags: views
---


title: Getting redundant records

text:
# Question
Title: Getting redundant records
> $result = $query-\>entityCondition('entity\_type', 'node')
>
> > -\>entityCondition('bundle', 'mypage')
> > -\>fieldCondition('field\_mymodule\_module','tid', 123,'=')
> > -\>execute();
>
> $nids = array\_keys($result\['node'\]);
>
> $or = db\_or();
>
> foreach($nids as $nid)
>
> > $or-\>condition('m.entity\_id', $nid, '=');
>
> $query2 = db\_select('metatag', 'm')
>
> > -\>fields('m', array('entity\_id', 'revision\_id', 'language', 'data')) -\>condition('m.entity\_type', 'node') -\>condition($or) -\>orderBy('entity\_id') -\>orderby('revision\_id') -\>execute();
>
> while ($record = $query2-\>fetchAssoc()) {
>
> > ```
> > dpm($record);
> >
> > ```
> >
> > }

As you can see in above code, I'm trying to get metadata information of each node. Getting nids of them turns out to be easy. However, when I use those nids to retrieve metadata, I get so many identical ones. That problem persists even after I removed "or" statement from the db\_select and hard-coded entity\_id, it returns like 10 identical records. Can anyone shed a light on the problem and where I am doing wrong here?

# Answer
> 0 votes
$result = $query-\>entityCondition('entity\_type', 'node')

```
        ->entityCondition('bundle', 'mypage')
        ->fieldCondition('field_mymodule_module','tid', 123,'=')
        ->execute();

    $nids = array_keys($result['node']);
    $array=array();

    foreach($nids as $nid)

{
    $query2 = db_select('metatag', 'm')

    ->fields('m', array('entity_id', 'revision_id', 'language', 'data')) ->condition('m.entity_type', 'node')

```

-\>condition('m.entity\_id', $nid, '=') -\>orderBy('entity\_id') -\>execute()-\>fetchAssoc();

```
$array[]=$query2

        }

$array contains all fields value.traverese this array.
Hope this will give you result.

```

---
Tags: 7, database
---


# Question
Title: bypass a character limitation rule (webform)
Maybe someone could help me ...

Ive got a webform with an input (postal code). I want its maxlength to be 5.

When users fill it, once the 5 digits entered, an autocomplete callback retrieves corresponding cities.

When a city is chosen, the input content is rewritten like "XXXXX - CITY". Now the field length is more than 5.

When the form is submitted, it is not validated.

I would like to bypass the validation of this specific property (maxlength) ...

Is it possible ?

# Answer
> 0 votes
you will need to write your own validation function - borrowed from here:

Adding custom validation rules - Webform Validation hooks

Last updated January 7, 2014. Created by svendecabooter on September 11, 2010. Edited by Liam Morland, wundo, crystaldawn. Log in to edit this page.

This page describes how to write custom validation rules for your webforms. This requires installation of the Webform and Webform Validation modules.

The following code should be implemented in your own custom module.

Adding custom validation rules The following steps will let you add custom validators through your module:

1/ Implement hook\_webform\_validation\_validators(). This hook implementation should return an array of validator key =\> options array entries. The options array can contain the following configuration keys:

name (required): name of the validator

component types (required): defines which component types can be validated by this validator. Specify 'all' to allow all types

custom\_error (optional): define whether a user can specify a custom error message upon creating the validation rule.

custom\_data (optional): define whether custom data can be added to the validation rule

min\_components (optional): define the minimum number of components to be selected for creating a validation rule

max\_components (optional): define the maximum number of components to be selected for creating a validation rule

description (optional): provide a descriptive explanation about the validator See function webform\_validation\_webform\_validation\_validators() in

webform\_validation.validators.inc for a live example

2/ Implement hook hook\_webform\_validation\_validate($validator\_name, $items, $components, $rule). This hook gets passed 4 parameters, which will allow you to react to your custom validator (or any other validator for that matter). Explanation about these parameters:

$validator\_name: this is the validator name (i.e. array key as entered in hook\_webform\_validation\_validators)

$items: array containing user submitted entries to be validated. $components: this array contains the definitions of the webform components in your form

$rule: this array contains the details of your validation rule See function webform\_validation\_webform\_validation\_validate() in webform\_validation.validators.inc for a live example

Additional hooks The hook hook\_webform\_validation($type, $op, $data) can be used to react on various webform\_validation based actions.\`

$type - possible values: 'rule'

$op - possible values: 'add', 'edit', 'delete'

$data - array with rule data in case of $op add/edit, rule id in case of $op delete.

The hook hook\_webform\_validator\_alter(&$validators) can be used to alter the array of validators that is being generated by hook\_webform\_validation\_validators().

$validators - array of validators as supplied by modules implementing hook\_webform\_validation\_validators(). Example

```
<?php
/**
 * Implements hook_webform_validation_validators().
 */
function idvalidation_webform_validation_validators() {
  return array(
    'validate_id' => array(
      'name' => "Validate ID",
      'component_types' => array(
        'textfield',
      ),
    )
  );
}
/**
 * Implements hook_webform_validation_validate().
 */
function idvalidation_webform_validation_validate($validator_name, $items, $components, $rule) {
  if ($items) {
    switch ($validator_name) {
      case 'validate_id':
        $valid_ids = array(1, 2, 3); // get this from database source instead
        foreach ($items as $key => $val) {
          if ($val && (!in_array($val, $valid_ids))) {
            $errors[$key] = t('%item is not a valid ID', array('%item' => $components[$key]['name']));
          }
        }
        return $errors;
        break;
    }
  }
}
?>

```

---
Tags: webforms, forms
---


# Question
Title: Conditional display of CCK field for certain profiles values
I have created a content type with CCK on Drupal 7, and I would like to display only a few fields according to certain values in their profile2 type.

Concretely, I have a profile2 field to specify if the member is VAT registered or not. When the members are submitting their invoices, I want to display specific fields if they are VAT registered.

# Answer
for this you have to create a field on your content type called vat registered or not. Autofill that field from profile 2 field for the specific users. Then use conditional module. If that field is filled by default show some fields otherwise do not show that fields.
> 1 votes

# Answer
you will likely need to use hook\_form\_alter in a custom module. The simplest way is to create the ecommerce section WITH the VAT fields as default, and then hide the fields if a condition is met (the profile doesn't contain the VAT). exactly how depends on field names and a few variables like accessing profile2 info that I'm not sure about, but this is the basic setup I think:

```
function mymodule_form_alter(&$form, $form_state, $form_id)  {

    // get Devel module(https://www.drupal.org/project/devel) for this line
    dpm($form_id);
    // this will output information on ALL forms - remove when complete, but use this to
    // get the correct form machine name if you can't find it elsewhere, as well as
    // determining the correct structure of the form in order to hide the fields further down

    switch ($form_id)  {
        case 'ecommerce_form':
            // pull data on $user (global $user)
            // you may need to use some direct db access (https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7)
            // to get profile2 info (I don't remember if it links into $user directly or not)
            // if statement - if field in profile contains value (assuming a boolean)
            // if so, do nothing (VAT is set to visible by default)
            // if not, hide VAT fields
            break;
     }
  }

```

do a simple search for modifying a form (hiding an element), there are thousands of examples and tutorials out there.

helpful link: Form API \- reference on form manipulation
> 0 votes

---
Tags: entities, users
---


title: How to print specific fields in a view?

text:
# Question
Title: How to print specific fields in a view?
I have 3 content types:

* Country
* Destination
* Attraction

Each attraction has an entity reference poiting to Destination. Each destination has an entity reference poiting to Country.

I need to create a view in a block, published on all content types Country that lists all Destinations within that country and the number of attractions within each Destination. For example, France destinations are Paris and Marseille. Paris has Eiffel Tower, Louvre and Pont Neuf as attractions. Marseille has Chateau d'If and Panier as attractions. In my country node I should be able to print: Paris (3) Marseille (2) I only need the title and that particular number, with links on title going to their specific nodes.

How could that be achieved? I was thinking about aggregation but I have tried to do so and failed. Thank you!

# Answer
try:

under Advanced Tab, create a relationship. the type will depend on your field names exactly, but if the view is for the country, you should be able to find the destination and attraction fields available.

the new related fields should show up now in your Fields list and you can add them to the view

For the count, try the following:

Entity Reference Count or Entity Reference Calc or take a look at this on SO
> 0 votes

---
Tags: views, entities
---


# Question
Title: validation question for webform validate
I need to validate that a field does not contain only numbers. in other words it can have some numbers but must have some letters as well. Can someone help me with the regex to do that?

I am using webforms 7.x-3.18+3 and webforms validation 7.x 1.1

thanks

# Answer
> 1 votes
Here are the steps you'll need to follow:

1. Go to your webform
2. Select the "form validation" button.
3. under the "Add a validation rule" select "Regular expression, case-sensitive"
4. For the regex, you can use `^\d*$` and check the negate rule box below

OR

1. Go to your webform
2. Select the "form validation" button.
3. under the "Add a validation rule" select "Regular expression, case-sensitive"
4. For the regex, you can use `[^\d]+`

---
Tags: webforms
---


# Question
Title: EntityMalformedException in custom module. Can anyone see what I did wrong?
I'm trying to create a custom module and found out that it's causing the following error message to appear:

EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7721 of ~/includes/common.inc).

```
if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
  throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
}

```

I'm using xdebug setup with netbeans to debug the error and found out what is causing the culprit.

I found out it was a specific field I added in my module that looks like this:

```
$form['base']['st-volume-pricing']['add'] = array(
'#type' => 'button',
'#value' => t('Add'),
'#name' => 'add_row',
'#limit_validation_errors' => array(
  array('price'),
  array('till-amount'),
),
'#ajax' => array(
  'callback' => 'bulk_and_user_pricing_add_volume_standard_ajax_callback',
  'wrapper' => 'error-placeholder',
  'method' => 'append',
  'effect' => 'fade',
),
'#prefix' => '<td>',
'#title' => t('Click this button to add a standard volume price'),
);

```

My debugger basically showed the following data:

```
$info['entity keys']['bundle'] = "type"
$entity_type = "node"

$entity stdClass
add string  "Add"
add_row string  "Add"
price   string  "123"
till-amount string  "123"

```

I checked my database and couldn't find any nodes without type so that shouldn't cause any problems.

I suppose I have to define the bundle in my code somewhere but I'm not that famillair with bundles yet.

The field is added to the node edit page of a product created by the ubercart module using `hook_form_FORM_ID_alter() -> hook_form_product_node_form_alter()`.

Does anyone have a clue as to what I should do to define the bundle?

Or in OOP terms, how can I make my field a class member of the ubercart product bundle (which is an extended class of the entity type base class)?

# Answer
Please check Examples, specifically entity\_example module to check how to define the bundle.

So for Drupal 7 it goes like:

```
/**
 * Implements hook_entity_info().
 *
 * This is the fundamental description of the entity.
 *
 * It provides a single entity with a single bundle and without revision
 * support.
 */
function entity_example_entity_info() {
  $info['entity_example_basic'] = array(
    // A human readable label to identify our entity.
    'label' => t('Example Basic Entity'),

    // The controller for our Entity, extending the Drupal core controller.
    'controller class' => 'EntityExampleBasicController',

    // The table for this entity defined in hook_schema()
    'base table' => 'entity_example_basic',

    // Returns the uri elements of an entity.
    'uri callback' => 'entity_example_basic_uri',

    // IF fieldable == FALSE, we can't attach fields.
    'fieldable' => TRUE,

    // entity_keys tells the controller what database fields are used for key
    // functions. It is not required if we don't have bundles or revisions.
    // Here we do not support a revision, so that entity key is omitted.
    'entity keys' => array(
      // The 'id' (basic_id here) is the unique id.
      'id' => 'basic_id' ,
      // Bundle will be determined by the 'bundle_type' field.
      'bundle' => 'bundle_type',
    ),
    'bundle keys' => array(
      'bundle' => 'bundle_type',
    ),

    // FALSE disables caching. Caching functionality is handled by Drupal core.
    'static cache' => TRUE,

    // Bundles are alternative groups of fields or configuration
    // associated with a base entity type.
    'bundles' => array(
      'first_example_bundle' => array(
        'label' => 'First example bundle',
        // 'admin' key is used by the Field UI to provide field and
        // display UI pages.
        'admin' => array(
          'path' => 'admin/structure/entity_example_basic/manage',
          'access arguments' => array('administer entity_example_basic entities'),
        ),
      ),
    ),
    // View modes allow entities to be displayed differently based on context.
    // As a demonstration we'll support "Tweaky", but we could have and support
    // multiple display modes.
    'view modes' => array(
      'tweaky' => array(
        'label' => t('Tweaky'),
        'custom settings' => FALSE,
      ),
    ),
  );

  return $info;
}

```

Or for simpler example, entity.api.php from Entity module which goes like:

```
function entity_crud_hook_entity_info() {
  $return = array(
    'entity_test' => array(
      'label' => t('Test Entity'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIController',
      'base table' => 'entity_test',
      'module' => 'entity_test',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'pid',
        'name' => 'name',
        'bundle' => 'type',
      ),
      'bundles' => array(),
    ),
  );
  foreach (entity_test_get_types() as $name => $info) {
    $return['entity_test']['bundles'][$name] = array(
      'label' => $info['label'],
    );
  }
  return $return;
}

```

The error EntityMalformedException which you're having it's saying that your bundle property is malformed on save, so Drupal core can't identify what type (bundle) is that.

Troubleshooting:

1. Check what's the value of `bundle` in `entity keys` section of array defined in entity information array via:

```
drush eval 'print_r(entity_get_info("entity_type"));'

```
2. If it's `type`, then that means your entity which you're trying to save, it's missing `type` attribute.

The common mistake is usually to load the entity via entity\_load() and trying to re-save it, but remember that return value is an array of entity objects indexed by their ids.

So the simple test to verify if your entity re-saving works correctly, it would be:

```
drush eval '$entity = entity_load("entity_type", array(1)); entity_get_controller("entity_type")->save(reset($entity))'

```

where entity\_type is your `entity_type` and `1` is your entity id.
> 1 votes

---
Tags: nodes, ubercart, entities
---


# Question
Title: Changes to Input Formats not saving: Default instance field is required
When trying to make any changes to any text format, when I click "Save" Drupal returns an error message: "Default instance field is required." and the changes are not saved. Screenshot: http://awesomescreenshot.com/0ff38my7f7 (Drupal version 7.30.)

Can anyone suggest what could be causing this?

# Answer
> 1 votes
I was getting this error because of qTip filter (https://www.drupal.org/project/qtip) which had a required field that wasn't visible on the text format page because qTip filter wasn't selected. The required field was still part of the form (visible in source) even though it was invisible in the rendered page.

---
Tags: input-formats
---


# Question
Title: How to set header and footer for any drupal_mail messsage?
I am working with drupal 7 site.

I would like to know how to create email template for any email sent from drupal system?

Is there any hook or template should I implement in my custom module or override to make it beautiful like any newsletter emails are received.

I want following emails should be theming.

1. User Activation User
2. Password reset
3. Comment Notification etc...

Email template should looks like

```
<header>
Dear <User>
<Message Body goes here>
Thanks
<footer>

```

# Answer
Take a look at hook\_mail. All emails from the system "should" go through that. You can alter the $message\['body'\] to add your header and footer. If you only want to do this for certain emails, you can use an IF condition on the $key.

Edit: I think I pointed you to the wrong hook. You probably want to use hook\_mail\_alter to change every email that Drupal sends.
> 1 votes

# Answer
You can use htmlmail module. which allow you to create template for your email and allow you theme your mail with Echo module. Even you can add your logo, header, footer and any other information with echo module. See detail on these two project's page.
> 1 votes

# Answer
If you are using custom module or willing to do some custom code then please follow this link How to use drupal\_mail() to send emails with custom template

I think this is what you are looking for.
> 1 votes

---
Tags: theming, emails
---


title: Multilingual site with different domain

text:
# Question
Title: Multilingual site with different domain
Is it possible to make multilingual site with each language has own domain? So I want to manage all domains with one code and database. All languages will be exactly same translated content.

# Answer
> 2 votes
It's quite possible to do. But there may be some cases where you need to do some custom code. That also totally depends on your business requirement.

However, please follow this one How to set different languages for different domains, and display the language switcher accordingly?
In Drupal 7 Domain Access module is the best one to make multi domain sites. This has a helper module called Domain Locale which is what you need I guess from the question asked.

---
Tags: i18n-l10n
---


# Question
Title: Programmatically publishing and unpublishing nodes: anonymous access
We have several nodes that serve as open job postings which need to "open" and "close" on specific dates. In order to accomplish this, we publish and unpublish them accordingly.

We have a query (based on publish unpublished node programmatically) that successfully updates both the `node` table and the `node_revision` table:

```
$result = db_query('update node n
JOIN field_data_field_jobs_date d ON d.entity_id = n.nid and d.revision_id = n.vid
JOIN node_revision r ON n.nid = r.nid and n.vid = r.vid
# Update the node_revision table
SET r.status = IF(
    (
    CURDATE() >= d.field_jobs_date_value
    AND
    CURDATE() <= d.field_jobs_date_value2
    ),1,0
),
# Update the node table
n.status = IF(
    (
    CURDATE() >= d.field_jobs_date_value
    AND
    CURDATE() <= d.field_jobs_date_value2
    ),1,0
)
# Only update our custom content type
WHERE n.type = \'job_posting\'');

```

This successfully updates the node status and node revision status in the database.

However, once a node has been published through this method, anonymous users still cannot see it (and are presented access denied if given a direct link to the node).

We have to manually edit each node and hit the save button for the published status to "take." This leads me to believe that we are omitting some sort of call to node access or something similar that updates the permissions on the node appropriately.

Any ideas besides the status field that may be *preventing anonymous users* from seeing programatically published nodes?

# Answer
The method that you are following to update your nodes/revisions is generally frowned upon by the Drupal community. However, since you seem to know what you are doing and the changes that you perform to the database do not break anything, I can give you a suggestion on how to fix it.

After updating the database table, you can use the node\_load and node\_save functions to programmatically retrieve and save the node using the proper Drupal way. This, is basically the same thing that you are doing by opening and saving the node.

As to why this is happening, you might check the node\_save function's code. Specifically, the fact that you do not update the node access table with something like:

```
    node_access_acquire_grants($node);

```

seems like something that could be causing the issue that you are facing.
> 3 votes

# Answer
Most probably caching. Directly changing something in the database is, though the fastest, not really the safest / most reliable way of doing things in Drupal.

I'd suggest to use enity\_query (or in this case even direct database access) to retrieve node ids of nodes you want to update and then use 'correct' drupal way of doing things -\> load all the nodes, individually change their publish status and save them.

Something along these lines...

```
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // set status property to 1
  $node->status = 1;
  // re-save the node
  node_save($node);
}

```
> 4 votes

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


title: Use views to display not voted polls

text:
# Question
Title: Use views to display not voted polls
I'm using polls (from core) to make some enquetes. Is there a way to use views to display only the polls that a user has not voted yet?

I didn't find anything on google. The only solutions where for Drupal 6. And I'm using drupal 7.

Thanks in advance =)

# Answer
First I tried to use the hook\_views\_pre\_execute.

```
<?php
function hook_views_pre_execute(&$view) {
    $uid = $GLOBALS['user']->uid;

    //gets one the poll and return it
        $query = db_select('node', 'n');
        $query->fields('n');

        $subquery = db_select('poll_vote', '');
        $subquery->fields('poll_vote', array('nid'));
        $subquery->condition('poll_vote.uid', $uid);

        $query->condition('n.nid', $subquery, 'NOT IN');
        $query->condition('type', 'poll');
        $query->condition('status', 1);
        $query->range(0, 1);

    $view->build_info['query'] = $query;
    $view->build_info['count_query'] = $query;
}

```

But when I tried to use the pager, it had too many bugs. It felt like a hack. So in the end I used:

```
<?php
/**
 * Returns a page with one not voted poll
 * @return [array] [drupal page array]
 */
function one_poll_page(){

    $page[] = "";
    $uid = $GLOBALS['user']->uid;

    //gets one the poll and return it
        $query = db_select('node', 'n');
        $query->fields('n');

        $subquery = db_select('poll_vote', '');
        $subquery->fields('poll_vote', array('nid'));
        $subquery->condition('poll_vote.uid', $uid);

        $query->condition('n.nid', $subquery, 'NOT IN');
        $query->condition('type', 'poll');
        $query->condition('status', 1);
        $query->range(0, 1);

        $result = $query->execute();

    foreach ($result as $record) {
      //saves the rendered poll node to the array
      $node = node_load($record->nid);
      $view = node_view($node, 'full');
      $rendered = drupal_render($view);
      $page['#markup'] .= $rendered;
    }

    return $page;
}

```

Because I can then control exactly what the page does.
> 0 votes

---
Tags: views, polls
---


# Question
Title: What is the drush sql-sync arguments for modules, themes, sites, but "not core"?
My live/staging Drupal site on remote host was installed without git version control (I don't even recall, but I guess I used wget). Also it has content, modules and themes I wish to keep. The new dev site is also Drupal 7.x but was installed with git version control. To update the dev server I'm thinking to pull down all the content, modules, etc. See if I can get it running, then push it back into a new git repo on remote.

I've added the necessary alieses, and with drush, I copied everything in sites to the local dev site,

```
drush core-rsync @test:%sites @dev:%sites

```

Now I wish to use `drush sql-sync` to pull down the database for the whole site, but minus core. Reading the drush help file for sql-sync, I can only see:

```
--tables-list  A comma-separated list of tables to transfer.

```

Which puts me in the same boat if I did a dump from MySQL.

*What is the drush sql-sync arguments for modules, themes, sites, but "not core"?*

# Answer
> 3 votes
There are also the `--structure-tables` and `--skip-tables` options. The `--skip-tables` option will completely remove the tables when dumping or syncing, while the `--structure-tables` option will sync table structure but not the data.

I don't think you want to drop the core modules tables in your development enviroment, so I suggest adding the tables to the `--structure-tables` option. You can add configure `drushrc.php` to have the tables listed separately, like this:

```
$options['structure-tables']['common'] = array(
  'cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog');

```

And then you can use the `--structure-tables-key` option:

```
drush sql-sync --structure-tables-key="common" @project.prod @project.dev

```

# Answer
> 0 votes
Drupal simply is not segregated the way that you think that it is. The largest counterexample to your expectation is the "variables" table, an unstructured collection of named variables where core and contrib modules store data.

The --structure-tables and --skip-tables options are occasionally useful; for example, it is possible to transfer users, permissions and roles from one site to another by transferring only these tables. However, in general it is not possible to migrate partial data from a site by carefully selecting tables. In order to be successful at this sort of an operation, you will need to export and then re-import your data. Look at the features or ctools\_export\_bonus modules for configuration, and the migrate module for data.

---
Tags: drush, migrations
---


# Question
Title: Change the default value of the node reference via hook_alter_form
field\_userid is a user reference field with an autocomplete widget

i want to set the default value of this field, but the code below doesn't work

Does anyone can help me?

Thank you very much!

```
 function mymodule_form_node_form_alter(&$form, &$form_state, $form_id)
    {
        global $user;

        if($form['#node']->type=="article")
        {

            $form['#after_build'][]='mymodule_after_build';

        }
    }

    function mymodule_after_build($form, &$form_state)
    {
        global $user;

        $form['field_userid']['#default_value'][0]['uid']=$user->uid;

        return $form;
    }

```

# Answer
> 1 votes
I can't think of any reason why your code would need to be in an `after_build` function, you would usually put it straight into the form alter hook. At the moment you've got the array keys the wrong way round. Without being able to see the structure of your form it's difficult to say exactly where the correct element is, but one of these should work:

```
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  // Try this one
  $form['field_userid'][LANGUAGE_NONE][0]['#default_value'] = $user->uid;

  // Or this one
  $form['field_userid'][LANGUAGE_NONE][0]['uid']['#default_value'] = $user->uid;
}

```

# Answer
> 0 votes
In my case I was trying to use `hook_form_alter()` to assign the current user as **entity reference** (not user reference) of node being created.

First I tried this in `hook_form_alter` but did not work:

```
$form['field_userid'][LANGUAGE_NONE][0]['target_id']['#default_value'] = $user->name;

```

Then I decided to use `hook_node_presave()` instead and this is how I assigned user to node created as entity ref:

```
function answers_node_presave($node) {
  global $user;
  $node->field_original_author[$node->language][]['target_id'] = $user->uid;
  $node->field_original_author[$node->language][]['target_type'] = "user";
}

```

Credit to Clive's answer that led me to my solution.

---
Tags: forms, users
---


# Question
Title: check box with dynamic content and error with submit handler
I have written a form that displays data with check boxes, I want the selected values to concatenate into a string. From the submit button the string would be passed as a URL.Inside the submit handler I tried navigating to localhost but the page doesn't navigate.I this error 'An illegal choice has been detected. Please contact the site administrator.'

Note: I am using a third party software which opens a port on the server and accepts the concatenated values.

```
  function basket_form($form, &$form_state) {
 // Build Breadcrumbs.
    $breadcrumb = array();
    $breadcrumb[] = l(t('Home'), '');
   // Link to current URL.
    $breadcrumb[] = l(drupal_get_title(), current_path());
   // Set Breadcrumbs.
   drupal_set_breadcrumb($breadcrumb);

   // Check for empty session.
  if (!isset($_SESSION['basket']['items'])) {
      drupal_set_title(t('Your basket is empty'));
      $form['empty'] = array(
      '#type' => 'markup',
      '#markup' => t('There is nothing in your basket at the moment.'),
     );
   }
  else {
    $form['clear'] = array(
    '#type' => 'submit',
    '#value' => t('Clear the basket'),
    '#name' => 'clear',
    '#href' => 'basket/clear',
   );

    $form['items']=array(
    '#type'=>'fieldset',
    '#title'=> t('Select from the following')
    );
    foreach ($_SESSION['basket']['items'] as $nid => $data) {
    GLOBAL $url;
    if(strlen($nid)!=0){
      $values = array(
     'biomaterial_id' => $nid
      );
     $features = chado_generate_var('biomaterialprop', $values);
     foreach($features as $f){
       if (preg_match("/bamURL/", $f->type_id->name)){
          if (preg_match("/http/", $f->value)){
             $url=$f->value;
            }
          }
       }
      if(strlen($url)!=0){
        $form['items'][$nid]['name'] = array(
        '#type' => 'checkbox',
        '#title' => t("<a href=biomaterial/$nid>$data[name]</a>"."(bam))"),
        '#options' => array (
         $url => $data['name']
       ),
     );
   }
    else{
       $form['items'][$nid]['name'] = array(
       '#type' => 'checkbox',
       '#title' => t("<a href=biomaterial/$nid>$data[name]</a>"),
     '#options' => array (
          1 => $data['name']),
      );
    }
   }
 }
   $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'IGV',
   );
  return $form;
 }

function basket_form_submit($form, &$form_state) {
    //concatenation help, I tried printing $form_state couldn't see
     anything.
    //"drupal_goto('http://localhost')
    drupal_goto('http://localhost:60151/load?file=concatenated string')
   }
 }

```

# Answer
> 0 votes
Make sure you understand the processing flow of drupal forms. See an illustration here for example: https://www.drupal.org/node/165104

The basic flow is like this:

* First request
    + Form build to represent the form to the user
    + User hits submit which results in a new request to the server
* Second request
    + Form gets rebuild by calling the form builder (`basket_form`)
    + Form gets processed (validate and submit handlers are called)

The error message that you see results from the fact, that after the user hits the submit button, the form is first rebuild. Because you are using the `$_SESSION` to store your values (you should use the `$form_state['values']` array instead) the checkboxes will not be build. And when drupal processes the form after the internal rebuild, it recognizes, that form items have been submitted that are not part of the form.

Also this might help: http://proofgroup.com/blog/2008/jul/debugging\_mysterious\_illegal\_choice\_has\_been\_detected\_please\_contact\_site\_administrato

---
Tags: forms
---


# Question
Title: Is there any online tutorial explains how can I map the requested URL to actions' code in drupal 7?
I'm beginner to Drupal 7. As I know, when the user request for example the URL: (**www.example.com/node/123**) then the Node module will responsible on responding to this request. How can I create a simple php function in my custom module so that it can respond to a specific request generated from my custom page or my custom form submission? for example: **www.example.com/mymodule/blablabla**?

# Answer
You are looking for hook\_menu(), you will need to implement this hook on your custom module to register path in drupal.

> Define menu items and page callbacks.
>
> This hook enables modules to register paths in order to define how URL requests are handled. Paths may be registered for URL handling only, or they can register a link to be placed in a menu (usually the Navigation menu). A path and its associated information is commonly called a "menu router item". This hook is rarely called (for example, when modules are enabled), and its results are cached in the database.

Since you are beginner, First I would suggest you to learn about hook system for drupal.

Checkout this answer for detailed use of hook\_menu.
> 2 votes

---
Tags: 7
---


# Question
Title: Removing main content block on frontpage
I'm new to Drupal 7 and I'm looking to replace the frontpage's default `main content block` with an equivalent block generated from Views (gaining more control over the block in doing so).

I have successfully generated the new frontpage block in Views and added it to the content section however now the homepage displays both the original and the new views block.

Attempting to remove the `main content block` by configuring it to not display on `<front>` does not work and for now the only workaround I have found is the following CSS:

```
.front #block-system-main {
  display:none;
}

```

I'd prefer a less hack-like solution. Can anyone suggest one?

# Answer
> 24 votes
Sorry, but that's not the way to do it.

Instead of creating a block display in Views, create a page display. Choose a path for your views page, for instance "home", and save the view. Next you go to /admin/config/system/site-information and change the value for 'Default front page' (it probably says "node" now) to the path you chose for your view ("home").

When you follow this approach, the main content on your front page will *be* the view.

# Answer
> 2 votes
First of all you have to remove the default home content, here is the way to do that:

```
<?php
function MYTHEME_OR_MODULE_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    $variables['title'] = '';
    unset($variables['page']['content']['system_main']['default_message']);
  }
}

```

Remove homepage default content

Then create the block view that you want.. then go to blocks.. show this block view in "content" region .. and restrict this content to "only the following pages" and write `<front>`

That's it

---

# Answer
> 0 votes
Although not a common approach, you *can* embed a view as main content block on frontpage. Views has the flexibility to do it either way in a wink. I suspect you misconfigured the block removal step you were trying or ... merely had to clear the cache to obtain the same result.

To be fair on the accepted answer, that approach is the usual way of doing it. End result is identical.

---
Tags: 7, views, blocks
---


title: Drush is not able to bootstrap

text:
# Question
Title: Drush is not able to bootstrap
I installed Drush 7 using Composer, and I created a Drupal 8 running on XAMPP on Windows.

1. H:\xampp\htdocs\d8\_test is the Drupal root.
2. Location of settings.php file is H:\xampp\htdocs\d8\_test\sites\default\settings.php.

None of the drush commands are working. All are failing with the same error:

```
H:\xampp\htdocs\d8_test>drush pmi
Command pm-info needs a higher bootstrap level to run - you will need    [error]

to invoke drush from a more functional Drupal environment to run this
command.
The drush command 'pmi' could not be executed.                           [error]

Drush was not able to start (bootstrap) the Drupal database.             [error]

Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version        :  8.0-dev
 Site URI              :  http://default
 Database driver       :  mysql
 Database username     :  root
 Database name         :  d8_test
 PHP executable        :  php.exe
 PHP configuration     :  H:\xampp\php\php.ini
 PHP OS                :  WINNT
 Drush version         :  7.0-dev
 Drush temp            :  Z:\Temp
 directory
 Drush configuration   :
 Drush alias files     :
 Drupal root           :  H:/xampp/htdocs/d8_test
 Site path             :  sites/default
 Active config path    :  sites/default/files/config_MoeSD5C7JSguok
                          xrBh4-UuwT_r9_jk2Z59QKdN-j9Zx9DIgHBy2dH8n
                          1rGOeKNJpaAAxBi4PzA/active
 Staging config path   :  sites/default/files/config_MoeSD5C7JSguok
                          xrBh4-UuwT_r9_jk2Z59QKdN-j9Zx9DIgHBy2dH8n
                          1rGOeKNJpaAAxBi4PzA/staging

```

Contents of my settings.php

```
$databases['default']['default'] = array (
  'database' => 'd8_test',
  'username' => 'root',
  'password' => '',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

```

Note that host of my MySQL installation is 127.0.0.1 instead of localhost.

Also note that H:\xampp\php\ is added to my PATH variable, so php.exe refers to H:\xampp\php\php.exe.

The output of `drush sql-connect` is the following:

> mysql --user=root --password= --database=d8\_test --host=127.0.0.1 --port=3306

# Answer
The output of `drush sql-connect` is `mysql --user=root --password= --database=d8_test --host=127.0.0.1 --port=3306`. Now, when I directly execute this command, it didn't work because `mysql.exe` was not there in the system PATH. So I added `H:\xampp\mysql\bin` to `PATH` (environment variable in Windows) and then it worked!
> 21 votes

# Answer
Make sure mysql-client-core-5.5 package is installed.

On Ubuntu:

```
sudo apt-get install mysql-client-core-5.5

```
> 5 votes

---
Tags: drush, 8
---