title: Clone View as attachment

text:
# Question
Title: Clone View as attachment
I am using Views-7.x-3. I have a master view and many content panes views under it. Recently I have a requirement in which I have to create attachment for one of the content pane view. When I clicked on adding an attachment it cloned the all the formats, fields, filter criteria etc from the master display, which I do not want as I want to have same copy of the my content pane view as an attachment which has many addition fields, context filter as well.

My query: Is there any way to clone desired view as attachment rather re-creating same fields again?

# Answer
It is possible to clone a View Display (in this case an attachment). For example:

1. Go to **admin/structure/views/view/frontpage** on your Drupal site
2. Select the 'Feed' Display under **Displays**
3. Under 'Feed details', notice the 'Display name' field, look all the way to the right of here and you'll notice a 'view Feed' drop down menu, click the 'down' icon
4. Then click 'clone Feed'

That will cone that particular display, click 'Save' when you're ready to save the changes. For your attachment, follow the steps above and replace the steps with your view, and the name of your attachment.
> 0 votes

---
Tags: views
---


# Question
Title: How can I upload photos from iphone/Android to Drupal?
I know that I can build iphone/Android apps with frameworks like phonegap and titanium.

I wonder if there is an easier way? Aurigma Up seems like an interesting idea. Has anyone used this or similar apps?

# Answer
> 1 votes
Check out github, there are some examples of iPhone apps that use services with drupal. this on has allot of functionality, and I know that the creator is quite active in the Drupal community. https://github.com/workhabitinc/drupal-ios-sdk-example. I find objective C realy intimidating and am more familiar with languages like java and js so titanium really great. Here is a great project for titanium https://github.com/palantirnet/drupalcon\_mobile it still has a pretty steap learning curve but much less than learning a new language. If you end up going the titanium rout and you are trying to post images via services, you have to make some alterations to code that compiles titanium (kinda hack it), so that the image blob data can be properly posted. It took me forever to figure this out, if you get that far, let me know and I'll elaborate.

unfortunately, there is really no canned way of facilitating image upload from mobile to drupal, your best bet is to try and use services to post the image through http.

# Answer
> 1 votes
phonegap and titanium are probably considered easier than for example, developing a separate native app for iOS and Android.

However, if you are looking for something even easier, perhaps you could explore using an existing application that uploads images to a service such as Flickr. A query for iPhone apps on Flickr's App Garden provides plenty of results. You could then use an app such as this one to upload images and then use Flickr's API to create image galleries in Drupal. Plus, you can make calls to Flickr from Drupal and receive data in different formats including JSON and XML. It really doesn't get easier than that.

The Flickr contrib module could then provide you with plenty of examples of how to query Flickr's API.

The fact that your images would be hosted by a third party could be seen as good or a drawback, depending on how you analyze it.

# Answer
> 1 votes
iOS 6 allows this to be done quite easily. Im working on a few projects myself. Here is my cross answer Is there any module for picking photos for image field on mobile platforms like iphone

But more feature are found here http://howto.cnet.com/8301-11310\_39-57507927-285/with-ios-6-you-can-upload-photos-in-safari/

# Answer
> 0 votes
DrupalGap is an open source mobile application development kit for Drupal websites. It uses PhoneGap and jQueryMobile. Out of the box, DrupalGap offers an image upload feature for your content types.

---
Tags: 7, theming
---


title: Unable to get the cycle 2 plugin

text:
# Question
Title: Unable to get the cycle 2 plugin
I have installed Views Slideshow module 7.x.3.1. Also, inside the sites/all/libraries I downloaded the cycle2 plugin. I placed jquery.cycle2.min.js into the jquery.cycle2 folder, so it is at sites/all/libraries/jquery.cycle2/jquery.cycle2.min.js.

When I tried creating a view using *Format : slideshow*, I encountered the following error:

> CYCLE OPTIONS You need to install the jQuery cycle plugin. Create a directory in sites/all/libraries called jquery.cycle, and then copy jquery.cycle.all.min.js or jquery.cycle.all.js into it. You can find the plugin at http://malsup.com/jquery/cycle.

Even after installing the cycle plugin in the libraries folder, I could not see an option for cycle2.

Along with with views slideshow, I need pager effect and continuous effect, with vertical effect instead of horizontal effect.

# Answer
> 1 votes
Readme says

1) Assure that you are using Views 3.x. http://drupal.org/project/views

2) Upload/install the Libraries API module. http://drupal.org/project/libraries

3) Upload/install the ctools library. http://drupal.org/project/ctools

4) Create a sites/all/libraries directory on your server.

5) Create a directory within sites/all/libraries named jquery.cycle.

6) Locate/download the jQuery cycle plugin. http://malsup.com/jquery/cycle

7) Upload/install the jQuery cycle plugin: place it inside the jquery.cycle directory. 8) Enable the Views slideshow and Views Slideshow: Cycle modules

9) You should now see the new views style option called "Slideshow"

**You need to install cycle plugin not cycle 2**. Try installing using cycle plugin and follow above instructions.

There is a sandbox module available if you want to use Cycle 2 plugin.

You can download using git commands.

git clone --branch master http://git.drupal.org/sandbox/BenYoung/1832338.git views\_slideshow\__cycle2

cd views\_slideshow\__cycle2

Follow the installations instruction in project page for the same.

---
Tags: 7, views
---


title: Migrate users from one site to another

text:
# Question
Title: Migrate users from one site to another
At the moment I've got 2 drupal 7 site. Now I want to merge those two sites together. If I export the user table in the database from one site and import the data directly into another site, will that be working? Btw, The users don't have any related contents like nodes or comments in the site so I guess the only table I need to worry about the user table. The only concern is the password. I'm not sure if I import the data the user password will be the same.

# Answer
> 1 votes
I can think of a few problems that might occur if you simply import the users table:

* Existing Users' IDs might overlap with the users to be imported (which would just give a SQL error about duplicate primary keys).
* No way to add roles to the imported users (if applicable).
* Imported Users' language might not exist on the new site.
* Imported Users' theme might not exist on new site.
* Likely many others

You're much better off using something like User Import to do this.

# Answer
> 2 votes
You need to use Drupal-to-Drupal data migration module. Project page says

"With migrate\_d2d 2.1, we are introducing a wizard-based UI for defining your Drupal-to-Drupal migrations. Enabling the migrate\_d2d\_ui module will add an "Import from Drupal" subtab to the Migrate dashboard - visit that tab, enter the credentials for your source Drupal database (versions 5, 6, or 7), and follow the steps to define how your legacy content maps to the destination Drupal 7 site."

---
Tags: users, migrations
---


# Question
Title: Upload Image browser widget for drupal 6
I need the following combined options, to browse and choose images from **previous uploads** (or) upload new image from **hard drive**. Currently I configured with default upload widget(file-\>Image), so I can choose image from hard drive only, but I don't want to upload the same(duplicate) image again and also it will save lot of space. I want to avoid same image upload, Is any module available with both options ?

# Answer
> 1 votes
Try FileField Sources module

> FileField Sources is an extension to the FileField module. The FileField module lets you upload files from your computer through a CCK field. The FileField Sources module expands on this ability by allowing you to select new or existing files through additional means, including:
>
> 1. Re-use files by an auto-complete textfield
> 2. Attach server-side files uploaded via FTP
> 3. Transfer files from a remote server (cURL required)
> 4. Paste a file directly from the clipboard (Drupal 7 only)
> 5. Select existing files through the IMCE file browser

the first one is what youre looking for.

---
Tags: 6, media
---


title: Omega 4 add region to layout

text:
# Question
Title: Omega 4 add region to layout
I've found info to add regions to a custom layout in an Omega 4 subtheme. Regions need to be declared in theme.info, layout.inc and then printed/rendered in layout.tpl.php.

I've done all that and they don't appear on the page after cache clearing.

Note:

* They do appear in /admin/structure/block (I can add blocks to the regions there but they aren't displayed on the actual pages).
* The regions also appear if I edit the theme.info file, and templates/system/page.tpl.php file, and disable the use of layouts in omega 4 subtheme settings.

Code i used in following files: /theme.info

```
regions[footercolumnone] = Footer Column one
regions[footercolumntwo] = Footer Column two
regions[footercolumnthree] = Footer Column three
regions[footercolumnfour] = Footer Column four

```

/layouts/owr/owr-layout.tpl.php

```
<div class="l-footer-column1"><?php print render($page['footercolumnone']); ?></div>
<div class="l-footer-column2"><?php print render($page['footercolumntwo']); ?></div>
<div class="l-footer-column3"><?php print render($page['footercolumnthree']); ?></div>
<div class="l-footer-column4"><?php print render($page['footercolumnfour']); ?></div>

```

/layouts/owr/owr.layout.inc

```
regions[footercolumnone] = Footer Column one
regions[footercolumntwo] = Footer Column two
regions[footercolumnthree] = Footer Column three
regions[footercolumnfour] = Footer Column four

```

# Answer
> 1 votes
I found that my /layouts/owr/owr.layout.inc file still said: template = simple-layout instead of template = owr-layout Changing it to the latter fixed my issue. Don't know why/where that parameter is used though.

---
Tags: theming
---


# Question
Title: How to set language for user register page / form per subdomain
For a custom module, I need to change the language of the registration form based on the subdomain the user is currently active on.

I tried changing the global $language variable in hook\_form\_user\_register\_form\_alter, but that does not work ($language variable is also not set at that point). I also tried setting the language in the $user object, but also no dice (probably because it is an anonymous user).

Finally I took a look at the language negotiation api, but setting up negotiation providers seems overkill for this (and haven't it studied enough to get a grasp on how to use it).

I just need to render the registration page in a different (but already available) language on /user/register, based on the subdomain. What would be the best way to achieve this.

I'm using Drupal 7.

# Answer
> 1 votes
Based on how it's done in the Domain Locale module (thanks Matt for pointing it out), I am now using this in hook\_init:

```
if (strpos($cp, 'user/register') === 0 || strpos($cp, 'user/password') === 0 || strpos($cp, 'user/reset') === 0) {
    global $language;
    $lang = my_get_language_function();
    $languages = language_list();
    if (!empty($lang) && isset($languages[$lang]))
        $language = $languages[$lang];
    return;
}

```

# Answer
> 1 votes
Maybe you can use the Domain Locale module. It allows you to change the available and default languages per domain.

# Answer
> 1 votes
I may not be understanding the question, but if you go here:

`/admin/config/regional/language/configure`

You can set how languages are set (Determine the language from the URL (Path prefix or domain).

Domains can be configured here: `/admin/config/regional/language/edit/`

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


# Question
Title: Commenting on each paragraph of node body
I want to provide this option in Drupal that users be able to put comment on each paragraph of an article beside putting comment on the whole article.

I use explode command to make an array which contains paragraphs:

```
$paragraphs = explode("<p>",render($content));

```

In order to put comment for the whole article I write:

```
print render($content['comments']);

```

I am trying to find the file where `$content` is defined, so I can add another array like `$content[]['paragraphcomments']` for comments for each paragraph of an article. Does anyone know in which file `$content` is defined. Also does anyone have any suggestion?

# Answer
`$content`is defined in node.module in the function `template_preprocess_node()`. You can add elements to the nodes content using `hook_node_view()`(D7) or `hook_nodeapi()` (D6).

See the accepted answer of this question for more details.
> 0 votes

# Answer
You should create a module and can use jquery to shown & insert comments within paragraphs. If you use jquery then you'd need to use Ajax. You should show comment paragraphs in accordion style and allow visitor to comment after expanding it.

You can see simple Drupal developer examples in the example module.
> 0 votes

---
Tags: nodes
---


title: How to hide Quick Tabs Title

text:
# Question
Title: How to hide Quick Tabs Title
I don't find a way to hide the quick tab title. Is there a hard way if not straight forward? Because I just cant use the title which doesn't make sense in my context/content.

My quick tab title is "Property Tabs". There are 3 tabs under it. Below SS is showing only one tab because I have checked "Hide empty tabs". My tabs are all **blocks**

1. 3D Gallery
2. Image Gallery
3. Video Gallery

I don't want to show the "Property Tabs" (highlighted in SS). I have tried to give title as "" but its still showing the title literally "". Its not accepting "empty string" or "space"

# Answer
In your Quick Tabs settings (admin/structure/quicktabs/manage/...) there's a checkbox to hide the title of your content and use the custom Tab-Title instead.

If you want to hide the block title (of the quicktabs block) itself, you can insert `<none>` in the block settings...
> 2 votes

---
Tags: blocks
---


# Question
Title: People Permission: View own unpublished content do not work
I want let anonymous user can visit unpublished content, So I enable `View own unpublished content` for anonymous user.

But I open other browser to visit the url of unpublished content. But it alert me:

**Access denied**

I clear the cache, but above problem again

So, It is a bug?

# Answer
> Drupal 7
>
> In Drupal 7, users are not allowed to view any unpublished content by default, not even content created by themselves. By enabling 'View own unpublished content', you grant users access to their own unpublished content.
>
> The only way to allow users access to all unpublished content in Drupal 7 (without using a contributed module), is to enable the permission 'Bypass content access control'. Use this permission with extreme caution as it has far more consequences than just allowing access to unpublished content. In combination with Organic Groups for example, this permission allows access to private group content regardless of whether the user is a group member.

https://drupal.org/node/1106606

On that page are some contributed modules to set permissions you need...
> 1 votes

---
Tags: users
---


# Question
Title: Replacing theme() with render() in a block_view
I'm trying to replace the theme() with render() as recommended:

https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7
So I started with:

```
 function mymodule_block_view()
 {
  $variables['module_path'] = drupal_get_path('module', 'mymodule');
  $block['subject'] = t('mymodule Slide');
  $block['content'] = theme('mymodule', $variables);
    return $block;
  }

```

And I tried

```
 function mymodule_block_view()
 {
    $variables['module_path'] = drupal_get_path('module', 'mymodule');
    $block['subject'] = t('OpenDTP Slide');
    $rdr = array(
      '#theme' => 'opendtp_slide',
        '#module_path' => $variables['module_path'],
     );
    $block['content'] = render($rdr);
    return $block;
}

```

But it says **Undefined variable** for **module\_path** that I used in the tpl.php file. How I'm a supposed to use variables in the template then ? What is the correct way of doing it ?

# Answer
> -2 votes
How about:

```
...
$rdr = array(
  '#theme' => 'opendtp_slide',
  '#module_path' => drupal_get_path('module', 'mymodule')
);
...

```

---
Tags: theming
---


title: date_popup + theme = infinite loop

text:
# Question
Title: date_popup + theme = infinite loop
I'm trying to create a templated form including date\_popup field in a custom module. There is a very basic example : mkl\_variousTest.module ( dependency : date\_popup from date API )

```
<?php

//mkl_variousTest.module

/**
 * Implementation of hook_menu()
 * @return array
 */
function mkl_variousTest_menu() {
  $items = array();

  $items['testFormTemplate'] = array(
    'title' => t('Test form template'),
    'page callback' => 'mkl_variousTest_form_page',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Implementation of hook_theme($existing, $type, $theme, $path)
 * @param array $existing
 * @param string $type
 * @param string $theme
 * @param string $path
 * @return array
 */
function mkl_variousTest_theme($existing, $type, $theme, $path) {
  $themes = array();

  $themes['formPage'] = array(
    'template' => 'mkl_variousTest_formPage',
    'path' => drupal_get_path('module', 'mkl_variousTest') . '/templates',
    'variables' => array(
      'form' => drupal_get_form('mkl_variousTest_form'),
    ),
  );

  return $themes;
}

/**
 * Implementation of hook_form($form, &$formState)
 * @param node $node
 * @param array $formState
 * @return array
 */
function mkl_variousTest_form($node, &$formState) {
  $form = array();

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Nom'),
    '#lenght' => 60,
    '#required' => TRUE,
  );

  $form['date'] = array(
    '#type' => 'date_popup',
    '#title' => t('date'),
  );

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

  return $form;
}

function mkl_variousTest_form_page() {
  return theme('formPage');
}

?>

```

Using this way, drupal run in an infinite loop and return this error :

> Fatal error: Maximum function nesting level of '100' reached, aborting!

There is a printScreen :

Next, the same function calls between #19 to #37 are repeated until drupal stop the loop. This append as soon as I have a date\_popup field in my form.

So how can I fix it ?

PS : This is my template file mkl\_variousTest\_formPage.tpl.php :

```
<p>before</p>

<?php print drupal_render_children($form); ?>

<p>after</p>

```

# Answer
Stab in the dark, but I think your problem is probably stemming from the fact that you're building the form from within a theme function, which in turn calls another theme function, then so on and so forth. Logically theming should be after you've built the form.

Replace `drupal_get_form('mkl_variousTest_form')` in `hook_theme()` to `NULL` and in your page callback add the following code.

```
$form = drupal_get_form('mkl_variousTest_form');
return theme('formPage', array('form' => $form));

```
> 0 votes

---
Tags: 7, forms, theming, datetime
---


# Question
Title: How can I add additional query parameters to a view title linked to a node?
I have a view (using the calendar module), which displays a title field for each displayed event. The title field is set to "link this field to the original piece of content".

I'd like to rewrite that link to add some additional parameters, e.g. ?return\_view=myview, so that I can link back to the view page from the content. The content might be linked to from any one of several different views, so it needs to take some parameter (i.e. return\_view) to tell it what to link back to.

I've tried adding a hook\_views\_pre\_render:

```
function mymodule_views_pre_render(&$view) {
    if ($view->name == 'myview') {
        foreach ($view->result as &$r) {
            $r->node_title = array(
                '#theme' => 'link',
                '#text' => 'xyz',
                '#path' => 'node/' . 123,
                '#options' => array(
                    'query' => array(
                        'rv' => $view->name,
                        'rvd' => $view->current_display
                    ),
                    'attributes' => array(),
                    'html' => FALSE
                )
            );
        }
    }
}

```

But that just leads to Drupal complaining that "warning: htmlspecialchars() expects parameter 1 to be string, array given in check\_plain()" - I'm assuming because some rendering function somewhere expects to get a plain string.

What's the cleanest way to add additional query parameters to a node title rendered by views?

# Answer
> 1 votes
You can do this in Views.

1. Add a new field to the View "Content: Path".
2. Check Exclude from display.
3. Click on Rewrite Results and the check "Use absolute link".
4. Click Apply button to Save.
5. Rearrange your fields so "Content: Path" is above "Content: Title".
6. Click on the "Content: Title" field.
7. Uncheck "Link this field to the original piece of content".
8. Click on Rewrite Results and check "Output this field as a link".
9. In the Link path textbox enter "\[path\]?return\_view=myview". (You can use the path replacement pattern because it is above the title field in the field order)
10. Click Apply.

---
Tags: views
---


# Question
Title: Why didn't we got rid of primary entity keys in favour of UUIDs?
I just remembered, while working with custom entities, that Drupal 8 was supposed to bring UUID support and replace the old "entity id" keys but then I've also noticed that the old fashioned entity id key is required by tye EntityType annotation and interestingly the UUID key is just optional.

Is this so that urls/entites are easier to remember by their "nid"?

And most importantly: should we use UUIDs or entity ids in logic and/or database operations?

Is this the final approach or we'll see entity id disappear in beta/rc/stable release?

Personally I don't see any good reason to keep using the typical serial keys when we have UUIDs now.

# Answer
For context and some related discussions, see #1726734 Replace serial entity IDs with UUIDs in URLs, or even globally?. There is also a related issue about using UUID's for references, which I can't find right now.

So one argument is that all URL's would then become very long, there's no user/1 anymore but user/LONG-UUID.

Another is the database performance, the primary key is the main index of every table, and making that bigger makes every change to that table more expensive. Yes, so does having 4 tables, but there's still the hope that to make that optional for non-multilingual sites. I doubt it will be possible, but we will see.

And you have to keep in mind that the storage would not only be increased by the actual field, but also every reference, so every single field table entry would then have to store the full UUID instead of the considerable shorter primary key.

And related to the issue that I can't find right now is that it would also slow down joins that involve entity tables.

That doesn't mean that it will never happen, but it has been pushed back to 9.x to be re-evaluated there.
> 1 votes

---
Tags: database, entities, 8
---


# Question
Title: How can I add a CSS class to all the tables?
I want to add a *table* class to all the tables, automatically. How can I achieve this by overriding a theme function?

# Answer
If your table is rendered using `theme('table')`, you can preprocess it from your theme function.

```
function my_theme_preprocess_table(&$variables) {
  $variables['attributes']['class'][] = 'table';
}

```
> 5 votes

---
Tags: theming
---


title: Customizing a Drupal 7 block menu

text:
# Question
Title: Customizing a Drupal 7 block menu
I installed the Menu block module, and it seems to work fine.

I need to change one of the menu HTML output; instead of the following HTML tags:

```
<ul class="menu">
  <li><a href="/" title="">Home</a></li>
  <li><a href="/our-rides" title="">Our Rides</a></li>
</ul>

```

I want to have:

```
<a href="/" title="">Home</a>|<a href="/our-rides" title="">Our Rides</a>

```

I tried implementing a hook, but it doesn't work.

```
function bsrentals_menu_item_link__menu_block($variables) {
      print 123;exit;
}

```

# Answer
> 2 votes
Well, what you want to achieve ... Eg, output a horizontal list of links with "pipes" between them can be done in Drupal with the HTML and CSS drupal provides you.

What you need to refer to is a book on CSS.

A random Google of this technique yields: http://jamesowers.co.uk/css-tutorials/50/horizontal-css-list-menu/

In a nutshell, you want to set the list-item as relative and to display inline in CSS. Give them some spacing and for instance add a right-border to every list item with your color choice. Then if you really want using a CSS/Jquery selector of :last-child remove the trailing right border if it bothers you.

If you are intent on rewriting and bending the HTML and CSS to your will because the above approach elludes you .... you can do 1 of 2 options:

1) using the http://drupal.org/project/devel\_themer you can find the specific block in question within your theme. You can then alter the necessary template file(s) in drupal to alter the HTML produced from Drupal to meet your criteria. Menus are shown in blocks on the page. So you could find the theme function for the menu in question and override its output in your theme. Devel\_theme should be able to tell you the correct function to override if your's isn't working.

Or you could create a really silly function like below in your template.php file and call it as needed from your .tpl files. The below code relies on the http://api.drupal.org/api/drupal/includes--menu.inc/function/menu\_tree\_all\_data/7 function to pull a menu's items by the menu-name. See the linked API page to find out how to find out what specific menu in drupal you want to load ... then we simply create the HTML from the menu links as in the function. I really really dont recommend you do this. Either learn CSS and Jquery to render the default content drupal provides you with to appear as you want, or learn how to change the template files gracefully ...

```
/*
What does menu_tree_all_data() return ... well let's see below:

$ drush eval 'print_r(menu_tree_all_data("main-menu"));'Array
(
[49950 Home 240] => Array
    (
        [link] => Array
            (
                [menu_name] => main-menu
                [mlid] => 240
                [plid] => 0
                [link_path] => <front>
                [router_path] =>
                [link_title] => Home
                [options] => Array
                    (
                        [attributes] => Array
                            (
                                [title] =>
                            )

                    )

                [module] => menu
                [hidden] => 0
                [external] => 1
                [has_children] => 0
                [expanded] => 0
                [weight] => -50
                [depth] => 1
                [customized] => 1
                [p1] => 240
                [p2] => 0
                [p3] => 0
                [p4] => 0
                [p5] => 0
                [p6] => 0
                [p7] => 0
                [p8] => 0
                [p9] => 0
                [updated] => 0
                [load_functions] =>
                [to_arg_functions] =>
                [access_callback] =>
                [access_arguments] =>
                [page_callback] =>
                [page_arguments] =>
                [delivery_callback] =>
                [tab_parent] =>
                [tab_root] =>
                [title] => Home
                [title_callback] =>
                [title_arguments] =>
                [theme_callback] =>
                [theme_arguments] =>
                [type] =>
                [description] =>
                [in_active_trail] =>
                [access] => 1
                [href] => <front>
                [localized_options] => Array
                    (
                        [attributes] => Array
                            (
                                [title] =>
                            )

                    )

            )

        [below] => Array
            (
            )

    )

[49951 Student Login 239] => Array
    (
        [link] => Array
            (
                [menu_name] => main-menu
                [mlid] => 239
                [plid] => 0
                [link_path] => student/login
                [router_path] => student/login
                [link_title] => Student Login
                [options] => Array
                    (
                        [attributes] => Array
                            (
                                [title] =>
                            )

                    )

                [module] => menu
                [hidden] => 0
                [external] => 0
                [has_children] => 0
                [expanded] => 0
                [weight] => -49
                [depth] => 1
                [customized] => 1
                [p1] => 239
                [p2] => 0
                [p3] => 0
                [p4] => 0
                [p5] => 0
                [p6] => 0
                [p7] => 0
                [p8] => 0
                [p9] => 0
                [updated] => 0
                [load_functions] =>
                [to_arg_functions] =>
                [access_callback] => 1
                [access_arguments] => a:0:{}
                [page_callback] => _dew_auth_login_page
                [page_arguments] => a:0:{}
                [delivery_callback] =>
                [tab_parent] =>
                [tab_root] => student/login
                [title] => Student Login
                [title_callback] => t
                [title_arguments] =>
                [theme_callback] =>
                [theme_arguments] => a:0:{}
                [type] => 6
                [description] =>
                [in_active_trail] =>
                [href] => student/login
                [access] => 1
                [localized_options] => Array
                    (
                        [attributes] => Array
                            (
                                [title] =>
                            )

                    )

            )

        [below] => Array
            (
            )

    )

)

*/

function i_dont_advise_this($menu_name) {
  $data = menu_tree_all_data($menu_name);
  $links = array();

  foreach($data as $MenuItem => $item) {
    $links []= l($item['link']['title'], $item['link']['link_path']);
  }
  return implode('|', $links);
}

print i_dont_advise_this('main-menu');
# yields =>
# <a href="/" class="active">Home</a>|<a href="/?q=student/login">Student Login</a>

```

# Answer
> 0 votes
Check out this module: https://github.com/Moonfuse/drupal-nav .

It's a simple little module I wrote to customize your menu's HTML by writing HTML.

You can also preprocess the menu items via hook\_drupalnav.

---
Tags: routes
---


# Question
Title: How to add class to all forms automatically?
I want to add .form class to all Drupal forms. How can I add class to all forms by overriding theme function?

# Answer
You can do something like this:

```
function MYMODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id) {
  $form['#attributes']['class'][] = 'MY_CLASS';
}

```
> 3 votes

---
Tags: theming
---


# Question
Title: Which Drupal function inserts the data in the history table?
So as far as I've seen, the *history* table holds timestamps when users viewed nodes.

Which Drupal function insert the data in that database table? The most logical place for me would be in `statistics_exit()`, where the *accesslog* table is being populated, but it's not there. The only place I've seen something similar is in `node_tag_new()`, but I am not sure if that's the right one.

Can anyone shed some light into this?

# Answer
It is `node_tag_new()`, the function that is part of the Node module (line 299 of that file in Drupal 7).

```
/**
 * Updates the 'last viewed' timestamp of the specified node for current user.
 *
 * @param $node
 *   A node object.
 */
function node_tag_new($node) {
  global $user;
  if ($user->uid) {
    db_merge('history')
      ->key(array(
        'uid' => $user->uid,
        'nid' => $node->nid,
      ))
      ->fields(array('timestamp' => REQUEST_TIME))
      ->execute();
   }
}

```

Here's the same function in Drupal 6.

```
/**
 * Update the 'last viewed' timestamp of the specified node for current user.
 */
function node_tag_new($nid) {
  global $user;

  if ($user->uid) {
    if (node_last_viewed($nid)) {
      db_query('UPDATE {history} SET timestamp = %d WHERE uid = %d AND nid = %d', time(), $user->uid, $nid);
    }
    else {
      @db_query('INSERT INTO {history} (uid, nid, timestamp) VALUES (%d, %d, %d)', $user->uid, $nid, time());
    }
  }
}

```

The function is called by `node_show()`, which uses the following code.

```
// Update the history table, stating that this user viewed this node.
node_tag_new($node);

```

As said from that comment, the purpose of the function call is updating the history table to record the fact the current user viewed the node.
> 6 votes

---
Tags: 7
---


title: Set custom header text size for teasers

text:
# Question
Title: Set custom header text size for teasers
I've created a frontpage which uses a the 34/33/34 panel layout and linked different contents to it (another pages). By checking the code using Firebug i see that teasers on this front page inherited the H2 class settings for header text, so they appear with the same text size just as they appear in full content view.

I'd like to customize the size of the header texts of the teasers on the front page. Any suggestion welcomed!

Thanks!

# Answer
Just use CSS to alter the size of your H2 elements on the home page.

Replace in this code XX by the desired font-size, and it will apply to all h2 elements but only on the home page (body.front)

```
body.front h2 {
  font-size:XXpx;
}

```

Otherwise, learn CSS to understand how to select your specific elements.
> 1 votes

---
Tags: nodes
---


# Question
Title: How can I move taxonomy terms to a different vocabulary and update term reference fields?
I need to split a taxonomy vocabulary into two different vocabularies in Drupal 7.

I can use the Taxonomy Manager module to move terms from one vocabulary to another; I have tested this and it works.

However, the big problem is that I have a large number of nodes with a taxonomy term reference field that include references to the terms.

This is what it looks like now: Nodes of **Content Type X** have a **Taxonomy term reference** (multiple values permitted) to **Vocabulary A**.

This is what I want to do.

1. Split **Vocabulary A** into **Vocabulary B** and **Vocabulary A** (which contains about half the terms). \[This step can be done with Taxonomy Manager.\]
2. Create a new **term reference field** to **Vocabulary B**. \[This can be done from the Field UI.\]
3. Move the term references to terms that are now in **Vocabulary B** in the **Term reference** to **Vocabulary A** to the new **term reference** for **Vocabulary B**. \[No idea how to do this except a lot of manual work.\]

Any ideas about how to go about step 3?

# Answer
This tutorial suggests doing it via directly performing SQL queries to change the associated vocabularies for the terms in question.

The term reference fields should be by term ID. The term ID should not be changing, only the vocabulary value associated with the term entity.
> 4 votes

# Answer
Did you try to move term to new vocabulary with Taxonomy Manager (with double tree)? Term references are to TID , when you move terms to another vocabulary TIDs are saved and are the same. So i think that this will work
> 2 votes

# Answer
I tried SQL queries, but in this case it turned out to be simpler to make a table using Views showing all content of type X and then listing the terms in Vocabulary A, checking for the terms that should be in Vocabulary B, and then opening a bunch of browser tabs and editing them manually.
> 0 votes

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


# Question
Title: Which hook is invoked when a user's roles are changed?
I am trying to set a custom role expiration date in a subscription website using Ubercart and Paypal. Role expiration date is set by the role expiry module when a user completes payment.

I am trying to achieve this by using `hook_user()`. Is there any other way to achieve this?

# Answer
There isn't any other hook to use, as it is evident from the code used from `user_multiple_role_edit()`.

```
  // The role name is not necessary as user_save() will reload the user
  // object, but some modules' hook_user() may look at this first.
  $role_name = db_result(db_query('SELECT name FROM {role} WHERE rid = %d', $rid));

  switch ($operation) {
    case 'add_role':
      foreach ($accounts as $uid) {
        $account = user_load(array('uid' => (int) $uid));
        // Skip adding the role to the user if they already have it.
        if ($account !== FALSE && !isset($account->roles[$rid])) {
          $roles = $account->roles + array($rid => $role_name);
          user_save($account, array('roles' => $roles));
        }
      }
      break;
    case 'remove_role':
      foreach ($accounts as $uid) {
        $account = user_load(array('uid' => (int) $uid));
        // Skip removing the role from the user if they already don't have it.
        if ($account !== FALSE && isset($account->roles[$rid])) {
          $roles = array_diff($account->roles, array($rid => $role_name));
          user_save($account, array('roles' => $roles));
        }
      }
      break;
  }

```

The only invoked hooks are the ones used by `user_save()`.
> 3 votes

---
Tags: 6, users
---


# Question
Title: Trying to get content type from a node entity
I'm trying to get the content type from a node entity.

The entity is being loaded as follows:

```
$synclist = entity_load_single('entity_synclist', $qid);

```

Now, how would I then get the content type? Would it be as simple as:

```
$contenttype = $synclist->type;

```

Or do I have to do some other Drupal magic?

# Answer
You're not loading a node there, you're loading an entity of type `entity_synclist`. Its bundle key *might* be `type`, but it depends on what's defined in the module's implementation of `hook_entity_info()`.

To be sure, you can get that information from the entity definition and use it to get the bundle like so:

```
$info = entity_get_info('entity_synclist');
$bundle_key = $info['entity keys']['bundle'];

$synclist = entity_load_single('entity_synclist', $qid);
$bundle = $synclist->$bundle_key;

```
> 4 votes

# Answer
If you are using the Devel module, you could do a `dpm($synclist)` in the code.

This will display the all the properties of the node entity. I think you are on the right track.

We just need to verify the type property is referred to as that.
> 0 votes

# Answer
Someone suggested here to use the bundle key from the entity into - this is just overdose for me.

Someone suggested to use devel - but this will display the node type only when you via the UI and not progrematiclly.

When using a node, or any other entity, when you know that the type the key you can use it as you suggested - just use the $node-\>type. Another thing you can use is the entity metadata wrapper which is a helpful tool - you can access field and properties the same way but it's also contain some good function:

$wrapper-\>getBundle() in order to get the type of the entity($node-\>type).

$wrapper-\>label() in order to get the title of the entity($node-\>title, $user-\>name).

$wrapper-\>getIdentifier() in order to get the ID of the entity($node-\>nid, $user-\>uid) and many other functions.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: How to sort feed aggregator's items in Views according to its category?
How to sort feed aggregator's items in Views according to its category? I have two category : infographics (category id = 1) and others (category id = 2). I want to show items from infographics first and then others, regardless the timestamp. Any idea?

# Answer
> 1 votes
I'm hoping you've answered the question by now but just in case, I'll answer it for anyone who comes looking for it.

(Drupal 7) If you only have two feed categories then after creating your aggregator view, add the "Aggregator Category: Category" field to your view. Make sure to check 'exclude from display' or it will show the category title in duplicates. Then, go up to your format settings of the view and add "Aggregator Category: Category" to "Grouping field Nr.1." This will sort and split your feed items into the different categories.

If you have several feed categories and only want to use two of them, you would add the filter "Aggregator Category: Category ID" with the values 1 and 2, or whatever the category ID is of the category you want. Then repeat the steps above.

---
Tags: views
---


title: How to direct add content in drupal?

text:
# Question
Title: How to direct add content in drupal?
Trying to look an answer for this but couldn't.

Default workflow of Drupal adding content is: "Add Content" \> Choose Content Type. Can I just make my website to do direct adding content without need to choose the content type in advance?

# Answer
You can add custom links that aim directly to your content type in the admin tool bar.

Take a look on this link: https://drupal.org/node/1664828
> 1 votes

---
Tags: 7
---


title: Non-core folders

text:
# Question
Title: Non-core folders
Unfortunately I inherited a directory structure that has additional non-core directories and files in the site root like so:

> includes/
>
> misc/
>
> modules/
>
> profiles/
>
> scripts/
>
> sites/
>
> themes/
>
> **non-core-directory/** (non-core dir, web access via http://domain.name/non-core-directory/index.html)
>
> **non-core-directory-2/** (non-core dir, web access via http://domain.name/non-core-directory-2/index.html)
>
> .gitignore
>
> .htaccess
>
> googlee30f06c3edhehe4d.html (non-core file)
>
> my-page.html (non-core file)
>
> ...other core files.

Is there a clever way to move those non-core directories and files into the sites/domain.name/files/ directory so that they are still accessible from the same URLs but leaving a clean directory structure?

# Answer
> 1 votes
The correct place for non-core directories in a Drupal site is below `sites/default/` (or `sites/subsite-name/` if you're site is a multi-site).

Provided you use Apache as a web-server, you can move them there and redirect incoming requests to the old location to the new location with Apache mod\_rewrite.

To do this, the lines below should be placed in the Apache host configuration file for your site (usually placed below `/etc` in the file system).

```
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule non-core-directory/(.*)$ http://example.org/sites/default/new-directory/$1
    RewriteRule non-core-directory-2/(.*)$ http://example.org/sites/default/new-directory-2/$1
    RewriteRule googlee30f06c3edhehe4d.html$ http://example.org/sites/default/googlee30f06c3edhehe4d.html
    RewriteRule my-page.html$ http://example.org/sites/default/my-page.html
</IfModule>

```

Replace `example.org` with your own domain.

This will automatically redirect any URL where the path starts with `non-core-directory/` or `on-core-directory-2/` and the two non-core files to an URL with the path indicated by the rule.

Remember to restart the Apache server after changing its configuration.

---
Tags: files
---


title: Confusion about files permission

text:
# Question
Title: Confusion about files permission
Accrding to drupal docs:

```
The following is an example file listing of a safe configuration showing two files in a site where uploaded files are stored in the "files" directory. In order to see the file permissions set for your setup, go to the command line and type: ls -al.

drwxrwx---  7 www-data    greg-group  4096 2008-01-18 11:02 files/
drwxr-x--- 32 greg-user   www-data    4096 2008-01-18 11:48 modules/
-rw-r-----  1 greg-user   www-data     873 2007-11-13 15:35 index.php

```

After running the shell given in the doc page,

```
#!/bin/bash
if [ $(id -u) != 0 ]; then
        printf "This script must be run as root.\n"
        exit 1
fi
drupal_path=${1%/}
drupal_user=${2}
httpd_group="${3:-www-data}"
# Help menu
print_help() {
cat <<-HELP
This script is used to fix permissions of a Drupal installation
you need to provide the following arguments:
1) Path to your Drupal installation.
2) Username of the user that you want to give files/directories ownership.
3) HTTPD group name (defaults to www-data for Apache).
Usage: (sudo) bash ${0##*/} --drupal_path=PATH --drupal_user=USER --httpd_group=GROUP
Example: (sudo) bash ${0##*/} --drupal_path=/usr/local/apache2/htdocs --drupal_user=john --httpd_group=www-data
HELP
exit 0
}
# Parse Command Line Arguments
while [ $# -gt 0 ]; do
        case "$1" in
                --drupal_path=*)
            drupal_path="${1#*=}"
            ;;
        --drupal_user=*)
            drupal_user="${1#*=}"
            ;;
        --httpd_group=*)
            httpd_group="${1#*=}"
            ;;
        --help) print_help;;
        *)
            printf "Invalid argument, run --help for valid arguments.\n";
            exit 1
    esac
    shift
done
if [ -z "${drupal_path}" ] || [ ! -d "${drupal_path}/sites" ] || [ ! -f "${drupal_path}/core/modules/system/system.module" ] && [ ! -f "${drupal_path}/modules/system/system.module" ]; then
    printf "Please provide a valid Drupal path.\n"
    print_help
    exit 1
fi
if [ -z "${drupal_user}" ] || [ $(id -un ${drupal_user} 2> /dev/null) != "${drupal_user}" ]; then
    printf "Please provide a valid user.\n"
    print_help
    exit 1
fi
cd $drupal_path
printf "Changing ownership of all contents of "${drupal_path}":\n user => "${drupal_user}" \t group => "${httpd_group}"\n"
chown -R ${drupal_user}:${httpd_group} .
printf "Changing permissions of all directories inside "${drupal_path}" to "rwxr-x---"...\n"
find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;
printf "Changing permissions of all files inside "${drupal_path}" to "rw-r-----"...\n"
find . -type f -exec chmod u=rw,g=r,o= '{}' \;
printf "Changing permissions of "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
cd sites
find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
printf "Changing permissions of all files inside all "files" directories in "${drupal_path}/sites" to "rw-rw----"...\n"
printf "Changing permissions of all directories inside all "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
for x in ./*/files; do
    find ${x} -type d -exec chmod ug=rwx,o= '{}' \;
    find ${x} -type f -exec chmod ug=rw,o= '{}' \;
done
echo "Done settings proper permissions on files and directories"

```

bash fix-permissions.sh --drupal\_path=your/drupal/path --drupal\_user=greg

After running the above script, the Security review module still warns me that:

```
Some files and directories in your install are writable by the server.

```

Ironically the doc page also links to the security review module for double check:

> As a quick test to confirm whether your site is secure or not you can run the Security Review module.

Does this mean that there is something wrong in the script? or in the security review module alert if false? Or simply there is no consensus in Drupal community about the files permission? Too bad, if it is so.

This can be a huge security hole when the permission to the uploaded files are not set properly. So I am wondering what is the proper permissions for files for a fairly paranoid setup?

Also, should greg be member of www-data group?

# Answer
> 1 votes
Your example permissions (as listed near the befinning of your question) are fine. The Drupal docs page you link to is correct and reflects IMHO the consensus of the communty. The script you're using reflects this consensus.

I'd say that this is a false postive from Security Review. It also appears that this bug has been reported to the module's issue queue.

As stated on the Drupal docs page: All you need to know to review this yourself is that it is *only* `files/` and the directories and files below it that shall be writeable by the server. So if the character `w`show up in anything owned by `www-data` or the `www-data` group on your site (letter 3 in the permission string is the setting for the `www-data` user, and letter 6 is the the setting for the `www-data` group) - then the site is not secure.

While it may appear insecure that `files/`, its subdirectories and uploaded files are writeable by the server, this is not the case. Drupal itself and the way Drupal sets up the web server (by means of `.htaccess`, etc. ) prevents code (shell scripts, php, etc.) that an attacker may upload (disguising it as an JPEG or other "allowed" upload file types) from being excuted. Drupal has built-in management of uploaded files that ensures, for instance, that file attachements is deleted when the node they're attached to is deleted. For this to work, the upload directory (e.g. `files/`) and the files it contain must be writeable by the server.

Also: `greg` should not be a member of the `www-data` group.

---
Tags: 6, security, files
---


title: Custom Entity Page not Found

text:
# Question
Title: Custom Entity Page not Found
I am actualy trying to implement my first own entity using this tutorial:

http://www.istos.it/en/blog/drupal-entities/drupal-entities-part-3-programming-hello-drupal-entity

So far anything worked fine, but now i ran in some problem I couldn't get fixed. After creating my new entity, I get redirected to the page "slider/(id)". But it says that the page could not be found. When I try to open the URL manualy I get the same error.

Here is my code: he\_slider.module

```
/**
    * Implements hook_entitiy_info()
    */

function he_slider_entity_info(){
    $slider_info['slider'] = array(
        'label' => t('Slider Item'),
        'controller class' => 'SliderController',
        'views controller class' => 'EntityDefaultViewsController',
        'base table' => 'slider',
        'uri callback' => 'he_slider_uri',
        'fieldable' => TRUE,
        'entity keys' => array(
            'id' => 'sid',
        ),
        'static cache' => TRUE,
        'bundles' => array(
            'slider'=> array(
                'label' => 'Slider',
                'admin' => array(
                    'path' => 'admin/structure/slider/manage',
                    'access arguments' => array('administer slider'),
                ),
            ),
        ),
        'view modes' => array(
            'full' => array(
                'label' => t('Full Slider Item'),
                'custom settings' =>  FALSE,
            ),
        )
    );

    return $slider_info;
}

/**
    * URI Callback function
    */

function he_slider_uri($slider){
    return array(
        'path' => 'slider/' . $slider->id,
    );
}

/**
    *  Load the a single or multiple entities
    */

function he_slider_load($sid = NULL, $reset = FALSE){
    $sids = (isset ($sid) ? array($sid) : array());
    $slider = slider_load_multiple($sids, $reset);
    return $slider? reset ($slider) : FALSE;
}

function he_slider_load_multiple($sids = array(), $conditions = array(), $reset = FALSE){
    return entity_load('slider', $sids, $conditions, $reset);
}

/**
    * Provides the Pages to administer and view the entities
    */

function he_slider_menu(){
    $items['admin/content/slider/add'] = array(
        'title' => 'Add Slider Item',
        'page callback' => 'he_slider_add',
        'access arguments' => array('create slideritem'),
    );
    $items['admin/structure/slider/manage'] = array(
        'title' => 'Slider Administration',
        'description' => 'Manage Slider Structure',
        'page callback' => 'he_slider_info',
        'access arguments' => array('administer slideritem'),
    );
    $items['slider/%slider'] = array(
        'title callback' => 'he_slider_page_title',
        'title arguments' => array(1),
        'page callback' => 'he_slider_page_view',
        'page arguments' => array(1),
        'access arguments' => array('view slideritem'),
        'type' => MENU_CALLBACK,
    );
    $items['slider/%slider/edit'] = array(
        'title' => 'Slider Edit',
        'title arguments' => array(1),
        'page callback' => 'he_slider_page_edit',
        'page arguments' => array(1),
         'access arguments' => array('edit slideritem'),
        'type' => MENU_CALLBACK,
    );
    $items['admin/content/slider/add'] = array(
        'title' => 'Add Slider Item!',
        'page callback' => 'he_slider_add',
        'access arguments' => array('create slideritem'),
    );
    return $items;
}

function he_slider_permission(){
        return array(
        'administer slideritem' =>  array(
            'title' => t('Administer Slider'),
            'restrict access' => TRUE,
        ),
        'view slideritem' => array(
            'title' => t('View Slideritems'),
        ),
        'edit slideritem' => array(
            'title' => t('Edit Slideritems'),
        )
    );
}

function he_slider_info() {
    return ('Welcome to the administration page for your Slideritems!');
}

function he_slider_page_title($slider){
    return $slider->sid;
}

function he_slider_page_view($slider, $view_mode = 'full'){
    $slider->content = array();

    // Build fields content.
    field_attach_prepare_view('slider', array($slider->sid => $slider), $view_mode);
    entity_prepare_view('slider', array($slider->sid => $slider));
    $slider->content += field_attach_view('slider', $slider, $view_mode);

    return $slider->content;
}

function he_slider_field_extra_fields() {
    $return = array();
    $return['slider']['slider'] = array(
        'form' => array(
            'title' => array(
                'label' => t('Title'),
                'description' => t('Slider Title'),
            ),
        ),
    );

    return $return;
}

/**
    * Implements the slider add form, where we are able to create our new entities
    */

function he_slider_add() {
    $slider = (object) array (
        'sid' => '',
        'type' => 'slider',
        'title' => '',
    );

    return drupal_get_form('he_slider_add_form', $slider);
}

function he_slider_add_form($form, &$form_state, $slider) {
    $form['title'] = array(
        '#type' => 'textfield',
        '#title' => t('Note'),
        '#required' => TRUE,
    );

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

    field_attach_form('slider', $slider, $form, $form_state);

    return $form;
}

/**
    * Implements the Entitiy Edit form
    */

function he_slider_page_edit($slider) {
    return drupal_get_form('he_slider_add_form', $slider);
}

/**
    * Validates the Entity Add form
    */

function he_slider_add_form_validate($form, &$form_state) {
    $slider_submission = (object) $form_state['values'];
    field_attach_form_validate('slider', $slider_submission, $form, $form_state);
}

function he_slider_add_form_submit($form, &$form_state) {
    $slider_submission = (object) $form_state['values'];
    field_attach_submit('slider', $slider_submission, $form, $form_state);
    $slider = he_slider_save($slider_submission);
    $form_state['redirect'] = "slider/$slider->sid";
}

function he_slider_save(&$slider) {
    return entity_get_controller('slider')->save($slider);
}

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

/**
* Implements hook_form_alter().
*/
function he_slider_form_alter(&$form, &$form_state, $form_id) {
    if($form_id=='_slider_add_form'){
        $form['submit']['#weight'] = 99;
    }
}

```

he\_slider.controller.inc:

```
class SliderController extends DrupalDefaultEntityController {
    public function save($slider) {
        drupal_write_record('slider', $slider);
        field_attach_insert('slider', $slider);
        module_invoke_all('entity_insert', $slider, 'slider');
        return $slider;
    }
}

```

# Answer
> 0 votes
Got help on stackoverflow.com

Quote from Clive:

The problem is here:

```
$items['slider/%slider'] = array(

```

Drupal's menu system will look for a function named `slider_load()`, whereas your entity load function is named `he_slider_load()`. This causes the router to bail out and throw a 404.

To fix it, simply change that line to

```
$items['slider/%he_slider'] = array(

```

And clear your caches.

---
Tags: entities
---


title: Services 3 and Node Reference

text:
# Question
Title: Services 3 and Node Reference
I am working with the module services 3 (D7) and I am calling the Drupal method from a Java client. I can login (and keep the session in the cookie) and I can create a simple node.

But I can't set a Node Reference Field.

To find the way to do it, I first looked to the node structure (with the reference field) in my drupal site:

```
 [field_presta_presta_suivi] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [nid] => 43
                    )

            )

    )

```

So, in my Java Client, I created a function to reproduce this structure:

```
public  static HashMap addReferenceField(String field, String language, String type_ref,Object value, HashMap node, int delta ){
        HashMap f = new HashMap();
        HashMap p = new HashMap();
        Object[] i = new Object[delta+1];
        HashMap val = new HashMap();

        val.put(type_ref, value);
        i[delta] = val;
        p.put(language, i);
        f.put(field, p);
        return f;
    }

```

This function is used to create a HashMap that will be add to the parameter of the service 'node.create'.

This function works with a User Refence Field (which has the same node struture), but when I used it for a node reference, the server returned "Not Acceptable".

I have already passed a lot of time on it and didn't find any example or similar case, so here my question:

How to you use services 3 (D7) to create a node with a node reference field ?

# Answer
> 2 votes
The default resources of Services are all fairly broken, because they rely on simulating an actual form submission (*blah!*). I recommend using those provided by Services Entity instead.

# Answer
> 0 votes
No need to go for an another module, following json structure will help you to create node reference field,

```
"field_specialization":
{
  "und":
       {
         "value":"10"
       }
}

```

---
Tags: 7, services
---


title: How to Limit Node Revisions

text:
# Question
Title: How to Limit Node Revisions
I added the diff module that keeps all node Revisions (it seems that I can't limit the number of Revisions to keep). Is there a code I can use where I can set a limit of the number of Revisions to keep? If so, where to add it?

# Answer
You can use the Node Revision Restrict module for this.

> The Node Revision Restrict module allows you to restrict revisions of node for each content type. This module has an admin interface to specify node revision threshold for each content type available. The possible settings include node type, the number of count provided on configuration form for each content type and more. Users with specific permissions can delete any unwanted revisions. Note that this module does not and cannot delete the current revisions of a node.

You could either use the module, or incorporate some of its code. It is a short module. Most of the code relevant to your task can be found in the node\_revision\_restrict\_node\_presave function:

```
/**
 * Implements of hook_presave().
 */
function node_revision_restrict_node_presave($node) {
  $node_type = $node->type;
  $nid = $node->nid;
  $node_data = db_query('SELECT * FROM {node} WHERE nid = :nid', array(':nid' => $nid));
  foreach ($node_data as $node) {
    $revision_data = node_revision_list($node);
    foreach ($revision_data as $revision) {
      $revision_ids[] = $revision->vid;
    }
    $count_to_restrict_set_value = variable_get('restrict_node_revision_number_for_' . $node_type);
    if (isset($count_to_restrict_set_value)) {
      $node_to_restrict = array_slice($revision_ids, $count_to_restrict_set_value, count($revision_ids));
      foreach ($node_to_restrict as $revision_id) {
        node_revision_delete($revision_id);
      }
    }
  }
}

```

In general, I prefer using a contributed module, if it provides the functionality needed, over maintaining my own code, because I won't have to worry as much about security updates, and other debugging issues, down the road.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Service module costume response after creating node
I want to get costume return from services module after creating a node. I would like to checks if the there is a similar title, and if so, to return the number of times it exists. (Services 3 / Drupal 7) What is the way to do this?

# Answer
> 0 votes
You have following hook to do the response modifications,

```
function hook_services_request_postprocess_alter($controller, $args, &$result) {

}

```

---
Tags: services
---


# Question
Title: Create a field to type in name of body class
I want to create a field where I can put in what will be a class on the body of the node that I'm creating. The picture below depicts my local and live environments:

How can I do this?

# Answer
> 2 votes
So, I found a module which did just what I wanted. If anyone else are looking for an answer to my question, you can check out this module: https://drupal.org/project/field\_formatter\_css\_class

It allows you to enter a class name from the editing page. You can select if you want the class to be appended to the body, node etc.

# Answer
> 2 votes
Johan, if the only thing out of sync between your live and local environments are the node nids, you can do this with css like so:

```
/* this will target both and will work on both environments if the other nid
   does not exist in the other environment */

.node-page-1521,
.node-page-1497 {
  /* whatever CSS you need here */
}

```

as Drupal puts the class `node-page-NID` in the body of each page created for a specific node. If the "other nid" exists in the local or live site, then you will have to get a bit fancier, but this does show that Drupal can target specific node pages.

Another way would be to use hook\_preprocess\_html() a custom module or theme, eg, something along the lines of:

```
function YOURMODULE_OR_THEME_preprocess_html(&$variables) {

  if (isset($variables['node']) && $variables['node']->nid == THE_NID_YOU_WANT) {
    $variables['classes_array'][]='SPECIAL_CLASS';
  }

}

```

Just realize the above snippet is dull ax; eg, you would probably want to do something better than just hard coding a nid in there, eg storing it in a variable specific to the machine (look into variable\_get() and creating an admin form for your theme/module).

If it is something else, eg, you want to have a field that allows the user to somehow specify something special in the display about this (and other similar nodes), you can certainly do that as well above, eg, look at that field instead of the nid and then add a class if it has a certain value.

# Answer
> 0 votes
Even if this was possible, it is not good practice. Use your CSS files to add styles to nodes. If you inspect the DOM elements of your node, you will see there are plenty of ways to single out the body without the use of your suggestion.

---
Tags: views, theming
---


# Question
Title: How to sort the language detection methods
In a two languages Drupal 7 site, I am using the following order of language detection methods:

* URL
* Session
* User
* Browser
* Default

With this order, every time I visit the site as an anonymous user it comes in the default language.

Instead I would like to:

* display the default language in the first visit.
* if a language selection is made, display that language in the next visit

Is there a way to achieve this?

# Answer
Well I think you are doing just fine, and don't get obsessive over this, it's ok!

the URL thing is the most important and should be always on top, I think session should be second since it can be generated via a request or parameter.

User I'm not sure since mostly users don't pay attention about their language preferences while registering on a webiste.

past these steps the rest doesn't really matter that much, but I'd put Browser the last one since it seems it can vary quite easy with plugins/extensions.
> 1 votes

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


title: Show menu on specific page

text:
# Question
Title: Show menu on specific page
I created a menu with one specific menu entry. I want to show the menu only on one page.

Does exist a module which places a menu like a block?

# Answer
> 1 votes
Yes, the aptly named Menu Block module.

> ...provides configurable blocks of menu trees starting with any level of any menu.

---
Tags: 7
---


# Question
Title: How to change a filter handler of the view?
I have created a nice Filter Handler for my View, and I set it up using `hook_views_data_alter`.

Does this mean that this will ALWAYS be the Filter Handler for this particular field? What if I want a different Filter Handler later, in a different view?

How can I specifically say "Only use the X handler on page X?"

For posterity, I thought I'd outline more of what I was trying to accomplish here:

I have "Friends" page and a "Content" page. On the "Content" page, I wanted to be able to filter by "Content posted by my friends." However, on the "Friends" page I want to filter by "Users in my Groups." Both of these query on the `user.uid` field, so it was making the filters the same, even though I wanted totally different logic for the two views.

# Answer
Nope currently there is no explicit way to achieve it. However there is an workaround.

1. Using hook\_views\_data\_alter make your custom handler as the filter instead of existing one(You already did that)
2. In your custom filter handler, add a new option to select which filter operation it needs to perform(whether normal one or custom one), Eventually a yes/no field.

Below is the example on adding extra options to the filter handler,

```
    function option_definition() {
      $options = parent::option_definition();

      $options['custom_filtering'] = array('default' => 0);

      return $options;
    }

    function extra_options_form(&$form, &$form_state) {
      parent::extra_options_form($form, $form_state);

      $form['custom_filtering'] = array(
        '#type' => 'checkbox',
        '#title' => t('Custom Filtering'),
        '#default_value' => $this->options['custom_filtering'],
        '#description' => t('Check this if you want to perform the custom filtering on this field instead of a regular filtering mechanism'),
      );
    }

```

3.Based on the above option do your filter mechanism like below,

```
function query() {
    // Do Custom filtering based on the option selected.
    if ($this->options['custom_filtering']) {
      // Do your custom filtering.
    }
    else {
      // Do regular filtering.
    }
  }

```

Now when you're adding the filter for this field, you can just select which filtering it needs to perform.

Edit by OP (I don't even know how I have the rights to do this): You must additionally implement the following:

```
function has_extra_options() { return TRUE; }

```

And then your extra options will be displayed!
> 1 votes

# Answer
I always take the following approach: Copy the existing views\_data code via php:

```
// Copy the existing definition.
$data['table']['field_special'] = $data['table']['field'];
// Force the real field, so views still consider it as a different field in SQL.
$data['table']['field_special']['real field'] = 'field';
// Set a special handler.
$data['table']['field_special']['field']['handler'] = 'foo_handler_field_...';

```

This allows you to easy reuse the custom handler if needed, but at the same time not conflict with existing views.

In contrast to the approach of berliner (which certainly works) this does not add any runtime code execution, which adds potential bugs. This approach just uses basically configuration.
> 1 votes

---
Tags: views
---


title: Sessions Table Getting Huge

text:
# Question
Title: Sessions Table Getting Huge
Currently, my sessions table is 1.6gb with 3,956,161 total rows. I think the sessions does not expired. I have a default settings in my settings.php as follows:

```
ini_set('arg_separator.output',     '&');
ini_set('magic_quotes_runtime',     0);
ini_set('magic_quotes_sybase',      0);
ini_set('session.cache_expire',     200000);
ini_set('session.cache_limiter',    'none');
ini_set('session.cookie_lifetime',  2000000);
ini_set('session.gc_maxlifetime',   200000);
ini_set('session.save_handler',     'user');
ini_set('session.use_only_cookies', 1);
ini_set('session.use_trans_sid',    0);
ini_set('url_rewriter.tags',        '');

```

is the variable above related to sessions table? If yes, what is the recommended settings to expire the session after 2 days?

Update:

I just found that this is due to OS limitation of ubuntu which I am currently using. This was explain at this drupal module: https://drupal.org/project/session\_expire

The problem is, Session Expire module is still in alpha release.

Is there any other module that can do this same?

# Answer
> 4 votes
While waiting for an answer, I found the solution at this blog.

All you need to do is to edit the settings.php under /sites/default folder.

Here are the two variables that need to be set:

```
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

```

Be sure to change also the cache expiry of the following variable according to your needs:

```
ini_set('session.cache_expire',     3600);
ini_set('session.cookie_lifetime',  3600);
ini_set('session.gc_maxlifetime',   3600);

```

The default is 200000. 3600 is equavalent to 1 hour.

---
Tags: 7, sessions
---


# Question
Title: How to use views taxonomy contextual filters with menu tabs?
I have a CT (let's call it Article) with a Status taxonomy field (let's say with values Open, Closed and Cancelled) and I want a **view of Articles with menu tabs for each status** value. And I would like to have it work **with contextual filters on Status** term name.

The **URLs** of the tabs should be like **articles/open**, **articles/closed** etc but the last argument should act also as the contextual filter value. I cannot make it work since drupal takes articles/open as part of the url and I should type articles/open/open to have it use the argument.

Is it possible to be implemented with contextual filters somehow? I would like to **avoid** hidden filter criteria with **taxonomy term value preselected**, as I want to track it with features and I do not want the id of the preselected taxonomy term tracked.

# Answer
I managed to resolve the above problem with the following configuration:

I created the *contextual filter* on taxonomy term field and in the filter settings section **When the filter value is NOT in the URL** I selected **Provide default value** and **Raw value from URL** with Path Component 2 and the option Use path alias checked.

In the filter settings section **When the filter value IS in the URL or a default is provided** I selected the appropriate vocabulary and for Filter value type **Term name converted to term ID**.
> 0 votes

---
Tags: views, routes
---


title: Page template for custom form

text:
# Question
Title: Page template for custom form
I'm trying to create a new page template for a custom form I'm building in my module. My goal is to use create something like a new `page.tpl.php` for this specific form and it looks like this method is creating the equivalent of a custom `node.tpl.php` within the content area of my site instead of generating a separate page template.

**For example**

```
/*
 * Implements hook_menu
 */
function mymodule_menu() {
  $items = array();
  $items['foo/my_custom_form'] = array(
    'title' => 'My custom form',
    'page callback' => 'mymodule_custom_page',
    'access callback' => TRUE, // Everyone has access.
  );
  return $items;
}

function mymodule_custom_page(){
  return theme('mymodule_template');
  return drupal_get_form('mymodule_form');
}

/*
 * Implements Hook_theme
 */
function mymodule_theme() {
  return array(
    'mymodule_template' => array(
      'template' => 'custompage', // template file called custompage.tpl.php
      'arguments' => array(),
    ),
  );
}

function mymodule_form($node, &$form_state){
//my form in here
}

```

I'm having an issue with the form not appearing.

Maybe I'm going down the wrong path and should be trying to create function in my theme's `template.php`, and then use a `hook_preprocess_page` to set some variables to create a `page--custom.tpl.php` for my form?

I can achieve what I'm trying to do by making some configuration changes to some blocks and redrawing the content area with CSS, but not sure if that's the best practice.

# Answer
> 1 votes
Here is your issue, your can't return twice in a function.

```
function mymodule_custom_page(){
  return theme('mymodule_template');
  return drupal_get_form('mymodule_form');
}

```

What you need to do is just the first line, `return theme('mymodule_template');` You also need to change your form function parameters to `&$form, &$form_state`.

Then, in your `custompage.tpl.php`, you do the `drupal_get_form('mymodule_form');`

**Result:**

```
/*
* Implements hook_menu
*/

function mymodule_menu() {
  $items = array();
  $items['foo/my_custom_form'] = array(
    'title' => 'My custom form',
    'page callback' => 'mymodule_custom_page',
    'access callback' => TRUE, // Everyone has access.
  );
  return $items;
}

function mymodule_custom_page(){
  return theme('mymodule_template');
}

/*
* Implements Hook_theme
*/

function mymodule_theme() {
  return array(
    'mymodule_template' => array(
      'template' => 'custompage', // template file called custompage.tpl.php
      'arguments' => array(),
    ),
  );
}

function mymodule_form(&$form, &$form_state){
  //my form in here
}

```

And in **custompage.tpl.php:**

```
print drupal_get_form('mymodule_form');

```

# Answer
> 0 votes
IF the page you want to theme differently is going to be on the path `foo/mycustomform`, you can use Drupal's built in template suggestions and "just" create a `page--foo--mycustomform.tpl.php` (D7) or `page-foo-mycustomform.tpl.php` (D6) file and put it along with any other templates in your theme's directory.

Clear your caches and you should be on your way.

More information about template suggestions are available for D7 here: http://drupal.org/node/1089656 and D6 here: http://drupal.org/node/1089642 but basically Drupal will recognize page-PATH template suggestions.

---
Tags: 7, theming
---


# Question
Title: Alter Views query limit using views_query_alter
I want to alter the limit of view using `views_query_alter` hook.

My code is :

```
function track_click_views_query_alter(&$view, &$query) {
  if($view->name == "click_list_days"){
  $w_count = count($query->where[0]['clauses']) - 1;
  $w_clause = array();
  for($i=0; $i <= $w_count; $i++) {
      $w_clause[] = "(".$query->where[0]['clauses'][$i].")";
      if($i > 0)
          unset ($query->where[0]['clauses'][$i]);
  }
  $w_clause = implode(" AND ", $w_clause)." Group By track_click.article_title ";
  $query->where[0]['clauses'][0] = $w_clause;
  }
}

```

How can I alter the limit of this views query? I didn't understand which query object i have to alter.

# Answer
> 3 votes
If it's only about the number of results to return, I think you could simply implement hook\_views\_pre\_build() and do the following:

```
function track_click_views_pre_build(&$view) {
  if ($view->name == 'click_list_days') {
    $view->set_items_per_page(YOUR_NUMBER_OF_RESULTS_HERE);
  }
}

```

Or inside `hook_views_query_alter()` you should be able to do:

```
$query->set_limit(LIMIT);

```

---
Tags: views
---


title: Set up login to open a specific view

text:
# Question
Title: Set up login to open a specific view
I created a page view where user only get articles to edit.

How can I set up the page that it opened when a user logged in?

# Answer
You are looking for functionality that is available in some ready modules. Login Destination looks like a solid bet:

> The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them.

Seems to be exactly what you need.
> 1 votes

# Answer
The Front Page module will also handle this. You can specify one page for anonymous user role and another page for authenticated user role so they get directed to that page after login.

You can also use Rules by specifying an Event of "User has logged in" then doing a "Page redirect" in the Actions.
> 0 votes

---
Tags: users
---


# Question
Title: User rights: Only create, edit and publish articles
There is a user role where users can edit, save and publish articles. But they don't see the admin menu.

Does exist a module to realize a "create content" button only or to modify the admin menu?

# Answer
There is no specific module for that, and it is well known problem. But if you want them to only create one content type, like Article, you don't need a module for that. You can simply go to */admin/structure/menu* and add links like */node/add/page* to a menu they can access.

For node listings for such users, create a view with table of titles and edit links.
> 0 votes

# Answer
If you're looking to use a specific role for content creation but do not want them to get into any of the administration areas, I'd recommend the Workbench module. Create a new role called something like "Content Moderator" then in Workbench you can specify which content types they can add, edit, delete, and publish.
> 0 votes

---
Tags: 7
---


# Question
Title: I have some difficulties with page.tpl.php
I've created a `page.tpl.php` for my website. it must only contain some blocks not the the `$content`. that's why I created a few blocks attached them to their region and embedded their corresponding views using `print views_embed_view("VIEW_NAME","DISPLAY");` this `page.tpl.php` works but it has some problems.

when I create a node, after redirecting to its page it only displays this `page.tpl.php` while the address bar is node address, I mean `page.tpl.php` overrides node pages. the same problem persists for page display of views. I set a path for page display of views but by going there it again displays `page.tpl.php` . what is wrong with it?

# Answer
> 2 votes
> I mean page.tpl.php overrides node pages

That isn't true, I just think you haven't quite understood how templates work in Drupal. The hierarchy for templates is:

```
html.tpl.php
  page.tpl.php
    Everything else (including node.tpl.php)

```

So as you can see, node.tpl.php is *inside* page.tpl.php, it's not a replacement for it, nor does it override it. But since you're not outputting the main content block in that template file, it stands to reason that the page content will be empty. Unless otherwise specified by perprocessing/template suggestions, page.tpl.php will be used for **every single page**.

You also need to know that everything (including the main content) is a block, which must be put in a region in page.tpl.php to be displayed. You would typically find the `main_content` block in the `content` (or similarly named) region.

To fix your problem, you need to add the main content region back into page.tpl.php.

# Answer
> 0 votes
If you override `page.tpl.php`, your other page will be overriden too. If you want to override specific page, consult Drupal 7 Template (Theme Hook) Suggestions.

In your case, you can:

* Create `page--node.tpl.php` for every page node.
* Or, create `page--internal/path.tpl.php` for specific page which its path is `internal/path`.

---
Tags: nodes, theming, 7
---


# Question
Title: Edit Content with out seeing the information in text box
Let me explain this. Lets say you have a form that you fill out to create a record.

In order to fill this form out you have to be registered and signed in. Any one can sign up.

This form includes couple peoples addresses and names.

Now any one can go and edit the form where they can see the info on the form.

The problem is that when the form is filled out the first time or edited there is some fields that have personal information and i dont want public to see this data.

Does any one have idea how i can hide the information but have the info available to be updated if needed.

I was thinking using password type but it hides all of it.

Or maybe hiding part of the text ?

I have no idea how to go about this. If any one that reads this has any idea please let me know.

Thanks in advance.

# Answer
You can use the Field Permissions module to enable create/edit/view permissions per role. So you can remove the view permission on those fields you want to hide for all roles but the admin role. That way authenticated users cannot view or edit the fields but the admin can.
> 1 votes

---
Tags: forms
---


# Question
Title: Add a "Like" button after "Edit" and "Reply" links
How can I add a *Like* link using the Flag Module, exactly after the *Edit* and the *Reply* links?

I know I must use `print flag_create_link('bookmarks', $node->nid);`, but I don't know exactly where to place it.

# Answer
Implement `hook_node_view()` in a custom module that you create.

```
$node->content['links'][] = array(
  '#markup' => flag_create_link('bookmarks', $node->nid),
);

```

Or use the function `MY_THEME_preprocess_node()` in your template.php and add:

```
function MY_THEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['content']['links'][] = flag_create_link('bookmarks', $node->nid);
}

```

Replace MY\_THEME with the name of your theme. Some reading that might help you: http://www.whenwhowhere.com/tech-blog/add-variable-theme-template-files-drupal-7
> 0 votes

---
Tags: theming, flags
---


# Question
Title: Conditionally aggregate (count) views field
I have a very simple view of content filtered by content type. Multiple content types are selected. For example, I am listing the latest contents of type Event, Forum topic, and Article. I am using Views Ticker display for this view.

Now I got a new request. Since there are so many articles being published (they are synced from an external publishers), the view should only show the amount of the articles, but it should still list other content types individually. An example output should look somewhat like that:

* Forum topic: Lorem ipsum
* Forum topic: Dolor amet
* New 26 articles
* Event: Meeting
* Forum topic: XYZ

How can I aggregate only for one content type in views? Can I use some view hooks to achieve that? Like `hook_views_pre_render()`, etc?

Since I am using Views Ticker as display plugin, I cannot simply add them to footer or header.

# Answer
> 1 votes
I have a feeling there may be a solution using a separate view with aggregation and then using the Views Field View module to embed the aggregated view as a field.

Another option (which feels like a bit of a cop-out and cheating) would be to create a content type called "articles count".

Then each time you do a sync with the external publisher you update the "articles count" node title to be "New \[count\] articles", and set the body to be a list of links to each of the new articles. This is neat as you always have an index to your new articles.

Then simply include this as one of your content types in the original view. To be honest this is probably the easiest way.

---
Tags: 7, views, hooks
---


title: PDO - Duplicate entry on file upload

text:
# Question
Title: PDO - Duplicate entry on file upload
I'm developing a module that uploads CSV file.

```
/**
 * Implements hook_menu().
 */
function geo_points_menu(){
    $items['geo-points-upload'] = array(
        'title' => 'Geo points',
        'description' => 'Upload users',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('geo_points_form'),
        'access arguments' => array('access content'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
        'menu_name' => 'main-menu',
    );

    return $items;
}

function geo_points_form($form, &$form_state) {
    $form = array();

    // Use the #managed_file FAPI element to upload a file.
    $form['file_fid'] = array(
        '#title' => t('File'),
        '#type' => 'managed_file',
        '#description' => t('The uploaded file will be processed.'),
        '#default_value' => variable_get('file_fid', ''),
        '#upload_validators' => array(
            'file_validate_extensions' => array('csv'),
        ),
        '#upload_location' => 'public://csv_uploads',
        '#process' => array('geo_points_my_file_element_process')
    );

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

    return $form;
}

/* It disables the default upload button that comes with this #managed_file form */
function geo_points_my_file_element_process($element, &$form_state, $form) {
    $element = file_managed_file_process($element, $form_state, $form);
    $element['upload_button']['#access'] = FALSE;

    return $element;
}

function geo_points_form_submit(&$form, &$form_state) {
    // Load the file.
    $file = file_load($form_state['values']['file_fid']);
    dpm(csv_to_array($file->uri));
    file_usage_delete($file, 'geo_points');
//    // Change status to permanent.
//    $file->status = FILE_STATUS_PERMANENT;
//    // Save.
//    $uploaded = file_save($file);
//    if ($uploaded == TRUE) {
//        dpm(csv_to_array($file->uri));
//    }
//    else {
//        drupal_set_message(t('The file could not be uploaded. Please contact the site administrator.'), 'error');
//    }

    //$file_path = $file->uri;

    //Function call to process file contents.
    //csv_import_create_node($file_path);

}

/**
 * @param string $filename
 * @param string $delimiter
 * @return array|bool
 */
function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

```

When I upload the same file more than one time I'm getting the following exception:

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'public://csv_uploads/points2014-01-16T14-22-48.csv' for key 'uri': INSERT INTO {file_managed} (uid, filename, uri, filemime, filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => points2014-01-16T14-22-48.csv [:db_insert_placeholder_2] => public://csv_uploads/points2014-01-16T14-22-48.csv [:db_insert_placeholder_3] => text/csv [:db_insert_placeholder_4] => 84 [:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] => 1390315536 ) in drupal_write_record() (line 7170 of C:\wamp\www\drupal7_poc2\includes\common.inc).

```

I have 2 questions:
1. How avoid this exception. 2. After I upload the file and read it's content I don't the file anymore, can I read the stream only without saving the file?

# Answer
> 1 votes
1. Use a try...catch block and recover in whatever way makes most sense to your application.
2. The file is already on the disk by the time you get access to it (in the /tmp folder), so no. If you don't explicitly choose to keep it, it will be deleted either by a system job or the system module's cron run.

---
Tags: 7, files
---


# Question
Title: how to theme select box drupal for css framework
I am making a theme using semantic ui framework in drupal. I want to apply semantic ui select box effect to my theme but i was not able to do this. Here is the link for semantic ui select box http://semantic-ui.com/collections/form.html.

They used this for markup select box.

```
<div class="ui selection dropdown" style="display: inline-block;">
      <input type="hidden" name="gender">
      <div class="default text">Gender</div>
      <i class="dropdown icon"></i>
      <div class="menu ui transition hidden">
        <div class="item" data-value="male">Male</div>
        <div class="item" data-value="female">Female</div>
      </div>
</div>

```

But the standard markup for select box is:

```
<select id="edit-date-month" name="date[month]" class="form-select">
<option value="1" selected="selected">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
</select>

```

How can i apply semantic ui select effect to my drupal theme. Any help would be appreciated.

# Answer
You need to override `theme_select()`, which you can do in your theme's template.php file:

```
function MYTHEME_select($vars) {
  // Your code to produce the markup you need. You can find all pertinent data in $vars.
  // The original form element is at $vars['element'], so the options array is at
  // $vars['element']['#options'].
}

```
> 2 votes

---
Tags: theming
---


title: combine 2 additional_settings fieldset

text:
# Question
Title: combine 2 additional_settings fieldset
I want to combine 2 fieldset that group in **additional\_settings**.

I have 2 group added by some modules, I want combine them one of it is

and another

I did combine 2 field, as author and path ... ( deafult field ) but here I have 2 fieldset. how can I merge them in one fieldset group?

I test this but they didnt combined correctly

`in form_alter`

```
    $circle=$form['user_relationship_circles_node_access'][1];
    unset($form['user_relationship_circles_node_access']);
    $circle['#group'] = '';
    $circle['#collapsible'] = FALSE;
    $circle['#element_validate'][] = 'MY_MODULE_path_form_element_validate';
    $circle['#element_validate'] = array_reverse($circle['#element_validate']);

    $form['user_relationship_node_access']['circle'] = $circle;

```

# Answer
Ok, this will be slightly different depending on exactly which 2 tabs you want to combine but in this example I will combine menu settings and url path settings like you mentioned in the question.

First you need to implement hook\_form\_alter:

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

    switch($form_id) {

        case 'page_node_form':

            // dpm($form);

            $path = $form['path']; // assign the path part of the form to a variable
            unset($form['path']); // and unset the path section from the original form

            $path['#group'] = ''; // remove the group - if we keep this in then the fieldset won't sit inside the menu fieldset
            $path['#collapsible'] = FALSE; // and we no longer want our inner path fieldset to be collapsible

            // we need to add an additonal validation function to run before the one in the path module does to put the variables back where it is expecting them
            $path['#element_validate'][] = 'MY_MODULE_path_form_element_validate';
            // reverse the array to get our validation function to run first
            $path['#element_validate'] = array_reverse($path['#element_validate']);

            // and finally put the modifed path part of the form back, but put it inside the menu section
            $form['menu']['path'] = $path;

            break;

    }

}

```

And then to put the values back where the path module will be expecting them we need to add our custom validation function:

```
function MY_MODULE_path_form_element_validate($form, &$form_state, $complete_form) {

    // here we just need to take our values out of the menu section and put then back in the path section
    $form_state['values']['path'] = $form_state['values']['menu']['path'];

}

```

This will be a very similar process for any other tabs that you want to combine - use dmp to inspect the $form array and see what you need to take out and where you need to put it back. Then it is just a case of saving the node and seeing which errors appear. Then just put some code in place (such as the custom validation function) to fix any errors you have caused.
> 2 votes

# Answer
In core modules -\> modules/node/content\_types.inc file, i found something useful info but it is not worked out completely for me. I kept two arrays in one array. In the form settings, it is concatenating but not in proper way. Look below code which I merged "Submission settings" and "Display settings". May this trails little bit helps you.

```
  $form['display'] = array(
    '#type' => 'fieldset',
    '#title' => t('Display settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#group' => 'additional_settings',
  );
  $form['display']['node_submitted'] = array( array(
    '#type' => 'checkbox',
    '#title' => t('Display author and date information.'),
    '#default_value' => variable_get('node_submitted_' . $type->type, TRUE),
    '#description' => t('Author username and publish date will be displayed.'),
  ),
    array(
    '#title' => t('Title field label'),
    '#type' => 'textfield',
    '#default_value' => $type->title_label,
    '#required' => TRUE,
  ),
);

/*  $form['submission'] = array(
    '#type' => 'fieldset',
    '#title' => t('Submission form settings'),
    '#collapsible' => TRUE,
    '#group' => 'additional_settings',
  );
  $form['submission']['title_label'] = array(
    '#title' => t('Title field label'),
    '#type' => 'textfield',
    '#default_value' => $type->title_label,
    '#required' => TRUE,
  ); */

```
> 0 votes

---
Tags: forms
---


title: FacetAPI graphs not working

text:
# Question
Title: FacetAPI graphs not working
I have been trying to use FacetAPI graphs for my site but no luck yet . after doing all the configuration set up facetapi - \> selecting 'Graph Combo' in filter option and display configuration. when I execute the search , the search gives blank page in chrome , the same operation done in IE gives error 500 . while doing the configurations setup I noticed In Facet Combo the Y FACET scroll has blank. I dont know if it can be cause of problem . Any pointers in fixing this is highly appreciated Regards Sakar

# Answer
FacetAPI graph doesnt work with solrsearch it seems , I installed search api and was able to get all the options and fixed the problem .
> 0 votes

---
Tags: search
---


# Question
Title: Gallery that can be added to a node via node edit page?
I want to have a gallery that I can easily add/edit/delete photos of from a node creation page and if a user adds a gallery it adds it to the node.

So let's say I want to have a gallery on a page, I would add all the title, body, then I would add 3 photos. And that would create a node with a title, body, and a image gallery with 3 photos. Similar to what I can do in wordpress for each page.

Or something that would function similar to what I want.

Any ideas?

# Answer
I usually use Galleria module to do so: https://drupal.org/project/galleria

Turns image fields of nodes into Galleria galleries with this JavaScript (JQuery) image gallery.
> 1 votes

---
Tags: 7, media
---


# Question
Title: User subscriptions using Webform and Rules
I set up a webform which is displayed as a block on a large number of nodes. The webform asks the user if they would like to subscribe to certain node updates - when a certain field changes value and when a new file is uploaded to another field. I therefore have two checkboxes which the user can check, but my problem is - what next? I can fetch the user email, node id and node title via the webform, but what to do with them? How to sort the users based on what they checked? How to display that on their profiles? Should I assign different roles to them? I would then need a role for every node x 2, which seems like overkill. I did quite a lot of googling, MailChimp seems to have many useful features... Any ideas?

# Answer
I eventually solved this by using the Flag module and doing everything as suggested in this tutorial.
> 0 votes

---
Tags: 7, rules, webforms, notifications
---