# Question
Title: How do I integrate custom PHP application with Drupal?
I am a PHP programmer but I have never developed anything yet for drupal. I have used Drupal as a CMS before but I didn't do any custom code since everything I needed at before can be accomplished with existing modules.

Now, with my new project, I have an existing single-page app using a PHP RESTful API and AngularJS on the frontend. I want it to be integrated with a Drupal CMS.

I am aware of the following possible ways to do this:

1. **Rewrite my existing code into a Drupal module** \- There is very little possibility that this app will be re-used. Furthermore, it is more likely that this app will be used stand-alone without Drupal. I also don't think I have the time to learn how to write a Drupal module.
2. **Keep the backend API as it is now and write the frontend as a Drupal page.** \- This will put my frontend code inside the Drupal database and NOT in the filesytem anymore so I can't version control the frontend code.

I am not happy with the above two choices and I believe that there is a better way to do achieve what I want.

**Additional background of my custom app:**

I created this app as a way for me to learn more about single-page applications. It is already currently functioning well as a standalone app. The app basically collects information from several users and collates all those information to be displayed on an HTML table.

I am sure there is also a Drupal way of doing the things that my Angular app does (something like a custom node type with fields coming from the input of different users) but I would like to use my existing code if that makes it easier.

# Answer
If your application can be displayed inside a Drupal page, writing a small custom module is the easiest *clean* solution. You don't need to rewrite your application, but only to provide some integration code. Your application should avoid output the complete HTML for the page, only its own content. It should also not initialize the PHP session as Drupal will take care of that. Otherwise it is as simple as:

```
/**
 * Implements hook_menu().
 */
function your_application_menu() {
  return array(
    'title' => 'Your Application',
    'page callback' => 'your_application_page',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
}

/**
 * Page callback: Displays Your Application on the page.
 *
 * @see your_application_menu()
 */
function your_application_page() {
   module_load_include('php', 'your application', 'your_application');
   $path = drupal_get_path('module', 'your application');
   drupal_add_js($path . '/js/angular.js');
   drupal_add_js($path . '/js/your_application.js');
   drupal_add_css($path . '/css/your_application.css');
   return your_application_output();
}

```

You may also be interested by the Angular JS module, which likely provide a much nicer way to embed Angular JS applications in Drupal.
> 6 votes

# Answer
I think you need to abstract your problem even more.

Answer this: What do you want Drupal to do for you?

With Drupal you can:

* Build a routing system and facilitate a RESTfull API
* Build a "single page" site.
* Manage the content.

I write custom modules (like many) on a daily base, but not always give it back to the community because it is to project specific. But i create patches when i think my code fixes a bug or improves a module.

So start small with 2 files (MYMODULE.info, MYMODULE.module) and copy paste the code from Pierre in the module file, and your set.

Then you can expand it with tons of functionality.

TIP:
> 6 votes

---
Tags: views, entities
---


# Question
Title: Show exposed filter value when returning results
I can't seem to figure this one out. I have a view that returns nodes with a set of taxonomy term exposed filters. What I would like to do is show the selection the user has made on the screen (e.g "Showing results for..."), preferably using a text field in the views header else through the views template files. Can anyone help me please?

# Answer
> 4 votes
a bit tricky, but works:

1. Add a field `(term) Taxonomy term: Name (Name)`
in settings check: *exclude from display*
2. Add header: Global: Unfiltered text
check: *Use replacement tokens from the first row*
set the text area with the available token: e.g *"Showing results for \[name\]"*

**Screenshot:**

---
Tags: views
---


# Question
Title: Commerce Paypal- How can I change the "Order No. at Site Name" string?
I'm using the Commerce PayPal module to redirect users to PayPal to pay for their orders.

However, when I do this, the transaction that Commerce provides to PayPal is called

> Order # at \[Site name\]

However, on my site, the store is just one part of it, and the store has a different name than the rest of the site, so I would like to override this string and replace `[Site name]` with the explicit name of my store.

However, I haven't been able to track down where I can edit this. I tried searching for a number of variations on the *Translate interface* page and I also tried using `grep` on my modules directory but I haven't been able to locate it.

# Answer
> 1 votes
All of my payment gateway modules, and my recommended best practice for others', is to include a final opportunity before the payment API request is dispatched for developers to alter the request parameters if desired. How you do that in the PayPal modules depends on which payment method you're using. I'm going to assume this is a PayPal Payments Standard (WPS) initiated payment, so the hook you want is:

hook\_commerce\_paypal\_wps\_order\_form\_data\_alter()

If it's one of the others, refer to their \*.api.php files to find the appropriate hook, but note that some API requests are run through a helper function in the root commerce\_paypal.module.

---
Tags: commerce
---


title: custom checkout pane submission

text:
# Question
Title: custom checkout pane submission
I'm using Drupal Commerce (7.x-1.4) + Commerce Coupon (and old version 7.x-1.0-beta6)

I'm using a custom checkout pane to handle my coupons redeem (we have a particular usage of coupons) and manually call the coupon redeem function after checking some stuff.

It works perfectly fine except that i cannot figure out how to make sure my custom pane form submit button doesn't trigger the whole form (and trigger all the checkout pane validations), but only my particular form

```
    function hook_my_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
    $order = $form_state['order'];
    $pane_form = array();
    $pane_form['ticket_code'] = array(
        '#type' => 'textarea',
        '#title' => 'Tickets',
        '#description' => 'Blahblah',
        '#rows' => 10,
    );

    $pane_form['submit_ticket'] = array(
        '#type' => 'button',
        '#value' => t('Submit my tickets'),
        '#validate' => array('_my_custom_ticket_validate_order'),
        '#submit' => array('_my_custom_ticket_submit_order'),
    );

    $pane_form['coupon_code'] = array(
        '#type' => 'textfield',
        '#title' => 'Coupon code',
        '#description' => 'Enter your coupon',
    );

    $pane_form['submit_coupon'] = array(
        '#type' => 'button',
        '#value' => t('Use my coupon'),
        '#validate' => array('_my_custom_coupon_validate_order'),
        '#submit' => array('_my_custom_coupon_validate_order'),
    );

    return $pane_form;
}

```

So this works ! Except that when I click on one of the submit button, it triggers the validation of the other checkout panes on the page.

**I would like to prevent this as the user is redirected to the same page after using his coupons / tickets anyway.**

How can I prevent this ?

Many thanks !

# Answer
The short answer is you can't do what you want, but there are other things you can do. You need to look into using the #ajax properties of form elements to submit data to the server when the customer clicks your button without initiating a POST redirect as you would for a full form submission.

However, that will still trigger a validation of the entire form, not just the pieces that you specifically want to validate. What Drupal allows you to do is limit validation errors from resulting in form errors when the form is rebuilt.

The topic is honestly a big bigger than can be answered here, but I hope this points you in the right direction. The best thing to do will be to investigate how a module with similar functionality achieves what it is you want to do and imitate the code (if it's up to date and / or well-maintained ; ).
> 2 votes

---
Tags: commerce
---


title: Adding a form to user profile?

text:
# Question
Title: Adding a form to user profile?
I would like to add a form to the user account page, is there a specific way of doing this?

I guess this leads me to a large question: how can you embed forms in pages? I understanding using hook\_menu & the drupal\_get\_form callback. But this creates a new page, what about adding forms to an already existing page.

I have a feeling the answer is here: https://api.drupal.org/comment/6679#comment-6679, but I can't seem to understand it. Anyone have any good suggestions or tutorials....

# Answer
> 1 votes
You can add user forms by creating a render array for the Form API and *print render($form)* in a custom template, but I would just use the Webforms module and include all elements in a Panel or View.

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


# Question
Title: WYSIWYG + TinyMCE: Pressing Enter inserts break instead of paragraph
Does anyone know, how I can manage TinyMCE to insert `<br>` instead of `<p>Paragraphs</p>` when pressing enter?

The best would be if you press enter once, it inserts a normal break. Pressing enter twice it starts a new paragraph.

And yes I know, that Shift+Enter would do it, but my client would like to have the behavior changed.

Thanks for any help

# Answer
> 2 votes
Give `shift+enter` a try.

That shortcut tends to be the default in a lot of different text editing apps for break type switching.

# Answer
> 0 votes
You need to adjust the WYSIWYG settings from /admin/config/. In CKEditor the section **Cleanup and output** has options for *Enter mode* and *Shift+Enter mode* where you set the tag for each action. I'm not 100% about the exact setting for WYSIWYG, but it should be similar.

---
Tags: 7, wysiwyg
---


# Question
Title: How to customize default add content page
I want to customize the default add content page, more specifically, to get rid vertical tab in the bottom, and add explanation text to each field.

How can i do this? what php file should i tinker ? is there already some modules to to this ?

thank you for reading this.

# Answer
> 2 votes
You can use the Renderable Elements module. If you've ever had any experience with Display Suite, it works exactly like that, but for forms like Add Content. You can change up the display, remove the vertical tabs below, etc.

For the explanation, each field comes with a description/help field that you can fill out. Now it depends on the admin theme you're using on how that text is displayed.

---
Tags: nodes
---


# Question
Title: Disabling Wysyig profile profile for particular content type
I am using CKeditor with wysiwyg profile . I want to disable this Wysyig profile for a particular content type. cant find a better way. please help me out with any module if its there or any configuration setting if its possible

# Answer
> 2 votes
I was having a similar issue and did it using Better Formats module.

* I created a new Input Format (for example "my input format")
* Disabled WYSIWYG in that format
* In the Content type settings, under "Input format settings", select that new profile as default

# Answer
> 0 votes
You could use plain text, (or create a text format called "No WYSIWYG" if you plan to support tags (*/admin/config/content/formats*) and set that profile in CKEditor as inactive (*/admin/config/ckeditor*).

Then just change the format for your content type to plain text or "No WYSIWYG"(*admin/structure/types/*).

---
Tags: wysiwyg, input-formats
---


# Question
Title: Translate custom string from programatically defined block
Alright, this one is probably easy but I found online documentation only little helpful and couldn't figure it out myself.

I run a custom module that renders a custom block programatically via `function hook_block_view()`. Assume that `$block['content'] = 'Hello';`. The custom string 'Hello' does *not* appear in the list of translatable strings (config/regional/translate/translate) but I want to display it in, say, Spanish ('Hola') when the site language is set to Spanish.

How do I translate it / make it appear in the list?

# Answer
In order to make strings translation possible you need to pass it through the **t** function.

```
$block['content'] = t('Hello');

```
> 1 votes

---
Tags: i18n-l10n, blocks
---


# Question
Title: Service API acting strange with Answers module
I'm currently developing an Android App that uses REST to communicate with drupal

I've setup the Service module and got it working with normal "post" content type nodes

But, if i post a `question` node from the Answers module, it would not work. So, I post an JSON string like this:

```
{"node":
{
   "title":"REST question",
   "type":"question",
   "language":"und",
  "body":[
  {
     "und":{
        "value":"REST content",
        "format":"filtered_html"

     }
  }
]
}
}

```

Drupal would respond like this:

Request header:

```
Request Url: http://www.mubie.com/rest_api/node.xml
Request Method: POST
Status Code: 200 //<- the request is valid...
Params: {}

```

Respond body:

```
<?xml version="1.0" encoding="utf-8"?>
<result>
    <nid />
    <uri>http://www.myhost.com/?q=rest_api/node/</uri>
</result>

```

now, normally, if I post something like a blog post, it would return the node(nid) url, but with a `question` content type, it returns the url that lists all nodes. Also, the **content is not added to drupal**

How do i make it post my `question` content properly and return a node url?

# Answer
> 0 votes
I've figured it out, basically the answers module was changing the submit form's submit button text value. Doing this would break `Service` and make it not add any node to the database. The solution for me was to remove that modification made by answers module by commenting out some lines:

```
answers.module , line 163
// $form["actions"]["submit"]["#value"] = t("Post your answer");

```

And everything works fine after saving.

---
Tags: 7, nodes, services
---


title: moving from test site to live

text:
# Question
Title: moving from test site to live
I currently have a test Drupal site where I am testing the different modules and Views, display settings, etc that I would like to eventually use on my live site. But I am adding data to the test site as well, data that will also end up on the live site.

Because I am installing and uninstalling modules, would it be better to start the live site from scratch or can I safely move the test site to the live site without worrying about orphan code/settings slowing down or otherwise adversely affecting the live site?

# Answer
One of the most common ways to move configuration data is to use the Features module. However, this will move only configuration, not data (nodes/content). Still, it's not too difficult to set up; you can take a look at this tutorial for an overview.

Moving data is much harder; the Migrate and Feeds modules are two common ways to do this but both are quite painful to set up and probably not worth the trouble. For content, I just keep a list of the info in an Excel file and then cut and paste it in-- it's not a great solution, but in my case it saves a lot of time.
> 2 votes

---
Tags: migrations
---


# Question
Title: Which newsletter module will fit my requirements?
I'm trying to implement a newsletter for my users to subscribe to and I'm noticing that there are a lot of different newsletter modules out there. I'm was looking for **one** that will easily allow me to:

1. Send weekly newsletters with a summary of the top 5-10 posts from that week.
2. Allow me to have multiple newsletters for the different "Categories" of content on my site (I have a taxonomy term "Categories" which I would like my users to be able to pick which "Categories" they'd like to subscribe to).
3. Allow me to customize the look of the news letter.

I've already tried simplenews but can't seem to get it to do what I want. I feel that this may be beyond what it can do.

# Answer
> 10 votes
Try the Newsletter module. The features portrayed in the project page:

> * Multiple newsletters lists configurable on existing terms.
> * Plain text or HTML out of the box.
> * Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg after 10 new posts for this term.
> * Centralized administration and configuration on a single page.
> * Users can customize the terms in the list they subscribe to.
> * Custom template per list.
> * Statistics (CTR and Open-Rate).

It allows using HTML for the email (uses regular Drupal filters).

# Answer
> 5 votes
Why don't you try MailChimp? Here is the Drupal MailChimp module.

# Answer
> 5 votes
I've had good luck with the Messaging & Notifications module. It will send out an email for a given "event" be that a new node, an updated node, etc. You can modify the settings so that the default is a digest like you are seeking, but the users can choose the frequency at which they'd like to be notified per taxonomy-term.

So for example, you default it to send once a week, but they want to receive notifications of new content daily, they can choose to do so but are not forced into it. Conversely, if they choose to receive a monthly digest instead, they can do that as well.

# Answer
> 5 votes
Maybe if you hear what we did for a government agency, you may get an idea.

We used a Simplenews effectively and modified it with the aid of five modules.

They needed to include four content types from several different sections of the website out in a bi-monthly newsletter

They also wanted to reorganize them into two distinct newsletters that uses could subscribe to.

The four content types were publications, funding opportunities podcast and the site blog.

The blog had five distinct categories (taxonomy terms), for the sake of this discussion we will call them category one through category five.

**For the form:**

In order to reference nodes, you need the node reference field which is part of CCK in Drupal 6

(For Drupal 7 use References - http://drupal.org/project/references)

We created a newsletter content type that had eight different node reference fields.

The first node reference field was set to only reference the publication content type. The second was set for funding opportunities content type and the third was set for podcast content type

The last five were set for the blog content type, but I needed to narrow down the selection of each of the fields so that one only showed posts tagged with category one, another showed posts tagged with only category two and so on.

To do this, we used the Node Reference views module. http://drupal.org/project/nodereference\_views (Reference views for Drupal 7 - http://drupal.org/project/reference\_views)

Node Reference views lets you create a specific view and then you can use that view to filter out the node reference options for a specific node reference field.

**For Display:**

In order to control the way the output of the different node reference fields looked, we used the Viewfeild module - http://drupal.org/project/viewfield. Once installed, you can choose viewfeild from the display options and then customize the view the way you want.

To control the rest of the newsletter, we used simplenews template - http://drupal.org/project/simplenews\_template . It lets you add multiple newsletters with customizatible headers and footers, and the ability for users to pick between them.

To futher customize the display of each newsletter, we used Contemplate - http://drupal.org/project/contemplate modules for Drupal 6

(I would really recommend using Display Suite - http://drupal.org/project/ds for Drupal 7)

Lastly, if you need help configuring all this stuff, there are plenty of awesome video tutorials over the net.

Hope you find this useful and let me know if you need any further clarification.

# Answer
> 2 votes
Considering your above requirements it is good to use Mailchimp of Aweber,You can create a Feed for Each category and assign them to different lists. You have a automatic function to generate a newsletter from feeds(just like feedburner). Another great advantage of using aweber or mailchimp is you can customize the signup form as you like.

Aweber Drupal Module

Mailchimp Drupal Module

Note : it is good to use Mailchimp than Aweber since the above module is unstable and not available for drupal 7.

# Answer
> 2 votes
I would highly recommend using phpList with the Drupal PHPlist Integration Module. It's worked perfectly for me in the past, and phpList is more advanced than any Drupal module you'll find.

# Answer
> 2 votes
Simplenes is good but recently I had some problems when sending e-mails with simplenews newsletter module for Drupal. While this is a very good module, sometimes made Drupal cron to fail and stuck. I also wanted full control on sending mails and to avoid some of the limitations of Drupal cron timings. Since I didn't have the time to enhance the simplenews module I did this script to be sure that my mails are sent. This script needs simplenews newsletter module and Drupal in order to work. It has been tested with Drupal 7 (but should work on any version) and simplenews 7.

The script works out of drupal and speaks to the database so its better for performance and mail control. You can set the time step and the mails it sends every time based on your server sending limits. At the end logs any bad mails. For me it is the solution for sending my newsltters.

You can learn more and get the script from

http://tecorange.com/content/mail-send-addon-drupal-simplenews-newsletter

---
Tags: 7, emails
---


# Question
Title: Tokens in blocks configuration for List only pages
I want to set a block to visible only for a certain path, with the logged in user id, like my-path/\[user:uid\]. I feel like I should be able to just do that.

How can I do this?

# Answer
> 1 votes
You can do that with using hook\_block\_info\_alter().

For Example:

```
function YOURMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  global $user;
  $blocks['THE_MODULE']['THE_BLOCK']['pages'] = my-path/$user->uid;
}

```

Where THE\_MODULE is the module defining the block you want to alter, and THE\_BLOCK is the 'delta' of this block.

# Answer
> 1 votes
1) Enable the core PHP filter module

2) Use **php** in the visibility setting of your block. Notice that the path 'mypath' must be registered somehow before using this code. I mean that if the path 'mypath' does not exist at all any code here will not work.

```
<?php
global $user;
$uid = $user->uid; // Get the logged in user id
// If the path is 'mypath/myarg' then arg(0) is 'mypath' and arg(1) is 'myarg'.
$show = (arg(0) == 'mypath') && (arg(1) == $uid); // It must return both TRUE

return $show;
?>

```

Alternative, use the Context module.

# Answer
> 1 votes
1. Add contextual filter: `Global: Null`

provide default value: raw value from URL

Path component: 1
2. Add contextual filter: `User: Uid`

When the filter value IS available or a default is provided
Specify validation criteria -\> Validator -\> user

> Path validation (contextual filter: Global: Null)

You can validate the first path component in two ways:

**#1**

use contextual filter settings:

When the filter value IS available or a default is provided:
Specify validation criteria -\> Validator -\> PHP Code

```
return ($argument == 'my-path') ? TRUE : FALSE;

```

**#2**

Alternatively, if you don't want to use PHP code validation in the contextual filter settings, you can use preprocess function in your `template.php` file. Not sure whether it's the right way or not, but works:

```
/**
 * Preprocess the primary theme implementation for a view.
 */
function YOURTHEME_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  switch ($view->name) {
    case 'YOUR-VIEW-NAME':
      if ($view->args[0] != 'my-path') $view->result = array();
      break;
  }
}

```

---

Assuming `'my-path'` it's the View or some other module custom path, in this case it has to be validated with the php. Of course if it would be an alias of some content type, then php validation wouldn't be needed.

---
Tags: 7, blocks, tokens
---


# Question
Title: Module config page linked on Management Toolbar
I created a config page for my new module. Whenever I enable the module, a link to the config page is added to the Management menu across the top of the screen as well as a configure link next to the module name in the Modules page. How do I configure this page so that it just shows up with the configure link on the modules page and not in the menu. Below is the code from hook\_menu:

```
$items['admin/mymodule/settings'] = array(
  'title' => 'mymodule Module Configuration',
  'description' => 'Settings for my module',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('_mymodule_admin'),
  'access arguments' => array('administer mymodule settings'),
  'type' => MENU_NORMAL_ITEM,
);

```

The module has a function called \_mymodule\_admin that returns a form array. The config page works great. I just want to prevent the link from appearing on the management menu when the module is activated on my production site.

My info file contains the following line

```
configure = 'admin/timesdb/settings'

```

And my form callback has includes this line

```
return system_settings_form($form);

```

With the relevant form elements assigned above it.

# Answer
> 2 votes
It is because you have added a MENU\_NORMAL\_ITEM under the admin menu, so it will automatically put it in the admin toolbar (that is also the default so if you exclude that parameter it will also be a menu normal item).

If you change it to MENU\_CALLBACK, that will create the link between that url and your page callback, but it will not create an item in the menu.

See hook\_menu() for all the menu item types.

# Answer
> 0 votes
Its a piece of code put it in the .info file Like :

```
configure = admin/structure/block

```

Take a look at BLOCK module or other contributed modules and see the HOOK\_MENU in the .module file.

---
Tags: routes
---


# Question
Title: Auto Refresh Div Using jQuery from 5 Seconds to Zero
How to create a countdown counter in Drupal 7 that says:

Your download will start in 5 seconds...

During page load and it countdown the number to 5, 4, 3, 2, 1

And change the value to "our download will start shortly... "

When finished?

# Answer
> 0 votes
Look at THIS demo...That is all you need...

Also look at THIS and THIS...

To learn how to include script in Drupal look at THIS answer...

---
Tags: javascript
---


# Question
Title: Zen sub theme: page--node--name.tpl.php not working!
I'm hoping someone can help me because I'm at my wits end! I'm using the zen theme - then created a sub-theme and now I can't seem to get the custom templates to be recognized by the custom content type name (page--node--custom\_content\_name.tpl.php).

I've created a new template.php in my sub-theme and placed text that I've found in other blogs and forums to help make it recognize the content type so I can use it in the tpl.php name but nothing seems to work. If I use the dev module it only says that I can name them page--node--1.tpl.php, which would be fine if we weren't going to be adding more content on an ongoing basis.

Right now I have so many tpl.php just so that I can show people what the pages will look like - it's crazy!! What am I doing wrong?! Help!!

# Answer
> 2 votes
Drupal doesn't provide content type based template suggestions for `page.tpl.php` but for `node.tpl.php`. That means you can use a template like `node--custom-content-name.tpl.php`.

However, if you want to have a page.tpl.php for your content type, you need to tell Drupal about your template suggestion. Put this code in your `template.php` file:

```
function YOURTHEME_preprocess_page(&$variables) {
  if (isset($variables['node']->type)) {
    $content_type = $variables['node']->type;
    $variables['theme_hook_suggestions'][] = 'page__' . $content_type;
  }
}

```

You should name your template file like: `page--custom-content-name.tpl.php`.

---
Tags: theming
---


# Question
Title: Can i populate /fill a Views exposed filter with a Rules result
I have a group of nodes which are delivery nodes -prices-location-type etc.

I can sort them with a View and exposed filters - 'country' 'type' 'weight' to out put a price - really happy with it so far.

This works great - however I wish to populate the weight field with a value 'calculated weight' calculated in Rules - leaving only the 'country' and 'type' field open to the user.

I have looked for days now and think I have module overload!

Really would be grateful for any insight!

Thanks

# Answer
> 2 votes
I don't know if it's possible with Rules, though most things are!

But that should be possible with the Computed Field Module. It allows you to do just that, compute fields based on others and you can use it in your views.

https://drupal.org/project/computed\_field

---
Tags: rules, views
---


title: User cancellation error

text:
# Question
Title: User cancellation error
When I delete/cancel a user account from admin, I got the attached error.
It is saying that the table `cache_entity_profile2` is not found. Yes, the table does not exist actually. I am using the modules entity cache and profile 2.
The error is not generated every time, but very often.

# Answer
> 1 votes
The underlying problem is which module's responsibility it is to maintain that table. All relevant info and links are in this issue: https://drupal.org/node/1387268

---
Tags: users
---


# Question
Title: different form state redirects in a hook_form_alter
i have the code in template.php:

```
THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'answer_node_form' && !isset($form['nid']['#value'])) {
    //dpm($form);
    // redirect after we created a new node
    $form['actions']['submit']['#submit'][] = 'node_reference_redirect';
  } elseif ($form_id == 'answer_node_form' && isset($form['nid']['#value'])) {
    // redirect after we have made changes to a node - node/17/edit
    $form['#submit'][] = 'node_save_reference_redirect';
  }
}

function node_reference_redirect($form, &$form_state) {
  $form_state['redirect'] = 'node/' . arg(1);
}

function node_save_reference_redirect($form, &$form_state) {
  $form_state['redirect'] = '/index.php';//$form['field_answer']['und'][0]['nid']['#default_value'];
}

```

function named node\_reference\_redirect() works as expected - it redirects after creating a new node: node/add/content-type, but the 2nd redirect - when we are doing changes to an existing node: node/\[nid\]/edit, when we press "save" it doesn't redirects to a index.php for example... Can't figure out what's wrong. Any ideas? Thanks

# Answer
> 0 votes
I think it should be like:

```
$form['#redirect'] = $base_url';

```

you are missing '#' in both of the forms.

---
Tags: 7, forms
---


title: How does Drupal render a node

text:
# Question
Title: How does Drupal render a node
I'm helping someone to maintain a Drupal site and I still have not figured out how drupal actually works, it's driving me bonkers. I need to make a change to the way some content is displayed, but cannot figure out where that change needs to be made - I could go around just changing up the site until I stumble on it, but would rather not put a wrecking ball through their site like that.

Would appreciate if anyone can point me to a simple explanation of how to find out how a node is rendered and how I can track down the views involved.

The setup of the site is they have content types candidate and survey

When you view a candidate you see a nice table with info on the candidate and their survey responses.

I want to add some new fields (some to survey, some to candidate) I've added the fields, but don't know which view is involved in rendering as the views are not named clearly.

How can I figure out which view is involved in rendering a candidate when I go to www.site.com/candidate/bob ?

# Answer
Your question is actually very generic and can have a big explanation but I will actually pickup a couple of points from the question description and will try to explain.

**How is node is rendered?** Node is drupal's "most" core part. Most of the code is written in node.module in "modules/" directory. https://api.drupal.org/api/drupal/modules%21node%21node.module/7

Drupal uses a theming layer to render the content to the browser. If you want to alter the display of any node, you can check node.tpl.php in the current active theme directory. You can override the HTML of a node using node--\[CONTENT\_TYPE\].tpl.php. For example if you want to change the HTML structure of article content type, you can copy node.tpl.php to node--article.tpl.php and can update the structure.

**How to check the view**

*The easy way* The easiest way is to login using admin and place mouse on the part of page you think rendered using views. You will see a dropdown menue with links like "Edit", "Delete" etc. If it doesn't help, there is a:

*Technical way* You can check the css class of the div enclosing the view data. For example if a view's div contains the class "view-front-page", then most likely the views name will be something like "front\_page" or "Front Page".

Thirdly, I will recommend that you install devel module. I have never seen any module for developers that is more helpful than devel. It helps your print a lot of debugging information like error stacks etc.

Hope this will help.
> 1 votes

---
Tags: views
---


title: how to use public:// in page content

text:
# Question
Title: how to use public:// in page content
As content author creates a page, she wants to have something like `<img src="public://picture.jpg" />`. Is it possible? the goal is to avoid hard-coded drupal installation path; that is she doesn't want to have `<img src="/drupaltest/sites/all/file/picture.jpg" />` on test site and `<img src="/sites/all/file/picture.jpg" />` on production site.

# Answer
> 3 votes
You should always be using relative paths in content, like `<img src="/sites/all/file/picture.jpg" />`

That way if you ever change the domain name (for example when you are on the dev environment or the site url changes) you don't have to deal with a lot of headache.

You just need to properly configure your test site to handle the /drupaltest/ part for itself.

The rest of the solutions currently are giving you PHP functions for dealing with file paths, so they won't help you when creating content (PHP really shouldn't be going in your content like that).

**To configure to run in a sub-directory**

There are a couple of ways you can do that. You could set up your development environment so that apache is pointing to the subdirectory for the web root for that site.

The least technical way though would be to:

1. In your site's .htaccess file, uncomment the line that says `# RewriteBase /drupal` and make it say `RewriteBase /drupaltest`
2. Install the pathologic module.
3. Configure the module so that your input formats use pathologic and add your path as `/`

The pathologic module is useful anyway as it rewrites links in your content to use path aliases instead of paths like node/234.

Be careful when using path auto across multiple domain names, you might find you need to clear the cache whem moving between the testing & live sites to refresh the cached path related content.

# Answer
> 5 votes
you can use one of this function

file\_create\_url($uri);

or

image\_style\_url($style\_name, $path)

# Answer
> 2 votes
It seems like the question is not about PHP. You can use Token Filter module to make global token values available as an input filter.

```
<img src="[site:url]sites/default/files/example.jpg"/>

```

If you install and configure Token Variable module you can type some thing like that.

```
<img src="[site:url][variables:file_public_path]/example.jpg"/>

```

# Answer
> 1 votes
You can also use

```
theme_image_style($uri)

```

if you don't want to use an image style.

https://api.drupal.org/api/drupal/modules!image!image.module/function/theme\_image\_style/7

---
Tags: 7, nodes
---


# Question
Title: How to use glossary contextetual filter?
I created a user type view and add a contextual filter of User:Name. I enabled the glossary mod add character limit to 1. Same setting as glossary view. But still it not showing the filter (A|B|C). Am I missing any setting?

# Answer
Solved by Adding a Attachment Display to views.
> 0 votes

---
Tags: 7, views
---


title: author posts in views

text:
# Question
Title: author posts in views
I have a content type and sort theme in a page with views as a table And now, I want when users go to this page, they can see just the posts that the made them. see just post made by their-self. what filter should I do? How?

# Answer
1. Add an contextual filter of type `Content: Author uid`
2. Under *WHEN THE FILTER VALUE IS NOT IN THE URL* select *Provide default value*.
3. Select *User ID from logged in user*.
> 4 votes

---
Tags: views, users, theming
---


# Question
Title: How to make fields available to users in Drupal 7?
I want users to participate in creating some content. I allowed them (people/permissions) to create own content on particular content type. The question is: how to provide them access to fields of content type, that are available to me as administrator? In other words, I can put content in fields through my admin panel, but how to make users possible to meet that fields, how to make fields public? Thanks in advance!

# Answer
> 0 votes
By default, all the fields added to an entity are visible to every user who has permission to create or edit entities of that type. (In the case of nodes, the users needs the permission to create or edit nodes of that content type.) field\_access() is the function that determines which users have access to a field, but Drupal doesn't implement hook\_field\_access().
If the field is not visible to the other users, check you don't have a module that implements `hook_field_access()`, such as the Field Permissions module. If you have one of those modules, check their settings.

Alternatively, there is a module that makes the field not visible to the users. Also in this case, check its settings or temporary disable it to see if the field is visible to any other user.

# Answer
> 1 votes
Give "Create content" permission to the user type who can create content at your instance.

There is the Field Permission module which lets you specify permissions for each field in a entity. You can set permission for each field by help of this module.

---
Tags: 7, entities, users
---


# Question
Title: Bypassing Drupal's htaccess rewrite for static page
I've created a site that is currently partly static while partly managed in Drupal.

I've managed to rewrite static HTML by specifying the /static directory in the following manner above Drupal's .htaccess code.

```
RewriteEngine on
RewriteRule ^about-us/(.*) static/about-us/$1 [L]

```

Though I now have a dilemma. I have a directory page which is static:

> website.com/products

but then the next level needs to go through the Drupal system:

> website.com/products/product-type

to add to complication the next level then should go back to the static directory:

> website.com/products/product-type/product

Is this possible? And if so how would you achieve it?

**Notes**

Please note that these do not need to be dynamic. Can easily declare 'product-type' as there will only be 3. It would be good if I didn't have to declare 'product' because there will be multiple under each 'product type'.

My temporary fix was to just use a different directory in the URL. I added 's' to 'product-type' (website.com/products/product-types) for that specific page, and then at product level went back to remove the s (website.com/products/product-type/product)

# Answer
Look at Drupal's .htaccess, lines 110 to 113:

```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

```

It means if you create directory "products", every static file that's there will be served and all the rest will be directed to Drupal. Simple as this. If it's not working for you, you need to provide more details or fill a bug report.
> 1 votes

---
Tags: 7, .htaccess
---


# Question
Title: Drupal automatically create hardcoded links and do such links impact performance?
I have a site which is being developed in Drupal. My developer was developing in the live site directly. No one knew of our existence, so we didn't bother.

I had to change developers midway through the project. When the new developer wanted to develop locally, he had a lot of issues: links not functioning etc. We have found around 25,000 instances of the original site URL.

So what he did was to find and replace all 25,000 URLs with the local site URL in the database itself. Now everything worked fine.

Once the site was perfect locally we moved to live site again by replacing all URLs back to the original URL.

When I checked with my original developer why he had hardcoded, he mentioned that as we wrote a lot of custom code, Drupal automatically created these links. Is this possible?

Will this affect performance or have any long term issues?

# Answer
> 1 votes
If by "a lot of custom code" he meant he created a custom module, then there is nothing that explains why the links were hard-coded. Keep in mind that Drupal has url() and l() to create URLs and links, which removes the need of using hard-coded links when they are links to the same Drupal site. For example, the following code (used by Drupal core) would work correctly even when the code would be moved from a site to another. As a matter of fact, it generates links that work for every site powered by Drupal.

```
  $link = l(t('Remove orphaned actions'), 'admin/config/system/actions/orphan');
  $count = count($actions_in_db);
  $orphans = implode(', ', $orphaned);
  watchdog('actions', '@count orphaned actions (%orphans) exist in the actions table. !link', array('@count' => $count, '%orphans' => $orphans, '!link' => $link), WATCHDOG_INFO);

```

To notice that, Drupal normally (as in the above case) generates links that are relative; that is why they work independently from the domain. `l()` works in many cases, even in the case Drupal is installed in a sub-directory of the server document directory, or when clean URLs are disabled. On my test site, the above code (`$link = l(t('Remove orphaned actions'), 'admin/config/system/actions/orphan');`) would create the following link.

```
<a href="/dr71/admin/config/system/actions/orphan">Remove orphaned actions</a>

```

If I disable the clean URLs, the same code would get me the following link.

```
<a href="/dr71/?q=admin/config/system/actions/orphan">Remove orphaned actions</a>

```

The same code would produce the following links, when Drupal is not installed in a sub-directory.

```
<a href="/admin/config/system/actions/orphan">Remove orphaned actions</a>

```

```
<a href="/?q=admin/config/system/actions/orphan">Remove orphaned actions</a>

```

The only case I can think where absolute URLs are necessary is when the URL is pointing externally to the Drupal site, for example to a sub-domain (to blog.example.com from exampl.com). That is the only absolute URL I have in my Drupal site, since I have added the link from admin/structure/menu/manage/menu-secondary-menu/add.

I could have used a custom module to add the link, and in that case I would have avoided to use an hard-coded link. For example, I could have used the following code.

```
global $base_url;
$blog_url = preg_replace('@(https?://)(.*)@', '$1blog.$2', $base_url);

```

In the case of my local test site, the above code would set `$blog_url` to `'http://blog.tero.local/dr71'`, while in the case of my Drupal site, it would set the same variable to `'http://blog.avpnet.org'`.

A quicker method would be adding to the settings.php file a function that returns the link.

```
function _get_absolute_url($type) {
  global $base_url;

  switch ($type) {
    case 'blog':
    $url = preg_replace('@(https?://)(.*)@', '$1blog.$2', $base_url);
    break;
  }

  return $url;
}

```

In this case, for my test site I could use the following code, since I don't have a blog sub-domain.

```
function _get_absolute_url($type) {
  global $base_url;

  return $base_url;
}

```

In that way, I don't hard-code 100 links, but I use a single function that changes basing on the settings.php used from the site. In the case I need a link to the blog site, I would use code similar to the following one.

```
$blog_first  = _get_absolute_url('blog') . 'node/1';
$blog_second = _get_absolute_url('blog') . 'node/2';
$blog_third  = _get_absolute_url('blog') . 'node/3';

```

The code is assuming that, in the case of link to a Drupal site, that Drupal site is using clean URLs. If you administer that other site/sub-domain, it would not be difficult to change the code to get the correct URL.

# Answer
> 0 votes
Answering your question 1: Yes, if you set Drupal to automatically generate or create the links, it will.

Answering your question 2: Drupal it's BIG, Drupal provide a lot of versatility for coders/developer, but generally, even if the site it's also BIG, it will works nicely and fast. Don't worry about that, and contact your developer.

---
Tags: uri
---


# Question
Title: Add custom content to custom layout Panels
Is it possible to add custom content to a custom Panels layout?

Specifically, I've created a layout with a couple of columns for a content type called 'Stuff' and I always want to add the same images in a certain column of the **teaser** (that means every node of the 'Stuff' content type has to contain these images). I created several custom content panes with these pictures, but I don't know how I can use them in the custom Panel layout or the content type.

Any ideas? Or is there a better way to achieve my goal?

# Answer
You could place the images in a mini panel. Changes to the images would be done in the mini panel and would affect all nodes.

In Panels you can activate the Node view variant and create a panel (with a selection rule for the content type: Stuff). then use your Panel layout and place the mini panel in the column you want the images.

All nodes of the type stuff, should now use your layout with a mini panel holding your images. You can easily change the content of the mini panel and reuse it on other parts of your site.

Hope I understood your problem correct.
> 2 votes

---
Tags: 7, media, panels
---


# Question
Title: How do I render this code in block/node page?
```
print render($page['content']['system_main']['nodes'][$nid]['rc_core_item_avail_form']);

```

I tried putting this into a node in the Omega theme and also in a block directly but nothing at all. Can anyone help?

# Answer
> 1 votes
You cannot use that code in a node or in a block, since in both the cases the `$page` variable is not available. It seems that code is taken from an implementation of hook\_page\_alter() or adapted from code used by an implementation of `hook_page_alter()`. In fact:

* `hook_page_alter()` receives `$page` as argument
* The documentation for `hook_page_alter()` shows that, for a node page, `$page['content']['system_main']['nodes'][$nid]['body']` is the content of a node body

If rc\_core\_item\_avail\_form is a node field, in a block you could use code similar to the following one.

```
// Load the currently shown node.
$node = menu_get_object();

// Render the field.
$elements = field_view_field('node', $node, 'rc_core_item_avail_form');
print render($elements);

```

In the case the field could not be visible to every user, but you want to make that field visible to every user when it is shown in the block, then I would use the following code.

```
// Load the currently shown node.
$node = menu_get_object();

// Render the field.
$elements = field_view_field('node', $node, 'rc_core_item_avail_form');
$elements['#access'] = TRUE;
print render($elements);

```

---
Tags: nodes
---


title: hook_cron() is not working

text:
# Question
Title: hook_cron() is not working
I've created a new Drupal 7 module, which has been installed and enabled.

I have this function in the module.

```
function remove_entries_cron() {
  $query = "INSERT INTO {search_dataset} (sid,type,data) VALUES (22061986, node, hello)";
  db_query($query);
}

```

I have cleared the cache, and ran the cron manually but the record doesn't appear in the database.

Is there a way to check if the cron hook is working?

# Answer
> 4 votes
To check if a cron hook is being invoked, you need to output something to an existing database, for example using one of the following functions:

* watchdog() requires you enabled the Database logging module; otherwise, no entry will be added to the watchdog table, and admin/reports/dblog would not show new entries
* variable\_set() always set a value in a database table, but the value returned from variable\_get() could be the value set in the settings.php file for the `$conf` array
* The database API functions can be used, but you need to be use the database table exists; for example, use a database table installed by a module, even if it a module of yours

In the second case, don't use a Drupal variable (e.g. this\_is\_a\_wrong\_variable), for which the following code exists in settings.php.

```
$conf['this_is_a_wrong_variable'] = 'This value will be always returned from variable_get().'

```

If you do so, whatever you set with `variable_set('this_is_a_wrong_variable', 'My hook is invoked: ' . time())` will not be returned from `variable_get()` which would return `'This value will be always returned from variable_get().'`, in the example I made.

As you discovered, every Drupal hook must have a name prefixed by the module short name. In fact, the code used by Drupal to invoke a specific hook used by all the modules is the following one.

```
  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

```

As you see the function name for the function implementating a hook is `$module . '_' . $hook`. For the Node module, the `hook_cron()` implementation would be `node_cron()`; for an hypothetical module\_with\_a\_long\_name module, the `hook_cron()` implementation would be `module_with_a_long_name_cron()`.

Bear in mind that, if you edit the code of an enabled module to add a new hook, you need to disable and re-enable it, or Drupal will not see you added a new hook has been added to the module, since the list of hooks implemented by a module is cached. See module\_implements().

```
  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }

```

---
Tags: hooks, cron
---


# Question
Title: Access to private file only from website, not using direct link
My private files has a visible URL like the following: https://mywebsite.com/system/files/myimage.jpg.

How can I restrict access to the file, so it cannot be viewed directly from this URL but only from link on my website?

I have tried to use SESSION as follows.

```
$_SESSION['file-access'] = TRUE;
$output = theme('image_style', array('style_name' => 'foto_preview', 'path' => $uri));

```

Then I controlled in `hook_file_download()` if the SESSION key 'file-access' exists, but the session key never exists. The image I wish to display is the value of an image field. I cannot use `$user` because I wish to display private files also for anonymous users.

Can anybody help on how to restrict the direct access to a private file, but allow access from website?

EDIT 30.7.2013: my mistake, using sessios works OK, I had a mistake in another unrelated part of code. The problem is solved.

# Answer
You need to use private filesystem as shown in documentation. Then you can create custom module to implement more advanced rules, like link timeouts et cetera.
> 2 votes

# Answer
You can do this similar with hot linking htaccess protection.

```
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.tld/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.mydomain.tld/image_or_page_to_show_instead [R,L]

```

Just put your condition instead `\.(gif|jpg)$`
> 1 votes

---
Tags: files
---


# Question
Title: Create a View that redirects to node content based on contextual filter?
I've created a view with a contextual filter for 'field\_object\_id' -\> this is a field that the content type has which is unique but it's not the Node ID, these field\_object\_id's are brought in from a JSON feed.

So I can go to my view page like this:

drupal-site.com/my-view

Which would display a page not found. Then going to:

drupal-site.com/my-view/230

Would load up the content node that has '230' set for 'field\_object\_id' -\> however that content node ID is not 230, I have no idea what it is. It could be 8509.

What I need to do, is set my view to automatically redirect the page to the node that it finds (I would set it to redirect to the first result it finds).

I have Panels installed too, would this be easier to do with Panels or should I look to creating a module?

# Answer
> 1 votes
One way I think of is to to this in a custom menu callback. So you could have an URL /mycallback/\[OBJECT\_ID\] which would redirect to the first node that has the given \[OBJECT\_ID\].

Something like this:

```
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items['mycallback/%'] = array(
    'page callback' => 'fieldvalue_redirect_callback',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Custom callback given a object id.
 */
function fieldvalue_redirect_callback($id) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_object_id', 'value', $id, '=')
  ->addMetaData('account', user_load(1));
  $result = $query->execute();

  if (isset($result['node'])) {
    drupal_goto(url('node/' . key($result['node'])));
  } else {
    drupal_set_message(t('Page not found'), 'error');
    drupal_goto('<front>');
  }
}

```

First comes the definition of the menu callback, MYMODULE\_menu().

The argument after mycallback/ is being passed on the the page callback function by defining it here `'page arguments' => array(1),`.

fieldvalue\_redirect\_callback() will get the id entered by the user after /mycallback as argument. In the function we use EntityFieldQuery to fetch the node that matches the given ID.

And last we redirect if we get a result, otherwise we show an error message and the front page.

Hope this can help you or someone else.

# Answer
> 0 votes
So I was able to get this working (although maybe not the best way) by doing:

Setting show fields instead of content.

Selecting node ID in the fields (and set it to be excluded from display, although not necessary)

Then in the Views' FOOTER, add Text Area and set the filter to PHP.

Then I put:

```
<?php
  global $base_url;
  header("Location: $base_url/node/[nid]");
?>

```

And this seems to do what I want. Now going to the view page with an ID, it automatically redirects to the Node which redirects to the nodes' URL Alias.

---
Tags: 7, views, redirection
---


# Question
Title: How to get Panels to pass a correct date to Views (D7, Views/Panels3)
I'm trying to get a date from a node to a view pane. When someone is viewing the node, they should see a view on the right that is just a list of other nodes with the same day in the "event\_date\_time" field.

Here's screenshots of how everything is set up: https://i.stack.imgur.com/1mrac.jpg

1) First is the pane layout. The left is the node content with event\_date\_time. The right top is a view panel that has no filters, so you can see all the nodes and dates. Below it is the same view panel with a contextual filter.

2) the current results. You can see the right bottom only matches the two nodes that have the exact same year, month, day, hour and minutes.

3) the contextual filter setup. It's set with granularity of days, but doesn't seem to make any difference what granularity is set. Even if it is changed to "year", it still only returns the one exact matching item. If I change one of the two matching nodes from 4:00 to 4:15, they no longer match.

4) I'm asking for the date field from the Panel context in Views

5) And it's set up in Panels to send

6) The contextual filter returns the correct 4 events that match the day, if I manually pass it a YYYY-MM-DD format.

I looked through the context and relationship options in both panels and views and can't see any other way to send or format this date. I feel like I must be missing something basic in my understanding of how this is supposed to work.

(I get the same results whether I create the contextual filter using "Content: Event Date Time" or "Date: Date (node)", and whether they are set to "date range" or "only this field".)

This is Drupal 7.22, Panels & Views both current dev.

# Answer
After struggling for some time, I've still not found any way that works via context from Panels. Other people have said Panels values were determined by the "token" content display mode, but that isn't the case, at least with dates. Of course you can put the value in the URL and have Views grab it there, but for my use that wasn't appropriate. It also seems more fragile since it makes all content dependent on the path structure.

The best option I found was setting the "Argument Input" on the View to "Input on Pane Config". Then in the Panel Pane, use keyword/token substitution. I created a custom date & time formatter that is CCYY-MM-DD, called "date only", and set the Panel option to "`%node:field-my-date-field:value:date_only`". That grabs just the first value from a date range. For a field without range, "`%node:field-my-date-field:date_only`" works.
> 2 votes

---
Tags: panels, views, datetime
---


# Question
Title: Checkboxes: how do I set the default values or show the user defined values using Form API?
I am using an checkboxes element within a form in module that I started developing for Drupal 7. This is my first attempt at module development and using the Form API. I am creating a list of checkboxes that list down all the content types of a specific site. An array of all the content types can be obtained by using the following: `$nodeTypesRaw=node_type_get_names();`. An array with the machine names of the content types as the keys and the human readable names as the values are obtained.

By default, I would like all the checkboxes to be selected and when the form is submitted. How do I achieve that? The Form API pages on the drupal site aren't very helpful with regards to setting the default values for checkboxes.

```
$nodeTypesRaw=node_type_get_names();
$nodeMachineNames=array_keys($nodeTypesRaw);
$form['process_comments']['custommod_published_comments_select_node_types']['custommod_published_comments_node_types_checkboxes']=array(
          '#deafult_value'=>$nodeMachineNames,
          '#options'=>$nodeTypesRaw,
          '#type'=>'checkboxes',
);

```

I initially started out with the above code, but it won't work. It does display the list of checkboxes, but they are not checked by default. The variable does get on form submission though (checked via drush and var\_dump).

# Answer
> 20 votes
From Drupal.org:

```
$form['element_id'] = array(
  '#type' => 'checkboxes',
  '#options' => array(1 => "One", 2 => "Two", 3 => "Three"),
  '#default_value' => array(1, 3),
);

```

Default value is set as an array representing keys of selected options.

Looking at the code in your question, problem is with spelling. you are setting `'#deafult_value'` when you want to set `'#default_value'`.

# Answer
> 11 votes
You need to give an array of option *keys* (not values) as the default value, e.g.

```
$options = array(
  'option_1' => t('Option 1'),
  'option_2' => t('Option 2'),
  'option_3' => t('Option 3'),
);

$defaults = array_keys($options);

$form['checkboxes'] = array(
  '#type' => 'checkboxes',
  '#title' => t('Something'),
  '#options' => $options,
  '#default_value' => $defaults,
);

```

---
Tags: forms
---


title: Panels modules got rid of all my pages

text:
# Question
Title: Panels modules got rid of all my pages
I recently installed a theme that called for Panels Everywhere, Mini Panels, and Page Manager modules to be installed. The theme looks great but I don't understand where all my custom pages went?

I had created a bunch of pages in my custom module using `hook_menu()`. Now my site is completely driven by Panels and Page Manager. I assume all my `MENU_NORMAL_ITEMS` were being stored in a block that is now being suppressed by panels everywhere.

How do I get all my old menu items to work with my new theme? How do I link up the elements of my theme with my existing pages?

# Answer
Panels everywhere is like it says, a way to use Panels all over your site. This means that whats normally outputted by `page.tpl.php` will now be run through a Panel.

Enable the site template (if not already done) here: `/admin/structure/pages` Edit the site template and add the page elements as you want your site to be built. Eg. add the site header, then the page title, page content etc.

There is also a setting to create a sample site template variant for you here `/admin/structure/panels/settings/everywhere`.
> 2 votes

---
Tags: routes, panels
---


title: How do I implement routes?

text:
# Question
Title: How do I implement routes?
How can I implement the most basic route in Drupal 8? What files do I have to write, and which classes do I need to implement?

# Answer
> 11 votes
Implementing the most basic route in Drupal 8 require:

* The file containing the routing definitions (helloworld.routing.yml)

```
helloworld.hi:
  pattern: '/helloworld'
  defaults:
    _controller: '\Drupal\helloworld\Controller\HelloWorldController::hi'
  requirements:
    _permission: 'access content'

```
* A controller class that returns a render array or a string (src/Controller/HelloWordCOntroller.php)

```
namespace Drupal\helloworld\Controller;

class HelloWorldController {
  function hi() {
    return 'Hello world!';
  }
}

```

This is the equivalent of what in Drupal 7 was a `MENU_CALLBACK`. Implementing a local task, or a local action requires other files to be added, differently from Drupal 7, where a local tab would be implemented using the same hook used for a `MENU_CALLBACK`.

---
Tags: routes, 8
---


# Question
Title: How to add block to only user/uid and not user/uid/edit
In my site the www.example/user/uid path contains the view and edit tabs. I want to add some blocks to only the view page and not edit page.

Using "user/\* (Only the listed pages)" under the visibility settings of block configuration attaches the block to both pages.

How can I make it appear on only the view page.

Thanks in anticipation.

# Answer
Hope this will help you,

In Drupal 7,

* You can achive it by enabling **PHP filter** module, which allows embedded PHP code/snippets to be evaluated. GO to **admin \> modules** and enable **PHP filter**. ````
<?php
    global $user;
    if (arg(0) == 'user' && $user->uid == arg(1) && is_numeric(arg(1)) && (arg(2) == NULL) ){
      return TRUE;
    }
    else {
      return FALSE;
    }
?>

````
* You can also refer **Extended block visibility** module. This will allows PHP block visibility to be defined in code.
> 3 votes

# Answer
you could write some php in the visibility settings checking the path like:

```
<?php
 $path = explode('/', $_GET['q']);
 if ($path[0] == 'user') {
   if (is_numeric($path[1]) && $path[2] != 'edit') {
     return TRUE;
   }
 }

```

...something like that (untested). This could be handled in a user\_view hook also, but this the simple solution.

Be carefull what PHP you write in there because if it breaks the site you will have to remove this code form block's records in the database!
> 1 votes

# Answer
I would enable Panels and Page Manager and under Pages enable the user\_view variant. Then place the block in where you want it in the layout.

You will also need to place normal "user" elements in the layout to not suddenly display nothing :)
> 0 votes

---
Tags: navigation
---


title: Drupal hook_preprocess_hook not working

text:
# Question
Title: Drupal hook_preprocess_hook not working
I have a webform with id 32.

I created a template (which works fine) in my theme/templates folder named webform-form-32.tpl.php.

I also created a preprocess function in my template.php file. My theme is called emuse and my hook is:

```
function emuse_preprocess_webform_form_32(&$vars){
}

```

but this doesnt get called. Can anyone help me out ?

# Answer
Nealv, the preprocess function can only be implemented for the base name, not for the additional suggestions you used for creating your tpl.php file. The suggestions for alternate template files are added in the preprocess functions themselves.

See https://drupal.org/node/223440 \- These naming suggestions are set from preprocess functions.

So call THEMENAME\_preprocess\_webform\_form and check if it's the right form to alter within the function itself.
> 1 votes

# Answer
Try this :

```

function THEMENAME_preprocess_webform_form(&$vars){
  print_r($vars);
}

```

For reference : http://www.ixis.co.uk/blog/webformblock-styling

Hope it helps
> 0 votes

---
Tags: hooks, theming
---


# Question
Title: How to add dynamic created css using drupal_add_css
I am trying to add a file which is located in sites/default/files/color/theme-768/color.css using `drupal_add_css()`.

I have tried `drupal_add_css($filepath)`, but it doesn't work. I tried putting it in template.php and `hook_init()`, but still it isn't included in the style tags of head section or anywhere.

How I do include a CSS file like this using `drupal_add_css()`?

# Answer
> 0 votes
I found a alternate way to include css file which is in some other location other than modules and themes.In my case including a dynamically generated file. Even though i can't find a way through drupal\_add\_css(),this helped me in adding css.

This is the way i included dynamically generated css file which is located at `sites/default/files/color/theme-768/color.css`

In the theme folder in the html.tpl.php after `<?php print $styles;?>` include this

```
<?php
       print '<style>';
       print '@import url("' . $filepath . '")';
       print '</style>';
?>

```

This includes the css file.

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


# Question
Title: Assign textfield to each checked option in a checkboxes field
Lets say I have a checkboxes field and when I check one of the options, I would like a textfield to appear so I can assign a number (quantity) to it. Every option I check would have its own textfield.

For example, I have a "Fruits" field and I want to be able to say how many of each fruit I have. So it would be something like that:

```
[x] Apple (3)
[] Grape
[x] Orange (2)

```

Is there any module that does something similar to that?

Edit:

Another thing that would do the work for me would be a select list of numbers for each option. So by default the options are like that:

```
[0] Apple
[0] Grape
[0] Orange

```

So I can simply change the number of fruits in each option by selecting in the dropdown.

# Answer
The conditional fields module should be suitable for this

> 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.
> 0 votes

---
Tags: 7, entities
---


title: Date elements wrap

text:
# Question
Title: Date elements wrap
How can i wrap date elements in this function?

```
function theme_date_display_single($variables) {
    $date = $variables['date'];
    $timezone = $variables['timezone'];
    $attributes = $variables['attributes'];
// Wrap the result with the attributes.
    return '<span class="date-display-single"' . drupal_attributes($attributes) . '>' . $date . $timezone . '</span>';
}

```

I think i can call $date with some parametrs, but don't which. I want something like:

```
return '<span class="date-display-single"' . drupal_attributes($attributes) . '> <label class="day">'. $day. '</label> <label class="month">'. $month. '</label>' . $timezone . '</span>';

```

# Answer
> 1 votes
Hope this will help you,

In Drupal 7 you can use **Custom Formatters** module for your requirement.

Steps

* Install and enable **Custom Formatters** and **TOKEN** module
* Create you own format using **admin/structure/formatters**
* Use the available TOKENS
* Use TOKEN and HTML TAGS to create new format
* After creating the new format
* Use the new date format where you want to show

---
Tags: datetime
---


title: Update Mysql table row

text:
# Question
Title: Update Mysql table row
I'm new to Drupal and its SQL API, and I am trying to update a row in a table I created.

```
// Admin form
function admin_Form($form, &$form_state) {
  $dbval = getVals();
  $form = array();

  $form['firstname'] = array(
    '#type' => 'textfield',
    '#title' => 'Fornavn',
    '#id' => 'fornavn',
    '#value' =>  $dbval['firstname'],
  );

  $form['lastname'] = array(
    '#type' => 'textfield',
    '#title' => 'Efternavn',
    '#id' => 'efternavn',
    '#value' =>  $dbval['lastname'],
  );

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

  return $form;
}

function admin_Form_submit($form, &$form_state) {
  $update_zoho = db_update('zoho')
    ->fields(array(
      'firstname' => $form_state['values']['firstname'],
      'lastname' => $form_state['values']['lastname'],
    ))
    ->condition('lastname', 'lastname', '=')
    ->execute();
}

```

Everything gets executed and the message gets displayed, but the row is not updated.

Can anyone point a newbie in the right direction? These are the table structure and the values is contains.

```
    title, firstname, lastname,  city, ... lots of colums
    ------------------------------------------------------
          - Bolli    - lastname - KBH  ....
          -          -          -
          -          -          -
          -          -          -

```

# Answer
I finally figured it out. It's because I use the #value parameter in my admin\_form.

From drupal dokumentation on #value:

> Description: Used to set values that cannot be edited by the user. Should NOT be confused with #default\_value, which is for form inputs where users can override the default value.

So the form did get submitted, but never with the user edited value. Instead it always submitted $dbval\['foo'\] and it seamed like nothing changed. Changing #value to #defualt\_value fixed everything. Thanks for all the help.
> 0 votes

# Answer
You need a `condition()` so that it knows which record to update. When you don't give a condition, it just doesn't update anything. More Info on db\_update()

The following says, "Update firstname to formvalue, lastname to formvalue WHERE the last name as stored in database is 'Bolli'". To avoid conflicts, your table should have a field that contains a unique value for each entry, such as an auto-increment primary key. That way, you can say "UPDATE ... WHERE id = unique\_id".

```
$update_zoho = db_update('zoho')
  ->fields(array(
     //'title' => $form_state['values']['title'],
     'firstname' => $form_state['values']['firstname'],
     'lastname' => $form_state['values']['lastname'],
  ))
  ->condition('lastname', 'Bolli', '=')
  ->execute();

```
> 1 votes

---
Tags: forms, database
---


title: Theming a Field Collection Widget

text:
# Question
Title: Theming a Field Collection Widget
Is it possible to theme the Field Collection widget for just one field? The example I am looking for is a list of text fields. I need some of the text fields to be in two columns instead of one long column, which is the default. I also need to add some formatting guide text for some of the fields. I know I can achieve some of this through CSS, but was curious if there is a hook or something that I could implement that would allow me to change the markup as well? This is in Drupal 7 as well.

Thanks!

# Answer
> 4 votes
Yes it's possible.

You need to go to the Field Collection module directory and copy `field-collection-item.tpl.php`. Then paste it into your theme directory and rename it to `field-collection-item--myfieldname.tpl.php`.

---
Tags: entities
---


# Question
Title: Multiple (bulk) upload with the media browser widget
I'm using Media 7.x-2.0, and I would like to be able to upload more than one image/media at the same time with the media browser widget. How can I do this?

I know about Plupload but I just need HTML5 support and don't want a special widget.

There is also Multiupload Filefield Widget, but I want to keep the media browser widget.

# Answer
You will need to use https://drupal.org/sandbox/fangel/1652676 to be able to upload multiple images and still be able to access the media library.
> 2 votes

---
Tags: 7, media, files
---


# Question
Title: how to get a list of all nodes that haven been created and are not in use on the system
as the title says.. i need to get a all published nodes of type A that have been created and not used (at the moment) by other nodes.

in other words a list of all node of type A that are on the Database except for those that are NOT been referenced in an entity reference field.

the easy approach will be to load all nodes that uses node of type A, and that load all type A nodes and check for each if it's has a reference for it. but then if i add another node that will use node of type A as an entity reference i'll have to go back check it as well.

is there an easy way to do it ?

# Answer
> 1 votes
You could set up a view showing title of content type A, title of content type B (using relations), hide both and create a custom PHP field that just returns title of ct A if ct A does not have ct B referencing to it. Maybe

---
Tags: nodes
---


# Question
Title: Wrong Javascript order: Undefined variable: jQuery
Since I moved all scripts form the header to the bottom of the page (in the template file of my theme) I have the problem that some scripts of contributed modules (chosen and device geolocation from smart ip) are added before the JQuery library. Using Jquery this leads to an error:

```
Undefined variable: jQuery

```

What can I do to get the right order and what could be the reason of the fact that the order is only wrong when the scripts are added at the bottom of the page and not in the header?

# Answer
> 3 votes
Modules, via `drupal_add_js()` can define the 'scope' and 'weight'. The 'scope' defaults to header, so unless you change this via `drupal_add_js()` in your template.php file, you can't move `print $scripts` from your header, or you'll have this problem with, likely, most contrib modules.

To change this, you could do something like this in `yourtheme_preprocess_page($vars)`:

```
$js = drupal_add_js();
$newJs = array()
foreach ($js as $s) {
  $s['scope'] = 'footer';
  $newJs = $s;
}

drupal_add_js($newJs);

```

---
Tags: javascript
---


# Question
Title: theme_hook process: calling a theme function not working(example from DGD7)
I'm just working through an example module in DGD7. The module reports statistics about the themes. It displays this information in the help region on the appearance admin page.

I can't get it to display and I'm wondering if I understand the theming process correctly.

My understanding is this:

1. I call my function. (with a function)
2. My function returns data.
3. I tell drupal about my theme function with hook\_theme
4. My theme function then turns my data into HTML.

Here's the module:

It uses a switch to call the function based on the path:

```
function xray_help($path, $arg) {
 switch ($path) {
  case 'admin/appearance':
   return xray_appearance_summary();
 }
}

```

Then this function calls data from a stats function which returns a compact. (the stats function works - tested with dpm())

```
function xray_appearance_summary() {
  $data = array();
  $data['themes'] = xray_stats_enabled_themes();
  return $data;
}

```

They give a theme function (I'll put it last because it's quite long) but don't show how to call it with hook\_theme. I tried using this hook\_theme to call the theme function:

```
function xray_theme() {
  return array(
    'appearance_summary' => array(
      'variables' => array(
        'themes' => NULL,
        'attr' => NULL,
      ),
    ),
  );
}

```

The theme function takes two variables $themes & $attr so I put both of those in. But I get the error.

Notice: Array to string conversion in menu\_get\_active\_help() (line 1722 of C:\XAMPP\htdocs\drupal\includes\menu.inc).

Am I misunderstanding hook\_theme?

```
function theme_xray_appearance_summary($variables) {
  $themes = $variables['data']['themes'];
  // Collapse attributes for paragraph tag to a string.
  $attr = drupal_attributes($variables['attributes']);

$output = '';
  $output .= "<p $attr>";
  $output .= t('This site');
  $output .= ' ';
  $output .= format_plural(
    $themes['num_themes'] - $themes['num_hidden'],
    'has only one theme available',
    'has @count themes available'
  );
  $output .= ' ';
  $output .= format_plural(
    $themes['num_hidden'],
    'plus one hidden theme.',
    'plus @count hidden themes.'
  );
  $output .= ' ';
  $output .= t('Of the non-hidden themes,');
  $output .= ' ';
  $output .= format_plural(
    $themes['num_enabled'],
    'one is enabled.  The enabled theme',
    '@count are enabled.  In the enabled themes,'
  );
  $output .= ' ';
  $summaries = array();
  foreach ($themes['summaries'] as $name => $info) {
    $summary = '';
    $summary .= $name . ' ';
    $summary .= format_plural(
      $info['regions'],
      'has one region',
      'has @count regions'
    );
    if ($info['overlay_regions'] || $info['regions_hidden']) {
      $summary .= ' ' . t('(including') . ' ';
      $summary .= format_plural(
        $info['overlay_regions'],
        'one overlay region',
        '@count overlay regions'
      );
      $summary .= ' ' . t('and') . ' ';
      $summary .= format_plural(
        $info['regions_hidden'],
        'one hidden region',
        '@count hidden regions'
      );
      $summary .= ')';
    }
    $summaries[] = $summary;
  }
  $output .= xray_oxford_comma_list($summaries);
  $output .= '.';
  $output .= '</p>';
  return $output;
}

```

EDIT ONE.

I've got rid of the error by changing the switch; thanks to Yuriy, but nothing still displays:

```
 case 'admin/appearance':
      $variables = array('data' => xray_appearance_summary());
      return theme('xray_appearance_summary', $variables);

```

# Answer
> 0 votes
Ok so I had two problems in the end. The first which I put in my edit above, was I needed to turn `$data` (an array) into a string. This was done by using the theme function to send the `$data` to the theme which then themes it and sends it back as a string.

```
case 'admin/appearance':
     $variables = array('data' => xray_appearance_summary());
     return theme('xray_appearance_summary', $variables);

```

The second was my hook\_theme. It's receiving `$data` from `xray_summary_appearance`. Not `$themes` from the theme function.

```
function xray_theme() {
  return array(
    'xray_appearance_summary' => array(
      'variables' => array(
        'data' => array(),
        'attributes' => array('class' => 'xray-help'),
        ),
      ),
    );
}

```

# Answer
> 1 votes
First of all, your `theme_xray_appearance_summary` should be `theme_appearance_summary`, and should take `$variables` by reference: `&$variables`.

Second of all, `hook_help()` expects you to return a string, but your implementation returns the data from `xray_appearance_summary()`, which returns an array, thus the error you're getting.

---
Tags: 7, theming
---


title: Error message AJAX "Add a code field"

text:
# Question
Title: Error message AJAX "Add a code field"
I always get the following error message when I try to add a code field to a content type in the section 'Manage display':

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /MYSITE/?q=admin/structure/ds/ajax/add\_field/custom\_field StatusText: Service unavailable (with message) ResponseText: PDOException: SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away in variable\_set() (line 971 of C:\wamp\www\MYSITE\includes\bootstrap.inc).

How can I solve this?

# Answer
This usually happens when the `max_allowed_packet` value in your MySQL configuration (my.cnf file) is set to a low value. Increase the value (to, say, `24M`), reboot your MySQL and give it another shot. Depending on your site & server, you may need a higher or lower value.
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: Module content type not removed after uninstall
My module adds content types by implementing `hook_node_info`. After *disabling* and **uninstalling** the module, the content type is still in the database and is merely marked as *disabled*.

*NOTE:* I also add create and instantiate custom fields for the created content type.

Since according to this answer content types created in `hook_node_info` are deleted automatically, is my problem a sign if DB inconsistency or am I doing something else wrong.

**Code:**

```
function test_core_node_info() {
    // Name of the proper localization function
    $t = get_t ();
    // Adding author
    return array (
            'test' => array (
                    'name' => $t ( 'Test' ),
                    'base' => 'test_module',
                    'description' => $t ( 'Test' ),
                    'title_label' => $t ( 'Title' ),
                    'locked' => TRUE
            )
    );
}

```

**-- EDIT --**

I mentioned **removing** instead of **uninstalling**. This is corrected now.

# Answer
You shall have to *uninstall* the module to get the type deleted automatically. Just disabling it will not remove anything. Deleting the module after disabling it - *without* uninstalling it first - is *not* a good idea.

After disabling the module, click on the “uninstall” tab at the top of the modules page and check the module you want to uninstall, then click the "Uninstall" button.
> 2 votes

---
Tags: 7, nodes
---


title: Edit button in teasers

text:
# Question
Title: Edit button in teasers
i'm using display suite and views in one of my teaser content type and i'm trying to add an EDIT button right in the teaser, but i can't find the function to do this. So i came here to ask for help. Can you help me? Thank you

# Answer
> 1 votes
Once you are using Display Suite module, you can simply create a new "Custom Field" and use the "Code field"(Add Code field) to generate the apropriate code to edit. Enable the Entities to Node and in the field code add this code and hit save:

```
<a href="[node:edit-url]">EDIT</a>

```

PS: As you can see, i'm using a token to generate the edit path of the node, so you need to have token module enabled. Make sure that you are adding this in the teaser display

# Answer
> 2 votes
The edit function is usually provided in teasers with contextual links.

Activate the optional core module, and when the teaser is displayed, a contextual links icon will be displayed at the upper right corner of the rendered teaser.

# Answer
> 0 votes
In Views add filed 'Content: Edit link' and on teaser field go to 'Rewrite results \> Rewrite the output of this field' in box use 'Replacement patterns' below and write something like \[your-teaser-field-replacement\]...\[edit\_node\].

Instead '...' you can use anything or just space.

Rearrange fields and set 'Content: Edit link' field above your teaser field.

On filed 'Content: Edit link' check 'Exclude from display'.

You can use css to set button instead text on edit link.

More info on THIS and THIS link...

---
Tags: nodes
---


title: E-Mail functionality for moderators

text:
# Question
Title: E-Mail functionality for moderators
I would like to allow moderator to send an e-mail to choosen user. The e-mail will be sent when the moderator observes a mistake made by the user. After that, moderator sends email with warning. How can I do it?

# Answer
> 1 votes
A simple solution would be, to give the moderators role the permission to use the users' individual contact forms ( in http://example.com/admin/people/permissions )

The messaging and notifications modules might have more functionality, however, they are still in alpha for drupal 7, so I would use them with great caution.

---
Tags: 7, emails
---


title: Radio buttons widget for boolean field

text:
# Question
Title: Radio buttons widget for boolean field
When I add new boolean field to content type in admin i can choose widget for it: checkbox or radio buttons. How can I describe it in code? When I do something like this there is no widget:

```
$i = 1;
foreach($questions as $question){
        $field_name = $name . '_q' . $i;
        $fields[$field_name] = array(
            'field_name' => $field_name,
            'type' => 'list_boolean',
            'required' => true,
        );
        $i++;
}

foreach($fields as $field){
        if (!field_info_field($field['field_name'])) {
            field_info_cache_clear();
            field_create_field($field);
        }
}

$instances = array();

$i = 1;
foreach($questions as $question){
    $field_name = $name . '_q' . $i;
    $instances[$field_name] = array(
        'field_name' => $field_name,
        'label' => $question,
        'widget' => array(
            'type' => 'radio'
         ),
         'required' => true
     );
     $i++;
}

foreach($instances as $instance){
    $instance['entity_type'] = 'node';
    $instance['bundle'] = $name;
    field_create_instance($instance);
}

```

# Answer
Simplest way is to use `field_create_field()` to create the field itself and `field_create_instance($instance)` to have an instance for your content type. Widget type should be set in `$instance['widget']['type']` sent to `field_create_instance($instance)`.

Taken from this answer.
> 0 votes

---
Tags: nodes, entities
---


title: create views page using entityreference

text:
# Question
Title: create views page using entityreference
I have two custom content types, Speaker and Presentation. Each speaker can have many presentations. I am using the EntityReference module to attach a Speaker to a Presentation. Using Views, I would like to create a page of Presentations that also lists the Speaker associated with the presentation such the page would look something like:

Presentation 1
details
Attached speaker details

---

Presentation 2
details
Attached speaker details

---

Presentation 3
details
Attached speaker details

---

How do I do that in Views. I followed the EntityReference documentation but it only talks about creating a block for a single node. I want to be able to show multiple Presentation nodes on one page using Views and EntityReference. Thanks in advance for any help anyone can provide.

# Answer
I assume that you have your entity reference field (pointing to speaker) on the content type "Presentation" below and that it is called "field\_speaker".

In Views add a new View. Choose Show:Content (nodes), of type: Presentation.

Now you have all your presentations listed, with their titles. Let's leave it at that for now.

Open up Advanced to the right and open up Relationships, choose "Entity Reference: Referenced Entity - A bridge to the Content entity that is referenced via field\_speaker".

Now we have the same result as before but we will be able to fetch data for the speaker through the relationship in the content type Presentation.

Under fields, click add and add the field called "Content: Title", now you have a dropdown that says "Relationship". Choose the only on available (field\_speaker). Click apply.

You now have each presentation listed with it's title and the title of the presentations speaker.

Now you can go ahead and add the fields you wanted, sort the list etc.
> 1 votes

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


title: 413: File entity too large ugly error

text:
# Question
Title: 413: File entity too large ugly error
When uploading an image that exceeds the server PHP upload image, I get the following error:

My question is: Why is this error displayed so ugly and is there a way to display it more nicely, for example, in the form itself?

To be clear: I know why this error is thrown, it's just a matter of userfriendliness.

# Answer
If you are experiencing it on Chrome only it's a problem with your setup, not Drupal itself. Here you have a bug report about it.

But more probable is that it happens on all browsers, and it's a problem with nginx config - you need to set up `client_max_body_size` about 35% larger than max file size you want to allow people to upload using Drupal (to have safety margin for Base64 and alike). That way your Drupal will catch "to large" exceptions, and not your nginx.

Note - HTTP does not force body encoding, so 35% margin may well stay unused. But nothing stops applications from doing it, and 35% is what I experienced to be safest bet to avoid future surprises. Hardly any encoding or wrapping wastes as much as Base64 with it's 4/3 overhead. Better safe than sorry and if your server is willing to accept 20MB files, then 27MB will not kill it.
> 5 votes

---
Tags: ajax, files
---


# Question
Title: Setup different pager settings for same view
Is there a way to display the same view with different pager configurations? For example have the same set up with 3 items for the homepage and full paged for a news list page? Thanks!

# Answer
> 1 votes
If you are using Panels, you can place "Content panes" with different configurations for each instance.

I've found this very useful when you want a news listing with title and image in one place and just titles in another and different number of items displayed but have the same view generate the list (for easy maintainability and overview).

I've attached an image below where you can see the pager settings set to be configurable in the View configuration. You'll need to have Panels and Views content panes (shipped with ctools) enabled to create the display type "Content pane" from Views.

If you use Content panes there are actually more settings that can be overridden in each instance of the View it's display. Here's a screenshot of what more that can be set to be configurable.

# Answer
> 1 votes
I dont think its possible, you can achieve this by adding another page/block display to an existing view and specify the pager values accordingly.

As Ursula said, When you change your pager on the second display, do not forget to change the 'for' pulldown menu on the modal window from 'all displays' to 'this page (overwrite)'. Otherwise, you changed the pager for all displays.

---
Tags: views, paging
---


title: Why isn't this ajax form working?

text:
# Question
Title: Why isn't this ajax form working?
```
function ga_script_script_question($form, &$form_state) {
    $form['question'] = array(
        '#type' => 'fieldset',
        '#title' => t('Question'),
        '#collapsible' => FALSE,
        '#collapsed' => FALSE,
        '#prefix' => '<div id="question-wrapper">',
        '#suffix' => '</div>',
    );

    if(isset($form_state['storage']['myflag'])) {
        $form['question']['new_thing'] = array(
            '#markup' => "new thing",
        );
    }

    $form['question']['original_thing'] = array(
        '#markup' => "original thing",
    );

    $form['next_question'] = array(
        '#type' => 'submit',
        '#value' => t('Next question'),
        '#submit' => array('ga_script_script_next_question'),
        '#ajax' => array(
            'callback' => 'ga_script_script_callback',
            'wrapper' => 'question-wrapper',
        ),
    );

    return $form;
}

function ga_script_script_next_question($form, $form_state) {
    $form_state['storage']['myflag'] = 1;
    $form_state['rebuild'] = TRUE;
}

function ga_script_script_callback($form, &$form_state) {
    return $form['question'];
}

```

When I submit this form, nothing happens. I get the little spinning thing next to my submit button, but the contents of question-wrapper are unchanged. It seems like the form is not getting rebuilt.

What am I doing wrong?

# Answer
I just realised I was missing the & in my submit function. It should have looked like this:

```
function ga_script_script_next_question($form, &$form_state) {
}

```

It works fine now.
> 2 votes

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


title: Site name with html tag

text:
# Question
Title: Site name with html tag
How can I have the site name with a span html tag without hard-coding it in a template? \[ex. `Good<span>4</span>You`\]

# Answer
> 2 votes
Its not at all difficult. I tried it in Drupal 7.22

`Goto Configuration` =\> `Site Information` =\> `Site Name` =\>

```
My Site <span class="dummy-class">This is my new website</span>

```

Add whatever tags you like to have. But remember `site title` itself is already inside `<span>` tag, which means you have some restriction *(Span tag is not container)*.

*This is what it looks when I inspect it using firebug in mozilla.*

In your case, its `Good<span>4</span>You`. Just by using `css` you can do the magic.

# Answer
> 1 votes
My suggestion would be to add a block via admin/structure/block/add and create the exact markup you want.

Then add the block to the region you want (probably **Header**), style, disable site name and site slogan in your theme settings, and go on your way.

# Answer
> 0 votes
And here comes the template way :), place in template.php in your theme and change MYTHEME to the machine name of your theme.

```
function MYTHEME_preprocess_page(&$variables) {
  $variables['site_name'] = 'Good<span>4</span>You';
}

```

---
Tags: 7
---


# Question
Title: How to determine if Varnish/Pressflow is caching content in a useful way?
I recently converted one of my D6 sites to Varnish/Pressflow and saw a very modest improvement in average load speed (from ~550ms before to ~450ms now). But, I also noticed that the initial load time for the first load in a round of tests were consistently much higher --- around 1000ms. They quickly fall down to ~450ms during subsequent reloads during the same test.

This makes me think that I've configured something incorrectly, and Varnish isn't serving from the cache until after the (anonymous) user has already visited the page in question. Perhaps the session IDs are causing each session to be cached independently from eachother (though I understand that shouldn't happen for anonymous users under Pressflow).

The X-Varnish headers appear in both the initial page load, and subsequent loads, so I know the content is at least getting passed through Varnish.

Is there a way to get details about part of the Varnish cache is serving a particular page (e.g. when the cached page was created)? I've tried looking at the logs generated by varnishlog, but apart from various apearances of "X-Drupal-Cache: HIT" I'm not sure what to look for.

# Answer
Below is the text that can been seen when using Google Chrome and under Network inspecting the response for you webpage. Observe the very last line. There you should get two numbers `X-Varnish:1125490268 1125489929`.

I've had problems before setting up Varnish and everything seemed to be going fine, then I noticed that only one number was present in X-Varnish. When fixed the two numbers appeared with a decrease in response time form 500ms to 45ms :)

Hope it can help you on the way.

```
Request URL:http://www.somepage.com/
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:www.somepage.com
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/28.0.1500.52 Chrome/28.0.1500.52 Safari/537.36
Response Headersview source
Accept-Ranges:bytes
Age:230
Cache-Control:public, max-age=900
Connection:keep-alive
Content-Encoding:gzip
Content-Language:en
Content-Length:6411
Content-Type:text/html; charset=utf-8
Date:Tue, 30 Jul 2013 08:03:13 GMT
Etag:"1375164849-1"
Expires:Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified:Tue, 30 Jul 2013 06:14:09 +0000
Server:Apache
Vary:Cookie,Accept-Encoding
Via:1.1 varnish
X-Drupal-Cache:HIT
X-Generator:Drupal 7 (http://drupal.org)
X-Powered-By:PHP/5.3.10-1ubuntu3.6
X-Varnish:1125490268 1125489929

```
> 3 votes

---
Tags: 6, proxies
---


# Question
Title: Views strips/merges unlimited values/fields of same field into one
I have a content type and a Text field 'Achievements'. Now it is set to Unlimited so every time when creating that content I enter an achievement per field. So then I have a nice list of achievements listed in separate divs where I can apply CSS and etc.

I made a view to list those content types including achievements fields and Views merges in all achievements into one view-field and makes a total mess and it becomes unlisted/unordered and no CSS cannot be applied because all divs and classes (even/odd) are gone.

It works fine via original node, but divs are stripped via Views.

# Answer
If you are displaying **fields**, you need to configure the settings for multiple values.

From the edit screen for the view, select the properties of the field set to *unlimited*. Then scroll down and find the part that says **Multiple field settings**:
> 3 votes

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