# Question
Title: How to find if file was successfully uploaded to webform
I am using the file field in webform, I would like to check if the file was successfully uploaded. I was using

> .onChange

But that only means that a file was attempted to be uploaded. How can I be sure if the file was correctly uploaded. Would like to do this via javascript/jquery to trigger some next steps.

Thanks.

# Answer
> 1 votes
I wouldn't recommend doing this with javascript, you should use a PHP function to inform the client-side of success.

However, if you insist on doing it, you could (in theory) just create a new AJAX call to the location wehre you expect the new file to be. If it errors, it means it wasn't uploaded.

```
$.ajax({
    url:'http://www.example.com/yourfile.jpg'
    error: function()
    {
        //file not there.
    },
    success: function()
    {
        //file is there
    }
});

```

---
Tags: 7, webforms, javascript, files
---


# Question
Title: Cache-Control: no-cache despite allowing cache for anonymous users
We have a D7 site I'm trying to cache with Varnish. The assets are caching fine but for some reason every page is served with this header:

```
Cache-Control:  no-cache, must-revalidate, post-check=0, pre-check=0

```

The pages are quite heavy to render and end users aren't authenticated, so I'd really like to find a solution. How can I find out if a module is preventing caching? What else could cause this? We have a similar site that plays completely nice with Varnish but I haven't been able to spot the difference yet.

**Edit**: I checked the site with http://www.isvarnishworking.com/ and it says Varnish is working - "sort of". That is, the age is smaller than one, meaning something is preventing the page from being cached. Below are the full response headers as reported by the service.

```
Server: Apache
X-Drupal-Cache: MISS
Expires:    Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified:  Mon, 27 Apr 2015 17:11:55 GMT
Cache-Control:  no-cache, must-revalidate, post-check=0, pre-check=0
ETag:   "1430154715"
Content-Language:   en
X-Generator:    Drupal 7 (http://drupal.org)
Content-Type:   text/html; charset=utf-8
Content-Length: 45567
Accept-Ranges:  bytes
Date:   Mon, 27 Apr 2015 17:11:56 GMT
X-Varnish:  1868715414
Age:    0
Via:    1.1 varnish
Connection: keep-alive
X-Varnish-Cache:    MISS

```

# Answer
Inspect your HTTP headers and see if session or other cookies are being set. This is the most common cause of Varnish "not working." Also make sure you are not logged in, and you can test using http://www.isvarnishworking.com/ to see what headers are outputted. If you could paste the headers would be helpful.
> 1 votes

---
Tags: 7, caching, proxies
---


# Question
Title: Views Data Export Not working for current page
I am using View Data Export to export users in csv. I am using a page view. Fields, User Name, Email. Same fields in Data Export display type and filters.

In Data Export display, using Parent Sort Checked.

Here are the page and Data Export Display using same settings.

Data Export Display.

On Page Display I am showing 5 users, with full pager. On Data Export Display I am using 5 as well.

When I change page, goto next page on /export-user, CSV Icon cant export users other than first 5 no matter on which page I am.

So the csv Icon shows the same link on each page.

Any idea if I am missing something.

# Answer
> 0 votes
Here is a patch that worked for me.

# Answer
> 0 votes
It seems issues with the module itself. You can just use view's template file or hook\_views\_pre\_render() rather than attachment.

Append a link after views content or in footer called `Export CSV`.

Your code will be like this :

```
print l('Export CSV', 'userexport.csv', array('query' => array('page' => $_GET['page']));

```

---
Tags: views, importing-exporting
---


# Question
Title: Passing a custom variable from preprocess view to a template file
I am preprocessing a view in order to create a custom variable and then pass it to a view template file.

I have added the following code to the template.php file:

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

    $currentpath = current_path();
    $path_alias = drupal_lookup_path('alias',$currentpath);

    // define the custom variable
    $vars['mycustomvariable'] = '';

    if ($view->name == 'mycustomviewname') {

        foreach($view->result as $key => $result) {
            $tid = $result->tid; // get the taxonomy term's ID
            $termpath = drupal_get_path_alias('taxonomy/term/' . $tid); // term's path
            // if the current path is same to the one of the term
            if ($termpath == $path_alias) {
                // give a value to the custom variable
                $vars['mycustomvariable'] = 'blablabla';
            }
        }
    }
}

```

Then in the views-view-list--mycustomviewname--block\_1.tpl.php file, I try to print the variable like this:

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

```

But I am getting the error:

> Notice: Undefined variable: mycustomvariable in include() (line 18 of views-view-list--mycustomviewname--block\_1.tpl.php)

I have spent a considerable amount of time on this issue and used dpm and print\_r to print out variables, arrays and objects but I cannot seem to find solution to this issue.

Any help would be appreciated. Thank you in advance.

# Answer
I'm not fully sure what I'm going to tell you is completely true, it is just my experience of how Views works.

From what I know, Every preprocess function has access to a specific `output` template file. As an example variables of `template_preprocess_views_view_fields` are available in `views-view-fields--AnyThingElse.tpl.php` template file, so the domain access of variables of `template_preprocess_views_view_fields` is `views-view-fields--AnyThingElse.tpl.php`.

In *Theme Information* there are three levels of output styles:

1. Display output
2. Style output
3. Row style output

The `views-view-list--mycustomviewname--block_1.tpl.php` is a TPL file in the second level (`Style output`) but I guess the `mycustomtheme_preprocess_views_view` domain of access of its variables is in the first level (`Display output`) TPL files.

To make sure, select one of the TPL files from `Display output` and check if the variable is set in there.
> 1 votes

---
Tags: 7, views, theming
---


# Question
Title: hook_preprocess_page(): how to tell a views page?
Im writing a custom module that need to insert some javascript and css files only in a Views page.

Im using hook\_preprocess\_page, but I can not tell if the current page is from a view:

```
function mymodule_preprocess_page(&vars)
{
    var_dump($vars); //output: nothings that reference the views!
    if([view page])
    {
        drupal_add_js([...]);
        drupal_add_css([...]);
        // Rebuild scripts
        $scripts = drupal_get_js();
        $vars['scripts'] = $scripts;
        // Same for css
    }
}

```

I know i could use a template file (page-my\_view\_page\_path.tpl.php), but the js and extra css must be included only if my module is enabled; **so I like to keep this things directly inside my module code**.

Ideas?

# Answer
`views_get_page_view()` finds out what, if any, page view is currently in use. If it returns NULL, then the current page is not a views' page.

But using `drupal_add_js()` and `drupal_add_css()` in a `hook_preprocess_page()` won't work as expected because the variable `$script` and `$style` variables have already been set by `template_preprocess_page()`. Views's template preprocessing (see Jeremy French's answer) is probably a better place to add your CSS and JavaScript.
> 12 votes

# Answer
There is a lengthy thread on preprocessors for views here. This comment looks very simple to me.

```
function mymodule_theme_registry_alter(&$theme_registry) {
  //dpm($theme_registry);
  $theme_registry['views_view__YOUR_VIEW_NAME_HERE']['preprocess functions'][] = 'mymodule_preprocess_func';
}

// now go on and play with your new preprocess function
function mymodule_preprocess_func(&$vars) {
  // etc
}

```
> 11 votes

# Answer
If you're in a hook\_preprocess\_page() then, by definition, your view has a page display and a menu path, which must be unique - so you can do this:

```
function mymodule_preprocess_page(&vars)
{
    var_dump($vars); //output: nothings that reference the views!
    if($_GET['q'] == 'my/view/path')
    {
        drupal_add_js([...]);
        drupal_add_css([...]);
    }
}

```

If you have arguments being passed to this page, so you need parts of `$_GET['q']`, then do this instead with Drupal's `arg()` function:

```
if(arg(0) == 'my' && arg(1) == 'view' && arg(2) == 'path')

```

http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/arg
> 8 votes

# Answer
For me this one works:

```
function MYMODULE_preprocess_page(&$vars) {
  $view = (array)views_get_page_view();
  if (!empty($view)) {
    // do stuff
  }
}

```
> 3 votes

# Answer
If you are adding JS or CSS to a specific callback then better to use `hook_page_build()`:
> 2 votes

---
Tags: views, 7, theming, javascript
---


title: Check if viewing a Views page

text:
# Question
Title: Check if viewing a Views page
How do I check if the page I'm viewing is a Views page? I want the breadcrumbs to be hidden if the user is viewing the view page I made, which I named "Products."

I am using Drupal 7 and Views 7.x-3.0-beta3.

# Answer
> 7 votes
Following Jeremy French reply, I must say that you can do it like this :

```
if(function_exists('views_get_page_view') && views_get_page_view()){...YOUR CODE HERE...}

```

Taken from here:

> views\_get\_page\_view() finds out what, if any, page view is currently in use. If it returns NULL, then the current page is not a views' page.

# Answer
> 3 votes
Quick and dirty would be to use CSS - take the class Drupal assigns to the views page and then do something like:

```
.drupal-views-page-class .breadcrumb-container {display:none}

```

Of course, you need to use your actual class names.

# Answer
> 2 votes
For d6 site the following trick might work.

```
/**
 * Implementation of hook_views_pre_render()
 */
function mymodule_views_pre_render($view) {
  if ($view->name === 'my_products_view') {
    drupal_set_breadcrumb();
  }
}

```

# Answer
> 0 votes
I have some code that shouldn't be displayed on certain content types. There's an easy approach for this:

```
<?php if (!empty($node) && (($node->type != 'article') && ($node->type != 'webform'))): ?>
     This content is shown everywhere except on articles and webforms. Yet it doesn't show up on views pages either while it should.
<?php endif; ?>

```

But it occured to me that it would hide this content for views pages as well (because the node is empty there: `(!empty($node)`).

My workaround for this is:

```
<?php
    if(function_exists('views_get_page_view') && views_get_page_view()){
      $viewspage = "yes";
    }
  ?>
<?php if (((!empty($node)) || (!empty($viewspage))) && (($node->type != 'article') && ($node->type != 'webform'))): ?>
     This content is shown everywhere except on articles and webforms. It does show up on the other content types ànd the views pages. So it's ok.
<?php endif; ?>

```

This is working, but I wondered if this is the right approach. It looks a bit like a kindergarten-method.

# Answer
> 0 votes
For me the following works in `hook_preprocess_page()` and in `hook_preprocess_html()` as well:

```
function MYMODULE_preprocess_page(&$vars) {
  $view = (array)views_get_page_view();
  if (!empty($view)) {
    // do stuff
  }
}

```

---
Tags: views
---


# Question
Title: Policy Question: Can I Use a Submodule that Does Not Follow Drupal Code Guidelines?
I have a fairly extensive plugin system that I wrote.

It uses an MVVM pattern, where the lions' share of the code is in a cross-CMS class.

I haven't submitted the Drupal plugin to the Drupal repo, because it does not follow their coding conventions.

It has extremely rigorous coding conventions; just not the ones prescribed by Drupal.

Fair enough. They have every right to dictate coding standards. That's a good idea, and I support it.

However, I can't rewrite the MVVM library to make just one of the targets happy.

Since the MVVM library is actually a submodule, can I submit the plugin to the Drupal repository if the Drupal-specific parts (just a couple of files) are set up to use Drupal standards?

For that matter, since Git is so horrible with submodules, I wonder if the Drupal repository can even handle submodules.

# Answer
> Since the MVVM library is actually a submodule, can I submit the plugin to the Drupal repository if the Drupal-specific parts (just a couple of files) are set up to use Drupal standards?

Yes, as long as your Drupal project conforms to the GIT repo policy \- where just *one* of terms are: "All code should comply to the coding standards." you can commit it (such projects are known as "bridge modules") to the Drupal repo (provided you have the access level required to do so - the access bar is low for sandboxes, but a lot higher for full projects). Note: You should *only* commit the Drupal-specific part. The rest has to be hosted somewhere else. Tell your users how to find it, and how it shall be combined with the Drupal-specific bridge.

However, there are other terms, and it looks like the BMLT License, as it currently appears, is a blocker:

> "BMLT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version **3** of the License, or (at your option) any later version." (my emphasis)

Drupal.org doesn't accept this license for *any* code in its repo. For code to be permitted in the repo, it *must* be licensed under: "version **2** of the \[GPL\] License, or (at your option) any later version". There are no exceptions to this rule.

Provided you can get the license right, there is nothing in the Drupal.org Git Repo Policy that prohibits a bridge module that requires *other* software (i.e. not packaged on Drupal.org) to be hosted on Drupal.org.

> For that matter, since Git is so horrible with submodules, I wonder if the Drupal repository can even handle submodules.

When a bridge module is hosted on Drupal.org (and there are plenty of them there already), it has to be combined with other required bits and pieces manually (i.e. there must be human readable instructions in the README about where to find the other software and how to assemble the pieces). While I can see the beauty of using *Git* to pull all the pieces together, that is not how it is done. Provided you and your users can deal with a two phase install where a human is required to do the assembly, it is doable.

As noted by Alfred Armstrong in a comment, the convention is to have a directory below the libraries folder (usually `sites/all/libraries`) to hold files the user must download from elsewhere. Then use the Libraries API module to integrate the bridge with the other files.
> 8 votes

# Answer
I recommend adjusting your coding style to fit with Drupal coding standards for your *bridge module*, otherwise you're not fully supporting Drupal.

I'd expect you to do the same thing for a Wordpress module, or Plone specific integration module -- follow those communities conventions.
> 2 votes

---
Tags: community-official-site
---


# Question
Title: How do you upload files using the RestWS module?
I have a remote front-end application under development and I would like to interface with Drupal as a backend service, using the RestWS module to create a RESTful service to my Drupal instance (using JSON as my data format).

I have a node content type of type "article", that has an image field on it called "field\_image".

I'm currently trying to figure out the proper way to upload a file to Drupal through the API created by RestWS.

I can retrieve a node with a file attachment via GET to the URL http://www.example.com/node/1.json, which retrieves the contents of node 1, including the information about the uploaded file:

https://gist.github.com/lhridley/8bbf95294aa529d74c74

I can also retrieve information specifically about the file attachment, using the FID returned when requesting information about the node, using the url http://www.example.com/file/1.json:

https://gist.github.com/lhridley/804eb93016845f369535

Now, my question:

How specifically do you upload a file using RestWS, so that you create a file resource to then use when creating a node?

# Answer
> 0 votes
i use services not restWS, but the steps are quite similar on every REST service.

with your REST client. ie, restsharp, in my case im using Http (plugin for unity). your first need to be connected, to do that call your server.dominio.co/site/apiName/user/login.json (you need to tick the option on your rest api, that enables user login service). also need to tick file creation permission. if your are using token rememter to save it, also the session name, and session id myForm.AddHeader(session\_name,session\_id) (is the cookie). in my case i dont send it because http already do it for me. after that this is how i upload a file with c# and services,

Hashtable hashdata = new Hashtable();

```
    WWWForm myForm = new WWWForm();
    myForm.AddField("file", base64Img);
    myForm.AddField("filename", name);
    myForm.AddField("filepath", "public://" + folderName);
    string path = server.dominio.co/site/apiName + "file";
    HTTP.Request theRequest = new HTTP.Request("post", path, myForm);

    theRequest.synchronous = true;
    theRequest.AddHeader("X-CSRF-Token", myTOKEN);
    theRequest.Send((request) =>
    {
        if (request.response != null)
        {
            request.response.GetHeaders();

            string result = request.response.Text;
            hashdata = new Hashtable();
            hashdata = (Hashtable)JSON.JsonDecode(result);

        }

    });
    return hashdata;

```

will return the fid of the file just uploaded... after that you will need to update the field of the node where you want the file to be attached to... you will need a new REST request to update that node, method update, etc, etc

Hopes this helps a bit.... know it's not THE solution... but hope it points you the right way.

---
Tags: 8
---


title: How to define Meta tags on Views?

text:
# Question
Title: How to define Meta tags on Views?
Is there any module or some configuration that I can define the meta tags for the views page display in drupal 7 using Views 3.0?

# Answer
> 7 votes
The Meta tags quick module allows you to specify Meta tags based on path for your views. If you enable path-based meta tags, you will see 'Edit meta tags' link on the views page (important - not in the views edit screen!).

# Answer
> 13 votes
The Metatag module has views integration from the box since 7.x-1.0-beta2.

Install the metatags\_views submodule and you'll get metatag options in the views UI for any views page display (Paul Querol's comment below).

# Answer
> 2 votes
If you don't want to use the "Path-Based Metatags" as mentioned earlier you could make the default metatags\_quick fields added to the term itself work as desired with the following approach. Here is an example of how I did it with robots and the help of `drupal_add_html_head()`:

```
/**
 * Implements hook_preprocess_HOOK()
 */
function MYMODULE_preprocess_page(&$vars) {
  // if this is a term page and not being edited
  if (arg(1) == 'term' && is_numeric(arg(2)) && is_null(arg(3))) {
    // if this is a Views page
    $view = (array)views_get_page_view();
    if (!empty($view)) {
      // if metatags_quick robots are set
      $term = taxonomy_term_load(arg(2));
      if (isset($term->meta_robots) && !empty($term->meta_robots[LANGUAGE_NONE][0]['metatags_quick']))

      $element = array(
        '#tag' => 'meta',
        '#attributes' => array(
          'name' => $term->meta_robots[LANGUAGE_NONE][0]['meta_name'],
          'content' => $term->meta_robots[LANGUAGE_NONE][0]['metatags_quick']
        ),
      );
      drupal_add_html_head($element, 'MYMODULE');
    }
  }
}

```

# Answer
> -1 votes
Most straight forward solution is to add the view as a block inside a node, and then use module like Metatag to place metatags on the node.

Avoids the views integration issue. Also provides benefit of breadcrumbs, menus, pathauto, etc. all easier to set up when page is a node rather than a view.

---
Tags: 7, views, meta-tags
---


title: How to override "action" of a form?

text:
# Question
Title: How to override "action" of a form?
after a form submission I want to redirect to an url. The "action" attribute of the form is `['#action']=homepage`. How can I override this?

I have used this code

```
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='views-exposed-form-job-search-search-page') {
    global $base_url;
    $form['#action'] = $base_url.'/search/job';
  }
}

```

However it doesn't work, it still redirects me to /homepage. What am I missing? Thanks

# Answer
The `$form_id` argument is the internal form ID, not the CSS ID. For views exposed forms it'll always be `views_exposed_form`.

I think this is the easiest way to target a specific exposed form:

```
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $view = $form_state['view'];
  if ($view->name == 'foo' && $view->current_display == 'bar') {
    // Alter the form...
  }
}

```
> 1 votes

---
Tags: forms
---


title: localhost not showing /import

text:
# Question
Title: localhost not showing /import
If I navigate to `http://localhost:8080/import` I am taken back to the index page.

If I navigate to `http://localhost:8080/?q=import` I am take to the import page.

If I navigate to `http://localhost:8080/admin` I am taken to the list of admin options.

The webserver for localhost is the default one that comes with Phpstorm (in ubuntu 14.04), which is the built in webserver that comes with php5.4 and above.

When deployed to a remote server `/import` works.

What might cause this issue?

# Answer
> 2 votes
Just to eliminate a possible cause of your problem, and **assuming your web server is Apache**: make sure the `mod_rewrite` module is enabled. If it is not, then enable it and restart Apache.

To verify this, open the file `httpd.conf` inside your Apache installation folder and find the line starting with `AllowOverride`:

**If** that line looks like `AllowOverride None`

**Then**:

1. edit it to look like so: `AllowOverride All`
2. and afterwards restart Apache.

If you're using PHP Storm (as mentioned now in the further edited question), it might help to try what is documented in Disabling clean URLs. Here is a quote about that page:

> It's possible that a Drupal site that was once configured to run with clean URLs later on stops doing so. After that, almost all content is inaccessible, because the paths being generated are not supported by the hosting platform.

---
Tags: 7, feeds
---


title: Menu links at the corners of the screen

text:
# Question
Title: Menu links at the corners of the screen
Used omega theme and stumped at menu part.

Top right - Home Top Left - Work Bottom Left - Contact Bottom Right - FAQ

Tried to set 2 menus: top and bottom in menu zone and then set id to each links so they can be positioned accordingly but it didn't work as expected. These menus sit next to the main menu in column 1, 3, 8

How do I put the menu links in menu block then set them at the corners of the screen?

# Answer
For those that are not familiar with Omega theme, it will be hard to help you without more information like a link or your HTML and CSS code. However, you may look up the CSS float property to achieve what you want.
> 0 votes

# Answer
You could use the Menu attributes module to add classes to each module (such as top-left, bottom-right, etc) and style based on those. This will be a lot more robust than using ids derived from the menu link's mid.

Next, to get the links to the corners of the screen, you will need to give them position: absolute or position: fixed. Bear in mind that that will allow you to position them relative to their first positioned (not static) ancestor element. This means that you'll have to make sure that none of the containers around the menu links have a css position of anything other than "static".

Finally you may need to add "min-height: 100%" to the html and body tags in order to make sure that the bottom-left/right links do get down to the bottom of the page.

These changes might break other styling on your page, which would probably mean that one of the containers around your menu links needs to have a position other than static. If you can't work around this then you'll need to move your menu outside of that container by (for example) overriding the relevant templates such as page.tpl.php, or if all else fails, you could use javascript to move the menu to another part of the DOM where it's styling won't effect other elements on the page. However, you should only do that if you're happy that non-javascript users will still get a sufficiently usable experience without the links being at the edge of the page.
> 0 votes

---
Tags: theming
---


# Question
Title: Can you filter nodes in a view by the last date of one node referencing that node
So I have two content types Tours and Concerts. Concerts has an entityreference field that references a tour. I want to filter a view of Tours and only show tours that still have upcoming concerts. Once all concert in a tour are over I no longer want to show the tour. Is there a way to do this? Could you use *hook\_field\_extra\_fields* to calculate the date and then somehow filter by that value in views?

# Answer
The following steps should set this up...

* Create a view of tours
* Add a relationship of type "Entity Reference: Referencing entity" to the concerts
* Make sure "Require this relationship" is ticked
* Add a filter for the date field on the concert type
* Select "Text" under "Date selection form element"
* Ensure the relationship you set up is selected in the "Use relationship" dropdown
* In the filter settings, change Operator to "Is greater than"
* Change "Select a date" to "Enter a relative date"
* type "now" under "Relative date"
> 1 votes

---
Tags: views, entities
---


title: Adding Node Reference to a Comment

text:
# Question
Title: Adding Node Reference to a Comment
If I add a Node Reference field to a node content type (with Reference from URL as a widget,) this field appears in the rendered content and can be used to jump to the referenced node.

I am trying to get a similar result in the rendered comment of the same content type: If I add a Node Reference field with Reference to URL in the Comment Fields edit page of the content type, it doesn't show up in the rendered comment page.

Why do I want to do this? Because when one leaves a comment in the rendered content, a message is sent to the author of the post that a comment was posted. In the email, there is a link to see the comment. The link is of the form *example.com/comment/000#comment-000* and that's not the original post with the comments below.

So I am trying to add a link to the comment page that would send the reader to the rendered node where the comment was originally posted.

Does this mean one cannot reference a node from the same node's comment page?

Or does it mean there is another way to accomplish this?

# Answer
You should be able to display a node reference in a comment, if your not seeing it show up, I would check ether your fields that are being displayed (at /admin/structure/types/manage/content\_type/comment/display) or check your theme to see what's getting printed out.

That being said, if your just looking for a way to put a link in the outbound email to the parent node, there's easier ways to do this. You might want to take a look at Comment Notify, which has a fairly easy to use interface on the back end that allows you to send a template email to the node author that uses tokens for replacement values.

Another option is to just use Actions, which also uses tokens, and add the url to the module. This is handy, as it can be used to send emails to site admins.
> 1 votes

# Answer
You could achieve this with Comment Notify module.
We use it on few sites and it works great out of the box.

From module page:

> Features
>
> Mail registered and anonymous users about comment follow-ups
>
> Allow users to unsubscribe from notifications on a specific post with a single click
>
> Allow registered users to preset their follow-up setting in their profile
>
> Users can choose to get notifications about all comments on a node or just replies to their comment Registered authors can get notifications about comments on their nodes Note: Since it only notifies you about published comments, this is not a solution to notify admins when they need to moderate comments on their site
> 1 votes

---
Tags: 7, comments, nodes
---


# Question
Title: How to make the content fills the space after the sidebar ends in a drupal site?
The client I work for won't accept the fact that the sidebar region continues until the footer. If that happens, the client wants the sidebar to stop when the sidebar content is finished, and the main content should fill the space that the sidebar is using now.

How to make the content fill the space after the sidebar ends in a Drupal site?

# Answer
> 1 votes
This really boils down to what theme your using, and how your content is laid out. But it should be doable with CSS if your theme is laid out correctly. Let's take Bartik for example (one of Drupal's default themes). Simply changing the sidebar-first class to float left and changing the float of the content to none will give you something like this:

And here's a really basic version the same idea running on JSfiddle.

The basic answer of it is, yes, it can be done, but you need to do it through the theme and css. Depending on where blocks are placed, the css already in place on your theme, how you go about doing it might change, but the answer is you need to use css.

# Answer
> 0 votes
If i have understood your question correctly, then as per my understanding i think there is no actual solution for this.

The width of any two elements lying side by side (in this case content block and sidebar block) will be same throughout the length of the blocks. So, content block cannot just take the remaining space, once the length of the sidebar finishes.

---
Tags: nodes
---


# Question
Title: How do I get a LEFT OUTER JOIN in Views that displays all rows with no match in the LEFT JOIN-ed table?
Views 7.x-3.x

```
Staff

sid name
1   Adam
2   Barbara
3   Carol
4   David

Staff Roles

sid rid
1   1
2   1
2   2
3   2
3   3

```

Let's say that I want a list of all staff, excluding staff who have a particular role, and that role id (rid) will be provided in the URL.

Let's say that the rid we want to exclude is 2. So we want our view to display Adam, David.

My approach has been to list all the staff in a view, then add the relationship to Staff Roles, put the rid into a contextual filter, and then say it is to be excluded.

Unfortunately, what this produces is a LEFT JOIN of all the rids except 2. So we get Adam, Barbara, Carol.

So you might think: let's not exclude the contextual filter for rid. Let's include it on a non-excluding LEFT JOIN. Then we can maybe filter for rows with a rid of NULL. Unfortunately, views puts the contextual filter into the WHERE clause of the query, so we end up with just Barbara and Carol.

So my question is:

How would you build a view to list all staff, excluding staff who have a particular role, where that role id (rid) will be provided in the URL?

Alternatively:

How can I get conditions from a contextual filter into the ON part of a view query, instead of the WHERE part?

# Answer
In your RID contextual filter, if you expand the "More" fieldset at bottom of the options modal, you should see an "Exclude" option which will flip the filter operator to negate.
> 0 votes

---
Tags: views
---


# Question
Title: How do I troubleshoot specific Products missing from Commerce Search?
Using Commerce Kickstart 2

Having a situation where certain Products simply do not appear in the Search results. Is there a way to troubleshoot specifically -why- certain products (or other content) are not appearing in the search index?

I looked through the search\_api\_db\_product\_display table and sure enough, the missing node is -not- there.

So: Is there a log or table which displays each node and index term and/or -why- a particular node was included/excluded?

Just to be clear: If I enter the URL for the Product directly, it displays fine.

ALSO: I can search from admin/commerce/products and the Product shows up as well as from admin/content.

Perhaps related: There seems to be a known issue where adding new products does not automatically update the index. But I have cleared the index and rebuilt several times and it makes no difference.

# Answer
Not sure if this is proper 'etiquette' but here is the solution for -this- problem:

My Product Display has an Entity field which displays a list of 'related products' -- a common enough situation in a Shopping Cart system. The related products are a View which displays products linked to the parent product NID.

Like most sites, I imagine, the Index excludes unpublished products.

Apparently if any one of the Related Products is unPublished, this affects the Commerce and/or SOLR Search index for the -Parent- product. IOW: if any child product is unPublished the index skips the -parent- product as being 'unpublished'.

Not sure which module is at the root of this... or who to notify... but if the Commerce Guys monitor, this is a real 'gotcha'. I've run into this many times in Drupal where SQL Queries are not 'isolated' from one another... ie. a child view will affect a parent query.
> 0 votes

---
Tags: commerce, search
---


title: Trigger context by filter value?

text:
# Question
Title: Trigger context by filter value?
I need to essentially trigger a context when a certain filter value is selected. Basically, in a view, when a filter is selected, based on the value selected I need to display a certain block.

Does anything like this exist? Or am I going to have to build my own extension to Context?

# Answer
> 5 votes
With Drupal there are so many way to do things - here is one way to achieve what you need:

1. Go to admin/blocks and add your block to the region you want it to show up in, then set it to display on only the page for that view
2. In your theme css hide that block (display:none)
3. Add some javascript to display the block and bind it to the onchange event for the value you want, either add the js in your module or your theme.

I have not gone into specifics as each step can have variations on how you would like to implement them, but the above is one potential solution to the problem

Using context could work if you submit the view filter to a different path and then set a context to show the block on that path, but if you wnat to do it via an onChange its easier using Js & Css.

**Modules that may also help:**

# Answer
> 3 votes
There is a patch for the context module to achieve exactly what your are looking for. I've just installed it and tested it out and it works perfectly.

There is a thread on drupal.org about it here: http://drupal.org/node/904416

Scroll down to post 28 and download the patch.

To run the patch put it in the context module folder, and then run this command:

```
patch -p1 < 904416.28-context-query-string.patch

```

This is assuming you are using a linux terminal. If you want to do this in Windows or Mac then see this post: http://drupal.org/patch/apply

Once you have applied the patch then run update.php (just go to www.your\_domain.com/update.php) and then flush the cache (always a good idea).

Now when you edit your context there is a new condition called Query String.

When I tested it out I had a field called category and I wanted my block to appear when it had the value of Javascript so I put "field\_category\_value=Javascript" as the value of the query string on the edit context page.

One thing to note here is that the block will only appear after the user has clicked Apply on the filter. If you want it to appear and disappear as soon as the value of the select box is changed then you will need to use Andre's solution.

# Answer
> 0 votes
I found this module http://drupal.org/project/block\_query and it does exactly what I need it to.

It lets you display a block based on query parameters.

# Answer
> 0 votes
https://www.drupal.org/project/context\_query\_param

This module introduces a context condition depending on query strings. Views exposed filters also work with query strings. So you can determine context conditions with the filter parameters.

---
Tags: 7, views
---


# Question
Title: How to create a single page application in Drupal?
I know Drupal and now I am creating a website by Laravel framework. I know what are single page application and how better they are. I used Angular and Backbone as JavaScript framework/library to creating a single page application with Laravel.

I am not professional in Drupal, How can I use these libraries to create a single page application (SPA) using Drupal?

Is there any module to make a (SPA) or automatically make the website Full-Ajax?

# Answer
You could use the Ajax Regions module.

It allows you to load specific regions via Ajax, thus load your whole website on one single page
> 3 votes

# Answer
Try one of the following modules. (They are very different despite similar names.) You can find demo links for each module in their pages.

Single Page Website

> This module provide the ability to display the content of all menu items of the main-menu on the Single Page Website module.
>
> On the page 'single\_page' the links in the menu will be replaced to the links to the correspondent anchors. You can set URL 'single\_page' as front page of your site, and your visitors will see the Single Page Website. But it will be the site managed by Drupal 7.

Single Page Site

> This module provides functionality to create a single page website.
>
> It allows you to automatically create a single page from a menu. The module will render all the content from the links, that are configured in the menu, on one page. It will then override the menu links so that they refer to an anchor instead of a new page. With some additional css you can develop a horizontal single page site.
> 0 votes

# Answer
To create a single page app using Drupal I would recommend you look into the services module to create your end points and then use the Backbone module for creating front end logic. Whilst there isn't a stable release of the Backbone module we are using it on a production website without any problems.

If you Google "Drupal single page app" there are a few talks about it that come up.

The company I work for has a Druapl 7 single page app and it works well, but it pretty complex stuff - not something to take on if you don't know what your doing.
> 0 votes

---
Tags: ajax, javascript
---


# Question
Title: Send email when a user has finished watching something
A user watched a video (added listening event to id of video via jwplayer), and a person is notified of said user finishing the video.

```
jwplayer('some-id-of-video').onComplete( function() {
  //$.ajax or .post whatever to send email to a person to let them know without refreshing page
});

```

I want to just add this script to this page (this functionality is only needed for this ONE VIDEO). How do I link the PHP code to send the email? Not a form everything will be a standard response.

This does not work.

```
$message = array(
  'to' => 'email address',
  'subject' => 'subject text',
  'body' => 'body text',
  'headers' => 'header text'
);

drupal_mail_send($message);

```

Where do I put this? Is this wrong? And if it is wrong, what do I need to fix it? How can I call this code from AJAX?

# Answer
> 1 votes
Create an end point for your ajax request to call using `hook_menu()`. In this example I'm passing the UID of the user as an argument.

E.g:

```
/**
* Implementation of hook_menu().
*/
function myModule_menu() {
  $items['mymodule/send-email/%user'] = array(
    'page callback' => 'myModule_ajax_send_email',
    'page arguments' => array(2),
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );
  return $items;
}

```

The callback for your menu item will be responsible for actually sending the email. See this question: How to send email in drupal

E.g.:

```
function myModule_ajax_send_email($user) {

  // Here you put the code to actually send the email
  $status = some_logic_to_check_email_sent();

  drupal_json(array('status' => $status));
}

```

So then once your video has finished playing you just need to make an ajax request to your new end point, passing any information required as parameters. E.g:

```
(function($) {
    Drupal.behaviors.myModule = {
        'attach': function(context) {

            jwplayer('some-id-of-video').onComplete(function(){
              //$.ajax or .post whatever to send email to a person to let them know without refreshing page
              var UID = 1; // actually set UID here
              var url = 'mymodule/send-email/' + UID;
              $.get(url, null, emailCallback);
            });

        }
    }
    var emailCallback = function(response) {
        var result = Drupal.parseJson(response);
        if(result.status !== 1) {
          // Some code to let user know there was an error
        }
    }
})(jQuery);

```

---
Tags: ajax, emails
---


# Question
Title: Theming a Fieldable Panel Pane — should I define a View Mode?
I added a Link field to Panopoly's Image fieldable panel pane, but I need to theme it so the link is silently wrapped around the image rather than displayed textually underneath. It also needs to be easily specified by content editors. (Use case: a full-width front page "hero image". Content editors should be able to specify a link for the image.)

How should I go about defining a new kind of Image FPP? Should I define a new view mode? (Since I want editors to be able to use link-wrapped images anywhere, a solution tied to the front page would be too restrictive.)

# Answer
Making a field template file would be easier than defining a new mode I think. That would be the normal way to go about it in Drupal.

In your view under `Advanced -> OTHER -> Theme: Information` you will find template names for the various fields in increasing granularity. Create a file with the name that best suits your purposes - in this case probably the one that references just the field name and not a specific view or view mode.

Still inside that window, if you click the field name it will show you the default code for the template file, start with that and then edit to your heart's content. I suggest using `dpm($output);` to inspect the content that is being passed to the template file, and following the suggestions in the code comment provided for your view mode.

\[edit: I misread, thought you were somehow using these in views. A template file is still probably the way to go.\]
> 0 votes

---
Tags: theming, panels
---


# Question
Title: How to add Retargeting tag into each page?
I am using drupal - 7.

I wanted to embed `<script>` tags for Retargeting tag into each page of the Website, between the `<body> </body>` tags.

I am new to Drupal. I am trying to create custom block module for this.

I have created custom module to place tags into custom block. I am not sure what I have done is right or wrong. Can any one help me with this?

**I just wanted to add script like this into each page for Retargeting tags for campaigns**

```
<script async src="http://i.simpli.fi/dpx.js?cid=0&segment=Segment+Name&campaign_id=0"></script>

```

I have added script tag into my js file which I have called from .info file. In my .info file I called;

```
scripts[] = MyCustomBlock.js

```

This is the code for my custom block module.

```
/**  * Implements hook_help().  *  * Displays help and module
information.  *  * @param path   *   Which path of the site we're
using to display help  * @param arg   *   Array that holds the current
path as returned from arg() function  */

function MyCustomBlock_help($path, $arg) {
  switch ($path) {
    case "admin/help#MyCustomBlock":
      return '<p>' . t("Displays links to nodes created on this date") . '</p>';
      break;
  }
}

/**
* Implements hook_block_info().
*/
/**  * Declaring the block  */
function MyCustomBlock_block_info() {
  $blocks['MyCustomBlock'] = array(
    // The name that will appear in the block list.
    'info' => t('MyCustomBlock'),
    // Default setting.
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

/**  * Preparing for a module configuration form  * Implements
hook_menu().  */

function MyCustomBlock_menu() {
  $items = array();

  $items['admin/config/content/MyCustomBlock'] = array(
    'title' => 'MyCustomBlock',
    'description' => 'Configuration for MyCustomBlock module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MyCustomBlock_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/*  * Adding JavaScript from within a module  */

function MyCustomBlock_add_js($data = NULL, $options = NULL) {
    $javascript = &drupal_static(__FUNCTION__, array());
    $jquery_added = &drupal_static(__FUNCTION__ . ':jquery_added', FALSE);
}

```

I can see my block module in the `/admin/modules` section and I can enable my custom block module. But, I am not sure how to add that script into my module.

Thanks for the help!

# Answer
`drupal_add_js()` doesn't support the async property (there is a patch however) but the simplest solution would be to just just add that line to your `html.tpl.php` as Geoff suggested.
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: programmatically get bundles from field collection?
Say I have the machine name of a given field collection. How can I programmatically get the names of the node bundles where one would find this field collection? This would be the same information you see on the `admin/structure/field-collections` page.

# Answer
What about:

```
$bundle = db_query("SELECT bundle, entity_type FROM field_config_instance WHERE field_name = :field_name", array(':field_name' -> $field_name))->fetchAll();

```

If you know the enity\_type then you can use `field_info_instances()`.
> 1 votes

---
Tags: entities
---


# Question
Title: How to use a views contextual filter OR?
After browsing the net and SE for a while it appears to me there is no good solution to combine 2 `contextual filters` with OR (rather than the default AND).

This post mentions a PHP hack and this post has some links to an issue stating a recent change in views 7.x-3.1. It also mentiones using `hook_views_query_alter(&$view, &$query)` to modify the view.

Does anyone have a working example or a better solution?

# Answer
> 7 votes
Try the patch in this issue : Pull filter value from an argument

It allows you to pass the value from the contextual filter to the "normal filter". There you can do your advanced conditions.

# Answer
> 8 votes
The comment thread starting here describes an effective workaround. MotoTribe linked to the same thread, but at the time of his question, there was no working example on that page. Now there is, as follows:

In your module, implement `hook_views_api()`:

```
function MODULENAME_views_api() {
  return array(
    'api' => 3,
  );
}

```

Then add a new file to your module called MODULENAME.views.inc, and implement `hook_views_query_alter()`:

```
function MODULENAME_views_query_alter(&$view, &$query) {
  if ($view->name == 'whatever_your_view_is_called') {
    $query->where[0]['type'] = 'OR';
  }
}

```

Also be aware of this caveat:

Apparently, the "Content: Published (Yes)" filter that comes with every View is considered to be a part of the same filter group as the contextual filters (group 0). So in order to make my view display only *published* nodes which belong to any of the groups specified by contextual filters (published AND (arg1 OR arg2 OR ...)), I had to move the "Content: Published (Yes)" into a new filter group (using the "And/Or, Rearrange" dialog). Note that the UI didn't display the "Content: Published (Yes)" filter any differently after I moved it into a new group (there weren't any other groups), but in the query object that gets passed into `hook_views_query_alter()` it did move it from group 0 into group 1, causing the code in the above functions to no longer affect it.

# Answer
> 4 votes
There is a module which changes handlers of Views to make contextual filters to be used with OR instead of AND: Views Contextual Filters OR

# Answer
> 2 votes
The situation with *Contextual Filters* and *Filter Groups* is indeed bleak. Here is thread on D.o about this toppic, which has the same solution as stated by @CoreDumpError.

https://drupal.org/node/1451218

Also, here is a module that can help resolve conflicting contextual and exposed filters... Views Filter Harmonizer

---
Tags: 7, views
---


# Question
Title: Drupal HTML.tpl.php file won't effect site?
My aim is to allow zooming in and out in mobile devices in my responsive Drupal 7 site. I have followed a Drupalize.me video and some more documentation that teach how to allow it via my theme's HTML.tpl.php and added the marked row there (Image attached), yet nothing happened. Maybe it should go to the system's HTML.tpl.php instead? maybe there is something to apply at the Drupal UI so that the site would be affected? P.S - I've cleared the Drupal cache.

# Answer
There are several ways to achieve this.

You could hand code the meta viewport tag in your html template file as you did. The proper tag may need to be used as shown below:

```
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">

```

You could also use a page alter to add the html to your page as shown below (place in theme template.php):

```
function YOURTHEMENAME_page_alter($page) {
  // Viewport array, change values in content below.
  $viewport = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' =>  'viewport',
      'content' =>  'width=device-width, initial-scale=1.0, user-scalable=yes'
    )
  );
  // Drupal add HTML head.
  drupal_add_html_head($viewport, 'viewport');
}

```

Or you could use the viewport module

Note: Do not alter the system html template file, puppies will die!
> 4 votes

---
Tags: theming
---


# Question
Title: Node content versioning and compare tool
I already know that node content versioning is supported in drupal, what I want to know is how much?

I for instance create a content type 'article' and add some extra text fields to it, The article content should have the capability to be reviewed and altered by many authors/reviewers and their changes will be saved as seperate records not impacting the real article record, only if I approve their changes will they be reflected on main article record.

Which of the functionality is currently supported and what is not?

Thanks

# Answer
> 2 votes
You can use Revisioning module for comparisons of different revisions:

> Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions.

or you can use Diff module:

> This module adds a tab for sufficiently permissioned users. The tab shows all revisions like standard Drupal but it also allows pretty viewing of all added/changed/deleted words between revisions.

---
Tags: nodes, version-control
---


# Question
Title: How can I implement user timezone & user's last login in this format?
Im trying to create a block and I'm having trouble. I'm trying to get the user's last login & the user's timezone. How can I implement those functions in these hooks. All I know is the fact that I need to use the functions of hook\_info & hook\_view.

```
function hook_block_info() {

  $blocks[‘syndicate’] = array(
    ‘info’ => t(‘Syndicate’),
    ‘cache’ => DRUPAL_NO_CACHE,
  );

  $blocks[‘recent’] = array(
    ‘info’ => t(‘Recent content’),
  );

  return $blocks;
}

function hook_block_view_alter(&$data, $block) {

  if (is_array($data[‘content’]) && asset($data[‘content’][‘#contextual_links’])) {
    unset($data[‘content’][‘#contextual_links’]);
  }

  if (is_array($data[‘content’]) && $block->module == ‘some module’) {
    $data[‘contentr’][‘#theme_wrappers’][] = ‘mymodule_special_block’;
  }
}

```

# Answer
You can use the global `$user` object to get user details, or load user details from a uid like this: `$user = user_load($uid);` From the `$user->login` property you can get last login timestamp.

Thanks
> 0 votes

---
Tags: 7
---


# Question
Title: Where to render? Preprocess or template?
We are constantly improving our coding performance and we are monitoring every page load to optimize loading en rendering times in our websites.
Above statement in mind, I stumbled upon the question where should we render the renderable arrays?

If you render them in your preprocessor, the template keeps pretty neat since you're only printing variables.

Preprocessor:

```
function template_preprocess_node__faq(&$variables) {
    $node = node_load($variables['nid']);
    $node_style = node_view($node, $variables['view_mode']);

    $faq_sets = array(
      '#theme'  => 'my_module_faq_set',
      '#sets'   => $variables['field_faq_set'],
    );

    $variables['faq_image']   = render($node_style['field_faq_image']);
}

```

Template:

```
<div class="faq_image">
     <?php print $faq_image; ?>
</div>

```

However, I'm not sure it this is the proper/fastest/neatest way to preprocess and print variables.

Drupal isn't consisting in this matter either I guess... In the default `node.tpl.php` variables are rendered while in other default templates (like `html.php.php`), variables are just printed.

Does anyone have a rule and/or some tips and advices on how to tackle this issue the cleanest and fastest way?

# Answer
> Drupal isn't consisting in this matter either I guess... In the default node.tpl.php variables are rendered while in other default templates (like html.php.php), variables are just printed.

That's not quite right. If you look at `template_preprocess_html()` you can see that nothing is run through `render()`/`drupal_render()`. So quite simply the variables in html.tpl.php are printed rather than rendered because they don't *need* to be rendered. All the vars are already strings, and no render arrays were used to build the template.

Conversely, the node content in node.tpl.php *is* a render array. So any parts of it that need to be rendered have to be run through `render()` and not just printed.

I would be tempted to follow core's example of using `render()` in templates, not in preprocess functions, unless you have a specific reason to do it differently.

From a performance point of view the difference would surely be negligible, but profiling the code in the context of your site and hardware is the only way to be certain.
> 7 votes

---
Tags: theming, performance
---


title: Profiler builder with custom modules

text:
# Question
Title: Profiler builder with custom modules
First things first: happy 2015 to everybody. :-)

Now, I am quite new with Drupal distributions and profiles and here is my situation: I have a running site where I have contributed modules and custom modules. I've installed profiler builder module. When I use `drush distro` to create a distribution, it generates 2 make files: drupal-org.make and local.make.example. The last one "contains" the first one and it contains the custom modules as well.

When I run `drush make local.make.example ./destfolder`, it throws some errors. It says "non-existent project type on custom-module". So after a bit of research I've been able to make it work adding some information to the local.make.example, and adding the custom modules in a zip format.

My question is, why does drush distro generates a useless folder structure (i.e. modules, themes, libraries)? Am I able to put something there to make drush-make work on local.make.example without needing to add extra information? Am I missing something?

The extra lines of code I added in each custom module to the local.make.example was:

* projects\[custom\_module\_name\]\[type\] = "module"
* projects\[custom\_module\_name\]\[download\]\[type\] = "file"
* projects\[custom\_module\_name\]\[download\]\[url\] = localurl

Thanks very much for your time and let me know if you need further information.

**EDIT**

I'm going a bit crazy about this… I've just found out that drush make creates the custom modules' folders but they are empty. Nothing inside… So basically, I just don't know how to tell drush-make to build the initial drupal folder's architecture when custom modules are stored on the same computer I'm executing drupal-make…

I've seen most of the examples that evolves custom modules use git, but I'd just like to know how to make it work with custom modules stored on my machine, if possible.

# Answer
In my experience, Profiler Builder has problem with modules, that are not full projects on drupal.org. I tried to use a module, that is hosted in GIT repository and the output was similar to yours. But it worked fine with `drush generate-makefile`, where generated output was like:

`projects[svg][type] = "module"
projects[svg][download][type] = "git"
projects[svg][download][url] = "http://git.drupal.org/sandbox/josegaert/1511596.git"
projects[svg][download][branch] = "7.x-1.x-dev"
projects[svg][download][revision] = "04db94c4dc2bf5c8c9a2a0da5452c4a79d26d863"`

I created an issue for Profiler Builder describing this at https://www.drupal.org/node/2479185. You may also want to look at https://www.drupal.org/project/make\_local
> 1 votes

# Answer
According to http://www.drush.org/en/stable/make/#project-download-options you should be able to specify `url` for `file` download method. Quoting Drush help:

> The URL can also be a path to a local file either using the bare path or the file:// protocol. The path may be absolute or relative to the makefile.

There's other question similar to yours, where you can find further examples and discussion: How do I use "drush make" modules with a local module code?
> 0 votes

---
Tags: 7, drush, installation-profiles
---


# Question
Title: add code automatically for any article/post
I built a Drupal website with a custom theme, but in the last stand I need to add a specific code after any post/article published on the site. For example:

article 1

code

article 2

the same code...

The pinpoint is that I don't know how to take a reference of a single post/article to include it in a buckle to add this code.

# Answer
> 0 votes
The easiest way is to **create a block** and add your code to it if it's html or javascript code. Then for **Show block on specific pages** select only on the listed pages and add `articles/*` This will affect all the pages that have articles in their url.

If it's php, you will need to **create a custom page tpl** file.

go to drupal/sites/all/themes/mythemename/templates and add **page--articles.tpl.php** This will affect all the pages that have articles in their url.

---
Tags: blocks, nodes
---


# Question
Title: Warning: strlen() expects parameter 1 to be string, array given in drupal_validate_utf8()
I have been getting this error: `Warning: strlen() expects parameter 1 to be string, array given in drupal_validate_utf8()`.

After troubleshooting I was able to figure out line that cause this error that is on a **if** stament.

```
  if (empty ($form_state['num_boxes'])) { // Line with the problem.
    $form_state['num_boxes'] = count($boxes) + 1;
  }

```

After researching I believe that have to deal something with filter\_xss\_admin. However, it seem unclear to me of how to implement with my code.

**Update 1 - Apparently, the code that I provide did not show the error. I have provide more code.**

```
/**
 * Form builder.
 */
function custom_module_overview_form($form, &$form_state) {

  $form['#tree'] = TRUE;
  $boxes = variable_get('custom_module_package_sizes', '');
  if (empty($form_state['num_boxes'])) {
    $form_state['num_boxes'] = count($boxes) + 1;
  }

  $form['sizes']['#prefix'] = '<div id="boxes-fieldset-wrapper">';
  $form['sizes']['#suffix'] = '</div>';

  for ($i = 0; $i < $form_state['num_boxes']; $i++) {
    $form['sizes'][$i] = array(
      '#type' => 'fieldset',
      '#title' => t('Package'),
      '#description' => t('Enter the dimensions of the packing box.'),
      '#attributes' => array('class' => array('physical-dimensions-textfields')),
      '#attached' => array('css' => array(drupal_get_path('module', 'physical') . '/theme/physical.css')),
    );

    foreach (physical_dimensions() as $key => $dimension) {
      $form['sizes'][$i][$key] = array(
        '#type' => 'textfield',
        '#title' => filter_xss($dimension)['name'],
        '#size' => 15,
        '#maxlength' => 16,
        '#field_suffix' => '×',
        '#prefix' => '<div class="physical-dimension-form-item">',
        '#suffix' => '</div>',
      );

      if (isset($boxes[$i][$key])) {
        $form['sizes'][$i][$key]['#default_value'] = $boxes[$i][$key];
      }
    }
    unset($form['sizes'][$i][$key]['#field_suffix']);

    $form['sizes'][$i]['unit'] = array(
      '#type' => 'select',
      '#options' => physical_dimension_unit_options(FALSE),
      '#prefix' => '<div class="physical-dimensions-unit-form-item">',
      '#suffix' => '</div>',
    );

    if (isset($boxes[$i]['unit'])) {
      $form['sizes'][$i]['unit']['#default_value'] = $boxes[$i]['unit'];
    }
  }

  $form['packing_add_more'] = array(
    '#type' => 'submit',
    '#value' => t('Add More'),
    '#prefix' => '<div class="packing-add-more">',
    '#suffix' => '</div>',
    '#submit' => array('custom_module_admin_add_more_submit'),
    '#ajax' => array(
      'callback' => 'custom_module_admin_add_more',
      'wrapper' => 'boxes-fieldset-wrapper',
    ),
  );

  $form['packing_submit'] = array(
    '#type' => 'submit',
    '#prefix' => '<div class="packing-submit-save">',
    '#suffix' => '</div>',
    '#value' => t('Save'),
  );

  drupal_add_library('system', 'drupal.ajax');

  return $form;
}

```

**Update 2 - I believe that the issue is in this block**

```
foreach (physical_dimensions() as $key => $dimension) {
          $form['sizes'][$i][$key] = array(
            '#type' => 'textfield',
            '#title' => filter_xss($dimension)['name'], // Removing this line would make the page disappears.
            '#size' => 15,
            '#maxlength' => 16,
            '#field_suffix' => '×',
            '#prefix' => '<div class="physical-dimension-form-item">',
            '#suffix' => '</div>',
          );

```

On the line `'#title' => filter_xss($dimension)['name'],`

How can I fix this issue ?

# Answer
> 1 votes
To solve this issue I had to change this line `'#title' => filter_xss($dimension)['name'],` to this On the line `'#title' => filter_xss($dimension['name']),`

# Answer
> 0 votes
If your detective work so far is correct, then try this:

```
$form_state['num_boxes'] = strval(count($boxes) + 1);

```

---
Tags: 7
---


title: Place a block in multiple regions

text:
# Question
Title: Place a block in multiple regions
Is there a module which can allow users to place the same block in multiple regions? That way I don't have to make the same View block twice.

# Answer
> 16 votes
Multiblock module makes this possible:

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

# Answer
> 6 votes
It is unclear if you want to use the same block more than once on the same page or place it in different regions on different pages. Either way I would recommend you take a look at the context module.

Using context you can place a block with in different regions on different pages. Alternatively you can create 2 contexts which apply to the same page/s and place the same block in different regions.

# Answer
> 3 votes
The Panels module also makes it easy to use multiple instances of the same block on a page.

# Answer
> 2 votes
If you already have a custom module for the site, you can define your own blocks to repeat the content of an existing block. It will then appear twice in the block listing

```
/* -------------------
    custom blocks
----------------- */

/**
* Declare what blocks are provided by this module.
* Implements hook_block_info().
*/
function MYMODULE_block_info(){

    $block['fibble_home'] = array(
        'info' => t('fibble (home)'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
    $block['fibble_members'] = array(
        'info' => t('fibble (members)'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
    return $block;
}

/**
* Define what our block is going to look like.
* Implements hook_block_view().
*/
function MYMODULE_block_view($block_key){
    $block = array();

    // tweets block to appear twice

    if($block_key == 'fibble_home' || $block_key == 'fibble_members'){

        //This is the title of the block.
        $block['subject'] = t('Fibble');

        $fblock = module_invoke('MODULE_ORIGINAL_BLOCK', 'block_view', 'ID_ORIGINAL_BLOCK');
        $fcontent = render($fblock['content']);

        $block['content'] = '<!-- content repeated by MYMODULE -->';
        $block['content'] .= $fcontent;

    }

    return $block;
}

```

# Answer
> 1 votes
Use the MultiBlock Module.

Go to Structure-\>Blocks-\>Instances. Give a unique instance title and select the block type and save. Then enable the block by assigning it to a region where you want.

# Answer
> 0 votes
The Bean module also now has this functionality. Not just for custom block entities but also for blocks defined in hook\_block. See the dev version and the bean\_all submodule.

---
Tags: blocks
---


# Question
Title: Can uploaded files be renamed in the server to avoid name collision?
I want my site to host some images. The user is able to upload images as a content type.

If two users create content and upload images with the exact same name (myImage.png), will the older image file be overwritten in the server (and therefore both content entries would end up with the same image file)?

If yes, it is rather troubling. So now I wonder: is there a module that renames the uploaded file so it will not collide with other uploaded files?

I have searched for a couple ones, not exactly tested them since they seem to add too much extra functionality I just don't need: I like the default file uploading system that comes with Drupal 7. I just want it to avoid name collisions (if it happens).

# Answer
> 5 votes
You don't need to worry about the renaming of the images; Drupal does that for you by default :)
Lets say if you upload `image1.jpg`, and again someone else does the same the second file will be renamed `image1_0.jpg`.

# Answer
> 2 votes
You might find some information about how to code changing file names in the File Path module.

File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

# Answer
> 0 votes
Also you can set a pattern for you files and with random or timestamp part it never duplicated

you can use hook\_file\_persave

```
function yourmodulename_file_presave($file) {
  $parts = pathinfo($file->filename);
  $file->filename = 'mystring_'.$file->uid .'_'. $file->timestamp . '.' . $parts['extension'];
}

```

---
Tags: 7, files
---


# Question
Title: How can one automatically rename files uploaded in a webform?
I would like to rename the files uploaded to a webform according to some tokens or the value in some other field.

I did some research on this and was surprised to find no definite solution.

For example:

# Answer
The sandbox project is removed as the issue queue get continued, the latest patch has been failed in simpletest, but you can still check this patch
> 1 votes

# Answer
You can change every file upload by hook\_file\_presave as your desire pattern as example

```
function yourmodulename_file_presave($file) {
  $parts = pathinfo($file->filename);
  $file->filename = 'mypattern_'.$file->uid .'_'. $file->timestamp . '.' . $parts['extension'];
}

```

**but this method do not rename filname(it just rename file name in file\_managed table),** if you want also rename file name (uri of file) you should use below code

```
function yourmodulename_file_insert($file) {
  $parts = pathinfo($file->filename);
  $uri = 'public://'.'mypattern_'.$file->uid .'_'. $file->timestamp . '.' . $parts['extension'];
  $file=file_move($file, $uri);
}

```
> 1 votes

---
Tags: webforms
---


title: Display users who flagged content

text:
# Question
Title: Display users who flagged content
In my Drupal 7 project I have users of role `A` and `B` respectively. Users of role `A` can create content and users of role `B` can flag it.

I'm building a view that displays on `A` users' account page their content and names of `B` users who flaggd it.

I have created a view `Content` (not `User`) and added relationship `Flags: Content flag` and consequently field `Flags: User uid` to display together with content related fields.

In view block I use `Grid` format. Same content information is displayed several times per each user who flagged it, like bellow

Content title **QWERTY**
Users uid who flagged **1**

Content title **QWERTY**
Users uid who flagged **2**

Content title **QWERTY**
Users uid who flagged **3**

How can I display content information only once and users who flagged in one field separated by comma?

# Answer
> 0 votes
you need to **edit** /drupal/sites/all/themes/MYTHEMENAME/**template.php**

then add the following code.

```
function MYTHEMENAME_preprocess_views_view_fields($vars){
      if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['id'] != 1){
        $vars['fields']['title']->content = '';
      }
    }

```

**What this code is saying is if your row is not equal to (`!=`) 1, then don't display anything. Thus, it will print your title only for row 1.**

* replace MYTHEMENAME with your actual theme name.
* replace VIEWNAME with your view's name. example: flagged\_content
* replace DISPLAY with your view's machine name. You can find this by editing your view, then under Advanced -\> other

examples: block, block\_1, page, page\_1 or default. It's default if you're using your master view.

For user's separated by comma you would have to use css for that.

JS FIDDLE EXAMPLE

PS: I think you would have to change it from grid to html list for your view.

---
Tags: views, users, flags
---


# Question
Title: on a multi-language site 'Entity translation' prefs don't show 'node' option
I'm working on a multi-language site and would like to pre-define the language per content type (as e.g. described here in the answer) but can't get the vertical tab "*nodes*" to show up.

The "*taxonomies*" tab however does show up – so I guess sometings are actually working correctly.

i do have a couple of content types with the publishing setting "*Multilingual support = Enabled*" – but still none of them shows up in the Entity translation options section. What I would like to achieve is one a *one-content-type-per-language* setup – therefore I would like to set the default language accordingly on the *Entity translation* page . What am i missing? Any pointers would be appreciated.

*Screenshot from the* Entity translation *interface:*

# Answer
> 1 votes
I just recently had this problem and after 6 hours of searching for a solution I tried the following, which seems to work for me:

Without having Entity Translation installed first update Internationalization (i18n) to the latest version. Then setup the necessary submodules like "Field translation" that you need from Internationalization.

After this is all done **then** download and enable Entity Translation, go to Entity Translation settings under /admin/config/regional/entity\_translation and enable "Content" under "Translatable Entity Types".

If you haven't configure any of your content types to be translatable with field translation (under publishing options) you won't see anything here. So after doing this for at least one of my content types this page showed the Content tab to add the correct settings for each content type.

---
Tags: i18n-l10n
---


# Question
Title: How do you get the display settings of a field on a particular content type/display
I'm looking to preprocess a field.

The field type I'm wanting to preprocess is an entity reference field.

I need to know what view mode has been selected on the display settings for this field (see screenshot below).

This information is not made available in the $variables variable passed into preprocess\_field.

So how can I get this load this information? I have tried looking for some Drupal-specific functions that would return these settings but haven't found anything that works.

Many thanks.

# Answer
> 2 votes
You're looking for `field_info_instance()`

> Returns an array of instance data for a specific field and bundle

Example usage:

```
$info = field_info_instance('node', 'field_foo', 'article');
$display_settings = $info['display'];

```

`$display_settings` will be an array of display settings keyed by the view modes that are customisable for that content type and bundle.

---
Tags: entities, theming, database
---


# Question
Title: How to pass on the user id(block user) after registration
I am working on a project where users need to pay to use site.Site have a registration form where user can register and redirected to the payment page.All the resisted users are blocked until they make payment. The registration process working fine but, when user redirects to payment page there is no method to get resisted user id. How to get registered user id on payment page?

# Answer
> 1 votes
This approach have two major issues.

1. Security issue - Passing userid to page without login is not considered as a secure method.
2. Spam registration - as it is clear from your requirement that user will need to fill the registration form first and then make payments to access site, but you mentioned that your need to pass user id to payment page it means user is already registered but is inactive (i guess), so now if users leave site without making payments he will be a users in database that should not exist ( if there is not other access area for these type of users )

Proper approach to handle this type of requirement

1. Create registration form and submit it to payment form page (after validation).
2. Grab all details submitted from registration form and hold them on payment form.
3. Ask user for payment details and accepts payments. if successful use form values to save/register user and send them confirmation emails
4. If payment failed, display message and ask for correct details.

Registration should be done with drupal hooks and functions but not be custom code. Make a module to handle payments ( validate payment form details and accept/manage payments)

With above approach users will be registered only if they have paid to access site.

# Answer
> 4 votes
The user registration form is generated by user\_register\_form(), and like normal Drupal forms, it can be altered via hook\_form\_alter or hook\_form\_FORM\_ID\_alter. When not explicitely set, the submit handler of a form is named `form_id`\_submit(), however, in user\_register\_form, a submit handler is added to the #submit property of the form - user\_register\_submit().

In the function user\_register\_submit, you'll notice the following codes:

```
...
$form_state['user'] = $account;
$form_state['values']['uid'] = $account->uid;
...

```

which saves the new user object and ID in $form\_state.

To access this after the registration form is submitted, simply add a custom submit handler via hook\_form\_alter() or hook\_form\_FORM\_ID\_alter(). Example:

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alters the user registration form by adding a custom submit handler.
 */
function foo_form_user_register_form_alter(&$form, &$form_state) {
  $form['actions']['submit']['#submit'][] 'foo_user_register_form_submit';
}

/**
 * Custom submit handler for the user registration form.
 */
function foo_user_register_form_submit($form, &$form_state) {
  $account = $form_state['user'];

  $uid = $form_state['values']['uid'];

  // Do something meaningful
}

```

---
Tags: 7, users
---


title: Remove Value of dependent field

text:
# Question
Title: Remove Value of dependent field
I've one date field which is dependent on another field if it is checked then only date field will display and will be compulsory. Issue is that if I give value once on date field and saved that page, then I'll edit again same node and uncheck that dependent field value then it will be hide from page but the previous value of that date field is not removed from database. If anyone have an solution to remove this value on remove dependency then let me know.

Thanks in advance.

# Answer
Try to use any of these modules.

1. Conditional Fields \- This module definitely solve your issue. How to use.

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.

2. Dependent Fields

> The Dependent Fields module (formerly AHAH Dependent Fields) allows cck based fields to specify another field as a controller field, and react to its changes on the form using AHAH/AJAX without the form re-loading.

3. Dynamic dependent fields

> Makes field value or options depend on other field values when editing entity.
> 1 votes

# Answer
Used Conditional Fields and attached screenshot for the setting up default clear value of dependent field.
> 1 votes

---
Tags: 7
---


title: Weform textbox placeholder

text:
# Question
Title: Weform textbox placeholder
I know I can set "default value" for textbox in D7 webform. Unfortunately, user needs to remove the default value and key in their own information. Actually I want something like placeholder feature. How to do this setting?

# Answer
You can do this by using Webform Hints module.

> This module allows users to enable automatic placeholders to textfields, textareas, select lists, and email fields within a webform created by the Webform module.
> 1 votes

# Answer
That is built in webform 7x-4.7 D7 already (I'm assuming you mean 'textarea' when you say textbox).

Steps:
\- Specific Wedform 'edit'
\- Components tab and 'edit' on the particular component
\- Scroll down to "Display" header
\- After height and width you should have "Placeholder", which is what it says.

Just add you text there. Behaves as placeholder text should.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: I want a Notice message when save configuration
I have a module and a form with a checkbox...What i really want is when the user press the button save configuration to take a notice message..Could anyone know how to do this thing?

```
foreach (watchdog_severity_levels() as $severity) {
    $severity_options[$severity] = check_plain(drupal_ucfirst($severity));
  }

  // Generate checkbox list for given severity levels.
  $form['severity'] = array(
    '#type'        => 'fieldset',
    '#title'       => t('Select the severity.'),
    '#collapsible' => true,
    '#collapsed'   => true,
  );

  $form['severity']['severity_levels'] = array(
    '#type'          => 'checkboxes',
    '#options'       => $severity_options,
    '#default_value' => array_values($severity_levels),
  );

  return system_settings_form($form);
}

```

# Answer
> 1 votes
Above mentioned is correct bit more Explanation on that

Syntax : `drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE);`

**Example usage:**

```
drupal_set_message(t('your message to the user.'), 'error');

```

**Parameters**

**string $message:** (optional) The translated message to be displayed to the user. For consistency with other messages, it should begin with a capital letter and end with a period.

**string $type:** (optional) The message's type. Defaults to 'status'. These values are supported:

```
**'status'
'warning'
'error'**

```

**bool $repeat:** (optional) If this is FALSE and the message is already set, then the message won't be repeated. Defaults to TRUE. Return value

array|null A multidimensional array with keys corresponding to the set message types. The indexed array values of each contain the set messages for that type. Or, if there are no messages set, the function returns NULL.

# Answer
> 0 votes
You can call `drupal_set_message()` (https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal\_set\_message/7) from your form submit function:

```
  function YOURFORM_submit($form, &$form_state) {
    // Perform your tasks...
    drupal_set_message(t('Button pressed'), 'status');
  }

```

Your message will be displayed on the default location of the page (depending on the theme) after submitting the form. You can specify different message types, such as 'status', 'warning' or 'error'.

Hope that helps,

---
Tags: forms
---


title: Can't see the block body

text:
# Question
Title: Can't see the block body
I'm working on a drupal site. Its already done by someone else but I have to change some things. I want to edit a block but when I want to edit, it doesn't show the block body. https://i.stack.imgur.com/d2Oun.png

# Answer
That is because it is a block provided by a view. Look at the block edit page url, it usually gives you a hint wich module provides the block: "admin/structure/block/manage/**views**/what\_we\_offer-block"...
> 1 votes

# Answer
The block is most like being generated by a module. It could be a view block if it's a list of content, or it could be a module that's causing it.

First I would check views, at /admin/structure/views. The url of your block contains "views," which makes me think that's whats generating the view (I'm not 100% sure about this, but I believe that the structure for block edit links is: admin/structure/block/manage/(Module making the block)/(block machine name)/configure ).

Look for the view that's generating the block, and edit it from there. Keep in mind that views are theme-able, and there may be a views template that is overriding the output as well. So if you have content that is appearing in your block that dosn't seem to be generated by the view, check to see if there is a view template being applied. To do this, click on "Advanced" in the view menu, then "Theming Information". The templates that are being used are bolded. Anything that is bolded beyond the first in the list will be a custom template and would be editable in your theme folder.

Again, I'm fairly sure this is coming from views, but for anyone else out there who stumbles upon this trying to find where a block is coming from, it could also be a custom template block. If you have any custom modules running on the site, that would be a good place to look. If you do have custom modules, look for hook\_block\_info(), if that is in there and contains something like this:

```
$blocks['what_we_offer'] = array(
    'info' => t('YOUR BLOCK'),
  );

```

then your looking in the right place.
> 0 votes

---
Tags: blocks
---


# Question
Title: Drupal 7 Views bulk operations based on terms
I want to do bulk operations based on terms instead of node id. For example, I have a term called "XXXX", I have selected this term for 10 contents. So, in manage views I want to display only the term name, if when user selecting that term and do publish/unpublish, that 10 contents should be publish/unpublish.

Is it possible with Rules? Can anyone please guide me?

Thanks in advance.

# Answer
> 0 votes
I use admin\_views to do that and more.

After enabling it, you'll find Views -\> Administration: Nodes, Edit that view.

Under Filter criteria you will find a default "(term) Taxonomy term: Vocabulary (exposed)". Add your "(term) Taxonomy term: Name (exposed)" and use the other as referene to get your settings correct.

Pending on how many terms you have, this dropdown can get messy, so you could refine your filter settings to only show some terms in the filter.

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


title: Sidenotes / Inline notes on nodes

text:
# Question
Title: Sidenotes / Inline notes on nodes
I was wondering, is there already a module making it possible to make inline or sidenotes/comments inside the content of a node. A good example is the notes you can add in Google Docs.

Would be great for editorial purposes!

# Answer
If I am not mistaken, it seems you want to have something like "private comments" on a node. You can find some information in the following question: How to have separate private comments for nodes apart from the general comments?

It mentions the Reply module, which is still in alpha. There might be other similar modules.

Hope it helps,
> -1 votes

---
Tags: 7
---


title: How can I change my footer?

text:
# Question
Title: How can I change my footer?
I am trying to change the footer on a Drupal 7.2 site.

How can I achieve it?

# Answer
It's ether in a block or in your template. First check the block admin page at `admin/structure/block`, and look in the section of footer (or something like that). If there is nothing there, it will be in your template. Most likely it will be located in `page.tpl.php`.
> 4 votes

# Answer
Based on what is shown in the image in the question, I can think of 2 possible implementations of that footer being shown:

* it's a display of **one of the menus** used in this site.
* it's **a block** shown in the footer of this site.

Both possibilities are further detailed below ...

## Display a menu in the footer

There are themes that have configuration options to yes or no show a menu like the navigation menu, primary menu, secondary menu, etc. If you use such options to actually show such menu, then the theme will typically put it in some spot on the page where it seems appropriate.

In this specific case, it could well be that (eg) the theme option to display the secondary menu (or maybe the primary?) is turned on, and that the theme in use will actually dispplay it in ... the footer! So to get rid of "that" footer, find the theme option related to it, and disable that option. That should make it disappear.

## Showing a block in the footer

Create an appropriate block and move it to the theme region of your choice. The block content can be whatever you'd like it to be, e.g. some custom HTML.

As of Drupal 7, you can use PHP as the Text Format of a block also, so you can add things like so also:

`<?php echo date("Y"); ?>`

That way, it will always display the correct year (instead of hardcoding it and then changing it each year) ...

If you'd rather not want to use such PHP based approach, you might also want to consider the Copyright Block module. Here is an excerpt about it from the module's project page:

> ... creates a block that allows you to configure a copyright message that automatically updates using the current year from the server that your site is hosted on.
>
> It does this by adding a new token called \[copyright\_statement:dates\] that you can place within your message. A start year when needed, and the date separator can be changed if needed.
>
> A default message is provided that includes the `[site:name]` token.

To configure the `[site:name]` token, navigate to /admin/config/system/site-information of your site.

If the site name is there and the name does not show up, then it's problably something related to the settings of the theme you're using. To check that, navigate to /admin/appearance of your site, and use the **Settings** link of your theme. Then verify if there are any options related to showing or hiding some copyright message.

PS: Consider editing your question by including the name of the theme you are using ...
> 0 votes

---
Tags: 7
---


# Question
Title: Pre-Populating a Form Field with something other than its default value
I'm having a strange problem. I am constructing a form with checkboxes to toggle email subscription preferences on and off. For the new user sign-up form, this is straightforward:

```
$form['marketing-container']['restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Subscribe to Restaurant Newsletter'),
    '#return_value' => "True",
    '#default_value' => "False",
);

```

However, when it comes to the update user form, I'm running into a problem. If I set #default\_value to the existing preference, it will check the boxes for those publications you're subscribed to correctly, but if you UNcheck those boxes, the form API just returns the default value....which would still be TRUE.

To work around this, I retrieved the subscriber object at the start of the form function, and I've added hidden fields whose default values are the existing subscription preference values, just like I attempted to do with the real fields in the first place. Then, I used #states to populate the real fields based on these hidden fields, like so:

```
$form['marketing-container']['existing_restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Restaurant Newsletter'),
    '#value' => $attributes[15]->Value,
);

$form['marketing-container']['restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Subscribe to Restaurant Newsletter'),
    '#return_value' => "True",
    '#default_value' => "False",
    '#states' => array(
        'checked' => array(
            ':input[name="existing_restaurant_newsletter_subscription"]' => array('checked' => TRUE)
        )
    )
);

```

Now this works! The problem is that the first field is visible. Now if I alter this to hide the field:

```
$form['marketing-container']['existing_restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Restaurant Newsletter'),
    '#value' => $attributes[15]->Value,
    '#access' => FALSE,
);

```

The field is hidden perfectly....but its value isn't copied over to the real field that's still visible.

I've searched all over and pored over the Form API documentation, and I'm stumped.

Is there some way to preserve this default value inside the hidden form so it copies over to another field correctly?

If there isn't, or if it's more efficient, is there a DIFFERENT method I could use to pre-check this checkbox but still keep a default value of FALSE so that if a user unchecks it, something actually happens? Is there another class of field I'm missing that is a sort of on-off switch that returns specified values for each state?

# Answer
Figured it out on my own. The solution was:

```
$form['restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Subscribe to Restaurant Newsletter'),
    '#return_value' => "True",
    '#default_value' => $attributes[15]->Value,
    '#prefix' => '<div class="subscription-toggle">',
    '#suffix' => '</div>',
    '#ajax' => array(
        'callback' => 'ajax_replace_default_callback',
        'wrapper' => 'restaurant_newsletter_subscription_div',
    ),
);

```

And for the callback:

```
function ajax_replace_default($form, $form_state) {
    $field_name = $form_state['triggering_element']['#name'];
    $form[$field_name]['#default_value'] = "False";
    return $form[$field_name];
}

```

And I also kept the hidden fields in the form:

```
$form['existing_restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Restaurant Newsletter'),
    '#value' => $attributes[15]->Value,
    '#access' => FALSE,
);

```

This was simpler to store the existing preference variables for comparison in my logic later on than to try to retrieve the subscriber yet again inside of that form submit handler (It already retrieved the subscriber when it loaded the form, to populate the fields....trying to minimize the number of API calls I have to make).

Implemented like this, if a box is checked and becomes unchecked, that Ajax callback function alters the default value to false, rather than returning just the pre-populated value. If you check the box again it still changes the default to false, but it doesn't matter since if the box is checked that's irrelevant.

Not the most elegant fix, you get a little loading circle thing for a second when the Ajax runs, but it works.

Note: I left the Ajax callback function generic because even though I keep using the same field on this page, there are lots of similar fields doing the same thing. Using the triggering\_element allows me to just recycle this code for all of them.
> 0 votes

---
Tags: 7, forms
---


title: $form table displays no table data

text:
# Question
Title: $form table displays no table data
I just made a $form\['table'\]. It shows enough rows (the count of the total rows in database) only it doesn't show the results. I tried using #value, #title, #markup but nothing works

Screenshot of result:

My code:

```
function push_notifications_stats_form($form, &$form_state) {
$form = array();
$id = $_GET['id'];

$query = db_query('SELECT * FROM push_notifications_messages WHERE msg_appID = :app_id', array(':app_id' => $id));
$qCount = db_query('SELECT * FROM push_notifications_messages WHERE msg_appID = :app_id', array(':app_id' => $id))->rowCount();

$form['table'] = array(
    '#theme' => 'table',
    '#header' => array(t('Message'), t('Device'), t('Date')),
    '#rows' => array(),
    );

foreach($query as $result) {
  for($i = 1; $i <= $qCount; $i++) {
    $form['table']["#rows"]["r$i"] = array(
        "'c1'" => array(
            '#type' => 'textfield',
            '#value' => t('hoi'),
          ),
        'c2' => array(
            '#type' => 'textfield',
            '#title' => t('device')
          ),
        'c3' => array(
            '#type' => 'textfield',
            '#title' => t('device'),
          ),
      );
  }
}

$form['id'] = array(
'#type' => 'item',
'#title' => 'Application ID',
'#description' => t('The application ID you are viewing: @appId', array('@appId' => $id)),
);

return $form;

}

```

When I check the $form with dsm it does show the results.. And also when I use my browsers element inspector it does show the values. Only it puts them inside the first tag. while it should be between the tags

```
<td #type="textfield" #value="hoi" #data="hoi"></td>

```

# Answer
I think you are mis-using `#header` and `#rows` properties of the Form API and getting them confused for variables passed to the theme\_table function that is being called with the `form['#theme'] => 'table'`.

This question is similar and might be what you're looking for: How to insert a theme table form inside an existing form?

Perhaps you want to use the tableselect element?
> 1 votes

---
Tags: forms
---


# Question
Title: How to render field attribute in foreach
I have a link field with multiple values. I want to display the link title for each of these fields. I can print the slide link titles individually but not using the foreach.

Currently I have:

```
<ul id="slideLinks">
<?php $slideshow_counter = 0;
    $slide_link = $node->field_slideshow_link;
    print $slide_link['und'][0]['title'];
?>
<?php foreach ($slide_link as $link) : ?>
    <li><a class="slideControl" href="javascript:void(0);"><?php print $link['und'][$slideshow_counter]['title']; ?></a></li>
    <?php print $slideshow_counter; ?>
    <?php $slideshow_counter++; ?>
<?php
if ($slideshow_counter == 4)
    break;
endforeach;
?>

```

# Answer
As I understand your question, I recommend you to use `for` statement, you can do this:

```
<ul id="slideLinks">
<?php $slide_link = $node->field_slideshow_link['und']; ?>
<?php for ($i = 0; $i < count($slide_link); ++$i): ?>
    <li><a class="slideControl" href="javascript:void(0);"><?php print render($slide_link[$i]['title']); ?></a></li>
<?php endfor; ?>
</ul>

```

This will print all your titles...
> 0 votes

# Answer
// Not enough points to comment on the good answer @mixerowsky

Drupal recommends using the field variable directly to avoid problems with language in the array (in your case `['und']` for undefined)

> Field variables: for each field instance attached to the node a corresponding variable is defined; for example, $node-\>body becomes $body. When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise they will have to explicitly specify the desired field language; for example, $node-\>body\['en'\], thus overriding any language negotiation rule that was previously applied.

So, extending the answer from @mixerowsky:

`

 <?php foreach ($field_slideshow_link as $link) : ?>

<?php print $link['title']; ?>

 <?php endforeach; ?>

`
> 0 votes

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


# Question
Title: How to add directions with a link to a webform in Drupal 7
I'm creating forms with the webform module. I'd like to add 'directions for filling out the form at the top of the form. I'd like those directions to include a link to another form if users clicked the wrong form.

This seems like it should be simple to do, but I can't figure out how to do it. When I add the directions with the link in a and put that at the top I get the link but no paragraphs, just one long running line of text, no matter how I split it up in the editor window. If I use a field, not only does it look ugly (even when disabled), because it has a white background on a gray background site, but it displays the link as html code etc..

I have wysiwyg enabled on my site and it shows up in other places but not on these editor windows so I can't use that (or select filtered html/full as those options also aren't available) in those data types I tried.

Anyone know a way to do this?

# Answer
> 1 votes
I'd recommend creating a custom module and using hook\_form\_alter() as shown in this example.

You can add a form element of type #markup to add custom html in your form. And set the #weight to a low number, `-50` for instance, for your markup element to show at the top.

# Answer
> 0 votes
It sounds like you may have editor limitations on that content type. Other than that make sure you are adding your directions to the 'body' field.

When editing the webform go to the 'edit' tab adjacent (where you set the title) the body field should have a switch. If that was not present, you need to check your editor module settings. Sometimes called profiles depends which one you use.

I recall one of them required that each content type had to be picked in the editor settings.

---
Tags: webforms
---