# Question
Title: How to make sure that panels classes are added to a CTools pane?
I am attempting to define a CTools content pane based on the tutorial here. However, **when I add my pane to the panel, no matter what region (left sidebar, header, footer) I add it to, it is printed at the top of the page without any of the region or pane CSS classes.**

This is the function I am using to render the pane:

```
function MYMODULE_messagelimits_content_type_render($subtype, $conf, $args, $context) {
  if (!empty($conf)) {
    $block = new stdClass();
    $block->title = check_plain("");
    // Show message limits
    $block->content = MYMODULE_show_message_limits();
    return $block;
  }
}

```

MYMODULE\_show\_message\_limits() is a function that prints out some information to show users what their messaging limits are, for example:

```
if ($sent_total > 1) {
  print '<div class="messagesng">';
  print t('You have already started conversations with 2 people this week.') . '</div>';    }
else if ($sent_total == 1) {
  print '<div class="messagesok">' . t('You can start a conversation with 1 more new person this week.') . '</div>';
}
else {
  print '<div class="messagesok">' . t('You can start conversations with 2 new people this week.') . '</div>';
}

```

If I make a change such as `$block->content = t("my sample content")`, then the pane is printed with the correct classes in the proper place on the page.

**So how can I set the output of `$block-content` to be the output of my custom module's function while retaining the panels CSS classes?** Please help me stop abusing the PHP filter within Panels!

# Answer
> 2 votes
In the following function, the content is provided by `t()`. `t()`, when called, *returns* the text `"my sample text"`. Because that text gets assigned to `$block->content`, the pane is rendered with `"my sample text"` as the content.

```
function MYMODULE_messagelimits_content_type_render($subtype, $conf, $args, $context) {
  if (!empty($conf)) {
    $block = new stdClass();
    $block->title = check_plain("");
    // Show message limits.
    $block->content = t("my sample content")
    return $block;
  }
}

```

By contrast, this function:

```
function MYMODULE_messagelimits_content_type_render($subtype, $conf, $args, $context) {
  if (!empty($conf)) {
    $block = new stdClass();
    $block->title = check_plain("");
    // Show message limits
    $block->content = MYMODULE_show_message_limits();
    return $block;
  }
}

```

Assigns the return value of `MYMODULE_show_message_limits()` to `$block->content`, rendering the pane with that function's return value. To understand why that doesn't work as expected, we must ask, what does `MYMODULE_show_message_limits()` return?

```
if ($sent_total > 1) {
  print '<div class="messagesng">';
  print t('You have already started conversations with 2 people this week.') . '</div>';
}
else if ($sent_total == 1) {
  print '<div class="messagesok">' . t('You can start a conversation with 1 more new person this week.') . '</div>';
}
else {
  print '<div class="messagesok">' . t('You can start conversations with 2 new people this week.') . '</div>';
}

```

The function above, lacks a return statement, so in pratice, it returns `NULL`. Hence the pane output is empty, not even an empty string.

`MYMODULE_show_message_limits()` does, on the other hand, execute several `print` calls. Since that happens at a stage when content is still being assembled, remember, this is not a template, the prints are thrown right out onto the page, in the same way it would have if it was executed in any hook invocation for example.

The solution then, is to do:

```
$output = '';
if ($sent_total > 1) {
  $output .= '<div class="messagesng">';
  $output .= t('You have already started conversations with 2 people this week.') . '</div>';
}
else if ($sent_total == 1) {
  $output .= '<div class="messagesok">' . t('You can start a conversation with 1 more new person this week.') . '</div>';
}
else {
  $output .= '<div class="messagesok">' . t('You can start conversations with 2 new people this week.') . '</div>';
}
return $output;

```

---
Tags: panels, chaos-tool-suite
---


title: Should my code use the Drupal class?

text:
# Question
Title: Should my code use the Drupal class?
When reading the documentation for the Drupal class, I notice the following sentence:

> This class exists only to support legacy code that cannot be dependency injected. If your code needs it, consider refactoring it to be object oriented, if possible. When this is not possible, for instance in the case of hook implementations, and your code is more than a few non-reusable lines, it is recommended to instantiate an object implementing the actual logic.

The example code that uses a service in a hook implementation, is the following one.

```
 // The preferred way: dependency injected code.
  function hook_do_stuff() {
    // Or, even better, rely on the service container to avoid hard coding a
    // specific interface implementation, so that the actual logic can be
    // swapped. This might not always make sense, but in general it is a good
    // practice.
    Drupal::service('stuff.doing')->doStuff();
  }

  interface StuffDoingInterface {
    public function doStuff();
  }

  class StuffDoingClass implements StuffDoingInterface {
    protected $lockBackend;

    public function __construct(LockBackendInterface $lockBackend) {
      $this->lockBackend = $lockBackend;
    }

    public function doStuff() {
      $lock = $this->lockBackend->acquire('stuff_lock');
      // ...
    }
  }

```

The code is still using the `Drupal` class.

Should my code use the Drupal class? Are there any methods of that class I should avoid using in Drupal 8 code written from scratch?

# Answer
By the definition of that class, anything that is not an object with injected dependencies is legacy code. That's a rather bold statement. ;)

In hooks, it is usually fine to use static methods on the Drupal class. Making that a service like suggested there is only useful if it's non-trivial code that someone might want to implement differently or/and you want to write unit tests for it.

If you're writing a service, plugins, form classes or controller classes, you should inject the dependencies.

So it's not really a question about which methods you should be using or not; it depends on where you would call it.
> 7 votes

---
Tags: hooks, 8
---


title: Disable the quick links menu on blocks

text:
# Question
Title: Disable the quick links menu on blocks
I've been searching all morning and cannot find the solution I need. I am sure I am overlooking something.

I want to disable the quick links menu on each block on my drupal 7.23 site when I'm logged in as an Administrator. I don't use them, and they are blocking the links on some small blocks.

How do I turn these off?

Thanks, Brian

# Answer
They're provided by the core Contextual Links module. If you don't don't need them at all disabling that would be the easiest thing to do.

There's also the Hide Contextual Links module if you want finer-grained control.
> 2 votes

---
Tags: routes, blocks, users
---


title: Node access based on condition

text:
# Question
Title: Node access based on condition
I'm adding an event list to a website and I want to limit what anonymous users see based on a field value, a checkbox "Private event". If the checkbox is marked then only a subset of the fields for the given event are shown. Furthermore, after a year of the event I want all fields to become visible to anonymous users. I took a look at the Access Control module but couldn't find a way to have this conditional type of access to fields. Is there another module that I could use?

# Answer
> 1 votes
I would do like this:

1. Define a new 'Restricted' View mode. Either manually with hook\_entity\_info\_alter or with Display Suite.
2. Create a new `Page` in Page manager, using the by default available `Node view`.
3. Create two separate `variants` in the page.
    1. The first one will use a selection rule on ´Role: Anonymous´ and ´Field Private event: True´. In this `Variant`, display the node with the 'Restricted' view mode.
    2. The second variant will not need a selection rule, as it will be the fall through option. Here you show the node with the normal 'Full' view mode.

For making everything visible after a year , it sounds like either a hook\_cron with some code in it, or perhaps a combination of some Rules with a VBO, which would flip the private field off after a year. Sounds like that might be a separate question though.

---
Tags: users
---


# Question
Title: Is there a maximum amount of data that a Drupal database can safely store?
Is there a maximum amount of data that a Drupal, let's say MySQL, database can safely store? If it gets too big will problems start to occur?

# Answer
> 4 votes
The short answer is no. There is not reasonable way you can store "too much data".

If you read the Limitations entry on wikipedia about MySQL, you'll see that "maximum amount of data" doesn't come into the picture.

More specifically, MySQLs documentation says

> The effective maximum table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits.

Depending on what you do with the data, however, you can get performance problems if you store a lot of data, but that's not a Drupal specific problem.

---
Tags: database
---


# Question
Title: Why doesn't a certain block appear on "view" pages of my site?
After much searching online, I can't figure out why my "search" block is not showing up on every single page of my website. I went to the configure screen for the block and ticked the "All pages except those listed" radio button and didn't list any pages in the field below. So that should make the block appear on every page of my site, correct? That's not the case, however; there are a handful of pages, most of which are "views" (i.e., the page shows a series of tabs -- View, Edit, etc.) where the block simply doesn't show up. Am I doing something wrong?

# Answer
I think you have got issue with the rendering of that particular region into the `page.tpl.php`, where this block doesn't show.

Follow this steps to identify the issue --

* Find the machine name for the region where you are putting your block from the THEME.info file.
* Open your all `page*.tpl.php` file in the theme one by one. May be your theme contain different `page.tpl.php` for different kind of content display. If it not done by you then this step can be hectic as sometimes we declare the custom `page.tpl.php` structure in template.php too. But initially you can check all the TPL files starting with `page`.
* Check for the rendering of the content by searching the machine name which you have got in `.info` file for the region where you are placing the block. I think somewhere it's not rendered.
* Render the region into the TPL file where it is not. Clear the cache & check you display.
> 1 votes

---
Tags: views, blocks, search
---


# Question
Title: custom search in drupal for custom content type page
I am trying to implement following functionality in drupal:

* From the admin interface add, edit, list multiple stores for a company. The store record would be: Store name, address, image and zip code. This will be like how its done in simple lists - a list of stores shows up with edit and delete links and a link to add a new store, thats all.
* Provide a search box in the homepage (separate from the standard site search) which will allow users to enter a zip code and view the image, title and address of stores in that zip code ( No need for proximity search or anything)

What I have done so far:

For adding store information: created a new content type called 'Store Locator'' and added custom fields for required data. I unchecked promote to front page, so the added records do not show up in the homepage. This works pretty much how I want so that is fine.

The main challenge is to give a search facility for the stores. I created a view called store locator with rule set to show only 'Store Locator' content types. Added 'Table' as the format for display, and added the fields I want to see in the table. This view was created as a 'Page'

Now when I got to the view's URL, I can see a list of stores in the defined table format. My problem is that I need to add a search box in the front page where the user can enter a zip code and it will show this same view page, but with only matching records. Basically the custom search result page should be in the same table format and not like how the results gets displayed when a standard site search is done. I am at a loss on how to add a new search box in the home page, and how to link it to the view page with filtered results..

I am not looking for a complete answer to this problem, just some pointers on what area I should be looking at..I am pretty new to drupal and its pretty daunting to figure out which way I should explore more. I installed/uninstalled a lot of modules to see if they can do it, but they did not really help. Any pointers on which direction to explore would be highly appreciated!

# Answer
As far as I understand you made 80% of the way. I think you can do the following:

1. Add contextual filter to your view so you will be able to filter to results according to the zip code
2. Use your custom module (if you don't have one, this will be a good time to create one) to define a custom block (use the following hooks - hook\_block\_info and hook\_block\_view)
3. Create a custom form that will contain the search box and the submit button
4. Make a custom submit handler that takes the field value (the zip code inserted by the user) and loads the views page with the inserted zip code (the contextual filter we defined in step 1 will allow it)
5. Place the form in your custom block and place that sweet block in your homepage

**References:** Create custom form

**Edit:** By the way, the first comment is exactly what you need.

```
   function my_module_my_form_submit($form, &$form_state) {
    $first_name = $form_state['values']['first'];
    $last_name = $form_state['values']['last'];
    drupal_goto("/my_view/".$first_name."/".$last_name);
}

```

Hope that helps.. Rotem
> 3 votes

---
Tags: views, 7, search
---


# Question
Title: synchronise development website with live website
I'm developing a business website with Drupal 7 that is currently running on a server at my home so that I can just upload everything to my VPS when it is all ready. I'm only a solo developer so I don't have the resources to have a production/staging site and different stages etc., but I do anticipate that there will be a time when this might happen and there will definitely be times when I need to do a major update on the website. So is there a way I can make changes to content, themes and modules on my server at home, and then once I'm happy 'synchronize' the changes with the actual website so that I don't have to keep putting the site in maintenance mode for long periods of time.

I can't just simply re-upload the site everytime though because it is an e-commerce site so hopefully orders will be flowing and there would be new user accounts since I pulled the database so that I could work on the website etc.

Hope that makes sense

# Answer
> 1 votes
This is a very long topic to cover fully so I will just push you to the right direction to get things rolling and save you from lot of trouble.

You should **never** sync your local db to production db after you have first installed the site to production environment. The sync process of db is always one way: **production -\> staging -\> local environment**. Also when syncing the db from production you should always **sanitize** the sensitive data (user emails and passwords) for example with Drush sql-sync --sanitize option (yes you can have Drush for Windows too). To able to use this kind of workflow you need to have the configuration of modules, views etc. in code not in db. In Drupal 7 you can use modules like features to achieve this. In Drupal 8 most of this will be covered with cores built-in configuration management. Of course on top of everything you need to use version control system to not go nuts when developing the site. Services like Bitbucket, GitHub and GitLab give you the needed tools and ge you going with VCS in no time. With version control you can compare different versions of code, fall back easily to previous versions in your code and easily take more collaborators in the mix in the future. Doing any size of development without version control system is just plain stupid.

If you can't afford to have a staging environment on a VPS you should use your local environment wisely. Having your local environment as close as possible to the production environment is a wise thing to do in any circumstance. Use a virtualization product like Virtualbox and install the exact same setup on your local computer than you have on your production. When managing several production environments tools like Vagrant, Chef and Puppet can help you to keep configurations in sync and make your life easier :)

Things you should also remember is to have regular automated backups of your production data, know how to fall back to previous versions of code, configuration and db if something fails and to treat production environment always as a production environment. Remembering all of this makes your life a lot easier :)

---
Tags: 7
---


# Question
Title: I want to use this font family: PTSansRegular
I want to use this font family: PTSansRegular for my website.

Do I have to instal the module: @font-your-face ?

or is there another easier way to insal it for my site?

(I found it here http://www.afontz.com/font/paratype/pt-sans/regular/) (i'm using boilerplate subtheme)

thanks alot!

# Answer
> 2 votes
You have two options, doing it using a module such as @font-your-face or just simply doing it without a module.

* Download the font from the site you specified above.
* Open the CSS from the folder and check the different styles of fonts.
* Copy the font folder to the CSS folder in your theme's directory.
* Open .info file of your Drupal theme and add the stylesheet link from the font folder.
* Use the font-family of the currenlyt downloaded font in your stylesheet.
* Clear your cache.

---
Tags: theming
---


# Question
Title: Can I use the CTools modal functionality under HTTPS adn Display Suite?
The client for a new project wants their content to display in a modal overlay. From my research so far, it seems using ctools is the way to go.

My question is, some of this content will be product displays (using Drupal Commerce). Will there be a conflict with the AJAX functionality while the pages are HTTPS? I'm also using Display Suite to lay out the content. Is anyone familiar with any issues that may arise while using ctools' modal functionality with Display Suite?

# Answer
HTTPS should just work, or I would say there's a bug in ctools.

I haven't used DS much, so can't really comment, but DS handles View modes, and I would expect all ctools modules to deal nicely with those.
> 1 votes

---
Tags: 7, chaos-tool-suite, display-suite, javascript, ssl
---


# Question
Title: Restoring accidentally deleted content type
I am an absolute Drupal newbie, so please forgive my ignorance.

I have got an old Drupal site to manage (Drupal version 6.22).

While playing with the site I defined a new content type called **My page** and based on **page**.

After playing with it a bit I deleted it, from then on all my pages lost their content type and became uneditable.

After a lot of googling I realized that because **My page** was based on **page**, after deleting it I lost page type too. Seems a very strange logic to me, but not going to argue.

How can I restore the "page" content type? I tried to add it again, it was added OK, still all old pages remained typeless and uneditable.

The last site backup is from a couple of month ago and is irrelevant, as a lot of user content was added since.

I have an access as admin to the site's Drupal system, however I do not have a remote access to the server. Should I request it? Where should I go and what should I change?

# Answer
If a content type has been deleted, possibly all content of that type have lost their type setting, and so even if the content type is recreated, they might not be recognized as belonging to that type.

This should go without saying, but clearly that's not the case. **Take a backup**, before you happen to make things even worse.

You'll need to manually update the `type` column of the `node` table to the machine name of the content type.
> 2 votes

---
Tags: 6, nodes
---


title: Wildcard link for user menu

text:
# Question
Title: Wildcard link for user menu
I have a dropping menu links for the user menu:

My account

* Profile edit
* My posts (track)
* Exit

Here's an example of my code:

```
  <ul id="userNavigation">
                <li><?php echo l(t("Profile edit"), "user/%/edit"); ?></li>
                <li><?php echo l(t("My posts"), "user/%/track"); ?></li>
                <li class="exit"><?php echo l(t("Exit"), "user/logout"); ?></li>
            </ul>

```

I've tried with wildcard %. With a Views module was very easy, but in this case (without views) it's not working. Is any other way so when user clicks on "My posts" will link to `user/user_id/track` or profile edit that will lead to `user/user_id/edit`?

# Answer
> 1 votes
You cannot use menu wildcards like that. You need to use the following code.

```
  <ul id="userNavigation">
    <li><?php echo l(t("Profile edit"), 'user/' . $GLOBALS['user']->uid . '/edit'); ?></li>
    <li><?php echo l(t("My posts"), 'user/' . $GLOBALS['user']->uid . '/track'); ?></li>
    <li class="exit"><?php echo l(t("Exit"), "user/logout"); ?></li>
  </ul>

```

The global `$user` is the user object for the currently logged-in user. Be careful: It is not a fully-loaded user object. If you need that, you should use the value returned from user\_uid\_optional\_load().

---
Tags: routes, users
---


# Question
Title: I can't log in after removing the user login left bar
I removed the user login block on the left of my default drupal instalation (7.21) and now i can't login.

When i try: mysite/drupal/?q=admin It gives me "access denid".

I Don't feel like reinstalling my drupal just for this there has to be a simple way to fix this?

# Answer
Simply go to `http://yoursite/user` or if you don't have clean url enabled `http://yoursite/?q=user`
> 4 votes

---
Tags: blocks, users
---


# Question
Title: how to create a sub menu accordian using api
I'm trying to develop an accordian sub menu, See image below. I've tried using the menu block module but i've found it a litte tricky to format. I'm wondering how can get an array of menu items base on a parent. So, say the submenu below were all children of /aboutus/ how would the php look? I'm using drupal 7

# Answer
> 2 votes
Try the jQuery Menu module. It was somewhat easy to style -- all I had to add was CSS.

> Jquery menu uses simple, cross browser compatible jquery to transform your multilevel menus into click and expand menus. Yes this module is similar to dhtml menus and active menus, but it is different in a couple of key ways.
>
> 1. Unlike dhtml menus (which requires you to click twice on a link to actually follow an expanded link) Jquery menus separates the link from the expanding mechanism (there is a small plus symbol that you click instead to expand the menu). This makes for a more natural navigation.
> 2. Unlike active menus, which makes ajax calls to fill in the lower level menus when you click the plus symbol, Jquery menu creates the menu in full on the initial page load. I personally have used active menus for several months and have found that those ajax calls sometimes fail, and are not as stable as jquery.
> 3. Unlike Active menus which transforms all menus into active menus once the module is turned on, Jquery menu only creates a jquery block for the menus that you specify. To chose which menus you want to be active you just have to visit the admin page at 'admin/settings/jquerymenu' .
> 4. Jquery menu is easily themable. Since the jquery menu blocks only use a small number of styles, and don’t use the default list styles, overriding it with your own css is easy. Also the important display elements are contained in themable functions so you can tinker with the layout if you like.

# Answer
> 2 votes
More reasonable is to add few line of js (e.g from my project):

```
      var allexpands = $('.pane-menu-menu-departments .menu li.expanded ul.menu').hide();
  $('.pane-menu-menu-departments .menu li.expanded > a').click(function() {
    $this = $(this);
    $target =  $this.parent().find('ul');
    if(!$target.hasClass('active')){
      allexpands.removeClass('active').slideUp();
      $target.addClass('active').slideDown();
    }
    return false;
  });

```

---
Tags: routes
---


# Question
Title: Plugin to make selecting a page on a menu easier
I'm in the process of building a drupal site and wonder if there is an easier way to create menu items.

When I create a menu item in a menu I need to manually enter the url of the link for the item. Is there a plugin available that will allow me to select from a list all the content created in the system so I can simply select the page I wish it to link to?

Obviously it would also need to allow me to type in a link for custom modules etc?

Does this exist as a plugin?

# Answer
> 1 votes
Content menu module improves Drupal's default menu management interface for tighter intergation of content authoring and menu management, so content can be created and edit right from the menu interface (e.g. creating content for a menu item that has been just created)

You can create a new menu item as

> * URL – With the traditional menu item form
> * Dummy – As a dummy menu item (with simple dummy link target)
> * New NODETYPE – directly create a new content for the new item
> * Existing content – selecting an existing content via a nice filterable view (if views is enabled)
> * Menu position rule (if the Menu Position module is enabled)

---
Tags: 7, routes
---


# Question
Title: 3-column fixed width Zen-based layout + SASS; giving exact width to columns
I'm using Zen theme with SASS (+Compass), and I have a site with fixed width layout. This means I include `fixed-width.scss` in my custom Zen subtheme's `.info` file.

I would like 3 columns - 2 for the sidebars, 1 for the main content. By default, I got these (I don't know why, because `$zen-column-count` is set to `5`...).

OK, the problem is that when generating the CSS-files, **the width of the columns get automatically calculated based on different SASS mixins**. I don't want to mess up the automatic calculation of margins etc., I just want to set the exact parameters.

The main outer grid width should be 920px wide (`$zen-grid-width: 920px;`).

Now I have these automatically calculated parameters:

**sidebars: `184px`, `184px`
main content: `552px`**

BUT I want it like this:

**sidebars: `220px`, `220px`
main content: `480px`**

Here is my `fixed-width.scss`: http://vpaste.net/n4ve0

**How should the exact parameters be set for the sidebar columns when using SASS in Zen?**

# Answer
This is really more a math question than anything, but here goes. Given that you're using a fixed width column layout, we have to start and find how many columns we need to achieve the proportions you posted. The least number of columns possible to achieve 220px | 480px | 220px is 46 with each column equating to 20px (920px / 46 = 20px). With 46 columns, the sidebars are 11 columns each and the main content is 24 columns.

The rest is just plugging in the numbers into the zen grids functions. See http://vpaste.net/VDwL1 for my example.

After defining the number of columns with $zen-column-count, you need to plug in the numbers so that each sidebar spans the correct number of columns while starting at the correct column with zen-grid-item($column-span, $column-position). The Zen starter sub-theme comes with three layouts to account for 1 (left) sidebar + main content, main content + 1 (right) sidebar, and 2 sidebars + main content. Here is how it looks with our new, 46 column system:

```
/**
 * The layout when there is only one sidebar, the left one.
 */
.sidebar-first {
  /* Span 35 columns, starting in 12th column from left. */
  #content {
    @include zen-grid-item(35, 12);
  }

  /* Span 11 columns, starting in 1st column from left. */
  .region-sidebar-first {
    @include zen-grid-item(11, 1);
  }
}

/**
 * The layout when there is only one sidebar, the right one.
 */
.sidebar-second {
  /* Span 35 columns, starting in 1st column from left. */
  #content {
    @include zen-grid-item(35, 1);
  }

  /* Span 11 columns, starting in 36th column from left. */
  .region-sidebar-second {
    @include zen-grid-item(11, 36);
  }
}

/**
 * The layout when there are two sidebars.
 */
.two-sidebars {
  /* Span 24 columns, starting in 12th column from left. */
  #content {
    @include zen-grid-item(24, 12);
  }

  /* Span 11 columns, starting in 1st column from left. */
  .region-sidebar-first {
    @include zen-grid-item(11, 1);
  }

  /* Span 11 columns, starting in 36th column from left. */
  .region-sidebar-second {
    @include zen-grid-item(11, 36);
  }
}

```
> 3 votes

---
Tags: 7, theming
---


# Question
Title: Solving performance issue DrupalDatabaseCache::clear
I am facing a performance issue when I open some of the pages. It is taking too long time. After checking the queries and the time for each query I found that these two functions are taking a long time:

```
DrupalDatabaseCache::clear
DrupalDatabaseCache::set

```

What to do?

# Answer
> 2 votes
If you are facing performance problems using database as cache backend you should consider moving the caches to a better performing cache backend. Suitable backends for general caching are for example Memcached and Redis. For both of these you can find proper contrib modules (Redis & Memcache) and a lot of help in using them. If you want to have high performance page cache you could use Varnish for that. Also setting up APC to improve general PHP performance is a wise thing to do. Some basic information on using APC can be found from here.

Whatever caching methods you choose to use you should remember that form-cache must use non-volatile storage. This means that you should simply remember to keep form-cache in database. This can be achieved by inserting the following to your sites settings.php file.

```
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

```

---
Tags: performance
---


# Question
Title: How to attach files using mimemail (Getting 0kb file)
(This isn't the same as the other issue I raised. I thought I'd got the attachment working but I haven't)

**Initial Problem**

I'm trying to attach a file to an email. It's part of job application so a person goes to a node, presses apply and it sends an email to the creator of the node. I want to attach a CV & cover letter to it.

Here are my submit and hook\_mail functions.

```
function tellafriend_form_submit($form, &$form_state) { ...

        $message = drupal_mail('tellafriend', 'notify', $email, language_default()); ...
}

function tellafriend_mail($key, &$message, $params) {

        global $base_url;

        $attachment = array(
          'filecontent' => file_get_contents('http://localhost/public/counciltax.txt'),
          'filename' => 'counciltax.txt',
          'filemime' => 'text/plain',
          'list' => TRUE,
          );
        $message['subject'] = t('Your friend thought you might like this site');
        $message['body'][] = t("Hello,\nYour friend thought you might like this site.  Please click the link below to visit.\n\n!link", array('!link' => $base_url));
        $message['params']['attachments'][] = $attachment;
}

```

Sometimes this will send an attachment. Othertimes it won't. It sent once, I repeated the same process and it didn't work. Mostly it doesn't work.

These two tests were run 10 seconds apart and I didn't change any code.

Here's the successful email.

And here's the unsuccessful email.

Am I doing this wrong, or is this just broken? How would I debug this?

(This was the example I used as reference http://rapiddg.com/blog-post/drupal-7-html-e-mail-pdf-attachments)

**EDIT ----- 05/08/2013**

I tried using frazras's technique (cheers!), of putting the attachment in the submit function however it still doesn't work every time. (Code not shown because it's identical to the section he posted.)

My public folder looks like this:

This is the information I'm entering:

```
'uri' => 'public://hashtags.txt',
'filename' => 'README.txt',
'filemime' => 'text/plain',

```

The results of sending 12 or so in a row. It mostly works now, but still randomly fails

I'm changing nothing inbetween the tries, it just doesn't work sometimes. Any other ideas or info about how I could debug this?

# Answer
> 0 votes
Solved! Not a clever solution, but changing to the dev version of Mimemail cleared this up.

That's uninstalling the alpha and then installing "7.x-1.x-dev".

Never found out why it was happening.

# Answer
> 0 votes
I usually do mine I little different from you, I add the attachment in hook\_submit then pass it as a param to hook\_mail, but even then some of our variables differ. here is an example from a working solution I have implemented, but changing to your text. I also added in the headers, maybe they arent necessary because I use it when dealing with jpeg file types.

```
function tellafriend_form_submit($form, &$form_state) { ...
    $attachment = array(
      'uri' => $filepath,
      'filename' => 'counciltax.txt',
      'filemime' => 'text/plain',
    );
    // Add attachments
    $params = array(
      'attachments' => $attachment,
      'file' => file_create_url($attachment['uri']),
    );

    drupal_mail('tellafriend', 'notify', $email, language_default()), $params);
}

function tellafriend_mail($key, &$message, $params) {
  $message['headers']['MIME-Version'] = '1.0';
  $message['headers']['Content-Type'] = 'multipart/mixed;';
  $message['subject'] = t('Your friend thought you might like this site');
  $message['body'][] =t("Hello,\nYour friend thought you might like this site.  Please click the link below to visit.\n\n!link", array('!link' => $base_url));
  $message['params']['attachments'][] = $params['attachments'];
}

```

---
Tags: 7, emails
---


title: Wrapping a block in jQuery Accordion

text:
# Question
Title: Wrapping a block in jQuery Accordion
**Problem**

I'm creating a search page for a module. On that page I have an exposed views filter block and I'd like to put it into a jQuery accordion.

*In case it's relelvant:* In the same sidebar below the filter block I have a series of facets which use the Facet API Collapsible Module.

At the moment I've put the script "facetaccordians.js" in mytheme/js/ and added it using the .info file.

**What I've tried so far**

Here is the .js file.

```
(function ($) {
        $(function() {
               $(document).ready(function(){
                    $(".views-exposed-form").accordion();
                });
            });
})(jQuery);

```

This selects the following horrible bit of HTML:

```
    <div class="views-exposed-form ui-accordion ui-widget ui-helper-reset ui-accordion-icons" role="tablist">
        <div class="views-exposed-widgets clearfix ui-accordion-header ui-helper-reset ui-state-default ui-state-active ui-corner-top" role="tab" aria-expanded="true" aria-selected="true" tabindex="0">
    </div>

```

But the accordion doesn't work correctly. It doesn't open and close.

I tried adding in `<h3>Test</h3>` into the tpl.php for views exposed forms to give this:

```
    <div class="views-exposed-form ui-accordion ui-widget ui-helper-reset ui-accordion-icons" role="tablist">
        <h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-state-active ui-corner-top" role="tab" aria-expanded="true" aria-selected="true" tabindex="0">
        <div class="views-exposed-widgets clearfix ui-accordion-header ui-helper-reset ui-state-default ui-state-active ui-corner-top" role="tab" aria-expanded="true" aria-selected="true" tabindex="0">
    </div>

```

However it still doesn't work. And that will cause me a bunch of other problems. What's the correct way to put this block into an accordian? OR what am I doing wrong? Do I need to select a div above the current ones, do I need different HTML?

(I know about the Accordian Blocks module, but it doesn't work either. The open close also doesn't work)

# Answer
> 0 votes
**Easy Solution 1**

As it turns out the accordion blocks does work. However if you're just using it for a single block it won't automatically because the default jQuery accordion only works with multiple objects.

Install Accordion blocks and open the accordion\_init.js file. It'll look like this

```
(function($) {
  Drupal.behaviors.accordion_blocks = {
      attach: function() {
        $('.accordion_blocks_container').accordion({header: "h2", autoHeight: false, });
      }
  };
})(jQuery);

```

You need to add the property, `collapsible: true`, as shown below. I've also removed the animation and made it start closed by default.

```
(function($) {
  Drupal.behaviors.accordion_blocks = {
      attach: function() {
        $('.accordion_blocks_container').accordion({header: "h2", autoHeight: false, collapsible: true, active: false, animated: false});
      }
  };
})(jQuery);

```

**Possible Other Avenue**

I also managed to get jQuery accordions working, it has to have a certain HTML structure (see the UI documentation) which is difficult to implement around blocks thus why I took the easy route.

But if you fancy trying it the following code will enable jQuery accordions on your website for your theme at a basic level. This code goes into the template file.

```
function themename_preprocess_page (&$vars) {
    drupal_add_library('system', 'ui.accordion');
    drupal_add_js('jQuery(document).ready(function(){jQuery("#accordion").accordion({ collapsible: true, active: false, header: "h3", animated: false});});', 'inline');
}

```

---
Tags: 7, blocks, javascript, navigation
---


title: Custom module permission function

text:
# Question
Title: Custom module permission function
I am creating a module whose purpose is to display some data. I have a input form that saves data to database; that data is then displayed to the user.

I have created a page where that data can be viewed, edited, and deleted.

My problem is that every user can see this. The best thing I have done is using the global `$user` variable, and verify that the currently logged-in user is the user who created the data being viewed. Every user could see the Edit and Delete tabs, even when no data was created.

I am trying to figure out how I use the permissions in the same way they are used with the content types, where users can edit any node of a content type, or can edit their own nodes of that content type.

How could I resolve this issue?

# Answer
If you want to do what done for the Article content type (and any content type), then the access callback for the *Edit* and the *Delete* tab should be similar to the following one. I assume the access callback is declared as follow:

```
// mymodule/data/%mymodule_data/edit
'access callback' => 'mymodule_data_access',
'access arguments' => array('edit', 1),

// mymodule/data/%mymodule_data/delete
'access callback' => 'mymodule_data_access',
'access arguments' => array('delete', 1),

```

If that is the case, then I would use the following code.

```
function mymodule_data_access($op, $data) {
  global $user;

  // The data saved in the database need to contain the user ID of the
  // user who created the data, which in this case is $data->uid.
  if ($user->uid == $data->uid) {
    // The currently logged-in user has created the data.
    return user_access("$op own data", $user);
  }

  return user_access("$op any data", $user);
}

```

This code requires also the following function to be defined, for paths like mymodule/data/%mymodule\_data/edit to be used.

```
function mymodule_data_load($data_id) {
  // Load the data with the ID passed as argument from the database.
  // Return it, or FALSE when no data is found matching that ID.
}

```

The module then needs to define its own permissions.

```
function mymodule_permission() {
  return array(
    'edit own data' => array(
      'title' => t('Edit own data'),
    ),
    'edit any data' => array(
      'title' => t('Edit any data'),
    ),
    'delete own data' => array(
      'title' => t('Delete own data'),
    ),
    'delete any data' => array(
      'title' => t('Delete any data'),
    ),
  );
}

```

As for mymodule/data/%mymodule\_data/view, I assume you want any user to see the data created by other users; in this case, I would use the following access callback, in `hook_menu()`.

```
'access callback' => 'user_access',
'access arguments' => array('access content'),

```

If you want to use your own permission, replace `'access content'` with your own permission, which should then be added to the permissions exposed by hook\_permission().

> Every user could see the Edit and Delete tabs, even when no data was created.

The page to create data should be different from the page showing the data to create. Taking as example the *Article* content type, the page to create a node of that content type is shown at node/add/article, while the page to see a node is at node/%node/view.

I assumed that every user can create the data more than once; if every user can create the data just once, then the code can be simplified. The code I shown is the most generic possible.
> 0 votes

# Answer
You should implement hook\_permission.
Then you will be able to add custom permissions to view, edit and delete for your custom form.

Nice tip I'm using myself with Drupal is to open the code of one of Drupal's core/contrib modules that implements the same thing you need and learn how it was implemented there.
> 1 votes

---
Tags: users
---


# Question
Title: Allow anonymous users to load site contact form without granting admin privileges
I'm including the site contact form on a page with these 2 lines.

```
  module_load_include('inc', 'contact', 'contact.pages');
  print render(drupal_get_form('contact_site_form'));

```

The page loads as expected when a user is logged in, but for an anonymous user the page returns a 403.

If I give the "Administer contact forms and contact form settings" permission to anonymous users, then the page will load for anonymous users. I gave the "Use the site-wide contact form" permissions to anonymous users, but they still get an access denied error.

Is there a way to allow the form to load for anonymous uses without giving them admin privileges?

# Answer
The Access Denied error is returned because the following code executed by code\_site\_form(). (Notice the call to drupal\_access\_denied().)

```
  $limit = variable_get('contact_threshold_limit', 5);
  $window = variable_get('contact_threshold_window', 3600);
  if (!flood_is_allowed('contact', $limit, $window) && !user_access('administer contact forms')) {
    drupal_set_message(t("You cannot send more than %limit messages in @interval. Try again later.", array('%limit' => $limit, '@interval' => format_interval($window))), 'error');
    drupal_access_denied();
    drupal_exit();
  }

```

Users with the "administer contact forms" permission don't get that error, since the limit for the sent messages doesn't apply to them.

Check those Drupal variables have not been set to different values that lower the number of allowed messages. The default is 5 messages in 1 hour.

As side note, `render(drupal_get_form('contact_site_form'))` would cause a "call-time pass-by-reference" warning in PHP 5.3, since render() is expecting a variable passed by reference, but drupal\_get\_form() doesn't return a reference. PHP 5.4 will raise a fatal error for that same code. The code calling `render()` should always use a variable.

```
module_load_include('inc', 'contact', 'contact.pages');
$form = drupal_get_form('contact_site_form');
print render($form);

```
> 1 votes

# Answer
The permission you should be looking at is **"Use the site-wide contact form"**
> 0 votes

---
Tags: users, emails
---


# Question
Title: How to get the image from the url and store in the custom path?
```
if(empty($nodevalue->field_beachesimages)){
    $imageurl=array(explode(",",$nodevalue->field_beach_migrateurlhidden[$nodevalue->language]['0']['value']));
    foreach ($imageurl as $imagechange) {
        $countimagurl=count($imagechange);
        if($countimagurl>10)
            $imgdata=9;
        else
            $imgdata=$countimagurl;
        for($i=0;$i<$imgdata;$i++){
           $image =$imagechange[$i];
           $file = system_retrieve_file($image,'public://beachesmigration/', TRUE, $replace = FILE_EXISTS_REPLACE);
           echo "<pre>";print_r($file);echo "</pre>"; exit;
           file_save($file);
           file_usage_add($file, 'iks_beaches', 'beaches', $file->fid);
        }
    }
}

```

# Answer
> 2 votes
Hope this will help you.

In Drupal 7 , system\_retrieve\_file function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to the file\_managed table if you want it to be managed.

* You need to create a folder **beachesmigration** inside **sites\default\files**.
* By using **system\_retrieve\_file** it will be store your images inside **beachesmigration** folder with the filename you no need to specify the filename manually.

```

 $image = 'http://wordpress.ikitesurf.com/wp-content/uploads/2012/09/2032239599_fdce5e0ab0_z.jpg';
//I have used picture folder to store images using image field settings
 $file = system_retrieve_file($image, 'public://beachesmigration/', TRUE, $replace = FILE_EXISTS_REPLACE);

```

Source

# Answer
> 0 votes
Try this :

```
function savefile($filepath, $uid = 1) {
  global $base_url;
  if (filesize($filepath) == 0 ) {
    return array();
 }
  $file = (object) array(
    'uid' => $uid,
    'uri' => $filepath,
    'filemime' => file_get_mimetype($filepath),
    'status' => 1,
  );
  if(file_exists($filepath)) {
    $file = file_copy($file, 'public://');   //Change path here
    return $file;
  } else {
    return array();
  }
}

$file = savefile("http://wordpress.ikitesurf.com/wp-content/uploads/2012/09/2032239599_fdce5e0ab0_z.jpg");

```

---
Tags: 7, hooks, migrations
---


# Question
Title: Setting a header for checkmark in tableselect
I am interesting in adding text next to the checkmark in the table #header.

As you can see from the photo there isn't any text there.

My code for the table:

```
$header = array(
    'campground' => t('Campground'),
    'name' => t('Name'),
    'phone' => t('Phone Number'),
    'message' => t('Message'),
  );

$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#default_value' => $values,
    '#empty' => t('No campground to claim'),
  );

```

Is it possible to add a title next to the checkmark?

# Answer
> 1 votes
I dont see a direct option to do this. but you could add the required label as header and make it the first column next to the check box. and remove the border to make it look like the are together as a label for the check box.

# Answer
> 3 votes
I ended up needing to keep the label actually in the correct column, and so went a different route. I have jQuery available to me as well.

I added an #after\_build to my form that would insert some JavaScript:

```
$form['#after_build'][] = 'mymodule_config_form_after_build';

```

Then in that function, added:

```
function mymodule_config_form_after_build($form, &$form_state) {
$data = <<< EOT
  jQuery(document).ready(function(){
        var liveTable = jQuery("#edit-variables table").filter(function() {return !(jQuery(this).css('visibility') == 'hidden' || jQuery(this).css('display') == 'none');}); // Get the right table
        var cb = jQuery("th.select-all input[type='checkbox']", liveTable); // get the right checkbox
        if (cb.length == 1) { // attempt at being smart
            var th = jQuery("th.select-all", liveTable); // Need the table head next
            th.css('width', '15%'); // I found the auto width logic was messing up the table, so I put in this hack to cover my label width
            cb.attr('name', 'form-select-all');
            cb.attr('id', 'form-select-all');
            var label = jQuery("<label for='form-select-all' style='padding: 0px;'>Active Replacement?</label>");
            cb.before(label).detach().prependTo(label); // put the label in and move the checkbox before it

        }
    });

EOT;
drupal_add_js($data, 'inline');
return $form;

```

The first jQuery filtering is needed because Drupal seems to add a hidden table to help facilitate header handling (???). I was coming up with too many tables and check boxes.

---
Tags: 7, forms
---


title: Drupal 7 Taxonomy term display page

text:
# Question
Title: Drupal 7 Taxonomy term display page
I am trying to display my content in Alphabetical group for a specific content type.

What I did?

1. Added a vocabulary "Category"
2. Added a term(Myterm) inside this vocabulary.
3. Added a field in content type and put the relation with this vocabulary and the default option is the term name.

This is working fine. Now I want to show up the Myterm page the content alphabetical group. For your information I used Pathauto module to create the taxonomy term url. So my current url is domainname.com/MyTerm

This page showing the results which are belongs to MyTerm term. I want to just display the Alphabetical group and each group will contain the content whose title starting with this group. Please guys advice me how to implement this. If any contributed module is available, please advice. Thanks in advance.

e.g. Suppose my requirement is like below:

\[A\]
Amazing Video
A good tutorial
Award wining software
\[B\]
British Council
Be right back
\[C\]
Case discussion
Content privacy
....

# Answer
> 2 votes
I think what you would like to achieve is like a glossary.

You can by default create a glossary with views. How to do this is best explained or shown in this video.

If you want to show each of these on one page, i think you need to have some kind of a special field to group your results by. For this, try to the Views PHP module. Make a field where you grab the first letter of each term, and group by this (for example).

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


title: Enforce Minimum Length by adding spaces

text:
# Question
Title: Enforce Minimum Length by adding spaces
So currently I am using the maxlength module (https://drupal.org/project/maxlength) in order to enforce the fields maximum length and I have a view set up that is embedded to a php Rules action (Execute custom PHP code).

Basically if a field is smaller than the maxlength defined, I am looking for a way to output the value with spaces.

For example: Maxlength 5. Field Value: xxx. Output: "xxx " (without quotes)

I can't seem to find the right module/php code to do this.

I think I have 3 directions I can go with this.

1. I have it save the spaces to the field based on the maxlength specified when saving the field. I don't like this option much since it actually adds spaces to the value in the database.
2. I somehow edit the view to display the spaces based on the maxlength of the field.
3. I edit the Rules views\_embed\_view php output.

Any help would be extremely helpful. Thank you.

Edit: I am using Drupal 7 by the way.

# Answer
> 1 votes
In template file for your field you can use good old PHP sprintf:

```
$right = sprintf("[%10s]\n",    $s); // right-justification with spaces
$left  = sprintf("[%-10s]\n",   $s); // left-justification with spaces

$right === "    monkey";
$left  === "monkey    ";

```

In your case
`<?php print $output; ?>`

should turn into:

```
 <?php printf("[%10s]", $output); /* if you want spaces before string */?>

```

---
Tags: entities, rules, views
---


# Question
Title: How to show only values matching filter in a view?
I have created a view, in which I apply a filter on a taxonomy term field that can contain multiple values. This field is also displayed in the view. Is there any way to only display those values in the view that match the filter?

For example:

* Field of one node contains both terms A and B.
* Filter set to select all nodes containing term A.
* The view should only display A (not B) for this node.

If I uncheck the "Display all values in the same row" option, the view splits the entries, but I can't seem to get rid of the extra values. I have also tried enabling "distinct" values and the "reduce duplicates" options; neither option helps.

Am I missing something simple?

# Answer
It's most important for you now to get how Views works. Views are nothing more than (really good and elaborate) query builder. Each time you set a filter, what you are really doing is adding another condition to query's `WHERE` line. It does not, in any way, affect anything before `WHERE` \- especially not list of fields to obtain.

Now, you are not first one to need this. So there is Views Filter Field module, that simply allows you to display filter's value as a field. That way if you want nodes with A, don't show the terms attached to a node. Just show a filter's value of A, and you will get what you wanted: A, but not B even if node contains both A and B terms.
> 1 votes

---
Tags: views
---


# Question
Title: How to get the value from the url in the function argument?
When I pass **nid** value in the url like '/abc/**\[nid\]**', I want a function to receive that nid value

the code is as the following:

```
function ort_view_menu() {
          $items['ox_view'] = array(
            'title' => 'Viewed Details',
            'description' => 'g a report',
            'page callback' => 'abc',
            'type' => MENU_CALLBACK,
            'access callback' => TRUE,
           );
return $items;
}

function abc($nid) {
$rows = array();
$node = node_load($nid);
}

```

What changes do I need to make in hook\_menu() to catch the nid value in the page callback function

# Answer
What you are looking for is either:

* `arg()` function:

> Returns a component of the current Drupal path.
>
> When viewing a page at the path "admin/structure/types", for example, arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns "types".
* or Callback Arguments:

```
function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
      'page arguments' => array(1, 'foo'),
    );
    return $items;
  }

```

When path 'abc/def' is requested, the page callback function will get 'def' as the first argument and (always) 'foo' as the second argument.
> 1 votes

---
Tags: 7
---


# Question
Title: Webform : how to count and live display results
Update

webform\_get\_submission\_count isn't precise enough (we need to count into submissions)

but

```
<?php
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load($nid);
  if ($node->type == 'webform') {
    $count = db_result(db_query('SELECT count(*) FROM {webform_submissions} WHERE nid = %d', $nid));
    $atelier_1 = "sources" ;
    $sql = "SELECT count(*) FROM {webform_submitted_data} WHERE data LIKE \"".$atelier_1."\" ;";
    $count_atel_1 = db_result(db_query($sql));
  }
}
echo $sql;
echo $count_atel_1;
?>

This webform has been submitted <?php print $count ?> times.

```

looks ok

end update-------------------

We'd like to use a webform so that our students should register on some workshops.

The webform works great. Now we'd like to display live the number of students that are already register in on of the workshops so that the other should know if there remains some possibilities of registration (each workshop can only accept 20 students at the same time)

I'm trying with that that doesn't work ($atelier\_1 = "sources" ;) is the name of one workshop :

```
<?php
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load($nid);
  if ($node->type == 'webform') {
    $count = db_result(db_query('SELECT count(*) FROM {webform_submissions} WHERE nid = %d', $nid));
    $atelier_1 = "sources" ;
    $count_atel_1 = db_result(db_query('SELECT count(*) FROM {webform_submitted_data} WHERE data LIKE %d', $atelier_1');
  }
}

echo $count_atel_1;
?>

```

Any help or suggestion welcome

# Answer
> 1 votes
I looked through the Drupal document from drupalcontrib.org and i saw that there is webform\_get\_submission\_count function to get a count of the total number of submissions for a node. I think you can use that function instead by create a new one.

---
Tags: webforms, database
---


title: Webform submission as new node

text:
# Question
Title: Webform submission as new node
I have a webform, that the user can fill out. After the user clicks on the "submit" button, a new node should be created with the content the user typed in (text, images, ...). The form itself should be multi-step (first page = personal data, second page = content, etc.). I'm not sure if I can use the regular node creation, because I would need to

1. customize the form
2. the form should be multi-step

Is this possible?

# Answer
> 1 votes
Alternative to Webform + Bala's answer is Multistep Nodeform. Using it you can redesign node creation into multistep form and simply allow anonymous to add noeds of given content type.

> For each step you can define which fields should be included in this step. "Fields" includes core-fields like "Title", "Body" or "Authoring information" as well as fields defined by other modules (e.g. Date).

# Answer
> 0 votes
Webform Default Fields

> With this module you can easily create much of nodes with same webform fields.
>
> Because you can create more than one webform-enabled content types, you respectively can attach different default fields for each of them.

---
Tags: nodes, webforms
---


# Question
Title: retrieving values from a database in drupal 7
I am new to drupal. I am trying to create a function that will retrieve rows from a database and display the results.From the tutorials I have read, I am trying to implement a function I have created but no results are displayed. There's just a whitespace. Where might I be going wrong? Here is my code.

```
function print_users(){
$query = "SELECT first_name, middle_name, last_name FROM {registered_users}";
$header = array(
array('data' => t('Cell 1'), 'field' => 'first_name', 'sort' => 'ASC'),
array('data' => t('Cell 2'), 'field' => 'middle_name'),
array('data' => t('Cell 3'), 'field' => 'last_name'),
);
$q = db_query($query . tablesort_sql($header));
while ($r = db_fetch_array($q)) {
    $rows[] = $r;
}
print theme('table', $header, $rows);

```

}

and am calling it as follows via a menu link

```
 $items['view_users'] = array(
        'title' => "view",
        'description' => 'Viewing service',
        'page callback' => "print_users",
        'access callback' => TRUE,
        'weight' => '2',

```

);

# Answer
```
$select = db_select('registered_users', 'c')
->condition('c.fieldname', $id)  //try the condition if u have anything
->fields('c');

$result = $select->execute();
if($result->rowCount() == 0) return false;

$val = $result->fetch();

```

for sorting try asc or desc followed by the condition you can get the answer in google itself
> 1 votes

# Answer
The title mentions Drupal 7, but `db_fetch_array()` no longer exists in 7.x so you want to make sure what version you're actually using, and that you're not wasting your time with tutorials for previous versions.

Also, looking at the last line of your function:

```
 print theme('table', $header, $rows);

```

A Drupal function called from the menu does not `print` directly its HTML output, it **must return it as a string**, so that the caller combines it with the rest of the page.
> 0 votes

---
Tags: database
---


# Question
Title: Using node author information in a module (efficiency)
**Problem**

I'm building a module to let users apply to a job. The user goes to a job advert, presses apply and it sends their CV to the author of the job advert.

I have it working, but I'm worried that the way I grab the users email is inefficient and I was wondering if there was a better way to do it.

**Current Set-up**

I have a custom form with a submit function. I grab the email of the author of the current node using the following:

```
function jobapplication_form_submit($form, &$form_state) {
    if(arg(0) == 'node' && is_numeric(arg(1))){
            $node = node_load(arg(1));
            $user = user_load_multiple(array(),array('uid' => $node->uid));
        };
    $email = $user['1']->mail;

```

Is there a way to get the node author email without having to load the entire node? It seems really inefficient (at least to my inexperienced eyes).

# Answer
It is a standard issue of **efficiency** versus **convenience**. You can, of course, simply join `{node}` and `{users}` tables on `uid` field and do it in simple select, taking just that one field you really need. And indeed it will be faster. But you will need to rebuild that part of the code if some day one of these tables will get renamed or restructured. That's why people are using CMS in the first place - to stop worrying about low level and get the job done simple and easy. Computers are cheaper than people these days.

It is possible that you will save a second of CPU time and 30kB of RAM. So what? Do you really expect so high traffic that it'll be a problem? Databases cache their results in RAM too, so it might be actually faster, overall, to always read whole node. It means one node set to cache instead of dozen sets with different fields selected. Or might not. It depends on to many variables to know, so it seems usual to considered adjusting these variables better than complicating code.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: How can I conditionally reference an entity?
I would like to have an inline entity reference form that will optionally provide a write-in text form if the entity doesn't already exist. Here's the use case: I want to reference a faculty profile that is associated with a particular research project; but I want the option to also associate another person who does not have a profile on the site. In a corresponding view, if the associated person has a profile on the site, their name will link to their profile, otherwise it will simply appear without a link.

# Answer
Use Entity reference module to insert the references of the existing users to the content type.

> This project provides D7 versions of the 'node\_reference' and 'user\_reference' field types, that were part of the CCK package in D6, at functional parity with the D6 counterparts.

For the rest of the users, you could use a textfield.
> 0 votes

---
Tags: entities
---


# Question
Title: Disable default site and only use multisite
On my server I have drupal with a multisite sub-directory set up *(example.com/www.site1.com)*, and do not use default for anything. However, when i go to default *(example.com)*, I am sent to the default install.php *(example.com/install.php)*.

How could I best prevent this from happening, and for example, show a custom index.html page when a user lands on just *example.com*?

# Answer
You can't have an index.html in the root of your default directory, Drupal doesn't treat these directories like normal web folders. If you want example.com to go to a folder with a plain index.html file in it, you're going to need to edit your vhosts configuration. Right now, your vhost file probably looks something like this:

```
<VirtualHost *:80>
  ServerName example.com
  ServerAlias www.site1.com, www.site2.com, www.site3.com
  DocumentRoot /var/www/YOURDOCROOT
...etc

```

What this is doing is redirecting all sites that match either the server name or server alias and sending them to the DocumentRoot folder specified. When it gets there, Drupal tries to map the http requests to the appropriate folder but finding none for example.com, it sends it to the default directory instead.

If you want it to go to a single-page index.html, you are going to have to remove example.com from your vhost above and setup a new one, pointing example.com to that new folder, ex.

```
<VirtualHost *:80>
  ServerName example.com
  DocumentRoot /var/www/EXAMPLECOMDOCROOT
...etc

```

and place your index file in there.

If instead you want Drupal to send all traffic to one of your subsites, you can try either of these two methods:

1. Remove the default directory (assuming there is nothing in there you want) and symlink it to the site directory you want it to be using instead, ex. if you want it to be pointing to site1

ln -s www.site1.com default
2. You could also point your primary domain there as well using symlinks, ex:

ln -s www.site1.com example
> 3 votes

---
Tags: multi-sites
---


title: Send system message to user

text:
# Question
Title: Send system message to user
i would like to send system message to user such as site announcement, notification and etc.

i know the private message module, but it could not differentiate the message is send by the real system/admin or a normal user.

How should i do that??

# Answer
Try the notifications framework:

> This is a complete Subscriptions/Notifications Framework aiming at extendability and scalability. It allows any number of plug-ins defining new event types or subscription types or a different user interface.

Its a full featured module with a number of companion modules for sending messages via different channels depending on different events but what you're probably looking for is the 'Web messaging' submodule:

> Sending Method: Show messages on user's page
> 0 votes

---
Tags: privatemsg
---


# Question
Title: How to make a logo resize properly in a responsive theme
I am creating my first responsive website http://islamabadpools.com; I have used the Omega theme as a starter theme, and it works almost perfectly for the layout.

I used the absolute image module for adaptive images but it's not working for views banner slideshow.
I am also unable to make the logo responsive so I removed the logo from theme options.

I created a new article content, and added a logo as an image and given it a title logo; then, I created a view block with an article image field and filtered that with the title "logo" and in field properties; in the view, I selected adaptive as the format.
Now my logo is responsive/adaptive but it's getting very small on lower screen sizes.

I repeated this for the quick assistance block displaying in the right corner of the header.

I just want to know what the right way to make the logo responsive is.

# Answer
> 2 votes
Add the following css to your site:

```
.view-logo img {
  max-width: 100%;
  height: auto;
}

```

---
Tags: theming
---


# Question
Title: Can I make a search that shows all results, regardless the user's permissions?
We have a knowledge base with very strict user access permissions. We want users to be able to see all pages in search results, even the ones that they can't access. We want users to be able to see if the content they are interested exists and ask for permission.

# Answer
> 2 votes
You can build this in views. Build your view as you normally would, use an exposed search, then under advanced \> query settings \> check off "Disable SQL rewriting". This will disable node\_access checks as well as other modules that implement hook\_query\_alter().

---
Tags: search
---


# Question
Title: Does "Boost" module work together with "Theme Key" module?
I wonder if the Boost module works together with the ThemeKey module.

Has anyone experience with both modules working together? Especially when it comes to different style-sheets for different devices.

# Answer
> 0 votes
The two work well together (Does ThemeKey supports Boost caching) with the caveat:

> ThemeKey supports page caching and external caches like boost - if the page is cachable.
>
> If you switch a theme depending on the user's browser, the page isn't globally cachable at all, because other users are using different browsers! That's not a ThemeKey issue.

---
Tags: caching, theming, theme-negotiation
---


# Question
Title: Limit image file size; if bigger, then decrease file size with lossy compression/resizing/etc. for saving disk space
When the user uploads an image with a large file size, I would like to allow him/her doing this (not restricting the file size generally, because many users don't know how to resize an image by themselves), BUT after this, **I would like to decrease the file size of this image (the original file!) somehow to save disk space** (lossy compression/resizing/etc.).
My site is on a shared hosting, so unfortunately ImageMagick is not available.

This question is very closely related, but does not contain any detailed information about the specific solution: How can I reduce the file sizes of the original versions of uploaded image files?

I also found the ImageAPI Optimize module, which can solve the **optimization** of the image via the online Yahoo! Smush.It service, but optimization is not a restriction for the file size.
There are some related topics about limiting the file size of an image on Stack Overflow and Super User too:

Is there a Drupal-based solution for this task?

If it's unaccomplishable or too complex, maybe I should use an integrated solution with http://www.jpegmini.com/, but I don't know any modules which solves this.

# Answer
> 2 votes
The built-in functions will not do this.

You will have to write a hook for the form, upload the image at the original large size and then use Imagemagick (or similar) to process the image.

I only suggest Imagemagick because it's got more tools than GD and you should be able to re-size the image in a loop, testing for filesize and resizing/re-compressing as necessary.

---
Tags: media
---


title: List of image links

text:
# Question
Title: List of image links
The aim is to render page (node) with text field and list of image links:

```
<p>some text</p>
<ul>
    <li><a href='img1.jpg'>img 1</a></li>
    <li><a href='img2.jpg'>img 2</a></li>
    <li><a href='img3.jpg'>img 3</a></li>
</ul>

```

To create content type with one text field is easy, but how to associate list of images with content type? And more, the images should be reusable, i.e. one image can be used/rendered in more nodes. Thus the images have to be content nodes as well probably.

Of course content manager must be able to associate different images to different nodes, i.e. list of image links is not static.

# Answer
> 2 votes
I don't see the problem here, but maybe I'm too regular to things, or I didn't understand it correctly.
If I understood correctly, you want the content manager to have the ability to add more than one image per node, and that it will be possible to select the same images again from another node.
If so,
1. Add image field to the same content type that has the textfield in it, and in the image field configuration make it multi value
2. Use the media module so that the content manager will be able to see images that has been uploaded in the past and will be able to select it as well

About the unordered list, override the image field's templeate file and make it render as UL.

---
Tags: nodes, media
---


# Question
Title: Adding a CSS, JS and HTML code to a block
Using Drupal 7.2 I've successfully added a Google Adsense banner to my website by creating a new block with **admin/structure/block/add** and puting Google's code as "raw HTML" (added that "raw HTML" format first in **admin/config/content/formats/add**) there:

```
<script type="text/javascript"><!--
google_ad_client = "XXX";
/* block1 */
google_ad_slot = "YYY";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

```

Now I'm trying to add another block containg a Like-button by the russian social network Odnoklassniki.ru:

My problem is - they want me to add:

Head:

```
<link href="http://stg.odnoklassniki.ru/share/odkl_share.css" rel="stylesheet">
<script src="http://stg.odnoklassniki.ru/share/odkl_share.js" type="text/javascript"></script>

<style type="text/css">
.odkl-klass, .odkl-klass:hover {background:none;}
.odkl-klass {background: url(/images/128x128.png) no-repeat;}
</style>

```

Body:

```
<a class="odkl-klass-stat" href="http://preferans.de" onclick="ODKL.Share(this); return false;"><span>0</span></a>

```

And call:

```
<body onload="ODKL.init();">

```

How could I do it the best way please? (it would be good not to have it updated every time I update the Drupal version)

When I just try to put all 3 pieces listed above into a block (as I did for Google banner) - the button doesn't work.

# Answer
> 6 votes
The link and the script can be added through drupal\_set\_html\_head() head

```
drupal_set_html_head('<link href="http://stg.odnoklassniki.ru/share/odkl_share.css" rel="stylesheet"><script src="http://stg.odnoklassniki.ru/share/odkl_share.js" type="text/javascript" ></script>');

```

On clicks are not good practice in drupal. Behaviors are used in stead.

So in your block you can output

```
  <a class="odkl-klass-stat" href="http://preferans.de"><span>0</span></a>

```

You can then set a couple of behaviors in your own script, which you can put in a file and add using drupal\_add\_js()

```
 Drupal.behaviors.my_module = function (context) {
   // This will load on page load
   ODKL.init();
   // This will attach a click handler to the links
   $('.odkl-klass-stat').click(function() {
   ODKL.Share(this);
   return false;
   });
 };

```

# Answer
> 3 votes
http://drupal.org/project/cpn Code per Node is really useful for including Javascript and CSS in seperate text fields.

Have a look

# Answer
> 1 votes
Quick and dirty. Put this in the block:

```
<link href="http://stg.odnoklassniki.ru/share/odkl_share.css" rel="stylesheet">
<script src="http://stg.odnoklassniki.ru/share/odkl_share.js" type="text/javascript" ></script>
<script type="text/javascript" >window.onload=ODKL.init();</script>
<a class="odkl-klass-stat" href="http://preferans.de" onclick="ODKL.Share(this); return false;"><span>0</span></a>

```

Dirty why? because best practices says to put the css in the `<head>` to be valid HTML, the scripts in the footer for performance reasons, etc. But it will work.

The best way to do it it's enabling PHP filter and using `drupal_add_js, drupal_add_css` functions, etc, or create a very simple Drupal module, only with a `hook_init` to add the js, css and then the block will contain only the `a` element.

# Answer
> 1 votes
For Adsense:

The solution which worked for me is that I used the adsense tags format and then used this format to show ads on the site. Actually I was getting Ads disabled for admin and for other users i was getting the empty ad with space occupied on page but nothing shown. After different tweaks and experiments I got the following code working for me

\[adsense:336x280:XXXXXXXXXX\]

2nd parameter is width x height 3rd parameter: XXXXXXXXXX denotes the google ad slot/id.

I hope this will help others.

# Answer
> 0 votes
The link and the script can be added through `drupal_set_html_head()` head

```
drupal_set_html_head('<link href="http://stg.odnoklassniki.ru/share/odkl_share.css" rel="stylesheet"><script src="http://stg.odnoklassniki.ru/share/odkl_share.js" type="text/javascript" ></script>')

```

The link and the script can be added through `drupal_set_html_head()` head

```
drupal_set_html_head('<link href="http://stg.odnoklassniki.ru/share/odkl_share.css" rel="stylesheet"><script src="http://stg.odnoklassniki.ru/share/odkl_share.js" type="text/javascript" ></script>')

```

---
Tags: 7
---


# Question
Title: Drupal 7 views exposed filter: Removing -Any- and sorting items
I am using Drupal 7.21 and views 3.7. I have date module installed. In one of my views, I want to give drop-down year as an exposed filter and it is working fine. I do have choices as -Any- 2012 2013 But I want to remove -Any- and sort the items, so it will be like 2013 2012 I checked Required in exposed filter option without success and also used BEF module but there is not any option to do so. I also saw some blog and issue suggesting using hook\__form\_views\_exposed\_form\_alter hook. I used that as http://eureka.ykyuen.info/2012/11/22/drupal-7-customize-the-exposed-filter-selection-list/ this blog suggested but in my form option there isn't even any options listed not as this blog said.

Can anyone help me to get the exposed filter I want to show? Thank you

# Answer
You should implement `hook_form_alter` on your exposed filters form (if you have devel enabled then use dpm to find the form's name). Using the form alter sort (or just revert) the date's array and remove the '-any-'. By the way to remove the '-any-' you may also use CSS which will allow you to quickly bring it back in the future if you'll want to.

I edited a similar code I used in the past according to your need, so you will need something like this:

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

  switch ($form_id) {
    case 'views_exposed_form':
      if( !empty($form['#id']) && $form['#id'] == 'views-exposed-form-myview') {
        // This is the myview view

      // Remove the start date label
      if( !empty($form['field_sw_date_value']['min']['#date_label_position']) )
        $form['field_date_value']['min']['#date_label_position'] = 'none';

      // Remove the end date label
      if( !empty($form['field_sw_date_value']['max']['#date_label_position']) )
        $form['field_date_value']['max']['#date_label_position'] = 'none';
      break;
    }
}

```
> 6 votes

# Answer
Although altering with **hook\_form\_alter** is correct if the exposed filter values are not created dynamicaly there is no need to alter the form.

1. In exposed filter "Configure filter criterion:" check "Required".
2. Select "one of" and highlight all the items you want user to select (if they are created dynamicaly this wil not work!)
3. Check "Limit list to selected items".

But, in my opinion if you remove the -Any- value it is bad for th UX and you will need to add another default option as selected.
> 2 votes

---
Tags: 7, forms, views
---


# Question
Title: in private message: also match last names in auto-complete of To-field
I am using the private message module and I do understand that one can use realname integration in the "To"-field to send a message. The auto complete feature helps finding the name.

Suppose I want to write to "John Smith". When I start typing "Jo.." it auto completes to "John Smith", but when I start typing "Smi.." auto completion fails. For my website it would be very nice to have that feature, since sometimes people don't know other peoples first names, but the last names.

How could I alter private message in the easiest way? Do you think other people would be interested in a more comprehensive auto completion?

# Answer
There is an issue in the Privatemsg queue with an incomplete patch, privatemsg\_realname: Permits to search inside realname field using "LIKE %...%". You're welcome to help re-roll and test the patch.

The patch is for 6.x-2.x but it could fairly easily be re-written for 7.x-2.x.
> 1 votes

---
Tags: 7, ajax, privatemsg
---


# Question
Title: How do I disable/enable a module on all sites within a multi-site Drupal installation using drush?
As an admin of a multi-site Drupal installation, I want to make module changes to all sites within that platform. On a regular basis, I want to disable/enable a set of modules to ensure consistency across all of the sites.

Using drush (any version 4.x, 5.x, or 6.x is acceptable), how can I perform this task without repeating the same command across each site?

# Answer
> 8 votes
Drush has the ability to interact with each site within a multi-site installation via the @sites argument. Anytime you are within the directory structure of your platform, the drush @sites command will target all sites rather than a single/no site. In this way, *any* drush task can be accomplished across all sites.

Some concrete examples:

* Disable the dblog (core database logging) and devel module on each site

```
drush @sites dis dblog devel -y

```
* Enable the speedy module on each site

```
drush @sites en speedy -y

```
* Change the admin theme for all sites

```
drush @sites vset --yes admin_theme "ember"

```
* Check to see if any sites in the platform have the cdn module enabled

```
drush @sites pml --no-core --type=module --status="enabled" -y | grep cdn

```

These (and many more commands) work with any version of drush \>= 4.x

# Answer
> 0 votes
**And also to add with above answer,**

if you have 3 sites under sites folder. sites/all , sites/new , sites/dev and now assume "some\_module" is installed and enabled in all 3 sites.

if you want to disable "some\_module" only in "new" and "dev" sites

Step 1 : `cd DRUPAL_DIR/sites/new`

Step 2 : `drush dis some_module`

Step 3 : `repeat Step 1 and Step 2 for dev sites as well`

---
Tags: drush, multi-sites
---


# Question
Title: Getting warning message in statistics module
Below is the warning message. I'm getting this message sometimes and I'm using Drupal 6.

> user warning: Table './ri5\_r3/accesslog' is marked as crashed and should be repaired query: DELETE FROM accesslog WHERE timestamp \< 1376371846 in /home/ri5/public\_html/modules/statistics/statistics.module on line 189.

not sure what to do, what is the proper way to solve this issue ?

# Answer
> 0 votes
Doing this in **phpMyAdmin** solved my problem.

> 1. Login to phpMyAdmin
> 2. Choose the affected database. If you only have one database, it should choose it by default so you don't need to do anything.
> 3. In the main panel, you should see a list of your database tables. Check the boxes by the tables that need repair.
> 4. At the bottom of the window just below the list of tables, there is a drop down menu. Choose "Repair Table"

This should fix your table, and let you access it again. Now that it is fixed... it's a good idea to make that database backup!

taken from this source

---
Tags: 6
---


# Question
Title: Node preview with different theme than editing
I'm using an admin theme for nodes editing, also for users that are not admin (with permission "View admin theme").

The problem is that in this way also the preview of a noded is displayed with admin theme, but I need to display the preview with the "default" theme.

Is there a way?

# Answer
Page Preview module could be the solution.

Simply add an iframe on the node edit form with the preview of the node in the "default" theme. It's in "dev" version but works.
> 3 votes

---
Tags: 7, nodes
---


title: How many items has a multi-value field?

text:
# Question
Title: How many items has a multi-value field?
I need to loop through all the values of a multi field as per example bellow:

`for ($i = 1; $i < ???; $i++) {`

````
    $a = $form['field_...']['und'][$i]['#entity']->field_...['und'][0]['value'];

````

`}`

of course I could do something like this

`foreach ($form['field_additional_sections']['und'] as $key=>$value) {
if (is_int($key)) {
....
 }
}`

but I was wondering if there is a nicer option to do this. I should probably mention that I'm implementing **hook\_FORM\_ID\_form\_alter**.

Thank you

# Answer
> 3 votes
`element_children()` is the easiest way to get a list of all child elements in a render array, e.g.

```
foreach (element_children($form['field_...'][LANGUAGE_NONE]) as $key) {
  $element = $form['field_...'][LANGUAGE_NONE][$key];
}

```

---
Tags: 7
---


# Question
Title: Reset Drupal 7 Site: NIDs, Revision VIDs, Taxonomy Term and Categories, etc
Is there a way to keep an entire Drupal 7 site intact, excluding content?

Basically after creating a test environment with many nodes, terms, revisions, etc, I would love to be able to delete all the content/taxonomy and have the IDs reset as well.

Thanks in advance for any help.

# Answer
> 5 votes
Delete all module does what you want :)

> This module is used to delete all content and/or users from a site. This is mainly a developer tool, which can come in handy in several cases, listed below.

---
Tags: taxonomy-terms, nodes
---


# Question
Title: How to stop autosuggest in node author field and write our own?
Is there anyway to stopping auto suggest in author field of node content and write our own author names instead of users??

# Answer
> 0 votes
You *could* write a small module that implements hook\_form\_alter in which you remove the autocomplete functionality for this field. This should convert it to a textfield. However, this will certainly break if an author name that is not also the username of a user is inserted, since this field is used to populate $node-\>uid, which must have a valid username.

A more viable solution would be to create a vocabulary of your author names, and a taxonomy term field on your content type (pointing at that vocabulary). And then display this field as you desire.

---
Tags: theming
---


# Question
Title: hook_field_views_data() not picked up in mymodule.views.inc
I have implemented `hook_field_views_data()` in mymodule.views.inc but the hook is not picked up.

In mymodule.module I have the following code to define where mymodule.views.inc resides.

```
/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule') . '/views',
  );
}

```

Below is the code for views/mymodule.views.inc. And the problem is that if I try dumping out $field for example it seems like hook\_field\_views\_data() is not picked up.

I tried to change mymodule\_field\_views\_data() to mymodule\_views\_data, and that function is picked up. I tried this just to be sure that the file is included at all.

```
/**
 * Implements hook_field_views_data().
 */
function mymodule_field_views_data($field) {
  $data = field_views_field_default_views_data($field);

  // Add a handler for localities.
  foreach ($field['storage']['details']['sql'] as $type => $tables) {
    foreach ($tables as $table_name => $columns) {
      if (!isset($columns['locality'])) {
        continue;
      }

      $column_real_name = $columns['locality'];
      if (!isset($data[$table_name][$column_real_name]['filter'])) {
        continue;
      }

      $data[$table_name][$column_real_name]['filter']['handler'] = 'mymodule_views_handler_filter_locality';
    }
  }

  return $data;
}

```

mymodule.info

```
name = mymodule
description = Bla bla
core = 7.x

files[] = views/mymodule_views_handler_filter_locality.inc

```

# Answer
That appears to be the correct behaviour.

If you look at the code for `field_views_data()`:

```
function field_views_data() {
  $data = array();
  foreach (field_info_fields() as $field) {
    if ($field['storage']['type'] != 'field_sql_storage') {
      continue;
    }

    $module = $field['module'];
    $result = (array) module_invoke($module, 'field_views_data', $field);

    if (empty($result)) {
      $result = field_views_field_default_views_data($field);
    }
    drupal_alter('field_views_data', $result, $field, $module);

    if (is_array($result)) {
      $data = drupal_array_merge_deep($result, $data);
    }
  }

  return $data;
}

```

You can see it only invokes `hook_field_views_data()` for the module that defines the field. So in the case of (what looks like) an addressfield, the function Views will call has to be called `addressfield_field_views_data()`.

It's more likely you're looking for `hook_field_views_data_alter()` which will allow you to alter existing definitions.

But if that doesn't do what you need, you might have to actually define the `addressfield_field_views_data()` function yourself on behalf of addressfield (if it's not already implemented somewhere). Should be a pretty quick test to find out.
> 3 votes

---
Tags: views
---


# Question
Title: How to add title of node (where order form was placed) to custom line item order in commerce
Alright I added a custom line item order form to a node. I read that somewhere the link to the node on which the order form was used gets saved within the order, but I need the title of the node where the order form was used to place the order. Currently I added a entity reference field which uses a view to just display the title of the actual node and the user needs to select the value manually. But I want this to be automatic and hidden if possible, how could I go about it?

Actual try: I tried to setup a rule to make this possible, but I am not able to do it since I am not able to access the data of of my content node and the form at the same time. I tried it with a simple rule, a component and last but not least through the rules forms module

# Answer
I found a pretty bad solution: I added to the node template the following jquery, which really just writes the node title of the current node to a field in the line item.

```
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
    $(document).ready(function(){
        var title= $('#page-title').text();
        $('#your-line-item-field-id').val(title );
        $('#your-line-item-field-id').prop('disabled', true);
});
</script>

```
> 0 votes

---
Tags: commerce
---


# Question
Title: Service Userpoints : Missing required argument points
My environment : Drupal 7 & service 3.x

I use userpoints and service-userpoints. I want to CRUD userpoints.

So i create a xmlrpc server and test it by Postman from Chrome store.

The xml code is belowed:

```
<?xml version='1.0' ?>
<methodCall>
  <methodName>pointss.add</methodName>
  <params>
    <param>
      <value>
        <struct>
          <member>
            <name>uid</name>
            <value>
              <int>1</int>
            </value>
          </member>
          <member>
            <name>points</name>
            <value>
              <int>150</int>
            </value>
          </member>
          <member>
            <name>description</name>
            <value>
              <string>test for xmlrpc service</string>
            </value>
          </member>
        </struct>
      </value>
    </param>
  </params>
</methodCall>

```

"pointss" is my userpoints-api's alias

i connect successful but got the message belowed.

```
<?xml version="1.0"?>

```

faultCode 401 faultString Missing required argument points

How can i fix my xml body? Does anybody have experience? Thanks a lot.

# Answer
> 0 votes
I finally get it.

The XMLRPC format is belowed:

```
<?xml version="1.0"?>
<methodCall>
   <methodName>pointss.addpoints</methodName>
   <params>
     <param>
           <name>uid</name>
           <value><int>1</int></value>
           <name>points</name>
           <value><int>150</int></value>
           <name>tid</name>
           <value><int>18</int></value>
           <name>operation</name>
           <value><string>test for operation</string></value>
           <name>description</name>
           <value><string>test for description</string></value>
           <name>entity_type</name>
           <value><string>node</string></value>
           <name>entity_id</name>
           <value><int>1</int></value>
     </param>
   </params>
</methodCall>

```

If somebody use service3.x and userpoints service, i hope i can help you.

---
Tags: userpoints, services
---


# Question
Title: Code to display multiple images using .tpl.php file in drupal 7
I use the following code to render the image from the template file. This code is used when the image name is known. Multiple images can be displayed by adding the same lines of code with different image names.

```
global $base_path;
print "<img src='" . $base_path . path_to_theme() . "/../../../default/files/styles/thumbnail/public/xyz.jpg' width='100' height='100' />";

```

Is it possible to render the multiple images from the content type with the field name created but without changing anything in the template file every time we upload the image?

# Answer
> 0 votes
If you have multiple images from the content type, and you want to render them. The .tpl.php file must have `$node` variable and in that variable you will have the image path and image uri for each image with field name, which you want to render. Just save the image path or image uri of image in some variable and do as following:

```
$img_uri = <image uri path here>;
$image_url = file_create_url($img_uri);
print '<img src="' . $image_url . '" width="100" height="100" alt="style image" />';

```

In case your are using **Image Styles** then you will need to get the image's url and style name and use it like this:

```
$style_name = <image style name>;
$file_path = <image file path>;
$image_url = image_style_url($style_name, $path);
print '<img src="' . $image_url . '" width="100" height="100" alt="style image" />';

```

And I can see that are using Image Style in which your path is something like:

```
 /../../../default/files/styles/thumbnail/public/xyz.jpg

```

The rest I think that once you get different image file paths then you can easily loop them as you like.

---
Tags: theming, media
---


title: How do I programmatically switch theme?

text:
# Question
Title: How do I programmatically switch theme?
I want to switch theme on the basis of URLs and roles. I have used `hook_custom_theme()` but it's working only on the frontend.

Is there a way to switch theme basing on the URL for every page?

# Answer
The reason it works only for the frontend pages is that:

* The System module implements `hook_custom_theme()` using the following code

```
function system_custom_theme() {
  if (user_access('view the administration theme') && path_is_admin(current_path())) {
    return variable_get('admin_theme');
  }
}

```
* The function that invokes that hook has the following code

```
$custom_themes = array_filter(module_invoke_all('custom_theme'), 'drupal_theme_access');
if (!empty($custom_themes)) {
  $custom_theme = array_pop($custom_themes);
}

```

In other words, the theme selected is the one returned from the last hook invoked, which in your case is system\_custom\_theme().
If you want that your module always sets its own custom theme, even for administrative pages, you need to tell Drupal to execute your hook implementation for last.

```
function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'custom_theme') {
    // Move mymodule_custom_theme() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

```

As side note, since the module would be override the theme set in admin/appearance, the module should give an indication of that in that page.

As for using the Themekey module, that module doesn't override the theme for the administrative pages, since its hook implementation (themekey\_custom\_theme()) contains the following code.

```
  // don't change theme when ...
  if ((in_array('system', variable_get('themekey_compat_modules_enabled', array())) || !(variable_get('admin_theme', '0') && path_is_admin($_GET['q']))) // ... admin area and admin theme set
     && strpos($_GET['q'], 'admin/structure/block/demo') !== 0 // ... blocks demo
     && strpos($_SERVER['SCRIPT_FILENAME'], 'cron.php') === FALSE // ... during cron run executed by cron.php
     && strpos($_SERVER['SCRIPT_FILENAME'], 'drush.php') === FALSE // ... during cron run executed by drush
     && (!defined('MAINTENANCE_MODE') || (MAINTENANCE_MODE != 'install' && MAINTENANCE_MODE != 'update')) // ... during drupal installation or update
    ) {
  // …
}

```

The comment reads as "don't change theme when admin area and admin theme set." I would rather do what the Themekey module does, but since you are trying to set the theme in any case, the Themekey module would not work for your case.
> 4 votes

---
Tags: hooks
---


title: Ajax Call on image button

text:
# Question
Title: Ajax Call on image button
I want to use ajax call on image button

here is my code.

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

    if($form_id=='user_profile_form') {

       $form['linkb'] = array(
            '#type' => 'image_button',
            '#href' => '',
            '#title' => t('something'),

            '#name' => 'linkb',
            '#ajax' => array(
                'method' => 'html', // this is important without this if else condition for ajax will not work.
                'effect' => 'fade',
                'callback' => 'clicktell_verification',
                'wrapper' => 'replace_textfield_div',),
        );
        $form['cardnresp'] = array(
            '#type' => 'hidden',
            //'#default_value' => '',
            '#title' => t('This is where msg comes'),
            '#prefix' => '<div id="replace_textfield_div">',
            '#suffix' => '</div>',
        );
        $form['#validate'][]='clicktell_error';

    }
    return $form;
}

```

and

```
function clicktell_error($form, &$form_state) {
  //my code
}

function clicktell_verification($form, &$form_state) {
 //my code
}

```

But now when i click on image button it jst refresh the page and no ajax call happnes

Does anybody have idea regarding this

Thanks

# Answer
```
function clicktell_form_alter(&$form, &$form_state, $form_id) {

    if($form_id=='user_profile_form') {

       $form['linkb'] = array(
            '#type' => 'image_button',
            '#href' => '',
            '#title' => t('something'),

            '#name' => 'linkb',
            '#ajax' => array(
                'method' => 'html', // this is important without this if else condition for ajax will not work.
                'effect' => 'fade',
                 'prevent' => 'mousedown',
                'callback' => 'clicktell_verification',
                'wrapper' => 'replace_textfield_div',),
        );
        $form['cardnresp'] = array(
            '#type' => 'hidden',
            //'#default_value' => '',
            '#title' => t('This is where msg comes'),
            '#prefix' => '<div id="replace_textfield_div">',
            '#suffix' => '</div>',
        );
        $form['#validate'][]='clicktell_error';

    }
    return $form;
}

```

This will run ajax but you may feel form is submitting but there is no actual submitting of form
> 1 votes

# Answer
You didn't set `#ajax_prevent`. It should default to 'click' all right, but my experience says sometimes it does not, and sometimes it is not sufficient. Try to add this to your ajax settings:

```
'prevent' => 'submit click mousedown',

```
> 0 votes

---
Tags: 7
---