# Question
Title: Clone field collection row value in form on add another item
I am new to this community and I hope I will be clear in my support request.

I have a custom form that uses nested field collection items as follows:

```
>     form
>      form_field_a
>      form_field_b
>      form_field_collection_tenant (with unlimited values) - add another item
>        field_collection_user_details (with unlimited values)  - add another item
>          field_u1
>          field_u2 etc
>        field_collection_instance_details (with unlimited values)  - add another item
>          field_i1
>          field_i2 etc

```

I would like to add a functionality so that when "add another item" for field\_collection\_user\_details is pressed it will do a custom callback and return field\_collection\_user\_details with previous field values populated so I can manually update only one field value an leave the rest unchanged.

Or, have another button created with a custom ajax callback to clone previous field\_collection\_user\_details filled on the first delta. (saves time for let's say a field collection with 10-20 fields that require only changing one or two field values)

I am updating my question: I have custom content type created which is being altered via hook\_form\_alter. begining of code pasted bellow: (is very long so I will just paste in until the relevant part)

```
function instanceform_form_plex_demand_node_form_alter(&$form, &$form_state, $form_id) {
drupal_add_css(drupal_get_path('module', 'instanceform') . '/css/instanceform.css', array('group' => CSS_DEFAULT, 'type' => 'file'));
$delta_i = 0;
$max_delta_i = $form['field_orig_tn']['und']['#max_delta'];
// we don't want to see additional settings block
$form['additional_settings']['#access'] = false;
$form['field_orig_tn']['und']['add_more']['#value'] = t('+');
$form['actions']['submit']['#attributes']['style'] = '-moz-border-radius: 5px; border-radius: 5px; width: 50px!important; height: 24px!important; background-color: #E60000; border: 1px solid #fff; line-height: 20px; font-size: 11px; text-align: center; color: #fff!important;';
while ($delta_i <= $max_delta_i) {
    $form['#tree'] = TRUE;
    $delta_j = 0;
    $delta_k = 0;
    $max_delta_j = $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ic']['und']['#max_delta'];
    $max_delta_k = $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und']['#max_delta'];
    // add custom class to select tags for tenant
    $form['field_orig_tn']['und'][$delta_i]['field_parent_nodes']['#access'] = FALSE;
    $form['field_orig_tn']['und'][$delta_i]['field_org_tn_en']['und']['#attributes']['class'][] = 'field-custom-select-tenant';
    $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ac']['und']['#attributes']['class'][] = 'field-custom-select-tenant';
    $form['field_orig_tn']['und'][$delta_i]['field_org_tn_lc']['und']['#attributes']['class'][] = 'field-custom-select-tenant';
    // add custom class to input tag for tenant
    $form['field_orig_tn']['und'][$delta_i]['field_org_tn_sn']['und'][0]['value']['#attributes']['class'][] = 'field-custom-input-tenant';
    $form['field_orig_tn']['und'][$delta_i]['field_org_tn_sn']['und'][0]['value']['#size'] = NULL;
    while ($delta_k <= $max_delta_k) {
        // add custom class to select tags for user
        $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_actions']['und']['#attributes']['class'][] = 'field-custom-select-user';
        $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_permission']['und']['#attributes']['class'][] = 'field-custom-select-user';
        // add custom class to input tag for user
        $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_email']['und'][0]['value']['#attributes']['class'][] = 'field-custom-input-user';
        // hide the parent node field as we are not using it within the Plex demand form
        $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_parent_nodes']['#access'] = FALSE;
        $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und']['add_more']['#value'] = t('+');

        $delta_k++;
    }
    while ($delta_j <= $max_delta_j) {
        ....

```

What i would like to accomplish is to add another "add another item" (e.g.: $form\['field\_orig\_tn'\]\['und'\]\[$delta\_i\]\['field\_org\_tn\_ud'\]\['und'\]\['add\_clone'\]) button that will clone the values previously filled by the user (for $delta\_k = 0) and return the form (field collection item form) with $delta\_k=1 having fields with the same values as in $delta\_k = 0.

EDIT2: I have managed so far to add the second "add another item" button to the form however I cannot manage to set the default values in the ajax callback

In function instanceform\_form\_plex\_demand\_node\_form\_alter I have created the "add clone" button as follows:

```
 $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und']['#prefix'] = '<div id="field-clonefield-add-more-wrapper'. $delta_i . '">';
  $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und']['#suffix'] ='</div>';
  $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und']['add_clone']= array(
    '#type' => 'submit',
    '#value' => t('Add Clone'),
    '#submit' => array('0' => 'clone_field_add_more_submit'),
    '#name' => t('field_clonefield_add_clone'),
    '#limit_validation_errors' => array ( ),
    '#ajax' => array(
      'callback' => 'clone_field_add_more_js',
      'wrapper' => 'field-clonefield-add-more-wrapper'. $delta_i,
      'effect' => 'fade',
    ),
  );

```

Then i have added the submit and callback functions:

```
function clone_field_add_more_submit($form, &$form_state) {
  $button = $form_state['triggering_element'];
  // Go one level up in the form, to the widgets container.
  $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  $field_name = $element['#field_name'];
  $langcode = $element['#language'];
  $parents = $element['#field_parents'];

  // Increment the items count.
  $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);

  $field_state['items_count']++;
  field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);

 >>>>>I THINK HERE IS WHERE THE DEFAULT VALUES SHOULD BE MODIFIED<<<<<

  $form_state['rebuild'] = TRUE;
}

function clone_field_add_more_js($form, $form_state) {
  $button = $form_state['triggering_element'];

  // Go one level up in the form, to the widgets container.
  $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  $field_name = $element['#field_name'];
  $langcode = $element['#language'];
  $parents = $element['#field_parents'];

  $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);

  $field = $field_state['field'];
  if ($field['cardinality'] != FIELD_CARDINALITY_UNLIMITED) {
    return;
  }

  // Add a DIV around the delta receiving the Ajax effect.
  $delta = $element['#max_delta'];
  $element[$delta]['#prefix'] = '<div class="ajax-new-content">' . (isset($element[$delta]['#prefix']) ? $element[$delta]['#prefix'] : '');
  $element[$delta]['#suffix'] = (isset($element[$delta]['#suffix']) ? $element[$delta]['#suffix'] : '') . '</div>';

  return $element;
}

```

# Answer
> 1 votes
I have managed to achieve this. I will post the answer maybe someone will use id in the future.

It seems that it was quite simple.

i have created an ajax callback function:

```
function _user_ajax_check($form, $form_state) {
// load the user then
$delta_tn  =$form['field_orig_tn']['und']['#max_delta'];
$delta_tn_ud = $form['field_orig_tn']['und'][$delta_tn]['field_org_tn_ud']['und']['#max_delta'];
$form_state['rebuild'] = TRUE;
return $form['field_orig_tn']['und'][$delta_tn]['field_org_tn_ud']['und'][$delta_tn_ud]['field_org_tn_ud_email'];}

```

The call with value assign:

```
$form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_email']['und']['#prefix'] = '<div id="field-'. $delta_i .'-user-details-'. $delta_k . '-add-more-wrapper">';
        $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_email']['und']['#suffix'] = '</div>';
        $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_email']['#ajax'] = array(
          'callback' => '_user_ajax_check',
          'wrapper' => 'field-'. $delta_i .'-user-details-'. $delta_k . '-add-more-wrapper',
          'effect' => 'fade',
        );
        if (isset($form_state['values']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_email']['und'][0]['value'])) {
            if((isset($form_state['values']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_cp_pre']['und'][0]['value'])) &&
                ($form_state['values']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_cp_pre']['und'][0]['value'] == 1)) {
                $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k+1]['field_org_tn_ud_email']['und'][0]['value']['#value'] =
                        $form_state['values']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_email']['und'][0]['value'];
                $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k+1]['field_org_tn_ud_actions']['und']['#default_value'][0] =
                    $form_state['values']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_actions']['und'][0]['value'];
                $form['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k+1]['field_org_tn_ud_permission']['und']['#default_value'][0] =
                    $form_state['values']['field_orig_tn']['und'][$delta_i]['field_org_tn_ud']['und'][$delta_k]['field_org_tn_ud_permission']['und'][0]['value'];
            }
        }

```

Result:

---
Tags: ajax, entities
---


# Question
Title: Unable to see URL path setting menu for a user edit page
I want to see "URL path setting" tab which appears while editing any content, but can't see it while editing a user. need help or suggestion regarding this.

thanks

# Answer
> 0 votes
Download & install Pathauto module & then check.

---
Tags: users, path-aliases
---


# Question
Title: which one has better performance to load views
When I want to print my views block result(or views) in my `tpl` files,I have several ways,

views\_embed\_view

views\_get\_view

module\_invoke for block ( I means something like `$block = module_invoke('views', 'block', 'view', 'map-block_1');` )

which one is better and has better performance?

# Answer
views\_embed\_view is just a wrapper for views\_get\_view:

```
function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);
}

```

So how would you set dynamic arguments on views\_embed\_view? With views\_get\_view you can at least do this:

```
  $view = views_get_view($view_name);
  if (!$view || !$view->access($display_id)) {
    return;
  }
  $view->set_display($display_id);
  $view->set_arguments($variables);
  $view->pre_execute();
  $view->execute();
  return $view->render();

```

module\_invoke for block is too roundabout and limited for my liking. Why limit yourself to a block when you can choose from any display available?

views\_block\_view contains this snippet:

```
if ($view = views_get_view($name)) {

```

So it also uses Views\_get\_view.

Performance-wise I reckon the differences are negligible.

So, IMO, views\_get\_view wins.
> 2 votes

---
Tags: views
---


# Question
Title: Drupal 7 Teaser Image Block - no titles or other data
I am setting up a pretty straightforward Durpal 7 site, so I am trying to keep things simple. I have an image gallery set up just fine. On the home page, I am trying to set up a block that simply displays 4 random thumbnails from the gallery. I only want the thumbnail images, but I currently also have the image titles, date posted, and posted by data. Is there a simple way to post only the thumbnails and not the other associated data? I have tried to strip down the teaser view to the bare bones, but still the other data are viewable.

# Answer
> 0 votes
Instead of showing the content with a view mode of Teaser, rather show fields, and only the image field.

If you want to continue using content with a view mode, install and use Display Suite

---
Tags: views, media, nodes
---


title: Is Drupal Cache Warmer for real?

text:
# Question
Title: Is Drupal Cache Warmer for real?
I am using Varnish + Default Page cache with a expiring time (1 day) in a site.

When I am browsing the site, everything seems loading fine; once I come back to the site after a day or so, the the pages start loading slow and they become okay after a while.

It seems like the cache is being cleared after a while and generated again once someone visit the site again. I do not want that user to suffer.

I read about **Drupal Cache Warmer**; is there something which can keep the cache alive and no user suffers?

# Answer
Well, there's the Cache Warmer module you can set up if you have drush access on your server.

You can also use a 3rd party service like Pingdom to do that as well.
> 1 votes

# Answer
See following for good description of Drupal caching and how cache is flushed on cron run.

http://tomroelandts.com/articles/how-to-ensure-that-visitors-always-see-cached-pages-in-drupal-7
> 0 votes

---
Tags: caching, proxies
---


# Question
Title: How to apply specfic coupon in ubercart while creating an order from backend means admin pages
I am using ubercart. I am facing two issues while creating an order from backend.

1.) How to add coupon codes on add order admin page ? i need to add orders manually from backend but not able to apply coupon codes for discounts, there is only a feature to "add a line item" but not for coupon. I think there should be a textbox to fill coupon code and apply button to apply it.

2.) If coupon is applied to manually created order then tax calculation should be done after coupon price deducted from subtotal.

# Answer
> 0 votes
> 1.) How to add coupon codes on add order admin page ? i need to add orders manually from backend but not able to apply coupon codes for discounts, there is only a feature to "add a line item" but not for coupon. I think there should be a textbox to fill coupon code and apply button to apply it.

If you want to apply a coupon code from the admin page. Use the uc\_discounts\_alt module that provides you three submodules(uc\_discounts,codeless\_discounts\_field,product\_price\_alterer\_field). Enable the uc\_discounts module it will provide you the textarea at the admin configuration page to apply the discount code. 1)Go to admin \>\> store \>\> orders \>\> create 2)Enter the customer information 3)It will open the create order screen as shown in the screenshot below

> 2.) If coupon is applied to manually created order then tax calculation should be done after coupon price deducted from subtotal.

Yes.

---
Tags: ubercart
---


# Question
Title: Entity Reference - Auto complete field in content type
I had an issue before (please click here to see it) related to entity reference and I was able to solve it with no problem. Now I have another issue:

I have 2 content types called projects and partners.

In the content type partners I have a field "projects" and I'm able to select from all the project pages that exist in my site. So far so great.

Now, in the content type projects I have a field "partners" and I would like **this field to be autocompleted** with the partners where that project was selected before.

What's the best way to do this?

Please let me know if you need any clarification, I know my English isn't the best.

Thanks so much in advance!

# Answer
> 1 votes
You can do this in various ways.

An easy option would be to display a view as the field. There are quite a few solutions that enable you to do so, such as:

Viewfield,

> Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.

Field Embed Views,

> The module provides a field type to attach any Views View display with, configurable on per-entity level, default values for exposed filters and sorting.

EVA,

> "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity.

Panels, Display Suite, etc.

The view will list partners and the contextual filter will be the current project you are looking at.

If your field is also an entity reference field, then you should probably look at Corresponding Entity References.

Think about your solution where you will be duplicating database storage (both ends of a relationship) when one end can easily be computed (via an sql query for instance). Maintaining the data on both ends means more work as you have to synchronize it constantly, as well as more storage. Maintaining the data on one end only and making the other end purely a display issue is more maintainable.

---
Tags: entities
---


# Question
Title: placing a menu block inside a views template
I need to place a menu block (the main-menu) inside a views template file - the template for the rows design.

I tried

$block = module\_invoke('system','main\_menu'); print render($block\['content'\]);

and

$block = module\_invoke('menu','main\_menu'); print render($block\['content'\]);

but nothing works.

Can anyone please give me a little help?

# Answer
I used the code which was rendering the `main-menu` from `page.tpl.php` file in the theme that I am using in my current project Nexus.

```
<div id="main-menu">
<?php
 if (module_exists('i18n_menu')) {
   $main_menu_tree = i18n_menu_translated_tree(variable_get('menu_main_links_source', 'main-menu'));
 }
 else {
   $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
}
 print drupal_render($main_menu_tree);
 ?>
</div>

```

So i used the following extraction:

```
<?php
$main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
print drupal_render($main_menu_tree);
?>

```

in a views template file for row design. The main menu appeared with content.

Note: The menu which will be rendered might not be themed.
> 0 votes

# Answer
I solved it by placing the region with the block into the view template:

```
<?php print render(block_get_blocks_by_region('mainmenu')); ?>

```

That works.
> 0 votes

---
Tags: views, theming, blocks
---


title: link tag is removed by ckeditor

text:
# Question
Title: link tag is removed by ckeditor
I am using Ckeditor in drupal 7.26. I placed HTML Content with link tag in the source of Ckeditor. It removes link tag. I want to send my css file through that html content. How can I add it into the editor.

# Answer
As Clive said there is almost certainly no situation that CKeditor can *validly* edit/create an html `head` element. Since `link` *must* be a child of a head element this means that CKEditor cannot create a valid `link` element.

That being said there is a way to add a stylesheet the the CKEditor. You will have to allow JavaScript in whatever filter you are using (**so use with caution**) and then insert a script like this:

```
<script>
  (function($) {
    $('head').apend("<link rel='stylesheet' href='my/added/stylesheet.css'>");
  }(jQuery))
</script>

```

Or if you don't want to use jQuery:

```
<script>
  var element = document.createElement("link");
  element.setAttribute("rel", "stylesheet");
  element.setAttribute("href", "/my/added/stylesheet.css");
  document.getElementsByTagName("head")[0].appendChild(element);
</script>

```
> 2 votes

---
Tags: wysiwyg
---


# Question
Title: Sub folders and how to namespace classes
In Drupal 7 I can have a module inside another module. Is this still the case in Drupal 8 and how would I namespace classes inside the sub module?

Another thing I can do in Drupal 7 is to create sub folders inside the modules folder to group my modules.

Example:

sites
--- / all
--- / --- / modules
--- / --- / --- / Collection\_Alpha
--- / --- / --- / --- / module\_a
--- / --- / --- / --- / module\_b
--- / --- / --- / Collection\_Beta
--- / --- / --- / --- / module\_x
--- / --- / --- / --- / module\_y

Is this still possible in Drupal 8? If yes, how would I have to namespace my classes so the autoloader can resolve it to the correct folder structure?

e.g.: Drupal\Collection\_Alpha\module\_a\myClass1 ?

# Answer
@Clive is correct.

The namespace is *always* `Drupal\{module_name}`. Where that module lives is irrelevant (as long as it is somewhere where Drupal can find it). That namespace always points to `$path_to_module/src`.

It would not possibly work in any other way. Different sites have modules in a different structure and different places, but the same code has to work no matter where.
> 7 votes

# Answer
The namespaces is based on PSR-4 autoload, check the specification http://www.php-fig.org/psr/psr-4.

If you want to sub-modules, You can use the next folder structure. d8:

```
/modules
   my_module/
     src/
      Controller/
        A.php
     modules/
       my_sub_module/
         src/
          Controller/
            B.php

```

The namespace for the "my\_module":

```
Drupal\my_module\Controller\A

```

The namespace for the "my\_sub\_module":

`Drupal\my_sub_module\Controller\B`

See PSR-4 namespaces and autoloading in Drupal 8 for more information.
> 6 votes

---
Tags: 8
---


# Question
Title: Add a new colum with a button to field collection
I'm trying to add a button or a link (\< a href=''\>\< /a\> or a \< button\>\< /button\>) in a new column in my field collection. For the moment i have 3 fields added by the administration of my field collection. I searched for add a button by the administration but we can't. what the best tips to add a button in a new column of my field collection ?

Do i need to "foreach" all element of my field collection and add a new element with the HOOK\_form\_alter ?

Here an example with the actual view (i cut the "delete line button" here so there aren't on the picture):

And now what i wanna create :

The "button" can be a link and after with css i style him.

PS : the button appear on edit content form

Thanks !

# Answer
> 1 votes
Use the Link Module to add a link field to your field collection

> With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs. It also supports additional link text title, site wide tokens for titles and title attributes, target attributes, css class attribution, static repeating values, input conversion, and many more.

And add the relevant bootstrap class to the output through the manage display UI.

---
Tags: entities
---


# Question
Title: Drupal 7 Rules: Compare Group Reference Field and fire Rule if data changed
I am using a content type called **"question"** which has an organic group reference field (`og_group_ref`).

I want to trigger an action with Rules, when the field "`og_group_ref`" is changed on node update.

So I have created the following rule:

```
{ "rules_notify_question_author" : {
"LABEL" : "Question has moved - notify user",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_update--question" : { "bundle" : "question" } },
"IF" : [
  { "AND" : [
      { "NOT data_is" : {
          "data" : [ "node-unchanged:og-group-ref" ],
          "value" : [ "node:og-group-ref" ]
        }
      }
    ]
  },
  { "NOT data_is_empty" : { "data" : [ "node:og-group-ref" ] } }
],
"DO" : [
  { "mail" : {
      "to" : "[node:author:mail]",
      "subject" : "Some handy subject",
      "message" : "E-Mail to author",
      "from" : "[site:mail]",
      "language" : [ "" ]
    }
  },
  { "drupal_message" : { "message" : "Message text" } } } }
]

```

The idea is that the author of a question gets notified, when the questions was moved to another group. The logic should be like this:

> **EVENT**: On Node question Update
>
> **CONDITION**: node\_unchanged:og-group-ref != node:og-group-ref AND node:og-group-ref != EMPTY
>
> **ACTION:** Send Mail an show a message

My problem is, that the rule fires when the content of the field og\_group\_ref was changed and when it was NOT changed.

I printed the compared values in the drupal message. The values are correct. But I do not know, why the rule is triggered although the field "`og_group_ref`" did not change.

Has anyone an idea?

# Answer
I solved the problem by creating an own condition for rules using the API of the rules module.

```
function hook_rules_condition_info() {
  return array(
    'rules_condition_text_compare' => array(
      'label' => t('Textual comparison'),
      'parameter' => array(
        'text1' => array(
          'label' => t('Text 1'),
          'type' => 'text',
        ),
        'text2' => array(
          'label' => t('Text 2'),
          'type' => 'text',
        ),
      ),
      'group' => t('Rules'),
    ),
  );
}

```

See hook\_rules\_condition\_info for more details.
> 0 votes

---
Tags: rules, entities, organic-groups
---


# Question
Title: add a new field in a view that uses a teaser view mode fomat
I have a view that extarct a specific content type, this view shows the teaser view mode for rendering fields and not fields format :

the teaser view mode is managed with display suite module to order content type's fields in custom regions.

Im using hook\_node\_view to add a new field conditionally :

```
function MYMODULE_node_view($node, $view_mode, $langcode){
    global $user;
    $uuid = $user->uid;
    switch ($node->type){
        case "rewards" :

            if(!empty($node->field_reward_users) && isset($node->field_reward_users[LANGUAGE_NONE][0]['target_id'])){
                if($uuid == $node->field_reward_users[LANGUAGE_NONE][0]['target_id']){
                    $node->content['get_reward_link'] = array(
                        '#type' => 'markup',
                        '#markup' => l('Click Here', '/', array('attributes'=>array('class'=>'my-link-class'))),
                        '#weight' => 100,

                    );
                }
            }
           // dpm($node);
            break;
    }
}

```

when i debug i can see the new field in the $node object, but it's not rendered. Have you any idea how to add fields conditionally in my case?

**Update**

I added a new preprocess field ("pre\_rewards") via display suite, like montionned in the answer of Reynold, then I added the following prerocess function :

```
function MYMODULE_preprocess_node(&$vars){

    if(isset($vars['preprocess_fields'])){
        foreach ($vars['preprocess_fields'] as $key => $pre){
            if($pre == 'pre_rewards' && isset($vars['content']['get_reward_link'])){
                $reward_link = drupal_render($vars['content']['get_reward_link']);
                $vars['preprocess_fields'][$key] = $reward_link;

            }
        }
    }
    dpm($vars);
}

```

and the same thing the element won't be rendered! and it exists in the $vars variable when i debug!

also the new field created exists in manage field page of my content type :

So why it's always not rendering the content of this field in my page!?

Thanks in advance.

# Answer
> 1 votes
Seeing that you are using Display Suite, you should add the field via Display Suite as node.tpl.php is no longer being used. Display Suite has 4 Custom fields that you can add via the interface. You should look into the 'preprocess field'.

You need to define a preprocess field in Display Suite

and the machine name of the preprocess field

should correspond with the name of the field that you provide in your preprocess\_node function:

```
function MYMODULE_preprocess_node(&$vars) {
  $vars['my_new_field'] = "some html or rendered field";
}

```

You are of course not limited to creating your field value in the preprocess\_node function, you could just hand the value over like this:

```
function custom_preprocess_node(&$vars) {
  $vars['my_new_field'] = drupal_render($vars['content']['get_reward_link']);
}

```

The only limitation (AFAIK) is that you have to render the field before you let Display Suite pick it up.

Once you have defined your preprocess field like this, Display Suite will make it available in the manage display tab for the node type.

Also look at Theming with Display Suite and Preprocess Functions

# Answer
> 0 votes
I think you need this extra field to the node type. Look for "hook\_field\_extra\_fields()" and "hook\_node\_view()"

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


# Question
Title: How to properly render a Calendar view title in a month display?
I have a calendar view set up as shown in these screen shots. Everything is working nicely, except the title. I'd like the title to be only the month, not the first of the month.

(larger)

That is, instead of the below screen shot reading December 1, 2014, I'd like it to render only December 2014 (omitting the "1st").

(larger)

Is there an answer that I'm missing in the Add Header area?

(larger)

**Update**: Contextual Filter

# Answer
There is a bug in the date module that causes this issue. I'm not sure if the latest version of the module resolves it or not. If it doesn't, then the workaround in #20 in the thread at https://www.drupal.org/node/2294973 will fix the issue.
> 2 votes

# Answer
I know that you can use a validation function (with your contextual filter) ... there you will be able to adjust the title with php date functions (formatting the date as you want)
> 0 votes

---
Tags: views, datetime
---


title: Viewing ID of organic group?

text:
# Question
Title: Viewing ID of organic group?
I am trying to display the ID of the group the user is currently viewing. I created a block, and added the following PHP code into it:

```
<?php
$group = og_context();
if ( !empty($group) ) {
   print "$group->nid";
}
?>

```

Problem is, when I run it, I get the following error:

Notice: Trying to get property of non-object

Any idea why this is happening, and how to fix it? Seems like it should be easy enough of a task.

# Answer
In Drupal 7 the NID is the group ID so you could just output $node-\>nid.
> 0 votes

# Answer
The basic problem is that `og_context()` doesn't return an object, or the group node - it returns an array of group information.

Basically, using your example code, you want `$group['gid']`, assuming that all of your organic groups are based off of nodes. If they aren't, you'll want to also look at `$group['group_type']`. See http://drupalcontrib.org/api/drupal/contributions!og!og\_context!og\_context.module/function/og\_context/7 for more information about this function.
> 0 votes

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


# Question
Title: Synchronize data between 2 sites dynamically
I currently have two Drupal sites and I would like to synchronize in a specific way the data of each one.

More precisely, the first one contains detailed informations and the other only has the main data necesary for its work. I would like to refresh (create/update) the data of the second one when the first one is modified and also would like to refresh (create/update) the first one when the second one is modified, taking into account the content types and field names are not the same in both. In my case, the data that should be manipulated are nodes and users.

I have already tried to find solutions through web services or feed import, but I didn't succeed to build a correct one. Moreover, I also studied the possibility to schedule periodic import from web services but it would be slow the site performance, due to the very important amount of data contained in each site.

Can someone help me?

# Answer
You need to work on the database a little bit.

I think it is impossible to make it work if you just write php. Because it will generate a lot of database login errors.

There might be a lot of ways to do that, but the only way I know is to: First, Combine two database into one, two different databases with two different prefix. Second, delete all the attributes you want to synchronize in the second database. Third, link the synchronized field in the second database to the first database, you can do this in the settings.php in the second drupal site.

But there might be some dependency problems when you do step 2. Don't forget to backup at first.

This link might be helpful How to connect to multiple databases within Drupal
> 0 votes

---
Tags: feeds, services
---


title: Export menu to html?

text:
# Question
Title: Export menu to html?
The project I'm working on has a specific requirement where I need to export the main menu as an HTML file. I figured the simplest way to do it would be using views but I found that views doesn't interact with the menu system.

I looked up the menu\_import module to see how it exports menus to JSON files to see if I could rewrite the output to be HTML but haven't really gotten too far with that.

Any ideas how I can approach this?

# Answer
> 2 votes
Use the next code:

```
$tree = menu_tree_all_data('main-menu');
$menu_html = render(menu_tree_output($tree));
file_put_contents('myfile.txt', $menu_html);

```

Source: Programmatically load a menu.

**EDIT** If you want to make it downloadable you can add next code to your page or submit callback:

```
// Get menu tree.
$tree = menu_tree_all_data('main-menu');
$menu_html = render(menu_tree_output($tree));

// Download menu txt file.
$filename = "menu.txt";
drupal_add_http_header('Content-Type', 'text/plain; charset=utf-8');
drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
drupal_send_headers();
echo $menu_html;
drupal_exit();

```

# Answer
> 0 votes
It really depends on how you made the menu. If it is coded in the template.php, you need to copy the coding from the template.php If it is made by some kind of module, you need to copy the html codes, js codes and css codes from module folder. Or maybe you just need to duplicate that block and show it on the page you want.

Or you can use , you can add css {display: none} to all other parts. and add the iframe like

To make it to be a html format, you just need to add tag.

# Answer
> -1 votes
XML Sitemap module or Sitemap module

Using the XML sitemap module would allows you to generate your content and/or your data on XML file that you can manipulate on a different end.

Sitemap Module would help you to generate a list of all your items on your menu on a Drupal page.

---
Tags: routes, theming, importing-exporting
---


# Question
Title: Remove link from title of custom content type in Drupal 7
I have created a custom content type that includes a title, body and an image. I am displaying this content type in a views slideshow which is working fine.

The problem is that the 'Title' on each slide is linked to a stand-alone page for that individual node. This is undesirable. Is it possible to remove this link, or at least change where it goes?

When viewing the content type, there is no 'edit' (or delete) link for the Title field on the 'manage fields' tab, and on the 'manage displays' tab, the title field does not appear at all, though it claims no fields are hidden. Why are we prevented from controlling the behavior of this field?

# Answer
> 1 votes
In the view configuration, click "Field: Title" and un-check "Link this field to the original piece of content".

If you can't find it, you can also add some css to that title. For example:

```
.view-id-case_studies h1 a{
   pointer-events: none;
   cursor: default;
}

```

# Answer
> 0 votes
You can target a field defined in the Display Manager by creating a custom "tpl.php" file in the default theme template folder called "field--field-name.tpl.php"

---
Tags: 7, nodes
---


# Question
Title: How to create (& pre-populate) multiple “field collection” fields on an ajax call
This is an extension of this question - "How to pre-populate multiple "field collection" fields in node form"

I'm trying to do the same thing, but I'm trying to get it to work on an ajax call rather than on the form load.

The form loads, the user selects an option on a dropdown and then the form automatically populates several field collections with ajax.

**The Problem**

The existing solution on the question above involves altering the form when it's first built, by changing:

```
 $form_state['field']['--machine-name-of-field--'][LANGUAGE_NONE]['items_count']

```

And then rebuilding the form using the new form state values.

The problem with an ajax call is that, it seems to ignore any changes made to `$form_state` in the callback. i.e.

```
function ajax_get_parent_field_collection ($form, &$form_state) {
  $form_state['field']['field_collection_entity']['und']['items_count'] = '3';
  return $form['field_collection_entity'];
}

```

The changes made in $form\_state above are ignored, so when the form is rebuilt nothing happens and if you then dump `$form_state` none of the changes made are saved.

I could manually create the field collection entities and insert them, but I was hoping there's a cleverer answer. Has anyone tackled this before?

EDIT:

The ajax is currently called on a select field, so the ajax triggers when the select dropdown is used.

```
$form['field_company_for_center']['und']['#ajax'] = array (
  'callback' => 'ajax_get_parent_field_collection',
  'wrapper' => 'ajax-wrapper',
  'effect' => 'fade',
);

```

# Answer
The form needs to be build again after `items_count` is changed.

```
function MYMODULE_form_alter (&$form, &$form_state, $form_id) {
  if($form_id == 'MYFORM'){
    $form['#attributes']['id'] = 'MYMODULE-form-ajax-wrapper';

    // Handle triggered ajax element.
    if(!empty($form_state['triggering_element']['#array_parents'][0])) {
      if ($form_state['triggering_element']['#array_parents'][0] == 'field_node_reference') {
        $form_state['field']['field_collection_entity'][LANGUAGE_NONE]['items_count'] = '3';
      }
    }

    // Add ajax callback.
    $form['field_node_reference'][LANGUAGE_NONE]['#ajax'] = array (
      'callback' => 'MYMODULE_ajax_rebuild_form',
      'wrapper' => 'MYMODULE-form-ajax-wrapper',
    );
  }
}

/**
 * Ajax callback, rebuilds and returns the entire form.
 */
function MYMODULE_ajax_rebuild_form ($form, &$form_state) {
  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);
}

```
> 2 votes

# Answer
Some surrounding thoughts and things that came up when discussing this with milkovsky. The problem looks like it came from the form not being re-built correctly.

As mentioned above any changes made to `$form_state` in the ajax callback seem to get erased when everything is returned.

That's the reason for the conditional. Because you can't set values in `$form_state` in the ajax call instead you put a conditional in `hook_form_alter` which will only run after the ajax call has been re-made.

But by explicitly returning `drupal_rebuild_form`, it appears that changes made to `$form_state` in the ajax callback are saved.

So conditional can be removed and callback changed to:

```
function MYMODULE_ajax_rebuild_form ($form, &$form_state) {
  $form_state['field']['field_collection_entity'][LANGUAGE_NONE]['items_count'] = '3';
  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);
}

```

You can't set `$form_state['rebuild'] = TRUE` in the ajax callback because it's not saved (because the form isn't rebuilt properly, which ironically is what we're trying to accomplish).

I tried putting the `$form_state['rebuild'] = TRUE` into a submit handler and forcing the select field to call the submit as shown here, but that also didn't work.

**If you're also trying to pre-populate the form**

By default ajax reloads a cached version of the form, so changes made to default values in `hook_form_alter` won't get applied when the form is rebuilt by ajax even though they'll appear in the `$form` if you print it out.

In order force a non-cached form you can wipe `$form_state['input']` in the ajax callback i.e.

```
$form_state['input'] = array();

```

This solution came from Reset node form after AJAX submit and you can find more detail on that question.

Hopefully the extra explanation is useful and if you can add any more please do!

**A second method for loading and pre-populating field collections**

I've come across a second method to do this which (at least in my situation) is more useful than the first. I'm trying to pre-populate field collections from another node and another way to do this, is to create a fake form instance and then plug it into the original form.

The method came from the final part of this blog post: http://drupal.cocomore.com/blog/field-collections-exposed

The only real differences between this example and the blog one is that this one builds the fake form in an ajax callback and rather than looping through all the fields it only changes a single one.

```
function ajax_get_parent_field_collection ($form, &$form_state) {
  //1. load parent node
  $parent_node = node_load($form_state['values']['field_node_reference'][LANGUAGE_NONE][0]['nid']);

  //prebuild fields
  $node_fields =  field_info_instances('node', 'field_collection_entity');

  //Re-create a fake form with all the trimmings which we can then attach
  //as a replacement.
  $tmpform = array();
  $tmpform['#node'] = $parent_node;
  $tmpform['type']['#value'] = 'node_type';
  $tmpform_state = array('build_info' => array('form_id' => $form['#form_id']) );
  field_attach_form('node', $parent_node, $tmpform, $tmpform_state, entity_language('node', $parent_node));

  //replace current form with our custom version
  $form['field_collection_entity'] = $tmpform['field_collection_entity'];
  $form_state['field']['field_collection_entity'] = $tmpform_state['field']['field_collection_entity'];
  $langcode = field_language('node', $parent_company, 'field_collection_entity');

  //iterate over the fields resetting the item and revision id so new
  //field collections are created rather than linking existing fc's
  $field_childs = &$form_state['field']['field_collection_entity'][$langcode]['entity'];
  foreach(element_children($field_childs) as $idx => $fc_entity) {
    $field_childs[$idx]->item_id = NULL;
    $field_childs[$idx]->revision_id = NULL;
  }

  //reset input to make sure cached version of the form isn't used
  $form_state['input'] = array();
  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);
}

```
> 2 votes

---
Tags: 7, entities, ajax
---


# Question
Title: Importing dates TO and FROM using Feeds module
I'm wanting to import some content to my drupal site. One of the fields for this new content type is a date field. The date actually has both to and from fields and in fact the nodes I will be importing have a start and end date...I've read about importing using the Feeds module (here for example: How to import date fields using CSV file? I haven't been able to find any material on importing a date range (for example, an event. The event begins on August 4, 2015 and ends on August 6). What would be the format for that?

I'm imagining something like MM/DD/YYYY - MM/DD/YYYY. Does anyone know the preferred format?

# Answer
> 3 votes
Nevermind, I discovered these can be handled by specifying the Date: Start and Date: End fields in the Feeds importer itself; sweet.

---
Tags: feeds
---


title: How to enable boolean fields?

text:
# Question
Title: How to enable boolean fields?
I installed the minimal setup when installing Drupal, and I want a boolean field in one of my Content Types. But this is not enabled. I found this Boolean module, but it only has 859 installs (as of 6th Jan, 2014), so I doubt I need to install that. So how can I enable 'Boolean' as one of the field types?

# Answer
> 1 votes
You need to enable the List module, which also gives you the List, List (numeric) and List (text) field types.

---
Tags: 7, entities
---


# Question
Title: How can I delete nodes when an arbitrary date has past?
I have a situation where future events will be posted to the website in question. These future events are a content type with a date field using the date module.

I wish to automatically delete these events once their date has past. I'm assuming that rules should do this but I have searched and I am struggling to find a way to do this.

# Answer
> 0 votes
You can use the hook\_cron to solve your problem

```
function mymodule_cron(){
  _mymodule_delete_nodes();
}

function _mymodule_delete_nodes(){
  //select all nodes from type X where date expired
  //node_delete($nid);
}

```

See hook\_cron for further information

---
Tags: rules, datetime
---


# Question
Title: there is no edit option on certain views of drupal site
There are certain blocks/views in drupal site where edit option is not coming and i am unable to figure out how to change them.

# Answer
> 2 votes
There is a "Hide contextual links" setting in views to turn contextual links on and off.

Set "Hide contextual links" to "No" as per this screenshot:

# Answer
> 0 votes
I think you have to set the "Format" -\> "Show" Option to "Content" (or even "Display Suite"). The contextual links will not appear if you display fields only.

---
Tags: views, blocks
---


# Question
Title: I am facing issue while posting on twitter using publish_away module?
I am getting the following message while submitting the message.

> There was an error 401 from Twitter. Visit Twitter HTTP Status Codes page to understand what is going wrong.

I don't find where I am wrong? Anything specific I am missing in twitter setting?

I have set all the tokens correctly. Attaching screenshot below :

# Answer
> 2 votes
I tried the module and it works fine. Follow these steps to enable auto posting to Twitter.

1. Go to https://apps.twitter.com, and click "Create New App". In Application Details, enter the name of the App, enter some description, in website enter http://example.com, leave callback URL empty.
2. Agree with the user agreement after reviewing it, and click "Create new app".
3. Go to "Keys and Access Tokens" tab.
4. Please make sure you give "Read, write, and direct messages" access level to the app.
5. Click on generate the Access token. Keep this page open.
6. In a separate tab open http://example.com/admin/config/services/publish-away after logging in as admin.
7. Enter "Consumer key", "Consumer secret key", "Access token", and "Access token secret" from the app.
8. Hit Save. The account should now appear under the "Accounts" section.
9. Create new content of type news for testing, check the "publish to Twitter" checkbox, and save.
10. The article's link should get Tweeted by your Twitter handle.

---
Tags: 7
---


# Question
Title: How to change default content type machine name in commerce kickstart?
I am using Drupal commerce kickstart 7 . I have installed perfecly . I am using demo store also. It have content types like **hats, storage devices , etc,..**. I am using hats content type. So products show url like that **hats/lloyd-l40s-40-full-hd-smart-led-television**. But i want to show like **products/lloyd-l40s-40-full-hd-smart-led-television**.How to rename???

Thanks in advance

# Answer
> 3 votes
You can only set the machine name when you create the content-type. After that, it is not editable anymore. That's why you have to think twice when you create a new content-type. Your only solution is to delete this content-type and recreate one with the right machine name.

If it is only the appearance of the URL that doesn't suit you, you can also use URL aliases modules like https://www.drupal.org/project/pathauto and replace the word 'hats' by the word 'products' for example (in the module configuration).

---
Tags: nodes, commerce
---


# Question
Title: String overrides doesn't override certain Commerce components
It actually overrides everything except 'Order total', I do not understand how that component doesn't get overwritten by String overrides. Order total is in Checkout page.

```
<table class="commerce-price-formatted-components">
<tbody>
<tr class="component-type-commerce-price-formatted-amount odd">
<td class="component-title">Order total</td>
<td class="component-total">$5,100.00</td>
</tr>
</tbody>
</table>

```

I cleared my caches.

# Answer
> 0 votes
It's a field label, meaning it doesn't get passed through the basic string translation system. You'd need to use something like the i18n Field module instead.

---
Tags: 7, theming, commerce, string-overrides
---


# Question
Title: Is it possible to hide a menu item using menu blocks in context based on user roles?
I am using the Menu block module to create menu blocks and have them attached to the menu in Drupal 7. I am also using the Context module to display the menu and items on different pages.

I have a certain menu item that I want only to be visible with certain user roles. I have created a context for the page (based on "path") that linked to the menu item and have selected the administrator role as a condition and selected require both (path and user role).

Using a non-admin test user I can still see the menu item (It should be hidden). When I click on it the page content doesn't show but the menu item is still visible to the user.

How do I use Context to hide the menu item as well.

Thanks in advance

# Answer
you could hide it programatically

```
function YOURTEMPLATE_menu_alter(&$items) {

 global $user;

  if (in_array('anonymous user', $user->roles)) {
  unset($items['user/%user/profile']);   // example link
  }

 }

```

This will hide that menu item for anonymous users.
> 0 votes

---
Tags: 7, blocks
---


title: An ajax jump menu using Drupal views?

text:
# Question
Title: An ajax jump menu using Drupal views?
I've got a Drupal view that contains a jumplist of items filtered by taxonomy (which is pulled from the current page URL).

The problem is that I need this jumplist to work without a page reload (so using AJAX).

I've tried a few different things and done a lot of Googling, but come up with nothing.

I've read that you can expose filters to users and use this for Ajax filtering, the problem with this seems to be that you can't populate a select element with values from the database when using a filter, it looks like the filter values have to be hard coded or user defined, so this looks like a no go.

Is there any way of accomplishing this? Or am I going about this in the wrong way?

# Answer
I am not 100% on your desired set up but there are a couple of ways that I can think of to get the functionality that I believe you want. If you have a view with filters and displays that also includes a jumplist (the jumplist is just a part of your desired view) I would suggest adding an attachment to your view. This attachment can share contextual and exposed filters.
> 0 votes

---
Tags: 7, views
---


# Question
Title: New Content type is not listing in Add Content in Drupal 7
When create custom content type through UI or programmatically in Drupal 7, there is no link is listed in the **Content \> Add content**.

I was creating the content types without any trouble, but now it is created(succes message is showing) when I check them in the **node\_type** table but not lising in the *admin/structure/types*.

But no content type is listing(not any links showing) in the **Content \> Add content**, or **Structure \> Content type** administration menu.

Here is the code that allows users to access node pages:

```
/*
 * Allow users to view the contents
 */
function mymodule_node_access_records($node){
    $grants = array();
    $grants[] = array(
        'realm' => 'example_realm',
        'gid' => 123,
        'grant_view' => 1,

  'grant_update' => 0,
    'grant_delete' => 0,
    'priority' => 0,
);
return $grants;
}

/**
 * Implements hook_node_grants().
 */
function mymodule_node_grants($account, $op){
    $grants = array();
    if ($op == 'view') {
        $grants['example_realm'] = array(
            123,
        );
    }
    return $grants;
}

```

Then I rebuild permissions using **Content Access** module.

# Answer
1. Check the permission for node creation of that type in **admin/people/permissions**
2. Clear all caches and retry and it should be OK
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Renaming the field label from "author" to "created by"
How can I implement a hook in my template file that will change the label of a field for the "group" content type from "author" to "created by"?

# Answer
To rename the label of a field add the preprocess function template\_preprocess\_node to your *template.php* file:

```
function *YOUR THEME*_preprocess_node(&$vars){
  //Supposing that your content type name is "group"
  if($vars['type'] == 'group'){
    //Supposing that your field name is "field_txt_group"
    $vars['content']['field_txt_author']['#title'] = 'created by';
  }
}

```
> 5 votes

# Answer
I'll take a guess that there are a few different ways you can do this.

1. Use jQuery to target the element and use text replacement. You could so something like:

```
$("#my-element").each(function () {
  var s=$(this).text(); //get text
  $(this).text(s.replace('Author', 'created by')); //set the text to the replaced version
});

```

Of course you will need to add on Drupal specific jQuery code depending on what version of Drupal you are using (6 or 7). See: JavaScript in Drupal 5 and Drupal 6 and Managing JavaScript in Drupal 7.

1. Try the String Overrides module
2. Write a template pre-process function (template.php in your theme folder) to replace that text.
> 0 votes

# Answer
You can also change the label from a field preprocess

```
function THEMENAME_preprocess_field(&$variables, $hook) {
  $field_name = $variables['element']['#field_name'];
  $view_mode = $variables['element']['#view_mode'];

  switch ($field_name) {
    case 'YOUR_FIELD_NAME':
      $variables['label'] = t('FIELD LABEL EVERYWHERE');
      // Possible to restrict by view mode
      if ($view_mode == 'teaser') {
        $variables['label'] = t('TEASER LABEL HERE');
      }
      break;

    // Duplicate for other fields
    case 'OTHER_FIELD_MACHINE_NAMES':
      // ...code
      break;
  }

}

```
> 0 votes

---
Tags: theming
---


# Question
Title: How to customize the display of a block?
I'm new to drupal, I'm using Finder module, I was able to hide some buttons and clean the presentation a little bit, but I also want to be able to customize the search fields display, I'm not sure if I will have to develop a module and implement a certain hook or this should be done in the template.

here's how the block looks like :

I'm trying to inline those input fields and add some style to them and my question is how can I achieve this.

# Answer
> 2 votes
You can customize the display of a block by using Block Class module.

> Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent element of a block. Hooray for more powerful block theming!

In this case, first look at the CSS selector and then add a single line to theme's CSS file such as:

```
.label { display: inline }

```

**It's about CSS.**

---
Tags: blocks
---


title: New Base URL is not working

text:
# Question
Title: New Base URL is not working
I have a site "damo1.com" now I want to use my drupal site in "damo.com", so I just change $base\_url in sites/default/settings.php. And I still can see my homepage very good, but I cannot check the others views or access to the site as user.

Do I need to do one more step? Thx

# Answer
> 0 votes
Before migrate your site I/You needed to:

Disable clean URLs in the live site - » Administer » Configuration »Clean URLs, disable and save.

Then in my/your new site enter with this:

**?q=admin/config/search/clean-urls**

And activate again Clean URL's, with this my/your site will reconize the clean url's

# Answer
> 1 votes
1. In your **sites/default/settings.php** file, comment the $base\_url line, you don't need to specify one, **Drupal** can do it for you.
2. In your **.htaccess**, uncomment **RewriteEngine on**
3. In the same file, **RewriteBase /** must be also uncommented, and if your website is hosted under a subfolder of your root web folder, you must specify your folder here. **Eg: RewriteBase /subfolder/**
4. Activate clean URL's in **admin/config/search/clean-urls**
5. In apache **httpd.conf** file, check if **mod\_rewrite** is enabled

# Answer
> 0 votes
try to remove $base\_url from your settings.php ? Drupal is supposed to guess correctly your base url in your situation.

---
Tags: uri
---


# Question
Title: MySQL 5.1 to MySQL 5.6 update causes php-cgi error: PDO issue?
I recently performed a MySQL upgrade on Windows Server 2008R2, moving from MySQL 5.1 to MySQL 5.6.22 (Community Edition). The server is currently using PHP 5.3.0.

Things went just fine for all my WordPress installs (no problems on cutover); however, all my Drupal 7 sites are now generating 500 errors (coming from php-cgi.exe via php5ts.dll from what I can tell).

To address concerns about the broad nature of the question, this is the specific Windows event log message:

> Faulting application name: php-cgi.exe, version: 5.3.0.0, time stamp: 0x4a492a25
> Faulting module name: php5ts.dll, version: 5.3.0.0, time stamp: 0x4a4929bb
> Exception code: 0xc0000005
> Fault offset: 0x0015e1b0
> Faulting process id: 0x7bb4
> Faulting application start time: 0x01d01fa8dec6e9a6
> Faulting application path: C:\PHP\php-cgi.exe
> Faulting module path: C:\PHP\php5ts.dll
> Report Id: 2e661541-8b9c-11e4-a303-001b210e0a6a

I've checked database credentials, time zone defaults, and haven't changed IIS settings, folder permissions, or anything of that nature.

The one difference that stands out is that Drupal uses PDO for access, and I'm wondering if there is a potential issue there with the version being used, since all these sites worked fine with MySQL 5.1.

PDO seems to be showing version 5.0.5-dev (rev 1.3.2.27).

I can't locate anything that leads to identification, troubleshooting or resolution.

(I'm off to try to replicate with just a simple PDO test.)

Has anybody encountered this and/or have documentation that might help isolate/resolve things?

NOTE: The closest I've come is to somebody using PDO drivers for MSSQL (not MySQL) where there was a faulty Drupal layer on top of PDO. Details here - http://forums.iis.net/t/1181446.aspx?PHP+5+3+8+Problems

---

UPDATE:

Not PDO...

The following example (with real values) works fine.

```
$dsn = 'mysql:host=localhost;dbname=DBNAME';
$username = 'USER';
$password = 'PASS';
$options = array();

$dbh = new PDO($dsn, $username, $password, $options);

if ($dbh) {

    $stmt = $dbh->query('SELECT * FROM MYTABLE LIMIT 1');
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    print_r($results);

}
else {
    echo 'Failed.';
}

```

---

UPDATE 2:

I have double checked any options set by the prior install of MySQL 5.1 that might not have been carried over. I realize more things are auto-set and defaults might have changed, which could be part of the issue.

The other issue that might come into play is changing the server collation default from **utf8** to **utf8mb4** ... It looks like Drupal 7 should support this (discussion, in the framework of Drupal 8 goes back to 2011 - https://www.drupal.org/node/1314214). The tables continue to show ut8 collation, so data should be unaffected.

MySQL 5.6 does introduce **explicit\_defaults\_for\_timestamp** but I haven't been able to find anything implying it should be an issue either (setting 0/1 results in the same error).

# Answer
> 1 votes
As noted above, the whole thing was resolved by pushing the default character set back to **utf8** from the incompatible (for Drupal, but not for WordPress) **utf8mb4**...

Relevant my.ini settings as follows:

```
[client]

default-character-set = utf8 # not utf8mb4

[mysql]

default-character-set = utf8 # not utf8mb4

[mysqld]

# REF: http://stackoverflow.com/a/24487309/3174018
collation-server = utf8_unicode_ci
character-set-server = utf8 # not utf8mb4

```

---
Tags: database
---


# Question
Title: How do I implement a reverse node reference using References?
Using the References module (D7 version), implementing a new field in an article content type for node reference was very easy, but now I cannot seem to figure out how to discern the reverse reference. Just as there is a link shown in my article to the node I have selected in the node reference drop down, I am expecting that on the "linked to" article, I should be able to see a link back to the first article. Has anybody done this? My understanding is that it is part of the D7 version of this module.

# Answer
You can use https://www.drupal.org/project/cer You can then setup the reference both ways so when you add a reference on the first piece of content CER can add the back reference to the other piece of content. Another option is to add a rule which will do this for you but CER is pretty solid when dealing with larger sites.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Exposed sort and filter for multiple value field
I came across a problem when I added some multiple value fields to my view (integer and text fields). I tried it on a fresh install to be sure that non of my other modules is causing the problem. An example of the setup of my view:

I have a own content type called "product" which has some fields (product attributes):

Field A (text field - 1 value allowed) Field B (text field - 1 value allowed) Field C (text field - unlimited values allowed) Field D (integer - unlimited values allowed) Field E (integer - unlimited values allowed) Field F (integer - unlimited values allowed) ...

Now, I created a page view that lists all my products in form of a table and where only Field A and Field B are shown (by clicking on Field A all other details of the product is shown).

I want users to be able to "search" the product list depending on their needs. Therefore, I use the exposed sort and filter from the module Better Exposed Filter (BEF). For instance, the integer fields can be filtered by the jquery slider from BEF.

The problem is, that the view displays some products multiple times on the table. I found out that this is due to the multiple value fields. For example, if a product has 4 values in Field D, the product is listed four times. Plus, if this product has 3 values in Field E, the product is listed seven times in the view.

Struggling with this problem, I noticed that there is a setting for multiple value field within the views settings. Altought my multiple value fields are not part of the views display I added them in the views settings and checked "Hide from display". "Display all values in the same row" in the multiple field settings was already enabled. Unfortunaltely, this has no effect. This is strange because the tooltip of the setting is exactely describes my problem.

What can I do to display each product only once in the view regardless if it has multiple values for some fields? Plus, filter and sorts should work for field with mulitple values.

Does someone has experience with this?

Thanks.

# Answer
> 0 votes
Now I remember this issue. We managed to get it working with aggregation (Advanced \> OTHER \> Use aggregation). However, it took a lot of tinkering to get the right settings and I am not sure if it would work for this case. My suggestion is if you do not have a pager use hook\_views\_post\_execute to modify the results and ensure distinct. Something like

```
function hook_views_post_execute(&$view) {
  if ($view->name === 'your_view') {
    $results = array();
    $nids = array();
    foreach ($view->result as $result) {
      if (array_search($result->nid, $nids) === FALSE) {
        $nids[] = $result->nid;
        $results[] = $result;
      }
    }
    $view->result = $results;
  }
}

```

There are also modules like Views Aggregation Plus but they did not work for the case I needed them for.

---
Tags: entities, views
---


title: How to translate custom date formats?

text:
# Question
Title: How to translate custom date formats?
I created a custom date format `j F Y` at `Configuration » Regional and language » Date and time » Formats`. I'm pleased with the overall look, but I'd like the months to be written in Dutch instead of the default English. The month names should be translated everywhere they occur and it would be perfect if the days should be translated too (maybe I'll need them in the future).

How can I do this?

# Answer
This is a lot harder to do than I first thought. Formatted dates, including strings for the month (and day) names are produced by `format_date()`. This function is not themable, and there is no hook to override it.

That means that (AFAIK) there is no *right* way to change how this function behaves (the *wrong* way is to hack it - i.e. hack core - which is not an option in my book).

What we can do is to make a tiny custom module with a version of this function that outputs months and days in Dutch, no matter what the default language for the site is. This function will do this:

```
function MYMODULE_format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL) {
  return format_date($timestamp, $type, $format, $timezone, 'nl');
}

```

(Where `MYMODULE` is the name of your custom module.)

Now, if you set the *default* language of your site to English, but keep the Dutch translation available, one of the following calls:

```
MYMODULE_format_date($timestamp, $type);
MYMODULE_format_date($timestamp, 'custom', 'j F Y');

```

(where `$timestamp` is the timestamp to print and `$type` is the format to use) will output names of months and days in Dutch, but everything else will be in your site's default language. The first will do this for any valid format (Long, Medium, Short, etc.), the second for the custom format `'j F Y'`.

This will give you Dutch month names if you call this custom function instead of the standard one when outputting formatted dates.

However, it will *not* change the output in existing code which of course uses the standard version of the function. This may not be a problem for you, since you want to use it with a custom date format (which obviously is not in use in legacy code), but I still want to make that clear.

If you want to change how months and days are spelled *everywhere*, you need to override the templates `node.tpl.php` and `comment.tpl.php` (and possibly other templates that uses `format_date`). In the override, just replace *any* calls to `format_date` with calls to `MYMODULE_format_date`.
> 2 votes

# Answer
For a simple case of the publishing date info, it's enough to alter your `node.tpl.php` following the lead presented here. In order to get translated months you need to push the month name (or the weekday name if you use it) through the `t` function. So my modified bartik-based node.tpl.php has

```
  <?php echo "<span class='custom_date custom_day'> " . date( "j",$node->created) . "</span>";
  echo "<span class='custom_date custom_month'> " . t(date( "F",$node->created)) . "</span>";
  echo "<span class='custom_date custom_month'> " . (date( "Y",$node->created)) . "</span>"; ?>

```

instead of a

```
<?php print $submitted; ?>

```
> 2 votes

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


# Question
Title: Change stylesheet for just one page in Drupal 7
How can I add an additional stylesheet for just one page on a Drupal 7 site?

I want to add an additional stylesheet to a section of content on one page, but want the rest of the elements of the page to use the existing theme stylesheets?

How would I go about this, can I make a call to the additional stylesheet or should I embed the css directly in the page?

Thanks-in-Advance,

John

# Answer
> 1 votes
Try adding this code snippet in a custom module :

```
function MYMODULE_init() {
  // You can verify actual page by using arg() function. Example for targeting node with nid 123
  if (arg(0) == 'node' && arg(1) == '123') {
    drupal_add_css(base_path() . drupal_get_path('theme', 'mytheme') . '/path/to/css/file.css');
  }
  // You can verify actual page by using the actual alias
  // Supposing your page alias is : http://www.example.com/first-part/second-part
  $args = arg(NULL, drupal_get_path_alias());
  if ($args[0] == 'first-part' && $args[1] == 'second-part') {
    drupal_add_css(base_path() . drupal_get_path('theme', 'mytheme') . '/path/to/css/file.css');
  }
}

```

Don't forget to change **MYMODULE** by your module machine name

# Answer
> 1 votes
You can use preprocess page in your theme template.php

```
<?php
function template_preprocess_page(&$variables) {
  $front_style = path_to_theme() .'/front-page.css';
  $path_style = path_to_theme() .'/path-'. arg(0) .'.css';

  if (file_exists($front_style) && $variables['is_front']) {
    $include_style = $front_style;
  }
  elseif (file_exists($path_style)) {
    $include_style = $path_style;
  }

  if (isset($include_style)) {
    drupal_add_css($include_style, 'theme', 'all', FALSE);
    $variables['styles'] = drupal_get_css();
  }
}
?>

```

Or use attach method in module code and so forth:

```
<?php
function foo_block_view($delta = '')
{
  if($delta == 'foo_delta')
  {
    $block = array
    (
      'subject' => t('Foo title'),
      'content' => array
      (
        '#markup' => '<p>' . t('Lorem ipsum text.') . '</p>',
        '#attached' => array
        (
           'css' => array('path/to/my.css'),
        ),
      ),
    );
    return $block;
  }
}
?>

```

Attached will only get loaded if that element is loaded on the page, so from above only if that block is shown on the page.

These examples were taken from drupal docs (see below for more info): https://www.drupal.org/node/2278795 https://www.drupal.org/node/225868

You can also target that content on this specific page with CSS by using the body classes added by your theme, most have either the content type or some other information in there you can use (e.g. `node-type-article` or `page-node-5`)

So your CSS could be:

```
/* Original Color */
.original-color {
  color: green;
}
/* Original Color for content type article */
.node-type-article .original-color {
  color: red;
}
/* Original Color for node 5 */
.page-node-5 .original-color {
  color: yellow;
}

```

That's just as example but should help when setting up pieces like this.

You can also use CSS injector It has block like settings to only load the CSS on certain pages.

# Answer
> 0 votes
The easier way to do this is by using the Code Per Node Module.

> Code per Node makes it possible to add custom CSS and Javascript per node, per content type, per block, and globally. The code is stored in the database, but served from the file system. It also supports syntax highlighting with CodeMirror.

You can override the elements that you want and the rest you don't need to add them.

---
Tags: theming
---


# Question
Title: How to update uber cart attribute pricing programatically in Drupal 7?
I am using the following code to alter a price, but after being saved, and viewing the node, I don't see any changes.

```
$node = node_load($nid, NULL, TRUE);
foreach ($node->attributes[4]->options as $attribute) {
    $attribute->price = 4363;
}
node_save($node);

```

I suspect the problem either being how I am trying to update, or perhaps some caching issue.

*UPDATE*

I fixed this by running a straight forward SQL query:

```
UPDATE uc_product_options set price = 333 where oid = 111

```

But it would still be nice to know how to do this the correct way.

# Answer
```
UPDATE uc_product_options set price = 333 where oid = 111

```
> 1 votes

---
Tags: ubercart
---


title: Notify Module Truncate Eroor

text:
# Question
Title: Notify Module Truncate Eroor
I received an error from the `Notify Module` when attempting to "truncate" the queue.

The error was:

Warning: Invalid argument supplied for foreach() in notify\_admin\_queue\_submit() (line 956 of /var/www/html/sites/all/modules/notify/notify.module).

Essentially, the queue was not cleared because of this.

Any ideas?

# Answer
> 0 votes
After hunting through `notify.module`, I saw what the issue was.

The line that the error was occuring at was:

```
foreach ($res_nopub as $row) {
  db_query('DELETE FROM {notify_unpublished_queue} WHERE cid = :cid AND nid = :nid', array(':cid' => 0, ':nid' => $row->nid));
}

```

The array `$res_nopub` is constructed by the function `_notify_select_content` by:

```
// Get published nodes in unpublished queue
$res_nopub = db_query('SELECT q.nid
FROM {notify_unpublished_queue} q
INNER JOIN {node} n
ON q.nid = n.nid
WHERE q.cid = :cid AND n.status = :status
ORDER BY q.nid asc',
array(':cid' => 0, ':status' => NODE_PUBLISHED));

```

The issue that occurred was that the only node within the queue of notifications was an unpublished page. There were no published pages within the unpublished table, and the unpublished table was not empty. Because of this, the array `$res_nopub` is constructed, but is empty. This throws an **error at line 956** due to attempting to iterate over an empty array with a `for each`.

I fixed this error by first checking the length of the array at line 956 before iterating.

```
if (sizeof($res_nopub) > 0)//check size of array before iterating
{
    foreach ($res_nopub as $row) {
      db_query('DELETE FROM {notify_unpublished_queue} WHERE cid = :cid AND nid = :nid', array(':cid' => 0, ':nid' => $row->nid));
    }
}

```

I've tested this very simple fix and yes, it does work.

---
Tags: 7, notifications
---


# Question
Title: How to include the same menu twice in a .tpl file
I am working on a responsive design for a site I am building and I currently am having trouble including the menu twice in the header template file. I need the menu displayed inside the content wrapper for large devices and outside the template wrapper on small devices so I intende to use bootstrap classes to show/hide the correct menus. However when I include the menu twice in my template file only the second instance is ever displayed. How can I get the menu to render twice in the same template.

```
<div class="region region-header">
<div class="hamburger-menu hidden-md hidden-lg">
    <span class="hamburger-btn"></span>
    <?php print render($main_menu); ?>
</div>
<div class="logo-wrapper">
    <?php print render($content); ?>
    <?php print render($main_menu); ?>
</div>
</div>

```

# Answer
You can probably use the `show()` function to un-hide the previously rendered element:

```
<div class="region region-header">
<div class="hamburger-menu hidden-md hidden-lg">
    <span class="hamburger-btn"></span>
    <?php print render($main_menu); ?>
</div>
<div class="logo-wrapper">
    <?php print render($content); ?>
    <?php show($main_menu); ?>
    <?php print render($main_menu); ?>
</div>
</div>

```
> 1 votes

# Answer
I was mistaken where the menu was being rendered from. I had the main\_menu block included in the header region and so it was being rendered in my header. Once I removed the main menu from the header region the menu was not displayed at all. To display the menu twice in the header region I created a new region for the menu named menu, I assigned the main menu block to that region, and then in my template.php file I store the content of that region as a variable.

```
function theme_preprocess_region(&$variables){
    $variables['menu_block'] = block_get_blocks_by_region('menu');
}

```

I can then use the variable $variables\['menu\_block'\] to nest my menu region inside my header region (region--header.tpl.php) wherever I need.

```
<div class="hamburger-menu hidden-md hidden-lg">
    <span class="hamburger-btn"></span>
    <?php print render($variables['menu_block']); ?>
</div>
<div class="logo-wrapper">
    <?php print render($content); ?>
    <?php print render($variables['menu_block']); ?>
</div>

```
> 0 votes

# Answer
Store the rendered main menu in a variable and then output it twice.

Sounds like the easiest solution unless there are considerations I'm not aware of.

Cheers.

```
<?php $rendered_main_menu = render($main_menu); ?>
<div class="region region-header">
<div class="hamburger-menu hidden-md hidden-lg">
    <span class="hamburger-btn"></span>
    <?php print $rendered_main_menu; ?>
</div>
<div class="logo-wrapper">
    <?php print render($content); ?>
    <?php print $rendered_main_menu; ?>
</div>
</div>

```
> 0 votes

# Answer
An alternative answer:

Personally I would say only print the menu once as bootstrap does. This way you don't have the extra markup. If you look at the way Bootstrap has the menu setup you will see what I am referring to there. They target showing the original menu and not a copy of the original menu. You can then restyle their implementation to achieve the same goal as you are needing.
> 0 votes

---
Tags: theming
---


# Question
Title: How can I change the precision of a field used in a field collection or content type?
I have a decimal field (ie field\_testing) with precision = 10 and scale = 8. I need to change the precision to 11. I was planning on writing a migration script that does the following:

* Update field\_config row with field\_name = 'field\_testing' -- set the 'precision' field to 11.
* Alter the field\_testing table structure to adjust the precision of the 'field\_testing\_value' field to 11.

Few questions related to this:

1. Given that I run this while in maintenance mode, is this safe to do?
2. Is there anything else I need to do? The default values is and will still be blank, so changes need to go into field\_config\_instance, I think.

Thanks, Larry

# Answer
> 1 votes
Larry, On the Drupal side, those are the only changes you need to make, the field\_config\_instance table doesn't track the data specifications. Just don't forget to clear the cache\_field table, and the MySQL tables themselves too.

# Answer
> 0 votes
Just changing the field data and field data revisions tables does not appear to be all that is needed.

I went through this and ran `drush cc all` when I go to:

> /admin/structure/types/manage/company/fields/field\_\[rest of field name\]

I am presented with the old precision value still. It appears **field\_config** also needs to be updated but I am not sure how to best change the data column. This appears to be a better solution which I have not implemented yet.

trying to change field type through sql: Notice: Undefined index: precision in number\_field\_schema()

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


# Question
Title: Can I register an additional namespace to point to the modules folder
In Drupal 8 is it possible to register an additional namespace which points to the modules folder in addition to the \Drupal namespace?

e.g.: MyOwnNamespace\\{module\_name} to point to $path\_to\_module/src? I am asking this, because I would like to better understand how today's class design will affect my migration process to Drupal 8 one day.

This was a follow up question from my original thread regarding namespacing.

As suggested by another user I split this off into a separate question thread, but the question has been answered in the original thread already.

# Answer
Splitting my comment over there into a separate answer then ;)

You can, yes, see system\_register() and drupal\_classloader\_register(). Those helper functions hardcode "Drupal\\" as they are all about modules, but you could get the class\_loader service directly.

As @Clive said there, I would not recommend doing it for your own classes, there isn't really a reason to do so, unless you're including an external library.

External libraries is a different story, that can be useful. As already commented in How to autoload classes from a 3rd party PHP library in Drupal 8, if you do not want to depend on Composer Manager, then you can implement your own autoloader service and register them either by loading a composer-style autoload.php, or if you have it available in a different way, by directly registering it in the cloassloader service.
> 2 votes

---
Tags: 8
---


# Question
Title: Search API - how to have blank page on initial page load
I am using Search API with Apachesolr module. I have created a view on the index, but for some reason, before I do any search (or if I search for a blank screen) I get full results. How do I make the initial search screen blank? I tried setting the No Results setting in the view, but that only sets the text when you entered a bad search entry.

# Answer
> 1 votes
This is more of a Views question than a Search API or Solr one, since the answer applies even when not using the latter. You want to set your "Exposed form style" to "Input required." See this answer for helpful screenshots.

---
Tags: views, search
---


title: Add class to menu link href tag?

text:
# Question
Title: Add class to menu link href tag?
I know that using hook\_menu\_link I can add classes to the `<li>` tags but I need to add a class to the `<a>` tags within the `<li>` of a menu. I've looked and can't find a way.

Any ideas?

# Answer
You can do it from `hook_menu_link`. You want to access the `$vars['element']['#localized_options']['attributes']['class']`

Something like this

```
$element = $vars['element'];
$element['#localized_options']['attributes']['class'][] = 'your-class';
$output = l($link_text, $element['#href'], $element['#localized_options']);

```

Then return the $output in the `<li>`. Be sure to account for `$vars['element']['#below']` if you have a sub-menu.
> 1 votes

---
Tags: routes, navigation
---


# Question
Title: SORT CRITERIA by GROUP BY datepart in Views
In views I have my items being sorted by date and then relevancy . Although unless the items are posted at exactly the same time this means that the relevancy score is made redundant.

I can’t seem to add a date boost to the relevancy but have figured if I could Sort the date in blocks of time ( i.e. a day ) this would give me the results that I’m looking for. Then items to be sorted by the day they are posted; and then by relevancy.

I understand that in SQL I can use ‘ GROUP BY datepart’ to do this. Has anyone done anything like this in Views.

# Answer
> 1 votes
I couldn't find any way to do this using the options in the View UI. One way to accomplish it, however, might be to add an additional field to your content type that stores only the day/month/year for the date (set the default to 'now' so that you don't have to manually enter the date, and set the field to 'hidden' on the display options), and then you could use that field to group by in the view.

---
Tags: views
---


# Question
Title: How do I write this PHP query the Drupal way (database abstraction)?
I am using the code below to evaluate if a panel pane should display. I've read the docs on database abstraction, but I just don't really understand how to apply it. Of course, the `dpm` values are for debugging.

(Just to be clear, this code is currently functioning exactly how I need it to, and I am not having any problems with panels itself. I just don't understand how to sanitize this the Drupal way to avoid injection.)

Any help would be appreciated. Here's the code:

```
// Gets NID of viewed node as well as the parent (passed by entity reference field)
$nid = $contexts['argument_entity_id:node_1']->data->nid;
$parent = $contexts['argument_entity_id:node_1']->data->field_webisode_series_reference['und'][0]['target_id'];

// Returns the 3 newest nodes with same parent as the view node
$recentNIDs = db_query("
    SELECT entity_id
    FROM field_data_field_webisode_series_reference
    WHERE field_webisode_series_reference_target_id = $parent
    ORDER BY entity_id
    DESC LIMIT 3
    ");
$result = $recentNIDs->fetchAll();

// Checks NID of the viewed node against NIDs of the 3 nodes above.
// If true, and NIDs match, then the block is displayed.
foreach ($result as $k => $v) {
    $nid2 = $v->entity_id;

    if ($nid2 == $nid) {
        $top3 = 1;
    }
}

// If $top3 is set, display. Else, do not.
if (isset($top3)) {
    dpm('TRUE', 'top 3?')
}

elseif (!isset($top3) {
    dpm('FALSE', 'top 3?')
}

```

# Answer
I think that you can review this answer:

> If you use db\_query() all the time without directly inserting variables, but using the arguments.

I hope information be useful.
> 0 votes

---
Tags: panels, database
---


# Question
Title: What is the best way to make a page that filters a content type using Ajax
I tried to use Finder module, but I had some issues with pagination and some weird issues when I parameter it to use Ajax, some friends told me that I can use the Views module, but they couldn't tell if it supports or could be hacked to support Ajax calls. (I mean by hacked being extended)

I'm new to drupal, it's been like a two days learning and practicing, and I would appreciate any proposition.

# Answer
Assuming you are using Drupal 7 Views is easily used and AJAX enabled. Advanced \> OTHER \> Use AJAX on the view edit screen. There are lots of documents, answers and functions to help you on your way.
> 1 votes

---
Tags: views
---


# Question
Title: Best way to dynamically change only the href of a link in the main menu not the markup
I have been digging quite a bit for this and cannot believe that I am not finding way to do this as I didn't think it would be all that difficult. I would like to alter the href property of my main menu items (potentially) on each page load.

I am building a site that will take the state name in to consideration on most pages. The default main menu links do not contain the state names in the urls. I want to be able to check for the existence of a state name on a given page, and when present, append that to all the main menu items so that the state continues to be taken in to consideration on future pages.

I have seen solutions for theming links, but I do not wish to change the markup of my main menu in any way, I simply want to have the link go to a new location. I would much prefer to do this on the server side rather than using jquery to update them.

Here is what I thought would work:

```
function THEME_preprocess_page(&$variables) {

  foreach($variables['main_menu'] as $key => $item) {
    $variables['main_menu'][$key]['href'] = 'my_new_url';
  }
}

```

However, when I print the results, I see that the values in $variables are changed, but they are not reflected in the markup. Is there another simple way that I can do this without having to rewrite the markup of my menu with a theme\_links\__system\_main\_menu() call?

# Answer
Check out `theme_menu_link`. You can add it to the template.php file of your subtheme. Be sure to return the correctly formatted string.
> 4 votes

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


# Question
Title: Exposed Filter Filtering on Unpublished Revision
I have a content type with a massive number of fields. The primary way this data is seen is through a view with several exposed filters (looking at the fields) which provides a list of matching records. I have installed the revisioning module in order to provide drafts.

The issue I'm running into is that the filters are looking at the most recent (unpublished) revision which doesn't match the published data.

**The exact problem I'm running into:**

There is a published product which is marked as energy star compliant (field on a node). The new version of this product is not energy star compliant, but it has not been released yet (unpublished revision under moderation).

When users filter for only energy star compliant products (using the exposed filter) this product is not displayed. When they do not filter the product is displayed, and it is shown as energy star compliant.

**What I've tried:**

I haven't made much headway. I've discovered that drupal is saving the unpublished field data in the "field\_data\_field\_..." tables, which is what I expect the filter works off of. The published data is in the "field\_revision\_field\_..." tables.

The node table stores the vid of the most recent revision, not the published one.

I logged all of the SQL and saving the unpublished revision updates the field\_data tables and saving the published revision does not.

Deleting and creating a new revision does not fix the issue.

Creating a new published and a new unpublished revision doesn't help.

The issue occurs on multiple nodes not just one.

I cannot find any settings in views, the view, revisions, or any other location that appear relevant.

**What I suspect:**

I'm guessing I have interference happening between modules. There are so many modules on this site that I do not have time to trace through the code and figure out what is actually happening, and there are over 60 modules enabled. My next step would be to start disabling modules but I did not build the site and I do not have the time-budget to figure out what all of these modules do and get the site working well enough without them to test if this behavior is the same.

My linux background says that this is a permissions issue (it's always a permissions issue).

My option at this point is to write a script outside of drupal (I'm not seasoned enough to know how to do this in drupal) that goes into the database and puts the correct data in there manually from the revision table. I don't want to do this, it's a bad idea and would be hell to maintain.

Any insight into what to try next would be very helpful.

# Answer
After figuring out the magical combination of keywords (it's "views filter exposed content revision") I found someone with the same problem:

"Unpublished data belongs to the latest revision of a content type is accessible for querying by the Views module"

https://www.drupal.org/node/2098211

Drupal user fbrooks replied:

> lavms,
>
> I don't think modifications to the Revisioning module are necessary to address this.
>
> I was dealing with, what I believe is, a similar issue. I have a content type with a boolean field used in a filter in a view such that a node will appear if the field if set to true. When you create a node revision under moderation that has the boolean field set to false, the node would be filtered out of the view before the revision is published.
>
> I was able to address this by recreating the view and selecting "Content revisions" instead of "Content" from the "Shows" drop down list on the new view page. This results in node\_revision instead of node being used as the base table, and automatically adds a join between the node\_revision and node table on vid. When selecting fields for display or filtering I used the ones that begin "Content (historical data)", which results in the values from the field\_revision\_\* instead of field\_data\_\* tables being used. All these things combined resulted in the correct revision being used by the filter.
>
> Hope this helps.
>
> Frank

This is the "core view" of the site and is quite entrenched so recreating it will not be simple, but it has turned from an unknown problem to a known and solvable one.

Thanks sareed for your help.
> 1 votes

---
Tags: views, nodes
---


# Question
Title: WYSIWYG module is not finding my custom plugin
I am building a custom plugin. I have the WYSIWYG module 7.x-2.x-dev. I have followed the instructions here.

I realize that this question is similar to this and this. However I think this may be a slightly different issue so I am going to try a new thread.

Pertinent code:

```
<?php
/**
 * Implements hook_wysiwyg_editor_settings_alter().
 */
function my_module_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'ckeditor') {
  $settings['extraPlugins'] = 'my_plugin';
 }
}

/**
* Implements hook_wysiwyg_include_directory().
*/
function my_module_wysiwyg_include_directory($type) {
switch ($type) {
  case 'plugins':
    // You can just return $type, if you place your Wysiwyg plugins into a
    // sub-directory named 'plugins'.
    return $type;
 }
}
/**
* Implementation of hook_ckeditor_plugin().
*/
function my_module_ckeditor_plugin() {
 $module_path = drupal_get_path('module', 'my_module');
 $plugins = array();
 return array('my_plugin' => array(
  'name' => 'My Plugin',
  'desc' => t('Custom plugin to add button styles in the WYSIWYG.'),
  'path' => $module_path . '/plugins/my_plugin/',
 ),);
}

/**
 *  Implements hook_wysiwyg_plugin().
 */
function my_module_wysiwyg_plugin($editor, $version) {
 switch ($editor) {
  case 'ckeditor':
   $module_path = drupal_get_path('module', 'my_module');
   return array('my_plugin' => array(
    'filename' => 'plugin.js',
    'path' => $module_path . '/plugins/my_plugin',
    'buttons' => array(
      'style_1' => t('Style 1'),
    ),
    'load' => TRUE,
    'internal' => FALSE,
  ),);
 break;
 }
}

```

This produces a blank area where the CKEditor should be and the error logs still say that it is looking in the sites/all/libraries/ instead of my custom module folder. Any ideas on what I am missing?

# Answer
Turns out the tutorials and answers were wrong (at least for my set up/needs) The extra hooks and `$settings['extraPlugins'] = 'button_styles';` were probably causing conflicts. I removed all but this;

```
function MY_MODULE_wysiwyg_plugin($editor, $version) {
switch ($editor) {
  case 'ckeditor':
    $module_path = drupal_get_path('module', 'MY_MODULE');
    return array('my_plugin' => array(
      'path' => $module_path . '/plugins/MY_PLUGIN/',
      'buttons' => array(
        'style_1' => t('Style 1'),
      ),
      'load' => TRUE,
    ),);
  break;
 }
}

```

and now it recognizes my plugin.js.
> 2 votes

---
Tags: wysiwyg
---


# Question
Title: Omega 3.x base theme missing after Drupal upgrade
After upgrading Drupal to 7.4.3, i am missing my Omega 3.x base theme in the ui. My subtheme is still present, but the layout is all messed up. Any idea's?

# Answer
> 1 votes
Where did you put your base theme?

It should be in the same folder as your theme "sites/all/themes". If you put it in the top themes folder, beside Bartik, Seven, etc, it was in the wrong place and this folder is overwritten when you update.

If his is the case you can probably just download it again and put it in the correct folder "sites/all/themes".

---
Tags: theming
---


# Question
Title: help me understand the drupal way to develop this module
Coming from a pure HTML, JS, PHP background to drupal 7.x has been a tough transistion, currently I have some code that I would normally use pure JS/PHP to code but I want to make this section managable through the drupal CMS and I'm not totally sure how I would do this. I believe I should be creating a module, but I don't understand how I would create the admin interfaces.

The end result should be structured like this:

* The admin can create 1 or more sessions all of which will be displayed in a drop down.
* Each session will have 1 or more topic listed once selected
* Each topic will have 1 or more files listed under it

For example:

* Session 1
+ Topic 1
- File 1
- File 2

+ Topic 2
- File 1

* Session 2
+ Topic 1
- File 1

So assuming I create a module and have that module display the data how then do I create the admin page the will allow a user to create 1 or more sessions, with 1 or more topics under each and 1 or more files per topic per session. In pure JS and PHP this is pretty simple and straight forward, in Drupal hell it doesn't seem so easy :(

# Answer
Yes it would be easier to develop as you have in your example. To make it so that anyone can update let's try to do it a Drupal way. This way may not be the quickest/easiest but it will give you an idea of Drupal and make it easy to update the content.

There are many distros that help make Drupal easier I would suggest Panopoly to start with. Or you can use core and install the modules as you go (I will probably miss several modules that I am just really used to always being there that are actually contrib).

**1. Custom Content Type** Create a 'sessions' CT and add the fields and fieldset that you need i.e. 'Read it' and 'Do it'. You can use file fields and field\_collections.

**2. Create View** Use the Views module to create a view of Content Type: 'sessions'. You can create an exposed filter for the drop down.

**3. Create a Basic Page** and add the view block to it (personal preference to suggest views block and not views page for expandability, etc.).

No code this way all GUI. The user would just have to create new content of this type and it would appear on the page.

**Tip:** Use Features to save your work and provide an exportable default.
> 4 votes

---
Tags: 7
---