# Question
Title: Why my website is showing junk characters?
My Drupal 6 website is showing junk characters like:

\<�h�3�\>�C�o�m�m�e�n�t�s�\<�/�h�3�\>� �\<�t�a�b�l�e�\>�\<�t�r� �b�g�c�o�l�o�r�=�'�#�E�7�E�7�E�F�'�\>�\<�t�d�\>�P�o�s�t�e�d� �O�n�:� �1�2�-�1�3�-�2�0�1�0�

It used to happen once in every 1-2 months, and with any page of the website. Clearing the cache resolve the problem. I think its the problem with cache\_page table and page compression, because when I manually clear the entry in cache\_page table for that particular page, it gets resolved.

# Answer
> 1 votes
When we remove � manually, we see:

```
<h3>Comments</h3> <table><tr bgcolor='#E7E7EF'><td>Posted On: 12-13-2010

```

Probably it comes from comment.tpl.php in your theme. At first glance looks like UTF-8 - UTF-16 issue, but only you can really debug that.

The exact part of code you pasted seems to appear in following threads:

See, maybe original developer was using them? Hope it helps you with debugging, we here cen't really help more.

---
Tags: 6, caching
---


# Question
Title: How do I know when a render array will be processed properly?
I'm still getting to grips with render arrays and there similarity to FAPI arrays is a point of confusion. I'm customizing a node form using `hook_form_alter` and I wanted to insert some custom markup in place of a field.

I have inserted a table render array as a child of a the field FAPI container array and much to my surprise the table was rendered. What's going on here?

How do I know when a render array will be processed properly?

# Answer
See Render Arrays in Drupal 7

> Note: While render arrays and arrays used by the Form API share elements, properties and structure, many properties on form elements only have meaning for the Form API, not for the Render API. Form API arrays are transformed into Render arrays by drupal\_get\_form.

Because form arrays are converted to render arrays before they are rendered if you add a render array to the form array it will be also rendered when the whole form-array-converted-to-render-array is processed.

As the quoted text says you have to keep in mind that form arrays are not directly renderable, they have to be converted first to a render array. During this conversion, render array attached to the form array are bypassed because they are already a render array.
> 4 votes

---
Tags: forms, theming
---


# Question
Title: Where Can I find the output of the debug() function displayed?
I have written `debug()` in a php file in my local Drupal project. I am trying to see the output. How do I do that?

# Answer
The output should be logged to the Drupal watchdog (admin/reports/dblog). If you're debugging a variable that is an array or object, don't forget to pass TRUE as the third parameter (ref).

Although the code in question may be in a function cached by Drupal, so sometimes you need to flush the cache to trigger that code to be re-run.

Personally, I prefer using the `dpm()` function from the devel module for debugging. If using an account with admin permissions, it displays arrays/objects in a way that is easier to inspect.
> 1 votes

---
Tags: debugging
---


# Question
Title: Call apachesolr_mark_entity without node_save
I need your advise. I have this code:

```
$nid = 5; //example
$engine = 'mustang';
$node = new stdClass();
$node->nid = $nid;          // node id
$node->type = 'car';  // aka content type
$node->engine[LANGUAGE_NONE][0]['value'] = $engine;
field_attach_update('node', $node);
//send to solr
apachesolr_mark_entity('node', $nid);

```

The code was used to update a field called engine in content type car without using `node_save()`. This way is used because more lightweight then calling using `node_load()` and then `node_save()`.

But unfortunately I can not send the entity to solr using `apachesolr_mark_entity()`. `apachesolr_mark_entity()` needs `node_save()` to work.

How to allow `apachesolr_mark_entity()` works although I don't use `node_save()`?

# Answer
> 0 votes
> `apachesolr_mark_entity()` needs `node_save()` to work.

I would have to disagree; this is the code:

```
function apachesolr_mark_entity($entity_type, $entity_id) {
  module_load_include('inc', 'apachesolr', 'apachesolr.index');
  $table = apachesolr_get_indexer_table($entity_type);
  if (!empty($table)) {
    db_update($table)
      ->condition('entity_id', $entity_id)
      ->fields(array('changed' => REQUEST_TIME))
      ->execute();
  }
}

```

As you can see it's just a simple database update, `node_save()` is not involved.

---
Tags: nodes, search
---


# Question
Title: How to group content in view by taxonomy terms?
I have a content type called blogs and in which I referred a Taxonomy term which have three different terms in it.

Now what I want to achieve is three blocks with two recent posts for each taxonomy term.

Which should look like :

```
||       TERM 1            ||          TERM 2           ||        TERM3        ||

         title1                        title1                     title1
          desc                          desc                       desc

         title2                        title2                     title2
          desc                          desc                       desc

         read more...                  read more...              read more...

```

I know we can create using seperate blocks each.

I need this to be created in a **single block in views** if this is possible.

I've tried group by in field settings, but it yields me something like this:

**TERM 1**

> title1
>
> desc

**TERM 2**

> title1
>
> desc
>
> title2
>
> desc
>
> title3
>
> desc

**TERM 3**

> title1
>
> desc

Since I specified 6 nodes to be displayed it displays 6 recent post irrespective of the taxonomy term.

# Answer
I found a way to display such view and render it as single block using **attachments**

Instead of creating separate blocks for each this seems to be a good idea. Just Create three different attachments in which you can **override the term filter** to get two recent posts each.

**1. Create a block in views and add required fields in it**

**2. Add a filter criteria for a specific term and add a sort criteria for post date(desc)**

**3. Now add an attachment and just override the term filter for another term and repeat it for the other filters too.**

To achieve the grid view I just applied CSS classes Since I use Bootstrap as my base theme by applying the class: **col-lg-4 col-md-4 col-sm-4**

Now you can render three different blocks as "one"....!!!!
> 0 votes

# Answer
I don't think a single View can you your job.

In the case you have fixed Term a non best practise approach will be to create 3 Views and a custom module

Views:

* Create new view without add a page or a block
* Add a filter to taxonomy term = 'Term 1'
* Limit the results to the desired number, remove pager, add read more link.
* Do the same for Term 2 and Term 3

Module:

```
term_display.info

name = 3 Term display
description = Display the articles of 3 terms
core = 7.x
package = My custom modules
version = 7.x-0.1

term_display.module

<?php
/**
 * Implements hook_block_info().
 */
function term_display_block_info() {
  $blocks['term_display'] = array(
    'info' => t('term display'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * Prepares the contents of the block.
 */
function term_display_block_view($delta = '') {
  // Initialize a block array.
  $block = array();
  // In case that we have more that one blocks the $delta will define witch one
  // to render.
  switch ($delta) {
    case 'term_display':

      // Give a block title.
      $block['subject'] = t('Term Display');

      // Tells the theme to render the content using ul list.
      $block['content'] = theme('item_list', array(
        'items' => term_display_create_items(),
        'type' => 'ul',
      ));
      break;
  }
  return $block;
}

/**
 * Create the items that will be render in the block.
 *
 * @return array
 *   Return an array of the block's items.
 */
function term_display_create_items() {
  // Initialize the items that will be rendered.
  $items[] = array(
    'data' =>  'Term 1' . views_embed_view('trem_view_1', 'default'),
  );
  $items[] = array(
    'data' =>  'Term 2' . views_embed_view('trem_view_2', 'default'),
  );
  return $items;
}

```

All the job is done in `term_display_create_items()` that embeds the View `views_embed_view('VIEWS_MACHINE_NAME', 'DISPLAY_ID');`

A better approach will be to give the Term as a parameter to the `views_embed_view()` and fetch it from the View. So you will have a single View that uses Contextual Filters to give you your results. But follow the above steps and you will find your way ;)

A third and more dynamically solution is using the Views Field Views but it will add a huge overhead to your site + will take more time to build it.
> 0 votes

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


# Question
Title: Is there a tpl.php file generated by Drupal 7 for custom content types
I seem to remember it being mentioned somewhere in the past that when you create a new content type in Drupal 7 that there is a corresponding node--\[content-type\].tpl.php file created somewhere by Drupal core. I may be wrong. However, if there is such a file created, how do I find it so I can copy it in to my theme?

Maybe it defaults to the node.tpl.php file, but I thought a new file for the custom content was created. Just don't know where to find it if it is created.

TIA

# Answer
No; Drupal doesn't ever create template files dynamically.

For new content types the default node.tpl.php, or the one provided by the enabled theme, will be used.
> 2 votes

# Answer
Yes you can per content type. Use #2 under node at https://www.drupal.org/node/1089656#node-suggestion it should be node--\[type\].tpl.php.

So for lets say a content type that has the machine name blog, it would be node--blog.tpl.php

As Clive said Drupal doesn't do this automatically.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Classify content in Views based on distinct values
Is there any elegant way to classify content in view, so that content with same value of some field gets the same value from some predefined list?

For example: I have nodes with entity reference field and would like to get different colors (from pre-defined palette) for different entities referenced through this field.

I know, that this might be solved by using Views PHP field, but this seems to be quite "hacky" to me. Also, classification lists can't be defined in user-friendly way.

Also, it's possible to add another field to referenced entity, which allows us to use this value for classification through views relationship. But this seems to overkill - and even then I would need to use something like Computed field to get randomly generated colors, which are compatible with each other (or use computed field in combination with list field - but that seems to be completely insane).

Do you know about any better solution?

# Answer
> 1 votes
I haven't done this myself, but off the top of my head...

On the node type, I would add a CCK Colour Field to allow the person adding the node to determine a colour for that node. (Then in the content type setting, manage display and hide the colour field).

Then in views, you can add the colour field, and exclude from display.

Then in the same view, add the node reference field you wish to change the colour for (for example node title colour or background colour). (Make sure the colour field is first in the list of view fields)

Then in the view admin, click on advanced, and click "Theme Information". Find the field you wish to override (something like views-view-field--title.tpl.php).

Then copy the field.tpl.php file from the theme folder in the views module folder, and place it in your themes template folder, renaming the file views-view-field--title.tpl.php

You can then place your own php in that template file, around the default $output variable, something like...

```
$color = $row->{$field->color_field};

<div style="color:<?php print $color ?>;">
<?php print $output ?>
</div>

```

I think that's what you mean? Please let me know if I have misread the question.

---
Tags: views
---


# Question
Title: How to expand TB Megamenu in opposite direction so it won't go outside of the site?
I am using TB Mega Menu for my drop down menu that has three columns with width: 665px and height: 335px.

I want to do something like this: There are total 8 menu tabs. When I click on first 6 menu tabs it expands to right as it is appearing. But when I click on last two menu tabs it should appears to the left. So, it won't go outside of the site.

Any suggestion?

# Answer
You can do this with css using the last-child or nth-child psuedo elements on the li element of your menu list.

As a rough example...

```
.menu ul li {
  width:200px;
  margin-left:0px;
}

.menu ul li:last-child {
  width:200px;
  margin-left:-100px;
 }

```

Or for the last two out of 8 menu tabs...

```
.menu ul li {
  width:200px;
  margin-left:0px;
}
.menu ul li:nth-child(7),
.menu ul li:nth-child(8) {
  width:200px;
  margin-left:-100px;
}

```
> 1 votes

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


# Question
Title: SQL command to remove hypens from data value
A commerce site that I am working on has products titles and skus in the format of DS-PC-CDJ2000.

The client wants the each hyphen removing and replacing with a space; DS PC CDJ2000

There are hundreds of products so I want to do this in the database if possible. What would be a suitable command to run on the relevant database tables?

# Answer
To ensure caches are invalidated properly, and contrib modules get the chance to act on data changes, you should always make this kind of global change with the API.

If you've checked, and you're sure you won't suffer any ill-effects by not using the API, then:

```
UPDATE commerce_product SET sku = REPLACE('-', ' ', sku)
UPDATE commerce_product SET title = REPLACE('-', ' ', title)

```

And the same for the commerce\_product\_revision table. You may also need to run something like

```
UPDATE node SET title = REPLACE('-', ' ', title) WHERE type = 'product_display_type'

```

And the same for node\_revision depending on how you have node revisions and product displays set up.

But direct DB access is not the recommended way to perform a task like this. Take a backup before trying anything just in case
> 1 votes

---
Tags: commerce, database
---


# Question
Title: How to redirect /user to /user/UID, for logged in users?
I run a social movement community site, which features links to the '/user' page, which either shows people the login/registration page, or shows them their user account if they're logged in. If people are logged in, how can I make these links to /user redirect to /user/UID ? (E.g. if I'm the one logged in, I'd like to redirect my visits to http://effectivealtruismhub.com/user to http://effectivealtruismhub.com/user/1 \- currently it shows me my user page, but just shows http://effectivealtruismhub.com/user in the address bar.)

This is a valuable feature because people benefit from seeing the URL of their user page, as on this community site and others they'll want to share it with people.

# Answer
If you were handcoding this, you would create a menu path using hook\_menu, with %uid as the second parameter. And the `page_callback` value of the menu item would be the function rendering the user page. You will then use `hook_user_login` to set the redirect rule.

If you were doing this using contrib modules, I suggest you looking into profile2, it comes with a built in functionality where each user has their own profile page.

**edited:** The last sentence on your question, makes me led to think that the user/%uid path needs to be accessible users/visitors other than the owner. So let's here is how you would do it.

1. Create your custom module, let's call it `ea_custom` for the sake of this example.
2. Add hook\_menu and page\_callback to your ea\_custom.module and register the path for the individual user page.

/*** Implements hook\_menu ***/ function ea\_custom\_menu() { $items\['users/%user'\] = array( //the %user will be used as argument for the page callback 'title' =\> t('User Profile'), 'page callback' =\> 'ea\_custom\_render\_userpage', 'page arguments' =\> array(1), //zero base array. This tells hook menu to first load user with the specified uid specified by %user parameter. 'access callback' =\> 'user\_access', //so non-onwer can also view it 'access arguments' =\> array('access content'), ); return $items; }

/\**** page callback for users/%user \****/ function ea\_custom\_render\_userpage($user) { //you now have accessed to the user object drupal\_set\_message('

```
' . print_r($user, TRUE) . '
```
');

//assemble your output using the values inside $user object $output = $user-\>uid; //etc.. etc...

return $output; }

**Additional notes:** you can use different methods to get values from entity objects such as user and node. I would recommend you to check `entity_metadata_wrapper` for one. Also, instead of using %user, to get user object, you could opt to use %profile2, since you have that module installed, and it will allows you access to fields you have attached to profile type.

wow, I can't seem to format this properly. Here is the paste bin: http://pastebin.com/kiv6GfPN
> 1 votes

# Answer
You can use the module **Login Destination**, Website: Login Destination

Once there you can create your the action destination after login and inside there create a code in PHP:

```
<?php
  global $user;
  return  "user/".$user->uid;
?>

```

That can work for what you need, let me know !
> 0 votes

---
Tags: users, redirection
---


# Question
Title: How to add css using the Preprocess_image function?
I'm trying to preprocess my image style like this example

`<img class="media-object img-rounded img-responsive" src="http://placehold.it/350x250">`

My preprocess\_image function looks like so:

```
function bootstrap_subtheme_preprocess_image(&$variables) {
  if(isset($variables['style_name'])) {
    if($variables['style_name'] == 'logged-in') {
      $variables['attributes']['class'][] = "media-object";
      $variables['attributes']['class'][] = "img-responsive";
      $variables['attributes']['class'][] = "img-rounded";
    }
  }
}

```

But it is not adding the classes.

Why not?

# Answer
> -1 votes
Try this.

```
function mytheme_preprocess_image(&$variables) {
   if(isset($variables['style_name'])) {
    if($variables['style_name'] == 'image_style') // this is an image style used in drupal's image styles {
     $variables['class']['img-responsive'][] = "true";
  }
 }
}

```

---
Tags: 7, media, theming
---


# Question
Title: How can I translate string templates in Metatag module?
I use Metatag module. How can I set different string templates for each site language? Or translate these templates.

# Answer
Basic internationalization support can be found in the i18n module:

> All default configurations may be translated using the Internationalization (i18n) module. The custom strings that are assigned to e.g. the "Global: Front page" configuration will show up in the Translate Interface admin page (admin/config/regional/translate/translate) and may be customized per language.

There exists at least 1 ongoing issue in Review still with Views, Panels and other 3rd party contrib modules and the metatags module.
> 1 votes

---
Tags: meta-tags
---


# Question
Title: Delete user account after checkout completion
Im trying to create a rule that deletes an user account after checkout completion for New users, but it is not working. Can anyone please help me to figure out what is wrong? after checkout completion, check if user is not admin or any other role, then delete the account. After anonymous checkout, an user account is created (blocked, registered).

```
{ "rules_delete_user_account_after_checkout" : {
  "LABEL" : "Delete User Account after Checkout",
  "PLUGIN" : "reaction rule",
  "WEIGHT" : "3",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules", "php", "uc_cart" ],
  "ON" : { "uc_checkout_complete" : [] },
  "IF" : [
    {
      "NOT data_is" : {
        "data" : [ "order:customer:roles" ],
        "value" : { "value" : { "3" : "3" } }
      }
    }
  ],
  "DO" : [
    { "php_eval" : { "code" : "\/\/ Delete the user.\r\nuser_delete(NULL, [order-uid]);" } }
  ]
}}

```

# Answer
Deleting a user after checkout is a bad idea. I assume you know this, but the client is asking/forcing you to do this.

check this link - automatically delete all Ubercart-created users, this has a solution.
> 1 votes

# Answer
thanks for the link. I did followed the recommendation from the post.

1. After saving a new user account, Customer completes checkout: assign new user an "ubercart" role.
2. Customer completes checkout, User has the ubercart role and user is not admin or any of the other roles, execute php code: // Delete the user. user\_delete($order-\>uid);
> 0 votes

---
Tags: rules, ubercart
---


# Question
Title: Form AJAX - Update button value via Ajax
I have a custom form in Drupal that ties into Entity-generating code. In essence, there's a button which should return an ideal Entity state (determined in a method that returns true or false).

The code below fires the method in question, but even if it gets a return value from the method, the value of the button never changes.

Am I overlooking something as simple as returning a new #value in the AJAX callback?

```
function example_mark_block_form($form, $form_state) {
  $form = array();

  $is_marked = _example_is_user_marked();

  $form['mark-changes'] = array(
    '#type' => "button",
    '#id' => "mark-changes",
    '#default_value' => t($is_marked),
    '#prefix' => "<div class='mark-wrapper'>",
    '#suffix' => "</div>",
    '#ajax' => array(
      'callback' => 'example_mark_follow_ajax_response',
      'wrapper' => 'mark-wrapper',
      'method' => 'replace',
    ),
  );

  return $form;
}

/**
 * AJAX callback for the follow response
 */
function example_mark_follow_ajax_response($form, $form_state) {
  global $user;

  return $form['mark-changes'];
}

```

# Answer
From the FAPI Reference:

> **`#ajax['wrapper']`**
>
> This property defines the HTML id attribute of an element on the page which will be replaced by the html returned by the #ajax\['path'\] or #ajax\['callback'\] function. Usually, a div element is used as the wrapper, as it provides the most flexibility for placement of elements before, after, or inside of its HTML tags. This property is required for using AJAX requests in on a form element. Note that the entire element with this ID is replaced, not just the contents of the element.

So this:

```
'#prefix' => "<div class='mark-wrapper'>",

```

Should be:

```
'#prefix' => "<div id='mark-wrapper'>",

```

Also buttons don't have a `#default_value`, so replace:

```
'#default_value' => t($is_marked),

```

with:

```
'#value' => t('@value', array('@value' => $is_marked)),

```

And you should be on track (the change to `t()` is just for sanitisation, see Translating Variables).
> 3 votes

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


title: How to add custom fields to menu items

text:
# Question
Title: How to add custom fields to menu items
I've been looking at using menu attributes module for Drupal 7 to add an extra field to the menu navigation system. However this adds a new attribute to the attribute array and thus prints it out in the anchor link.

e.g.

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

  if ($element['#below'])
  {
    $sub_menu = drupal_render($element['#below']);
  }

  $element['#localized_options']['html'] = TRUE;

  $subtitle = $element['#localized_options']['attributes']['subtitle']; //get sub text

  $linktext = $element['#title']. '<span>'. $subtitle .'</span>';
  $output = l($linktext, $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

But it comes out like this

```
<a subtitle="subtitleexampletext" href="/node/13">About us<span>subtitleexampletext</span></a>

```

is there anyway to hide the attribute in the link and just spit it out where ever I want it in the html? Or is there a better way of doing this? I've looked at power menu module as well, but thats not quite what I'm after either.

TIA

# Answer
> 3 votes
You can use hook\_form\_alter to alter the menu link edit form. This way you can add a extra field to the form, in your case:

```
$form['subtitle'] = array(
 '#type'=>'textfield',
 '#title'=> t('Subtitle'),
);

```

Then add an extra submit hanlder to the form:

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

```

In your submit handler you can access your custom value by using `$form_state['values']['subtitle'].`

You will have to store this value in an extra sql table or a variable\_set,together with the menu-item ID.

Once you have done that, in your theme function you can access your subtitle by menu id. Or you can use `MYTHEME_preprocess_menu_link` to add extra info to $variables, which you then can access in your theme function.

Hopes this helpes you out.

---
Tags: 7, routes
---


title: Alter ctools_ajax_command_redirect()

text:
# Question
Title: Alter ctools_ajax_command_redirect()
My problem is redirect after webform submission. So I have a webform node and AJAX on this submit button (hello "Webform Ajax"). How I do redirect: I'm just using hook\_form\_alter() and add to this webform "submit" special redirect function. It must be make redirect after webform submission. In general it works if I doesn't use the "Webform Ajax" module. But I need use the "Webform Ajax" (Do not ask me why) I'm catching a mistake. In code I found how the "Webform Ajax" makes redirect: ctools\_ajax\_command\_redirect() function. Well the QUESTION: How can I "alter" this functionality?

Any Ideas how I can make redirect after submit, thanks!

# Answer
> 0 votes
You could use hook\_form\_alter and unset the `$form['#submit']`. Then you add your own submit handler by using `$form['#submit'][] = '_my_callback';` THen in your callback just copy the code of the Ajax redirect and alter it to your needs.

---
Tags: ajax, webforms, redirection, forms, chaos-tool-suite
---


# Question
Title: How to remove the submit button on the form included by drupal_get_form?
I have a `hook_field_widget_form` where I call `drupal_get_form` multiple times.

Here is my code:

```
foreach ($suppliers AS $supplier_id => $supplier) {
    $delivery_information = sbsl_order_delivery_information_new();

    $element['suppliers'][$supplier_id] = array(
      '#type' => 'fieldset',
      '#title' => $supplier['supplier_information']['visible_name'],
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );

    $delivery_information_form = drupal_get_form('sbsl_order_delivery_information_1_form_' . $supplier_id);
    $element['suppliers'][$supplier_id]['delivery_information'] = $delivery_information_form;
  }

```

How can I remove the submit button on the form included by `drupal_get_form`, and only use the submit of `hook_field_widget_form` to submit all the forms included by `drupal_get_form`?

# Answer
If you look at the function drupal\_render it will ignore all elements marked as #printed so just add that to the submit button's array.

You'll need to inspect the $delivery\_information\_form array to see exactly where your button is at, and when you find it you can do something like this:

```
  $delivery_information_form = drupal_get_form('sbsl_order_delivery_information_1_form_' . $supplier_id);
  $delivery_information_form['path']['to']['button']['#printed'] = TRUE;

```

before adding it to the $element array.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: view results not show for unadministrator users
There is a views that it `access` set to `permission:view published contents` ,every thing seems ok but I meet strange things, The views result not show for non-administrator user, first I think the views result node are unpublished but they are not ,another idea was check the permission `view published contents` but It check for all `roles`.
**any idea about where is the problem and how can I solve it ?**
thank you

# Answer
> 1 votes
What is your view path or URL? Is this URL protected for any specific user role?

1) Is there any field permission is given?

2) Can you please select `role` instead of `permission` from `access`? And set specific role you want to give permission.

3) Is there any contextual filter is applied?

4) Check your views filter criteria. Remove some of the filters which you have doubt on that filter and try it.

# Answer
> 0 votes
to solve / workaround the issue, remove the relationship, and the non-admin user gets the results when they use the exposed filters.

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

---
Tags: views, users
---


# Question
Title: In Tinymce editor, how to set default font family style in select list?
I have TinyMCE editor configured and under font family select list, I am able to see 'styles' label as default when loading. But I want to see any font family as default. Suppose, Times new roman as default in select list.

# Answer
> 1 votes
You can try execCommand to make that work.

> Executes a specific command on the currently active editor.

Try this.

```
editor.execCommand("fontName", false, "Arial");

```

Another way is to use the `content_css` configuration option and name an own css file where you can overwrite the editors defaults (the content.css you were recently looking for). In your init function use something like

```
content_css: "http://sitename/css/my_tiny_styles.css",

```

and in my\_tiny\_styles.css or whatever file you choose you use

```
font-family: myfont1, myfont2, sans-serif;

```

# Answer
> 0 votes
In the init\_instance\_callback from http://www.tinymce.com/wiki.php/Configuration3x:init\_instance\_callback it says:

```
function myCustomInitInstance(inst) {
        alert("Editor: " + inst.editorId + " is now initialized.");
}

tinyMCE.init({
        ...
        init_instance_callback : "myCustomInitInstance"
});

```

but if you try to just enqueue some javascript with those functions Drupal, you can't access tinyMCE since the tinyMCEs are not initialized yet.

Original code I figured out how to reference here, but I extended it.

http://www.group42.ca/adding\_and\_controlling\_tinymce\_fonts\_in\_drupal

You have to create your own function and tap into hook\_wysiwyg\_editor\_settings\_alter.

```
 /**
     * Implements hook_wysiwyg_editor_settings_alter().
     * adding custom font in there and setting default size
     */
    function mymodule_wysiwyg_editor_settings_alter(&$settings, $context) {
      if ($context['profile']->editor == 'tinymce') {
        // you can change your font styles there
        $font_styles = array(
          "Calibri=calibri",
          "Comic Sans MS=comic sans ms,sans-serif",
          "Tahoma=tahoma,arial,helvetica,sans-serif",
          "Times New Roman=times new roman,times",
        );

        $settings['theme_advanced_fonts'] = implode(';', $font_styles);
        $settings['theme_advanced_font_sizes'] = "8pt,9pt,10pt,11pt,12pt";

        // this function LangTinyMCEInitialized should be defined in your enqueued javascript file
        $settings['init_instance_callback'] = 'LangTinyMCEInitialized';
      }
    }

```

You also need to have a javascript file containing the **init\_instance\_callback** callback that is enqueued when the page loads. The two execCommand calls set up the font and size respectively.

```
//initialize default options in instance callback
function LangTinyMCEInitialized(ed) {
  console.log("Editor: " + ed.editorId + " is now initialized.");
  try{
    ed.execCommand("fontName", false, "Calibri");
    ed.execCommand("fontSize", false, "11pt");
  }
  catch(err){
  }
}

```

---
Tags: wysiwyg
---


title: How do I set a range of views results?

text:
# Question
Title: How do I set a range of views results?
I have 2 views in a page. The first view displays 3 articles and the second view displays a list of all the articles. The problem is that I get duplicated articles in the second view since it is displaying all the articles.

I need to set a range of the last 3 articles added to Drupal and display them on the first view and on the second view I need to display the remaining articles. I´ve been looking for something like this is in the filters but I haven´t found something.

Thank you for your help !

# Answer
You can do this by adding an offset (you can find this in the pager options in your view), in your example "3". The offset "3" will show all results, but skips the first 3. Make sure that the sort criterea in both views are the same.
> 1 votes

---
Tags: views
---


# Question
Title: Dynamic Field Adition / Subtraction using FAPI
**Goal** Provide a user with a drop down menu defaulted to a value of `none`. Other options are the number 1 through 27. Based on the value select have drupal FAPI generate a fieldset that has anywhere from 1 to 27 required text fields. And should they then change their mind it would re-render accordingly.

**What I have** So far I am able to get the FAPI to hide the field on initial form render however I can't seem to figure out how I'd take the selected array value and use that to generate out a new field set dynamically.

```
function single_add_ucm_form($form, &$form_state) {
$form['number_subscribers'] = array(
'#type' => 'select',
'#title' => t('How many subscribers are in the CUCM cluster?'),
'#required' => TRUE,
'#default_value' =>  0,
'#ajax' => array(
  'callback' => 'ajax_select_callback',
  'wrapper' => 'replace_subscribers_div',
  'effect' => 'slide',
 ),
'#options' => array(
  0 => t('none'),
  1 => t('1'),
  2 => t('2'),
  3 => t('3'),
  4 => t('4'),
  5 => t('5'),
  6 => t('6'),
  7 => t('7'),
  8 => t('8'),
  9 => t('9'),
  10 => t('10'),
  11 => t('11'),
  12 => t('12'),
  13 => t('13'),
  14 => t('14'),
  15 => t('15'),
  16 => t('16'),
  17 => t('17'),
  18 => t('18'),
  19 => t('19'),
  20 => t('20'),
  21 => t('21'),
  22 => t('22'),
  23 => t('23'),
  24 => t('24'),
  25 => t('25'),
  27 => t('26'),
  27 => t('27'),
),
);
$form ['subscribers_wrapper_container'] = array(
'#type' => 'container',
'#prefix' => '<div id="replace_subscribers_div">',
'#suffix' => '</div>',
);

if (isset($form_state['values']['number_subscribers'])) {
$form_state >= 1;
$form['subscribers_wrapper_container']['UCM_SUB'] = array(
    '#type' => 'textfield',
    '#size' => 30,
    '#title' => t('Subscriber IP Address'),
    '#required' => TRUE,
  );
}
}

function ajax_select_callback($form, $form_state) {
return $form['subscribers_wrapper_container'];
  }

```

# Answer
> 0 votes
```
if (!isset($form_state['values']['number_subscribers'])) {
   $form_state['values']['number_subscribers'] = 0;
}

for($i = 0; $i < $form_state['values']['number_subscribers']; $i++){
$form['subscribers_wrapper_container'][]['UCM_SUB'] = array(
    '#type' => 'textfield',
    '#size' => 30,
    '#title' => t('Subscriber IP Address'),
    '#required' => TRUE,
  );
}

```

You should add `'#tree' => TRUE` on your form, it will be easier to extract the form values afterwards

---
Tags: 7, forms
---


# Question
Title: Search for product displays based on info from products in Commerce
I have a website with various articles of clothing for sale. Here's how I have it set up:

Product Display content items:

```
Mens V-Neck Tshirt
Mens Tank Top Tshirt
Womens Tshirt
Childrens Tshirt

```

Product content items (in Commerce):

```
Mens V-Neck Tshirt - Red - Large
Mens V-Neck Tshirt - Blue - Large
Mens Tank Top Tshirt - Green - Small

```

etc...

**Colors** (**Red**, **Blue**, **Green**) and **sizes** (**Large**, **Small**, etc) are set up as Select-List fields with the *Enable this field to function as an attribute field on Add to Cart forms* option enabled.

I need to allow my shoppers to search for shirts that have **Red** as an available color, or that have **Small** as an available size. So if they searched for shirts that are **Red** and **Small**, they would receive no results based on the product list above, but if they search for **Green** and **Small**, they would see the `Mens Tank Top Tshirt` product display item in their search results.

How can I set this up? With Views/exposed filters, perhaps? Or...?

Thanks!

# Answer
> 0 votes
Use Commerce Search API module. Basically you are gonna have to set up Facets to achieve what you want.

This screen cast here walks you through on which modules you have to enable and how to tweak your configurations.

---
Tags: 7, commerce
---


# Question
Title: How do I create a content type that has another content type embedded inside of it?
I'm building a content type for a journal-type product. In each journal there are a number journal articles that vary from journal to journal, which have their own unique fields (like author, date, subject, synopsis, etc). Right now I've set it up so you fill out all of the contents for the articles and then you pull them into the journal via entity reference.

Ideally though, it would be great if I could just streamline all of this into the same "create content" form. For example, when I click "create new journal", I want to get all the fields for my journal plus the ability to dynamically add journal articles and all of their fields. It could be in a different tab or something, it just needs to be in the same create journal content type form.

# Answer
> 1 votes
You will find Inline Entity Form useful.

> Provides a widget for inline management (creation, modification, removal) of referenced entities. The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form. Existing entities can also be referenced.

# Answer
> 1 votes
Use References dialog. "This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog"

# Answer
> 0 votes
I think this module can help you: https://www.drupal.org/project/editableviews If you embed the view in a block on the path node/add/journal

---
Tags: nodes, entities
---


# Question
Title: Send reminder to referenced users day before event date in cck date field
I have a node type called event.

An event has a "Event Date" date field, and a "Staff" user reference field.

I need to send a reminder emails to all referenced users, 1 day before the event date to remind them they are working.

I'm getting lost in Rules trying to work out what actions I need it to react on, and how to get the users emails to send the message to.

My problem is pretty similar to "How to send notification for an event for users that have signed up with the list of events for that month?" which was asked 3 years ago and didn't get a reply.

Can someone who is an expert with rules help me out?

**UPDATE:**

I have it working for one user reference field now. Added relationship "User: Duty Manager (field\_duty\_manager) - reverse" and contextual filter "(field\_duty\_manager) Content: Nid" with "Hide view" when filter is not available. I can type in "55" into the perview, and it only lists the Duty Manager, perfect.

My next struggle is to get this to work for the mulitple user reference fields. Am i going to have to clone the rules for each individual field?

# Answer
I will show you how to do it when a new event is created. You must in addition provide for when an event is updated (by deleting the scheduled event and rescheduling it) and when an event is deleted (by deleting the scheduled event). If an event does not exist and you delete it it won't throw an error, so it is acceptable to do it.

You need the following additional modules installed: Views and Views Bulk Operations, reason being you will use views to obtain the list of emails and VBO is needed to interface it with Rules.

**STEP 1** Start by adding a view (don't select page or block in wizard as we only want a master) of type 'Users'. Remove the sort and pager as it is not necessary.

Add a relationship 'A bridge to the Content entity that is referencing User via field\_staff' and make it required.

Add a contextual filter of nid: 'The node ID.', make sure the relationship created earlier is selected, and Hide view when filter value is not available.

Add a field 'Bulk operations: User' and accept the default. This is the important field and technically the only field needed.

Test the view by typing a known node id in the preview field.

**STEP 2** Create a Rules component of type 'Action Set' and call it 'Send Notification'. Add a Variable of 'Entity: Node', give it a label and machine name of 'node'.

Add an action to this component: 'Load a list of entity object from a VBO View'. Select the view you created earlier. Set its argument to '\[node:nid\]' and leave the provide variables at default. Note the variable name of the List of entities: entity\_list.

Add a loop to this action, and select 'entity-list' as the Data Selector. Note the default name of the current list item: list\_item.

Add an action to the loop (note: add it to the loop and not the component) of 'System: Send Mail'. In the to value select '\[list-item:mail\]'. Fill the rest out the way you want.

**STEP 3** Add a new rule and call it 'On new event', to react on 'Node: After saving new content'. Restrict it to type 'event'.

Add an action to this rule, 'Rules schduler: schedule component evaluation', and select the 'send notification' component you created earlier.

Set the evaluation date to node:field-event-date.

Add an offset: -1 days

Add an identifier of 'node-\[node:nid\]-event' and note its pattern as you will be using it to delete events.

Select the Node as 'node'

That should be the gist of it.
> 4 votes

---
Tags: rules
---


# Question
Title: How to customize drupal node using 'PANELS'
I am trying to implement the "PANELS" module in drupal 7.31 to customize a page display.

Panels Module : 7.x-3.4

Drupal version : 7.31

I have created courses(as a product) using "COMMERCE" module. I am able to display the LIST Courses using Panels. But I am also want to customize the course detail page(User click on course and then redirect to detail page).

You can see list of courses using Panels on here:

Now I want to customize the detail page where all details show from Database using Panels.

You can also see Course Detail page here:

# Answer
> 0 votes
You can't customize the node detail page with panels. You will have to use display suite. DS allows you to do a lot of things, and one of them is "Display Suite allows you to take full control over how your content is displayed using a drag and drop interface."

Hope this helps

---
Tags: nodes
---


title: Backreference in PHP

text:
# Question
Title: Backreference in PHP
I have a Content Type **Courses** & a User Role **Student**

In the student I used EntityReference to refer to a number of courses.

Is it possible to get a list of all the students that have a particular course referenced to them, in PHP?

Right now I'm only accustomed in getting a value from a field in a content type like this:

```
$user_surname = $profile_info['student']->field_surname['und'][0]['value'];

```

---

**PS** I think this has to do with back-reference,which is a module I already installed.

# Answer
> 4 votes
You could do this with views (without PHP), but if you want to use PHP you should check out Entity Field Query

You will have to do something like this:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('your_field_course', 'target_id', $nid, '=')
  ->addMetaData('account', user_load(1)); // Run the query as user 1.
$result = $query->execute();
if (isset($result['user'])) {
  $uids = array_keys($result['user']);
  $users = entity_load('user', $uids);
}

```

---
Tags: 7, entities
---


title: Make session time longer on Drupal 7

text:
# Question
Title: Make session time longer on Drupal 7
I got a webform and it seems to timeout after one or two hours, I want to increase the timeout session to like 4-5 hours or more.

How do I make this possible?

# Answer
> 2 votes
In your settings.php change/add this line

```
ini_set('session.cookie_lifetime', desired time in seconds);

```

it will increase your timeout length in desired way.

---
Tags: configuration
---


# Question
Title: How can I recover from a backup but include many changes from a dynamic site?
After the Drupageddon disaster, I've discovered that my backup plan is not sufficient. I have daily, weekly, monthly and yearly DB and file backups thanks to backup\_migrate and backup\_migrate\_prune, but my site is a dynamic one with many users making posts daily. So I was able to easily find a DB backup from pre-Oct 15th to restore to, but I had no easy way to incorporate the thousands of legitimate changes that had occurred on the site since then.

I recognize that it's probably too late for this time, but I'm thinking about how to make sure I'm not screwed in the future. Is there any good method to accomplish this sort of thing? A module that logs all database transactions so they can be individually inspected and reapplied if they're deemed legitimate? Or anything at all better than either loosing weeks of user data or doing a manual diff of the current and known-good databases and praying that I didn't miss something?

# Answer
> A module that logs all database transactions so they can be individually inspected and reapplied if they're deemed legitimate?

Where it would log to? Database? Impossible, it would kill your server. Filesystem? It's slow. And it's big. Another thing worth noting is that if you would want to manually approve / disapprove each query, you can either:

1. Inspect them carefully, and you already told us there is a lot of them, so it could take you up to hours per one edit, if your content types are complicated enough - not nice on dynamic site.
2. Inspect them fast, probably making your data inconsistent.

Last but not least, if you will add that as a module, anyone with proper permissions will be able to disable that module, making your efforts void.

Modules that should be able to help some are:

Sadly, as far as I understand, neither would help in this particular case.

# What I would do is:

* Hourly backup. If possible, done as a snapshot of virtual machine, because that's fast and unobtrusive.
* Mail about each new user, new role assignment, and password change. Sadly, if no one monitors that mail, no one can help.
> 0 votes

---
Tags: database, backups
---


# Question
Title: CSS styles not working while included in .info.yml file
For some reason my theme can't find css/style.css in Drupal 8.

This is the .info.yml:

```
name: Adminimal
type: theme
description: Drupal Administration Simplified.
# version: VERSION
# core: 8.x
base theme: seven

# Include CSS.
 stylesheets:
  all:
   - css/style.css

# Information added by Drupal.org packaging script on 2014-10-23
version: '8.x-1.x-dev'
core: '8.x'
project: 'adminimal_theme'
datestamp: 1414059738

```

This is how the folders look like:

```
Theme/adminimal.info.yml
Theme/css/style.css

```

The css in the style.css file:

```
html{
    background-color: blue !important;
}

```

It doesn't even show up in the styles section in my Google Chrome console so I think it doesn't find the file but why?

And about jQuery in Drupal, I can't manage to get this working: https://www.drupal.org/node/1541860 To work with: //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js How should I do this?

# Answer
Working for me creating drupal8 theme using bartik theme as base theme. Successfully call the css file present in my custom theme. Hopes this will helps you.

```
name: Smart
type: theme
description: 'Smart business templates'
core: '8.x'
package: Custom
base theme: bartik
project: 'drupal'
stylesheets-remove:
 - colors.css
stylesheets-override:
 - css/colors.css
regions:
 header: Header
 primary_menu: 'Primary menu'
 help: Help
 featured: Featured
 content: Content
 sidebar_first: 'First sidebar'
 sidebar_second: 'Second sidebar'
 triptych_first: 'Triptych first'
 triptych_middle: 'Triptych middle'
 triptych_last: 'Triptych last'
 footer_firstcolumn: 'Footer first column'
 footer_secondcolumn: 'Footer second column'
 footer_thirdcolumn: 'Footer third column'
 footer_fourthcolumn: 'Footer fourth column'
 footer: Footer

settings:
 shortcut_module_link: false

```

Also take reference from https://www.drupal.org/node/1876600
> 1 votes

---
Tags: javascript, theming, 8
---


title: Unable to save textfield on node_save()

text:
# Question
Title: Unable to save textfield on node_save()
```
   $fbuser = new stdClass();
   $fbuser->first_name = 'abc';
   $fbuser->last_name = 'cde';
   $fbuser->location = 'Vas';
   $fbuser->link = 'http://www.facebook.com';
   $fbuser->gender = 'male';
   module_load_include('inc', 'node', 'node.pages');
   $node = new stdClass();
   $node->type = 'profile2';
   node_object_prepare($node);
   $node->uid = 1;
   $node->field_profile_fn[0]['value'] = $fbuser->first_name;(textfield)
   $node->field_profile_ln[0]['value'] = $fbuser->last_name;(textfield)
   $node->field_profile_city[0]['value'] = $fbuser->location;(textfield)
   $node->field_profile_facebook[0]['value'] = 'http://www.facebook.com';(textfield)
   $node->field_profile_gender[0]['value'] = $fbuser->gender;(select list)
   node_save($node);

```

In the above code I am trying to create a new content of type profile2 . My node is created but some of the fields show empty text like

field\_profile\_facebook which is textfield does not show value provided above and gives empty text.

# Answer
> -1 votes
You forgot to add the language to your fields:

```
$node->field_profile_fn[LANGUAGE_NONE][0]['value'] = $fbuser->first_name;

```

But even then, this is not the way to go. You should take a look at https://www.drupal.org/documentation/entity-metadata-wrappers

This approach allows you to use something like this:

```
 $wrapper->field_profile_fn->set($fbuser->first_name);
 $wrapper->save();

```

---
Tags: 6, nodes
---


# Question
Title: Are Drupal .php files associated with a module cached?
I am wondering if they are, as that would explain why a simple change to one of my variables in my `config.php` file is not showing up in the DOM.

Here is what is making me suspect this.

In my `fls_price_calculator_2012` module in my `includes` directory I have a file called `config.php`.

I am trying to change my `$START_DATES_OPTIONS_COMBINATIONS['Specialty Tours']` variable to look like the following:

```
$START_DATES_OPTIONS_COMBINATIONS['Specialty Tours']['Surf Camp - Saddleback College'] = array('June 29, 2014', 'July 6, 2014', 'July 13, 2014', 'July 20, 2014', 'June 28, 2015');

```

Simply adding `June 28, 2015` as a last option to the array.

The php file is included in my `.module` file for the module, following this line:

```
include_once('includes/config.php')

```

in my `fls_price_calculator_2012.module` file.

The variable itself is added into a hidden `<input>` variable in the DOM in the same `.module` file like so:

```
$tour_start_dates = '<input type="hidden" id="tour_start_dates" etc...>'
foreach ($START_DATES_COMBINATIONS['Specialty Tours'] as $key => $value){
  //populates the above created input with the keys and values
}

```

once it is all loaded in the DOM, I search via the Javascript console for the `#tour_start_dates` element but I get the only the old value for `Surf Camp - Saddleback College` and I don't understand how that is happening.

# Answer
> 0 votes
To answer it literally - probably, yes, on many levels:

* Filesystem cache
* Opcode cache
* Possible other caches, depends on your configuration

Above caches should not create the effect you are seeing, but outout of the whole page is also cached, in your browser. Inspect headers to make sure it was not the case, and if so, clear caches and try again. If you have any proxy or reverse proxy, make sure they are not interfering, too.

If you are sure pages are not cached at output, and you **didn't make Drupal to cache** your variable, it shouldn't be cached. So there are two options:

1. Problems with include path:

> Files are included based on the file path given or, if none is given, the include\_path specified. If the file isn't found in the include\_path, include will finally check in the calling script's own directory and the current working directory before failing.

Maybe there is another instance of this file somewhere, one that gets higher priority in including? That's one of the reasons to use `module_load_include` instead.
2. Problems with uploading. You know what you sent to your server. But have you inspected (from console, for example) what really is there? Maybe you are looking for something that isn't even there.

---
Tags: 7
---


# Question
Title: How to how a table with previously collected data in a custom form page?
I have a table named "Table1" in my Drupal, where I added fields by getting the inputs via form. The form is created by custom module. My next requirement was to again create another form, but this time I want to show the user by means of a Table format, the previously collected data in the form page itself. But I got stuck in this part.

**The idea is:** I want to bring the contents of "Table1" having attributes "empid" and "empname" in the right side of Form Page, so that the user can check the contents and enter current input accordingly. How is it possible?

# Answer
> 1 votes
Yes you can do this. First of all you need to fetch the 'Table1' data in top of the form.

```
$query = db_select('Table1' , 'tb');
    $query->fields('tb');
    $results = $query->execute()->fetchAll();

```

//table structure

```
$Details = '<table><tr><td style="width:15%;"></td><td style="width:30%;">Employee Id</td><td style="width:10%;">Employee Name</td></tr>';
    foreach($results as $res)
    {
        $Details .= '<td>'.$res->empid.'</td>';
        $Details .= '<td>$'.$res->empname.'</td>';
    }

$form['details'] = array(
        '#type' => 'item',
        '#markup' => $Details,
        '#suffix' => '</div>'
    );

$form['eid'] = array(
    '#type' => 'textfield' ,
    '#title' => t('Employee Id'),
    '#maxlength' => 45,
    '#required'=> true,
);
$form['ename'] = array(
    '#type' => 'textfield' ,
    '#title' => t('Employee Name'),
    '#maxlength' => 45,
    '#required'=> true,
);

 $form['submit'] = array(
        '#type' => 'submit' ,
        '#value' => 'Submit'
    );

```

---
Tags: forms
---


title: Drupal Views Slideshow + Galleria

text:
# Question
Title: Drupal Views Slideshow + Galleria
Image Gallery with the use of View slideshow does a trick for me.

what I need :

But for thumbnails & for main image galleria provide image crop with 4 options like `height, width etc.`

Is there any way that we can use custom image style that we have added from back-end to create those thumbnails?

Please Guys Suggest. I stuck in this since many time.

# Answer
Use jCarousel module for slideshow. I think this is what you want.
> 0 votes

---
Tags: views
---


# Question
Title: SQL injection Drupal Core - Highly Critical - Public Service announcement - PSA-2014-003 issue
I got this news today about SA-CORE-2014-005 - Drupal core - SQL injection.

We are not using drupal in build authentication. We have a custom authentication, which resides behind SSO and gateway. A user can only get access or even get access page if the user is the in SSO and Gateway servers.

Is this kind of setting also vulnerable to this attack, as access is not handled by drupal?

# Answer
Yes, your site is vulnerable. If your network is stopping people accessing the Drupal site without prior authentication then you're (potentially) safe from those outside the network, but still vulnerable to those inside it.

As with all security issues, upgrade as soon as physically possible.
> 4 votes

# Answer
I have gone through this link about the vulnerability Drupal Core - Highly Critical - Public Service announcement - PSA-2014-003 and suggest you to monitor your website for any backdoor attack as advised in the above link.

Consider changing your server location and all important passwords to remain in total safe area.
> 0 votes

---
Tags: 7
---


title: ajax on webform

text:
# Question
Title: ajax on webform
I have added a button to webform:

```
   $form['submitted']['some_placeholder']['own_btn'] = array(
       '#type' => 'button',
       '#value' => t('Add'),
       '#name' => 'ob_add_food',
       '#weight' => 19,
       '#prefix' => '<td>',
       '#suffix' => '</td></tr></table>',

       '#limit_validation_errors' => array(),
       '#ajax' => array(
          'callback' => 'callback_js',
          'wrapper' => 'wrapper-div',
          'method' => 'replace',
          'effect' => 'fade',
          'speed' => 'slow',
    ),
);

```

and callback\_js:

```
  function callback_js($form, $form_state) {
     return  $form['submitted']['some_placeholder'];
  }

```

When I go to it form admin user(Administration -\> Content....) and view it, everything works fine, but when I go to it from simple user(I show form at first screen) callback does not work? Any ideas?

# Answer
> 0 votes
Try changing `'#type' => 'button',` to `'#type' => 'submit',`.

---
Tags: 7, ajax, webforms
---


# Question
Title: Can't log in to Drupal websites after upgrading to OSX Yosemite
I have just upgraded my local machine to OSX Yosemite which has changed my Apache version from 2.2 to 2.4 and my PHP version from 5.4 to 5.5.

When I visit both example.dev/user and example.dev/user/login and enter my username and password, the login form appears to post the data and then 'loops' back to it's original state i.e. blank fields.

This is the same across all websites and all browsers and is the same for all users.

There is nothing in any of the error logs but…

```
"POST /user HTTP/1.1" 404 16744

```

… in the access logs

Has anyone encountered a similar problem?

Thanks,

S

# Answer
Thank you for the answers/suggestions provided.

To fix my specific problem i.e. not being able to log in after upgrading to Yosemite (Apache 2.4, PHP 5.5), you need to edit your httpd.conf file, uncommenting the following line:

```
LoadModule rewrite_module libexec/apache2/mod_rewrite.so

```

(Line 168 in my httpd.conf)

Then restart Apache using `sudo apachectl restart` command.
> 2 votes

# Answer
That happen to me when I upgraded to OSX Yosemite. I had to reconfigure my apache to make it work. Make sure that the rewrite module in apache is enabled, that you are allowing override. I had a similar problem also with mysql. I had to reinstall again.
> 3 votes

# Answer
I experienced a similar issue w/ my Drupal install after upgrading...Also had a codeigniter site disappear b/c of the new OS re-writing all my apache directives...I found this article is super-useful in going back thru re-initializing apache server for OS X Yosemite...

http://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-10-yosemite/
> 1 votes

---
Tags: 7, users
---


title: Location taxonomy

text:
# Question
Title: Location taxonomy
I want to add a location to my `products/articles` in 2 different ways :

> -user enters a town (linked to a taxonomy) -\> I know how to do it
>
> -user enters a county which is automaticly linked to a state (with taxonomy too) -\> I don't know which module do that

In this way,

all users could find all products in a city, in a county or in a state.

The other difficulty is that I want a module which "knows" all country and regions of several countries (actually all European countries).

# Answer
> 0 votes
I am not sure on how to help you with your approach, but alternatively you could use the Location module:

> The Location module allows real-world geographic locations to be associated with Drupal nodes, including people, places, and other content.

The module Gmap can be combined with it:

> The GMap module provides an interface to the Google Maps API within Drupal. It integrates with the Location module to provide users a clickable map for entering latitude and longitude, as well as to display maps of Drupal nodes and users.

Location allows to add a location field to your content with several capabilities which may cover your requirements.

There are also other similar modules such as Geolocation.

---
Tags: location
---


title: Why does menu items start disappearing

text:
# Question
Title: Why does menu items start disappearing
In Drupal 7 some menu items, even though they exist in menu\_links db table, do not appear in the menu. I wonder if it has something to do with cache, but I have disabled the cache and cleared it.

If I add a menu item that goes for instance to `<front>`, it appears in the menu, but if I add a menu item for a certain node, it does not appear. I can't find the logical reason for it.

# Answer
> 8 votes
The only reason I can think of is that the viewing user does not have access to the linked node. Internal menu links that point to unauthorised content do not appear in menu.

Make sure the node has been published and your user can view it.

Some people actually consider dolbydolby's work around a bug :-) http://drupal.org/node/483150

# Answer
> 5 votes
I also had this problem.

Building on Jan Tomka's answer, it appears that for unpublished nodes, when you create menu links these are indeed written to the database, but they do not appear in the menu, either on site (as you would expect), or - surprisingly - even in the list of menu links in the admin screens.

(This does not apply if you use an absolute url for the links, even if they are unpublished).

However, if these nodes are published, the menu links then appear both on site and in admin screens.

Not having menu items that are created appear in the admin screen - despite being written to the database - is counter intuitive, but as soon as I understood this behaviour I was able to work around it.

# Answer
> 1 votes
I spent days looking for a solution, but when I added the full path (http://example.com/?q=node/2) instead of the internal Drupal path (node/2) it worked, finally, I saw the menu item.

# Answer
> 0 votes
Also I have this problem but i resolve it by delete the voice in the menu and after i add the same voice to the menu (linked to the same node) and it's all right, the menu appear. Try in this way.

# Answer
> 0 votes
We too experienced this problem: suddenly the first item of our main navigation (link to the home page) disappeared.

The link was also gone in the Admin \> Structure \> Menu. So I was not able to check the settings.

But in the table menu\_links the item was still there.

I could **solve the problem** by changing some values for that entry in the menu\_links table.

1. I removed the value in \*router\_path\* column (original value was node/%)
2. I filled in a:1:{s:10:"attributes";a:1:{s:5:"title";s:0:"";}} in the *options* column
3. I set the value of the *external* column to 1 (original value was 0)

Then I cleared the drupal cache and the problem was solved!

# Answer
> 0 votes
In case you use **Node view permissions** you have to make sure that the **Content Types** you have linked into the menu for all (= incl. anonymous = "Guests") to see are not selected under .../admin/config/content/node-view-permissions.

If you select them to be included in the node view permissions process the menu items will not show up when a user is not logged in, but they can still see the content with the right path. The menu items do show for logged-in-users.

It is a reminder that you should use **Content Types** carefully and directly related to the **User roles**. IMHO it is not good to define access on a node by node basis to different **User roles** (or even individual users), this should be done through using **Content Type** and **User roles** in a structured way.

Therefore **Node view permissions** is the right module and one just has to remember to exclude all **Content Types** intended for **anonymous users** and that may be directly linked (relative path, i.e. node/x) to a menu when the page is created (.../node/add).

---
Tags: 7, routes, caching
---


# Question
Title: How can I define the activity and/or case in a CiviCRM-integrated webform?
I have a Drupal webform that is integrated to my CiviCRM installation and uses numerous custom fields that are associated with a particular activity type. I want to use the form to allow specific contacts to edit an activity that is part of a pre-existing case.

The contact who will be submitting the webform (contact 1) has an assigned role in the case and a relationship to the case manager. We're using Views to show some data to this contact including a link to the webform. I understand that I can pass a case ID and/or an activity ID into the form via the URL that is presented to the contact in the View, and I can see how I can do this by rewriting the output of one of the Views fields.

The question is: do I need to pass in both the case ID and the activity ID, or is it enough just to pass in the activity ID?

And what should I have as the settings for the case and activity in the CiviCRM tab for the webform?

# Answer
> 5 votes
Case and activity settings are a bit tangled up with each other in the current (v4.9) version of the module...

BUT, I've just committed several changes to 4.x-dev (soon to be released as v4.10) which:

* Support multiple activities and multiple cases on a webform
* Detach the activity and case tabs from each other so you can more cleanly work with one or the other
* Allow you to file an activity on a case without having to go through the entire case configuration on the webform

When I get this into working shape (probably next week) I would love your help testing it out.

And to answer your question, if you are updating an existing activity it should be sufficient to pass the activity id. In the current version this will only work if contact 1 is the creator or target or assignee of the activity. I may be able to make this more flexible in the next version.

# Answer
> 4 votes
We use Drupal Webform-CiviCRM to create cases, but ofcourse not for the steps you are asking about :-) I would reckon passing in the activityID should be enough, have a play and let me know!

---
Tags: civicrm
---


# Question
Title: Create a new facet block from Taxonomy terms
Hi I am using recruiter distribution, I have creates a new taxonomy named as trades, having few terms, Now I want to create a facet block from these taxonomy terms, could anyone please suggest me any tutorial for doing this. I already have few default facet blocks provided by recruiter distribution. I could not find any proper tutorial regarding creation of facet from taxonomy terms.

Thanks

# Answer
Here is a tutorial for creating facet blocks :Faceted search using search api tutorial

To add a taxonomy term as a facet just check the fields tab to find your term field and enable it and after enabling it you have to re-index and now your facet can be rendered as a block !!!
> 1 votes

---
Tags: taxonomy-terms, search
---


# Question
Title: How can I use WordPress-like short codes?
I am new to Drupal. Previously I was working with WordPress, where you can use short codes for getting plugin functionality for pages.

Is this possible in Drupal as well?

For example in WordPress when editing a blog post I can use this in the editor:

```
[foobar] // This is a short code.

```

And here's how it got defined in WordPress:

```
function foobar_func( $atts ) {
  return "foo and bar";
}
add_shortcode( 'foobar', 'foobar_func' );

```

How to do that in Drupal?

# Answer
> 4 votes
The Shortcode module provides this functionality, it even has this comment:

> Initial work is based on the Wordpress Shortcode API but was reworked for Drupal.

So I think it's the closest thing you're going to find (although the Drupal 7 version is currently only in alpha).

It's not quite the same as the one in Wordpress from the looks of it. It seems you'll need to define a shortcode for each function that you want to run (using `hook_shortcode_info()`), or else define a more complex shortcode that will allow the adding of arbitrary functions.

There are a few extension modules included with the main module that look pretty easy to understand so I'd have a look through those to see exactly what you need to do to add your own functionality.

# Answer
> 0 votes
You might also consider using this premium module: http://codecanyon.net/item/azexo-composer-drupal-page-block-builder/8231339?WT.ac=category\_item&WT.z\_author=azexo

I've been working with it and it is pretty stable. Interface is awesome.

---
Tags: 7
---


title: Drupal 7 Clean URLs and Image Upload

text:
# Question
Title: Drupal 7 Clean URLs and Image Upload
I am currently having problems with uploading images and using clean urls on my website. File permissions are working correctly.

When I upload an image to an article page and then I click refresh to view the page, the image doesn't appear. I check for the image url and an example url would be:

http://example.com/sites/default/files/styles/large/public/field/image/01.jpg

but the image would appear if I modify the url on the address bar to:

http://example.com/?q=sites/default/files/styles/large/public/field/image/01.jpg

I have tried:

turning on and off clean urls (sometimes the images appear, but then they disappear again) modifying rewrite rules in the the .htaccess file folder permissions This happened when I uploaded the site to a server and the url would change, but before uploading the site to the servers and testing it on my computer, the url doesn't change. I am currently thinking that it has something to do with some of the rewrite rules in the .htaccess file.

# Answer
Even if Clean URLs are successfully enabled at install-time, if you have a dedicated server you may still want to follow the steps (below) to enable the more efficient httpd.conf rewrite method for clean URLs. If you choose to do that, you might want to turn off Clean URLs while you are working on the server. Server configuration for Clean URLs on a dedicated server, with httpd.conf
> 1 votes

# Answer
Uncommenting the RewriteBase at line 110 in .htaccess file of root solved the problem for me. Depending on your installation folder, you might uncomment and modify line 106 instead of 110. I found that solution, in a drupal.org article and in case that doesn't solve your problem there are alternative solutions there as well.
> 1 votes

# Answer
I went on another direction with my photos but I figured it out anyway. All I had to do was to delete the .htaccess file in the site/default/files.
> 0 votes

---
Tags: .htaccess, uri
---


title: How to modify drupal views query

text:
# Question
Title: How to modify drupal views query
So Drupal views is creating a query and I need to change the where clause conditions and move it to the on clause. This seems to give me the results that I am looking for. I can not figure out how to do this with views in its self so I have to alter the views query in order to do this.

This is the query that drupal is creating.

```
SELECT field_data_field_procedure_date_time.delta AS     field_data_field_procedure_date_time_delta, field_data_field_procedure_date_time.entity_id     AS date_id_field_procedure_date_time, field_data_field_procedure_date_time.delta AS     date_delta_field_procedure_date_time, node.title AS node_title, node.nid AS nid, field_data_field_procedure_date_time.language AS field_data_field_procedure_date_time_language, field_data_field_procedure_date_time.bundle AS field_data_field_procedure_date_time_bundle, field_data_field_procedure_date_time.field_procedure_date_time_value AS field_data_field_procedure_date_time_field_procedure_date_ti, field_data_field_procedure_date_time.field_procedure_date_time_rrule AS field_data_field_procedure_date_time_field_procedure_date_ti_1, 'node' AS field_data_field_procedure_date_time_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_procedures} field_data_field_procedures ON node.nid =     field_data_field_procedures.field_procedures_target_id AND     (field_data_field_procedures.entity_type = 'user' AND field_data_field_procedures.deleted = '0')
LEFT JOIN {users} field_procedures_node ON field_data_field_procedures.entity_id = field_procedures_node.uid
LEFT JOIN {field_data_field_pre_op_procedure} field_data_field_pre_op_procedure ON node.nid = field_data_field_pre_op_procedure.field_pre_op_procedure_target_id AND (field_data_field_pre_op_procedure.entity_type = 'user' AND field_data_field_pre_op_procedure.deleted = '0')
LEFT JOIN {users} field_pre_op_procedure_node ON field_data_field_pre_op_procedure.entity_id = field_pre_op_procedure_node.uid
LEFT JOIN {field_data_field_procedure_date_time} field_data_field_procedure_date_time ON node.nid = field_data_field_procedure_date_time.entity_id AND (field_data_field_procedure_date_time.entity_type = 'node' AND field_data_field_procedure_date_time.deleted = '0')
WHERE (( (DATE_FORMAT(CONVERT_TZ(field_data_field_procedure_date_time.field_procedure_date_time_value, 'UTC', 'America/Boise'), '%Y-%m') >= '2014-10' AND DATE_FORMAT(CONVERT_TZ(field_data_field_procedure_date_time.field_procedure_date_time_value, 'UTC', 'America/Boise'), '%Y-%m') <= '2014-10') )AND( (field_procedures_node.uid = '3' ) AND (field_pre_op_procedure_node.uid = '3' ) )AND(( (node.status = '1') AND (node.type IN  ('procedures')) )))

```

and I need to get it formated to look like this.

```
SELECT DISTINCT
field_data_field_procedure_date_time.delta AS
field_data_field_procedure_date_time_delta, field_data_field_procedure_date_time.entity_id AS
date_id_field_procedure_date_time, field_data_field_procedure_date_time.delta AS
date_delta_field_procedure_date_time, node.title AS
node_title, node.nid AS
nid, field_data_field_procedure_date_time.language AS
field_data_field_procedure_date_time_language,   field_data_field_procedure_date_time.bundle AS
field_data_field_procedure_date_time_bundle,    field_data_field_procedure_date_time.field_procedure_date_time_value AS
field_data_field_procedure_date_time_field_procedure_date_ti,   field_data_field_procedure_date_time.field_procedure_date_time_rrule AS
field_data_field_procedure_date_time_field_procedure_date_ti_1, 'node' AS
field_data_field_procedure_date_time_node_entity_type
FROM
node node left JOIN
field_data_field_procedures field_data_field_procedures ON node.nid =   field_data_field_procedures.field_procedures_target_id AND   (field_data_field_procedures.entity_type = 'user' AND field_data_field_procedures.deleted  = '0')  LEFT JOIN
users field_procedures_node ON field_data_field_procedures.entity_id =   field_procedures_node.uid AND ( field_procedures_node.uid = '53' ) LEFT JOIN

field_data_field_pre_op_procedure field_data_field_pre_op_procedure ON node.nid =   field_data_field_pre_op_procedure.field_pre_op_procedure_target_id AND  (field_data_field_pre_op_procedure.entity_type = 'user' AND   field_data_field_pre_op_procedure.deleted = '0') LEFT JOIN
users field_pre_op_procedure_node ON field_data_field_pre_op_procedure.entity_id =  field_pre_op_procedure_node.uid AND (field_pre_op_procedure_node.uid = '53' )  LEFT JOIN

field_data_field_procedure_date_time field_data_field_procedure_date_time ON node.nid = field_data_field_procedure_date_time.entity_id AND  (field_data_field_procedure_date_time.entity_type = 'node' AND  field_data_field_procedure_date_time.deleted = '0')
WHERE

(( (node.status = '1') AND (node.type IN  ('pre_op', 'procedures')) ))

```

Its basically the same query except I moved the where conditions of the uid=53 into the ON clause instead of the where clause. Anyone know how I can do this with either changing some settings in the views or by manually modifiying the query with a hook\_views\_query\_alter or a hook\_views\_pre\_exectute?

# Answer
I will show you a sample of how to do it...

In this case if you want to alter the nid to be passed as query to views via filter

```
function hook_views_query_alter(&$view, &$query){
    switch($view -> name){
        case 'view_name':
            if($view->current_display == 'block'){
                $nids = calculate_nid();
                $nids = !empty($nids) ? $nids : array(0);
                $query->where[1]['conditions'][2]['value'] = $nids;
                $query->where[1]['conditions'][2]['operator'] = 'IN';
            }
            break;
}

function calculate_nid() {
// calculations to get nid.
// here you can write sql queries
}

```
> 1 votes

# Answer
Maybe this is too obvious, but have you looked at hook\_views\_query\_alter?

There is a more general Drupal query alter hook, but if it's coming from views, it'll be more efficient to intercept it with the more specific hook.
> 1 votes

---
Tags: views
---


# Question
Title: link to node field on another content type
I have a field that uploads a pdf, I want to get the uri in another node and content type to create a link.

Is this possible to do without knowing the id of the node (so not using node\_load) but by the field name? I tried to create an existing field in my node (see screen) but this seemed to just provide a duplicate field without the already uploaded pdf.

The idea is have the users upload the file in one place.

# Answer
> 0 votes
You should be able to accomplish this using the Linkit module which has access to managed files.

---
Tags: nodes, files
---


# Question
Title: Views 2 - How to show exposed filters when results list is empty?
I have a page that displays all events after the current date. It has an exposed filter where you can set the date - all events after that date will be shown. This all works fine.

However, if there are no results on the initial page load (i.e. no events listed that are after the current date) then the exposed filter isn't shown (so you can't set the date to some time in past and view past events).

I found the relevant view theme template and over-rode the If($exposed) conditional but this did not do it - obviously the decision to show filters or not is made before the template but I haver no idea where.

Please could somebody enlighten me?

Thanks

# Answer
> 0 votes
Ok. The ominous non-sound of tumbleweed lol

Well, after a bit of faffing and a \>slap forehead\< "D'Oh" moment I sorted it.

I added some text in the "Empty text" setting (under "Basic Settings") and the exposed filters now show when there is no result.

---
Tags: views
---


# Question
Title: Use image from view as background image of div in page.tpl.php
I need to use the image resulting from a view as the background image to a div in my page.tpl.php.

I am able to render the page title with the view below it using:

```
<div class="container-inner clearfix">
  <h1 id="page-title">
    <span><?php print $title ?></span>
  </h1>
  <?php $views = views_embed_view('photos', 'block'); print render($views);?>
</div>

```

However, is there a way that I can pull the image from the view, and use it as the background image for `container-inner`?

# Answer
Sure. Just look at what's inside `$views` and grab the path/url of the image there and stuff that into `$background_image` and then do something like:

```
<div class="container-inner clearfix" style="background: url(<?php print $background_image; ?>)">

```

**Sidenote:** it might be better to this in a preprocess hook and pass in this as a variable instead of putting this logic in your `page.tpl.php` file, eg, something like:

```
function my_module_or_theme_preprocess_page(&$vars) {

  // $views=views_embed_view('photos', 'block');
  $views=views_get_view_result('photo', 'block'); // appears to work easier :)
  $background_image=// however you get the url/path to the image from $views;

  $vars['background_image']=$background_image;

}

```

which will create a `$background_image` variable that is now available inside `page.tpl.php`.
> 2 votes

# Answer
Make sure to have a look at Background Images Formatter. It allows you to define a background-image (and size) for any given CSS-selector, as specified in your view (using an image field).
> 1 votes

---
Tags: views, theming
---


# Question
Title: How to use entity field as div background image in Views Slideshow?
I have a "background image" field for a particular entity type. I want to be able to upload an image there, and have that image be displayed as a background image in a div created by a View. An example use case would be a Views slideshow where that background image would be the background image of the slide being viewed, and the entity title and any other chosen fields would be laid on top of that.

One thought I had was to rewrite the output of one of the slideshow fields but I'm not sure how I can rewrite the image into a "background image" position.

Is this possible? Any ideas on how to accomplish this?

Thanks!

# Answer
> 1 votes
This seems more like a css/html question but here goes:

You can theme your view so it outputs each slide as follows:

```
<div class='container'>
    <div class='background'><img src='/img/url/here.jpg' /></div>
    <div class='foreground'>Overlay copy</div>
</div>

```

With your css as follows:

```
.container {
    position: relative; /* this is required to keep all absolutely positioned child elements contained */
    overflow: hidden;
    height: 100px;
    width: 1200px;
}

.background {
    position: absolute;
    left: -200px;
    top: 0;
    height: 100px;
    width: 1200px;
    z-index: 1;
}

.foreground {
    position: absolute;
    left: 50px;
    top: 50px;
    height: 50px;
    width: 300px;
    z-index: 2;
}

```

This will position the background div at 0,0 (relative to container) and position the foreground div in front of the background.

# Answer
> 1 votes
Make sure to have a look at the Background Images Formatter module. It allows you to define a background-image (and size) for any given CSS-selector, as specified in your view (using an image field).

This actually takes care of the popular demand of using specific background images in views (and avoiding the inline-style method, which is impossible in Views)

---
Tags: 7, views
---


title: Permission rebuild fail

text:
# Question
Title: Permission rebuild fail
My Drupal 7 site is upgraded from Drupal 6. When I install the Domain Access (not installed with Drupal 6) module, I need to rebuild permissions.

I tried rebuilding them from the administrative pages, but it fails; I tried doing it with Drush, but it failed again.

```
drush php-eval 'node_access_rebuild();'

```

I can't find any information in watchdog and PHP logs.

Does anyone know why it happens, or how I can fix this?

# Answer
> 0 votes
I was having a similar problem (Rebuild Permissions failing) and tracked it to Organic groups.

1. Go to Administration \> Configuration \> Organic groups \> OG field settings
2. Under **Bundles** select the **Group** content type
3. Under **Fields** select **Group visibility**
4. Click **Add field**

---
Tags: 7, domain-access
---


# Question
Title: How to create mutliple order statuses in Ubercart?
Is it possible to create multiple order statuses?

I.e. order can be "In checkout" and "Paid" (I have a list with few parameters which may be set to `true` or `false`).

My software: Drupal 7.24, Ubercart 3.6

# Answer
First off, just a friendly reminder to get yourself on the latest release of Drupal 7 core ASAP, as there was a major vulnerability discovered in all versions of Drupal 7 prior to 7.32.

As for your direct question, I don't believe you can set multiple order statuses for the same order at the same time. What you can do, however, is setup a couple of other fields on orders to handle your additional statuses and then automatically set those statuses using Ubercart's Checkout Rules. For the example you stated, though, I'm not sure if it makes sense that an order would be "In checkout", which means that the user hasn't completed the checkout process, and "Paid", which usually happens as part of completing the checkout process.

Regardless, you can add a custom field for an Order at "/admin/store/settings/orders/fields". Then, you can add a new Checkout Rule at "/admin/store/settings/checkout/rules" and set the value of the new field automatically triggered by one of the Rules events Ubercart lists when creating the rule.

If you provide more detail on what the fields are and how you're planning on using/reporting on them, I may be able to help further.
> 2 votes

---
Tags: ubercart
---


title: Why I can not find some css with grep?

text:
# Question
Title: Why I can not find some css with grep?
I'm newbie and I don't know how Drupal 7 work! I want to remove with and height from below code:

```
<img typeof="foaf:Image" src="http://ashkanplastic.loc/sites/default/files/styles/large/public/slider-1a_0.jpg?itok=k4X3QU5U" width="480" height="236" alt="">

```

Could you please introduce to me why I can not find 480 with `$ grep -H -R 492`? And please help to remove width and height.

# Answer
Please check Remove width and height from img tag in Drupal output (for certain content type) for removing width and height from image.

You will never find width and height with grep command because width and height are added by drupal theme function.

Check https://api.drupal.org/api/drupal/modules%21image%21image.module/function/theme\_image\_style/7 and https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_image/7 for more details.
> 1 votes

---
Tags: 7
---


title: Form elements as arrays #tree

text:
# Question
Title: Form elements as arrays #tree
So I'm struggling with the concept of trees in Drupal. I have a form that presents a user with a drop down of number 1 - 27 depending on what they pick the form renders out an equal number of text fields. The goal is to collect all the values put into the text fields into an array even if it's a single element. Right now all that seems to happen is the last field is written as a string to the variable.

What I have:

```
if (!isset($form_state['values']['number_subscribers'])) {
$form_state['values']['number_subscribers'] = 0;
}

for($i = 0; $i < $form_state['values']['number_subscribers']; $i++){
$form['subscribers_wrapper_container'][]["#tree"] = TRUE;
$form['subscribers_wrapper_container'][]['UCM_SUB'] = array(
'#type' => 'textfield',
'#size' => 30,
'#title' => t('Subscriber IP Address'),
'#required' => TRUE,
);
}

```

End goal would be to read `$form_state['values']['UCM_SUB']` and have it return an array.

# Answer
This:

```
$form['subscribers_wrapper_container'][]["#tree"] = TRUE;
$form['subscribers_wrapper_container'][]['UCM_SUB'] = array(...

```

Can't be what you meant to do. You're creating two new elements there, one with only `#tree` in it.

Surely you want the tree on the outer element, e.g.

```
$form['subscribers_wrapper_container']['UCM_SUB']['#tree'] = TRUE;

for($i = 0; $i < $form_state['values']['number_subscribers']; $i++){
  $form['subscribers_wrapper_container']['UCM_SUB'][] = array(
    '#type' => 'textfield',
    '#size' => 30,
    '#title' => t('Subscriber IP Address'),
    '#required' => TRUE,
  );
}

```
> 1 votes

---
Tags: 7, forms
---


title: Equivalent of file_transfer()?

text:
# Question
Title: Equivalent of file_transfer()?
I am porting a Drupal 7 module to Drupal 8; it has a call to `file_transfer($uri, $headers)`. What's the equivalent Drupal 8 code for this?

# Answer
> 3 votes
It seems `file_transfer` was removed in favor of `BinaryFileResponse`.

> Symfony has a `Symfony\Component\HttpFoundation\BinaryFileResponse` class that can be used to deliver files through PHP to the client. It also supports `X-Sendfile` and `X-Accel-Mapping` via BinaryFileResponse::trustXSendfileTypeHeader().
>
> file\_transfer() has been dropped in favor of that.
>
> Drupal 7:
>
> ```
> <?php return file_transfer($uri, $headers); ?>
>
> ```
>
> Drupal 8:
>
> ```
> <?php
> use Symfony\Component\HttpFoundation\BinaryFileResponse; ...
> return new BinaryFileResponse($uri, 200, $headers);
> ?>
>
> ```

When looking for exact replacements and changes in D8, check the relevant api.drupal.org doc page and change records. I find it really comprehensive and has almost every change.

On a side note, I would reevaluate the module code if it happens for you to `file_trasnfer()` a file. Entire menu system was replaced with Symfony components and I think the odds are, you are still using the old system if it happens to `file_transfer()` or use some request-response thing in the site.

---
Tags: 8
---


# Question
Title: Is there any way to use SQL Views in Drupal Views
I have some very tricky reports to develop (with multiple subqueries) and it occurred to me that the Data module would be perfect: I can create my complex queries as SQL Views (I know how to do this), then adopt them with Data and use them as ordinary tables in Views. Perfect!

Except that although you can adopt a SQL View, it won't show up in Drupal Views (apparently because no primary key) and of course you can't add a primary key to a SQL View.

Is there any way round this by using a module to replace the View SQL query? I have searched a lot on the web and cannot get around the problem without coding object PHP which to be honest I find intimidating.

# Answer
I dont know your use-case. But look at new Raw SQL Query module, and see its attached screenshost(s) for how you define the `SELECT queries` and the report pages it generates:

> It builds "tables" (mysql views using "CREATE VIEW" statement) based on raw sql queries. I would say it is like a lightweight version of a materialized views approach. It uses Ctools to manage data storage and PHPExcel to export data into a Excel file :) After installation, go to admin/config/development/raw\_sql\_query Do not forget clean cache after you store a query.

It sounds like this module is caching the returned data (I'm not 100% sure). But that would be helpful since a mysql view is literally a `SELECT` query upon every access to the data.
> 1 votes

---
Tags: views, database
---


# Question
Title: How do I log in as a different user when there isn't a login link on the front page?
I created a user with limited rights and logged in as that user.

Now I have discovered that I have not placed a login module on the front page.

How do I log back in as administrator?

# Answer
> 0 votes
Click logout - *usually* in the top right corner (but may vary depending on theme); `/user/logout` is the address.

Then log back in (from `/user`) with your administrator credentials.

---
Tags: users
---


# Question
Title: D8. How can check is a formatter in use?
I contribute a module that provides additional formatters for the core image and link fields.

To protect the module from uninstall, I need a possibility to check if a providet formatter used on a image or link field.

To do this, I use the hook\_system\_info\_alter() with `$info['required'] = TRUE;
$info['explanation'] = t('Field formatter(s) in use');`

Someone has an idea?

# Answer
Solved.

See the function dsbox\_system\_info\_alter() of the Drupal Swipebox module to get detailed informations of the solution.
Or, here is the link to the code of the module file: dsbox.module
> 0 votes

---
Tags: hooks, entities
---


title: Ajax breaks jQuery Toggle

text:
# Question
Title: Ajax breaks jQuery Toggle
I use a small script that hides/shows a pane when a certain element is clicked.

```
(function($) {
Drupal.behaviors.luminary = {
    attach: function (context, settings) {
         $(".toggle-visible").click(function () {
         var targetselector = $($(this).attr('data-target-selector'));
         targetselector.slideToggle("fast");
      });
    }
}
})(jQuery);

```

It works well, but when an ajax event occurs, the pane will slide visible, and immediately slide invisible again. It goes down, and comes right back up. It only happens after an ajax event. Any ideas?

# Answer
> 1 votes
Change

```
$(".toggle-visible").click(function () {

```

for

```
$('.toggle-visible').unbind('click').bind('click', function() {

```

---
Tags: ajax, javascript
---


title: Webform Submission Count using views

text:
# Question
Title: Webform Submission Count using views
I am trying to create a view that will count the number of submissions that a particular webform has.

So far I have added the field: Webform: Webform submission count

and added in a Node:ID filter to the ID of my webform.

When I preview the webform it works fine, however when I place the view on my front page it returns 0 results.

I am thinking this is because anonymous users don't have permissions to access submissions? Which I don't particularly want them to anyways.

The field also links to the submissions page of my form, which I don't want it to do either, i just want text there. I have checked the settings and there is nothing to say that the field should link to the submissions.

Bottom line, how can I create a view or perhaps if there is a count module, that will show the number of times a particular form on my site has been submitted?

Thanks! :)

# Answer
For removing the link all you have to do is click on REWRITE RESULTS Then click on "Rewrite the output of this field" and then check "Strip HTML tags" That should remove the link.

The easiest way to achieve the other one is a bit of a hackish solution. You need can go to webfor/views folder and look for the file webform\_handler\_field\_submission\_count.inc

with in that file check for the render function.

```
  function render($values) {
    global $user;

    $output = NULL;
    if ($this->count_type == 'node' && in_array($values->{$this->aliases['type']}, webform_variable_get('webform_node_types'))) {
      module_load_include('inc', 'webform', 'includes/webform.submissions');
      $node = node_load($values->{$this->aliases['nid']});
      //if (webform_results_access($node, $user)) {
        $count = webform_get_submission_count($node->nid);
        $output = l($count, "node/$node->nid/webform-results");
      /*}
      else {
        $count = webform_get_submission_count($node->nid, $user->uid);
        $output = l($count, "node/$node->nid/submissions");
      }*/
    }
    elseif ($this->count_type == 'users') {
      $output = db_select('webform_submissions')
        ->condition('uid', $values->{$this->aliases['uid']})
        ->countQuery->execute()->fetchField();
    }

    return $output;
  }

```

In this above code I have commented a section. You can do the same it should work now for anonymous user. As I said this is a hackish solution and wont advice to do the same. The cleaner method would be to create a custom module and add the handler you want in the custom module and use that instead.
> 1 votes

# Answer
Webform 7.x-4.2 will have this feature built-in. If the user has access to NEITHER the list of all results NOR the list of the user's results, then a simple count of all the results will be displayed, with no link. See: https://www.drupal.org/node/2367065
> 0 votes

---
Tags: views, webforms
---


# Question
Title: How can I detect a "page's" content type?
I have begun work on a Drupal website and unfortunately I did not have an opportunity to have them walk me through the website as is.

I'm now trying to replicate content from a development site to a live site, but there is a page which I cannot identify as a particular content type, though I know it is content, because it says on the page "Clone Content."

How can I figure out this page's content type so that I can replicate it? Is this the right question to be asking?

I apologize if this is an ambiguous question, I will clarify any detail needed.

As a side note: Is there any way to clone content *between* Drupal websites? Like exporting and importing? Perhaps a tutorial I should check out?

Thanks so much in advance.

# Answer
A few quick answers to your questions:

1. If you view source on any page, you should see a class name on the body element, something like: node-type-article. This is one way to see the content type. Also, if you edit a page, you'll see that the edit title will look something like this: Edit \[content type\] \[title\]
2. Alternatively, navigate to: \[domain\]/admin/content to see a list of all content, which includes the 'type' column
3. The "clone content" link content comes from a module called "node clone" https://www.drupal.org/project/node\_clone, designed to allow in-place duplication of content (fields that should not be duplicated are reset to safe values)
4. There is another module that will allow you to export/import nodes between drupal installs: https://www.drupal.org/project/node\_export It's probably not worth it to get into this unless you have quite a lot of content to move.
> 0 votes

---
Tags: nodes, importing-exporting
---


# Question
Title: Is it OK to programatically access fields defined through the UI?
This is a question about "best practise". I've taken over a project which I'm working on right now, and the custom modules this project comes with all access fields defined through the UI. In other words, the field names are "hard coded" in code - even though the fields are not defined in code. Is this alright?

I'm thinking that the code depends on data (in fields) which it has no guarantee will be there. Anyone could delete the fields at any time.

If you need to access fields from code, how do you make sure that the fields exist? Do you make sure that the modules define the field (programatically)?

# Answer
I usually use the entity\_metadata\_wrapper() function to create a wrapper, and deal with fields through that. But if the field doesn't exist, you can get some not-very-helpful wrapper errors.

To see if a field exists, you don't need a wrapper. You can use:

```
if ($node->my_field) {
...
}

```

You can create content types in code, but nothing (except common sense) is stopping a rogue user from deleting fields after they are created. So if you are really worried about fields disappearing, you should check that they exist before using them, as above.
> -1 votes

---
Tags: 7, entities
---