title: How to Create Web Application in Drupal

text:
# Question
Title: How to Create Web Application in Drupal
I have a platform independent specification for a web application. I have attached a very small portion of the UML specification posted here. Is it possible to implement the classes as shown by the diagram.

I am not a Drupal Expert and I am having very difficult time in explaning the feaures I want to the Drupal Expernt.

Is it possible to develop content type with this kind of structure and do the data entry from single Page.

It would be great if someone could show me the right direction.

# Answer
> 1 votes
Yes, you can build that type of data model using fieldable entities in Drupal 7.

For example add base "Member" fields to the user entity and use entityreference for the related reference fields on other entities (similar to a foreign key relationship)

The addressfield module provides a good standard address field and associated data structure to hold that info.

In your model, because it appears a "Member" may have many "Member Contact" records, you could perhaps just create a node type for "Member Contact" and add an entity reference field to the relevant "Member".

More info on Drupal 7 Entity API

Lastly, if you want to do it completely custom, you can define your own entity types with `hook_entity_info`

---
Tags: nodes
---


# Question
Title: How to display uploaded files as images in Views?
Is it possible to display uploaded image files (not File Entities or Image Fields) as images inside a View? When I create a file View I can either choose to format it using fields, which allows me to display the file name etc, or as a rendered entity which does not display anything at all. I would like to be able to display a list of uploaded images via Views, as oppose to a list of file names. Can this be done?

Here is why I am trying to do this. I have CKEditor module enabled and I am using One Click Upload module to allow users to upload image files into their text areas. I have tried using Media and File Entity with CKEditor but they were very unstable and caused a great deal of database errors on my website. I also prefer One Click Upload's minimal interface, as the name of the module implies. The problem of course is that One Click Upload does not use File Entities or File Fields for uploading, which is why I am trying to work out how to format the files in Views to show up as rendered images. Is this possible?

# Answer
> 0 votes
Ok I managed to work it out, it is quite simple really; you need to rewrite the output of the field using the html img tag and the replacement patterns available. This will convert any image files uploaded into the website from file names into actual images.

---
Tags: views, files, media
---


title: rewrite custom field on user profile

text:
# Question
Title: rewrite custom field on user profile
I have a custom field on my user profile pages where users can enter their Twitter user name. When the user's profile is rendered (either on the user profile page itself or via views) I would like to rewrite this field so that it links to the user's twitter profile following the pattern http://twitter.com/\[field\_twitter\_name\].

I discovered the twitter username project on DO yesterday (https://drupal.org/project/twitter\_username) and this would help me accomplish the objective, especially for new users. However, we currently have ~900 active users on our site.

Is there a way to create a new field and update its tables with the existing user's twitter names? Or is there a way to change the field type from it's current setting of "Text field" to the new type made available by the twitter username project "Twitter username"?

Any help would be greatly appreciated.

# Answer
You could write a small one-off DB copy function to accomplish the task. There a couple of modules around but they appear to be quite old, so it would depend on what version you run. Here's a tutorial for MySql (if that's what you use) DB access: http://www.w3schools.com/php/php\_mysql\_intro.asp
> 1 votes

---
Tags: users
---


# Question
Title: how to create a apply button in view table result ?
I have created a view with display format as table I want to create a button in the last column for every row
So that when user click on that button form then form open. So how can I create that button for every row

# Answer
In field type create a field for nid and do not expose it display.
The use Global Php for creating button and add nid with the link to button
Use that nid to fetch that details and fill that form
For any clarification please ask
after researching so much Now I can ans this question.
> 0 votes

# Answer
1) On the left side of the Views admin screen, click the "Add" button next to Fields to add a new field

2) Search for "custom field" and select Custom Field

3) For Create a Label, enter: Apply for Job

4) For Text, enter:

```
<a href="/link/to/destination" class="button">Apply for Job</a>

```

(class="button" is what makes the link look like a button)

5) Replace /link/to/destination above with the location of where they can apply for the job. If you need to use replacements in the URL like the node ID number, add the NID field to the view, and replace the URL with something like /node/\[nid\]/apply

View attached screenshot for what it should look like.
> 4 votes

# Answer
Take a look at Views accordion module.

> Features
>
> * Works with field grouping and relationships.
> * Option to use the field grouping headers as the headers for the accordion items. (yay!)
> * Configure settings for jQuery UI Accordion through the views interface.

Have a look at this is quick demo video.
> -1 votes

# Answer
Add a `Header Global: Text area` (or Footer) and add your HTML to render a submit button.
> -1 votes

---
Tags: views, forms
---


# Question
Title: How to position Image field in body content
I have a content type that has title, body, image etc. I am displaying the Title, image with caption and body using Manage Display. But here there is no option to align (Left, Right, Center) the image. How to align the image node wise.

To meet the requirement I found INSERT module. This module is placing the image inside the body content but the caption of the image is missing.

Please help on this issue and let me know if anything is unclear.

# Answer
> 1 votes
Try the CSS Injector module and use CSS float property or other properties on the .class or #id of the image field or body/description/captions.

# Answer
> 0 votes
Your best bet is to use a wysiwyg editor like ckeditor. The other option is to created a node template where content type fields are stacked like so:

* Intro copy (above image copy)
* Image
* caption
* Body

This method is not as flexible as a wysiwyg but works for consistent node presentation.

---
Tags: 7, nodes, media
---


# Question
Title: How do I pass the nid of the current node to the first step multistep modal form?
I am using the ctools plumbing to create a nodal form. This is what the relevant part of my code now looks like:

```
/**
 * Implements hook_entity_view_alter().
 */
function mymodule_entity_view_alter(&$build) {
  $nid = $build['body']['#object']->nid;

  // Set up ctools etc. to use modal omitted for brevity.

  $build['links']['popup']['#links']['mylink'] = array(
    'title' => 'show popup',
    'href' => 'mymodule/nojs/modals',
    'html' => TRUE,
    'attributes' => array(
      'class' => array(
        'ctools-use-modal',
        'ctools-modal-mymodule-style',
      ),
    ),
  );
}

```

The `nid` of the node this link will be attached to is known at this point. (See first line of function.)

However, my code need to be aware of the `nid` at each step in the modal form.

I think it possible to do this by stashing it in a session cookie, but I would like to avoid using cookies, if possible.

Is there another way to do this?

# Answer
> 4 votes
I think the simplest way would be to change your path to incorporate the nid, e.g.

```
function MYMODULE_menu() {
  $items['mymodule/%ctools_js/modals/%node'] = array(
    'title' => 'Title',
    'page callback' => 'MYMODULE_callback',
    'page arguments' => array(1, 3),
    ...
  );

  return $items;
}

```

Change the path in the link

```
$build['links']['popup']['#links']['mylink'] = array(
  'title' => 'show popup',
  'href' => 'mymodule/nojs/modals/' . $nid,
  'html' => TRUE,
  'attributes' => array(
    'class' => array(
      'ctools-use-modal',
      'ctools-modal-mymodule-style',
    ),
  ),
);

```

And in your callback:

```
function MYMODULE_callback($js, $node) {
  // $node is fully loaded, continue as normal...
}

```

---
Tags: chaos-tool-suite, javascript
---


title: Template tpl File Naming Question

text:
# Question
Title: Template tpl File Naming Question
I am currently assigning a theme using hook\_custom\_theme and just allowing the pathing system for .tpl files to override displays that I want to edit by using custom .tpl files. I CANNOT find the correct file name for this path:

(base url)/admin/content/node/article \<-- Where in admin, it is displaying all node content types of 'article'.

I think I've tried every combination possible of page, node, article, admin... think I'm going crazy, please help. Other overrides are working just fine. Thank you for sanity check!

# Answer
> 0 votes
After way too much research into this, I still have NO CLUE why none of the normal naming suggestions work. Even using the theme\_hook\_suggestions provided, none of them work on the content type listing pages. No idea why. All other nodes and pages worked fine in admin but for some reason these content type listing pages would not use a different .tpl template.

So, I had to set all of them using theme\_process\_page hook, then redoing $vars\['theme\_hook\_suggestions'\]\[\] to a different page name. Unfortunately, you have to manually set them.

Using Ember theme in admin. Hopefully this saves someone else some time in the same situation.

# Answer
> 0 votes
Isn't your admin theme uses a different template.php? I am assuming you try to theme /admin/content/node/article. If so, your active admin theme is where your override should go.

---
Tags: theming, nodes
---


# Question
Title: Views Slideshow alternating blank screens with content items
Views Slideshow with JQuery Cycle had been working successfully for a long time, displaying a cycling set of 8 photos with cross-dissolve transitions. Now it's displaying a blank screen between each content item, for the same duration specified for those items in Views\>Slideshow\>Settings. All content is being displayed, nothing skipped, and transition is correct. But it acts as if a blank item is alternating with the intended content. I tried going back to earlier versions of Views and JQuery but there was no improvement in this problem.

Suggestions on why this might happen and how to fix? Thanks.

# Answer
> 0 votes
I found that the problem disappeared when I disabled the module "devel\_themer." I began to suspect it only after looking at the dynamic code in Firebug, which showed the images trying to cycle and to cross-dissolve by animating transparency. I saw a lot of modified code referring to this module name, and figured that since it's not the native code that should be seen here, it would be worth trying the disable and see what happens. Problem apparently solved.

---
Tags: views
---


title: How to change path of taxonomy facet

text:
# Question
Title: How to change path of taxonomy facet
I am using facet search on my site. The search paths for taxonomy term facets are of the pattern "search/term-name", but I would like them to be of the pattern "search/term-tid".

Is this possible? How can I change this?

# Answer
Please try this:

```
/**
 * Implements hook_facetapi_searcher_info_alter().
 */
function mymodule_facetapi_searcher_info_alter(array &$searcher_info) {
  foreach ($searcher_info as &$info) {
    $info['url processor'] = 'term_facet_url';
  }
}

```

Create a folder inside your *mymodule* directory, and name it *facetapi*.

Next is create an *.inc* file and name it, *url\_processor\_term\_facet\_url*

So you should have this structure:

```
mymodule/facetapi/url_processor_term_facet_url.inc

```

Inside of your *url\_processor\_term\_facet\_url.inc*, add the following code.

```
<?php

/**
 * @file
 * A custom URL processor.
 */

/**
 * Extension of FacetapiUrlProcessor.
 */
class FacetapiUrlProcessorTermFacetUrl extends FacetapiUrlProcessorStandard {

  public function getQueryString(array $facet, array $values, $active) {
    $params = $this->params;
    unset($params[$this->filterKey]);
    return $params;
  }

  public function getFacetPath(array $facet, array $values, $active) {
    // Change the line below to your desired taxonomy term path, currently it
    // is set to 'taxonomy/term/[tid]'. And also make sure only taxonomy terms
    // are affected. Check other parameters to pull the data you might need.
    $path = 'taxonomy/term/' . $values[0];
    return $path;
  }

}

```

I hope it helps.
> 0 votes

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


# Question
Title: Pre-process drupal_goto or use hook_exit() to stop redirect
I want to unit test some custom modules but `drupal_goto()` is causing problems by creating header errors (for example, *PHP Warning: session\_start(): Cannot send session cookie*).

Is it possible to stop `drupal_goto()` from redirecting to the destination page or somehow tap into `hook_exit()` to return `$destination`?

# Answer
> 0 votes
This is most often caused by UTF-8 with BOM. Check your editor and change the file format if it is.

The only way to redirect in hook\_exit() is another drupal\_goto(). Be careful that you don't create redirection loops.

# Answer
> 0 votes
You may be interested in:

`hook_drupal_goto_alter`

```
function EXAMPLE_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  // example debug
  drupal_set_message('<pre>'.print_r(func_get_args(),1).'</pre>');
  drupal_set_message($_REQUEST['destination']); // maybe
}

```

# Answer
> 0 votes
I would prefer to use either of following options for redirection in this scenario.

```
$_GET['destination'] = $redirect_url;

```

or

```
$form_state['redirect'] = $redirect_url;.

```

---
Tags: 7, testing
---


# Question
Title: Adding extra button on node edit form with save functionality enabled
I want to add an extra button on the node/edit drupal 7 form. That can be done by hooking into the form\_alter:

```
$form['actions']['push'] = array(
 '#type' => 'submit',
 '#value' => t('Save && Push'),
 '#callback' => 'my_callback',
);

```

In my callback I want to run my **custom Push function** and save the node.

Any ideas how to achieve this?

```
function my_callback_action(&$form, &$form_state) {
  dpm('my_callback_action');
  return '';
}

```

# Answer
> 2 votes
You need to add your own extra submit function to your form. The big question is - where is default one?

If default function is attached to form itself, all you need to do is:

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

```

Then in callback test if it was your button that triggered it.

If it's attached to button, you need to copy original button's submit array to your button, and attach your callback:

```
$form['yourbutton']['#submit'] =  $form['originalbutton']['#submit'];
$form['yourbutton']['#submit'][] ='my_callback';

```

If it's attached to form, but you want yours attached to button, the way is of course:

```
$form['yourbutton']['#submit'] = $form['#submit'];
$form['yourbutton']['#submit'][] = 'my_callback';

```

# Answer
> 1 votes
There is a Drupal module called Content Type Extras that make it easy to add another "Save" button at the top of an edit page. It also includes other extra buttons, such as a "Save and New" button and a "Save and Edit" button.

> This module provides some additional features and the ability to set default settings for content type options, such as 'Promoted to front page', 'Display author and date information', etc.

---
Tags: forms, nodes
---


# Question
Title: Does disabling a module erase its settings?
This is kind of a basic question that I can't find the answer to in the Googles. In the process of debugging, I know disabling modules is a good start but I'd like to be able to go back and turn them on without losing any pre-configured settings.

# Answer
> 1 votes
"Disabling" a module means to disable its user interface aspects only.

This means:

* All code of disabled modules remains to be loaded.
* Services of disabled modules remain to be functional.
* Routes, plugins, info hooks, etc. remain to be available.
* Access to all data items that support any notion of access is denied for all users.

hook\_enable(), hook\_disable(), hook\_modules\_enabled(), hook\_modules\_disabled() are removed, without replacement.

# Answer
> 1 votes
The default in Drupal 7 is that when you only *disable* a module (i.e. untick its checkbox in the "Enabled" column on the *Modules* "List" page/tab and press "Save Configuration"), all its data and settings are retained. Re-enabling the module should take you back to where you left off.

However, if you *unistall* a disabled module (i.e tick its checkbox in the "Uninstall" column on the *Modules* "Uninstall" page/tab), all its settings as well as any schema it has defined by means of `hook_schema`, and any data that is stored in that schema, is supposed to be purged from the database. This can usually be relied upon to get rid of the module's settings and data. You then get a fresh start when you re-enable the module.

The above is the *default* behaviour for Drupal 7, and just now I cannot think of any modules with full releases for Drupal 7 that doesn't have the default behaviour.

*However*, for Drupal 7 (and older) there exists hooks that are run when a module is disabled (i.e. `hook_disable` and `hook_modules_disabled`. These are gone (without any replacement) for Drupal 8.

But unless you're using Drupal 8, be aware that these hooks *can* be used by a misguided module developer to remove settings and data when a module *disabled* (without being unistalled). I am not *aware* of any module for Drupal 7 that does this, and IMHO, it would be an un-Drupalish thing to do. But as long as these hooks exists and are available, one never knows what some misguided maintainer of a contributed module might have considered a "good" idea (there are about 26 000 modules available for Drupal, and some of these. I am sure, have misguided developers).

It may therefore be a good idea to examine the module's `.install` file to see if there are a `hook_disable` there and what it does, and also to *rgrep* your modules directory to see if there are any surprises hidden inside any `hook_modules_disabled`.

From time to time, somebody proposes that the "disabled" concept is "bad" and should be *removed* from the Drupal framework. I think the people making these proposals are misguided (being able to disable a module temporarily without losing its settings or data is beneficial to developers) - but I can imagine that some of these misguided individuals may try to to remove some settings using \[`hook_disable`\], to "simulate" the behaviour they want to see universally adopted.

Therefore, always back up your database *before* disabling (or enabling) anything to avoid being bitten by a misguided developer's bad code. Then examine your database for unwarranted changes before proceeding.

---
Tags: 7
---


# Question
Title: How to implement 'phonetic typing' for performing a language conversion of a field (using CKEditor)?
I am using CKEditor in a Drupal website. I am looking for a technique to **convert** (not **translate**) words from English to some other language (say Telugu), while typing those words.

Below are 2 examples to illustrate *Phonetic typing* (during the creation of a node):

1. If I start with typing "*What*" in a text-area (long text), then it should suggest something like so:
2. If I then continue typing "*oka*" in a text-area (long text), then it should suggest something like so:

... 2

How can I achieve (implement) this while using CKEditor?

# Answer
Finally I found a module called Indic Script.

> This Module enables IME (Transliteration Input Method) for Indian Languages in Drupal Text Fields and Text Area Fields So that users can create their content in their own Language within Drupal without installing any additional software.
>
> 6.x-3.0 and 7.x-2.x version has the integration for CKEditor (CKEditor.module and WYSIWYG.module)
>
> Indic Script module supports Type writer (TW) as well as Phonetic typing for the following languages.
>
> * Tamil, Tamil Tw, Tamil 99
> * Hindi, Hindi Tw, Hindi Remington Tw
> * Malayalam, Malayalam Tw
> * Bengali, Unijoy, Bengali Tw
> * Gujarati, Gujarati Tw
> * Kannada, Kannada Tw
> * Oriya, Oriya Tw
> * Punjab, Punjab Tw
> * Telugu, Telugu Tw & Telugu Apple Tw

I've tested this module. Here is the screenshot of this module usage with CK field

I hope it helps someone.
> 1 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How to remove 'None' from forum options?
In D7 advance forum, when users want to create a forum thread at node/add/forum, they are presented with a dorp-down menu fo froum whose default is set to .

So when users do not choose an existing forum from the menu, their thread is just added to 'None' forum, which is so bad. I need frequenty to remove these 'none' forum threads.

So I'm wondering how remove this option or otherwise solve this problem?

# Answer
The forum is set as a taxonomy reference in the field list of the content type 'forum post'.

Can you not just set it to be a compulsory field at /admin/structure/types/manage/forum

This way if somebody entered a blank value it would reject the answer and ask them to resubmit, which works better than the default being one of the forums, in which case lots of topics still end up in the wrong place.

The only thing I'm confused by is that I thought this was the default setting for Drupal's inbuilt forum content type anyway? Buy maybe I'm wrong on that.
> 0 votes

---
Tags: nodes
---


# Question
Title: Unwanted <p> tags inserted before and after a rendered $item
First time creating a custom template for a field.

I've created the `field--field_phone_number.tpl.php` and know it's working.

I'm trying to make it so when a user enters a phone number, it displays as a link with the "tel:" prefix so that readers can click the link on their mobile phones to call directly.

Here's what I have:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><a href="tel:<?php print render($item); ?>"><?php print render($item); ?></a></div>
    <?php endforeach; ?>
  </div>
</div>

```

Only problem is that it actually prints out something like

```
<a href="tel:<p>3035551212</p>">3035551212</a>

```

Where are those `<p>` tags coming from?

I see many posts around about those tags coming from WYSIWYG editors and the like, but I'm not using one of those. I've also seen a suggestion that this is related to a default line-break converter, which I'd rather not turn off.

# Answer
> 0 votes
There can be some better solution of this question but as you are facing of this extra html tag issue inside href, here is solution for this.

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item):
    $phone_link_data = render($item);
    $phone_link = strip_tags(html_entity_decode($phone_link_data));
    ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><a href="tel:<?php print $phone_link; ?>"><?php print render($item); ?></a></div>
    <?php endforeach; ?>
  </div>
</div>

```

---
Tags: entities, theming
---


# Question
Title: How to show "Log in or register to post comments" message when no comments on content?
The "Log in or register to post comments" message does not display when there are no comments on a piece of content.

However, it does show when there is at least one comment.

Looking in the comment module code, the "Log in or register to post comments" message is in the code that only runs when there are already one or more comments!

How dumb is that?! Is there a module or an existing approach to making this display when there are no comments?

I can write a hook in my own module to override this but it might be re-inventing the wheel if it's already been done.

# Answer
The root cause was that Display Suite has not been set up correctly. Action for me is to do this, including appropriate CSS classes.

Because it wasn't setup, comments were not being displayed.

I was able to confirm this by simply switching off Display Suite - which meant that comments weren't managed though this.

I still want to use display suite but need to set it up OK.
> 0 votes

# Answer
this is my temp solution.. i copy the ds-1col template to my ds-1col--node.tpl.php and add this code at bottom.

```
<?php global $user;
if (!$user->uid) {
print render($content['links']['comment']['#links']['comment_forbidden']['title']);
} ?>

```
> 2 votes

# Answer
The solution in this link work for my https://groups.drupal.org/node/349753
> 0 votes

# Answer
Here's another solution that might help someone: Copy the display suite template into your theme and in the bottom add this lines:

```
   <?php global $user;
    if (!$user->uid && $comment_count == 0) {
      print render($content['links']['comment']['#links']['comment_forbidden']['title']);
    } ?>

```

It's similar to the Willard answer, but if you don't add $comment\_count == 0 in your code, you'll have duplicated links if there are already comments on the comment form.
> 0 votes

---
Tags: 7, users, comments
---


title: Add author's name to view

text:
# Question
Title: Add author's name to view
Is there some simple way I can add the author's name as a field to be displayed in my view?

# Answer
> 8 votes
In view add a relationship Content: Author

Then choose User: Name under fields,

this will display author name

# Answer
> 1 votes
**Beyond a Views only Solution**

I would recommend using the module Realname, as it provides a solution that will work for views, but will also alter the display name on the author archive pages, and the author's display name on a node created by them:

1. Download and enable Realname module
2. Create a new field on users (admin/config/people/accounts/fields) I called it "Display name" (field\_display\_name)
3. Configure the Realname settings to use that new field (admin/config/people/realname) in my case the value was \[user:field\_display\_name\]

After this the username was concealed from public display; Author display, User page alias & title and any views displaying author.

If you are using metatags module or some others you will need to configure them specifically to use the Realname value rather than the default username value, but it is a far more comprehensive way of solving the display name issue.

---
Tags: 7, views
---


title: how to get date filter settings

text:
# Question
Title: how to get date filter settings
I want to exposed date filter option but am getting just textbox instaed of datepicker I have installed date module still am not getting following options:

installed modules are as shown bellow:

Please guide me how to set datepicker and add search option using that?

# Answer
You can use Date picker Module for **popup date** on exposed filter.

It includes the date popup. You can use this module to easily add an exposed filter with the date popup.
> 0 votes

---
Tags: views, datetime
---


title: Multiple validation

text:
# Question
Title: Multiple validation
I have a problem regarding validation. I have created a custom validation for email, but i want two additional validations for user name and last name. But only email field is getting validated. My code:

```
function mymodule_form_alter(&$form,&$form_state,$form_id) {
if($form_id == 'email') {
   $form['#validate'][]='mymodule_form_validate_email';
}
if($form_id == 'name') {
   $form['#validate'][]='mymodule_form_validate_name';
}
}

function mymodule_form_validate_email($form, &$form_state) {

  $valid_email = $form_state['values']['email'];
  if (!valid_email_address($valid_email)) {
  form_set_error('email', 'Email adress, ' . $valid_email .' , is not valid. Please enter a valid email adress. Example: username@example.com');
  }
}

function mymodule_form_validate_name($form, &$form_state) {

  $validate_name = $form_state['values']['name'];
  $name='user';//example
  if ($validate_name==$name) {
  form_set_error('Error');
  }
}

```

Now the problem is that 'email' validation works but the 'name' does not. I tried to copy the email validation to the validate\_name function etc. but the same thing , nothing happens.

# Answer
> 1 votes
Attach the `#validate` property to the form submit button like this:

```
$form['submit']['#validate'][] = 'yourmodule_form_validate'

```

# Answer
> 1 votes
Is this correct code, do you have two different - 2 forms one is "email" and another is "name". I think this code is not correct your $form\_id can not be of this type. You can use Get Form Id module for this. Please correct your $form\_id first and then attach validation for every field or you can also call custom validate function and can validate both field together over there.

**Approach 1:** Validate all fields at one place in one function.

```
function mymodule_form_alter(&$form,&$form_state,$form_id) {
    if($form_id = 'Your form id') {
        $form['submit']['#validate'][] = 'mymodule_form_validation'
    }
}

function mymodule_form_validation($form, &$form_state) {
    $valid_email = $form_state['values']['email'];
    if (!valid_email_address($valid_email)) {
      form_set_error('email', 'Email adress, ' . $valid_email .' , is not valid. Please enter a valid email adress. Example: username@example.com');
    }

    $validate_name = $form_state['values']['name'];
    $name = 'user';//example
    if ($validate_name == $name) {
        form_set_error('Error');
    }
}

```

**Approach 2:** Validate individual field with individual function. You can also validate individual element by attaching an #element\_validate to the form element, with the element specific validation function. This function will be passed $form\_state and $element. Using the same form example as above, define a validation function for the email and name element, rather than for the whole form.

```
'#element_validate' => array('mymodule_form_validate_email'),

'#element_validate' => array('mymodule_form_validate_name'),

```

---
Tags: forms
---


# Question
Title: how to bring Core forum discussion with comment on front page
I am using core forum in drupal 7. my requirement is how to bring forum discussion question with comment on front page.

# Answer
You can create views of type **Forum topic**. and put the views page on your sites front page.

navigate to `[your-site]/admin/config/system/site-information` change the **default front page** to your views page link.
> 1 votes

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


# Question
Title: Is there any rule when to use panels and when to use templates in drupal 7
I want to know about the panels and templates use cases as i am confused when to use panels and when to use templates as each page can be designed by both the ways then which is the best solution. As we can easily layout both the things through html css.

# Answer
Simple rule:

* If you want to add some other blocks, content panes, or other information that is related but not included in content; you need to use Panels.
* If you want to display the content in a custom way and all information you want to display is already included in content, then you don't need Panels, use a template.
> 1 votes

---
Tags: theming, panels
---


title: Problem with multiselect module

text:
# Question
Title: Problem with multiselect module
I've installed the multiselect module, to add this option in a custom form.

The problem is that when I see the options, it shows this:

Does anybody know if there is a way to solve this?

This is the code of the form.

```
  $form['municipios'] = array(
 '#type' => 'multiselect',
 '#title' => t('Municipios'),
 '#options' => $options2,
 '#required' => TRUE,
  );

```

($options2 is an array with all the option)

Thank you.

# Answer
Seems like you are messing up with Multiselect and Improved multiselect modules.

Navigate to `[your-site]/admin/config/user-interface/improved_multi_select` and disable Improved multiselect settings as below.
> 1 votes

---
Tags: 7, forms
---


title: Taxonomy term translation

text:
# Question
Title: Taxonomy term translation
I am working on a multi lingual site. I had installed the i18n (Internationalization). I wanted to get the taxonomy terms translated. But I was not able to do so.
In the translation mode I had chosen " Localize. Terms are common for all languages, but their name and description may be localized. "
Can anybody help me please...

# Answer
It's not like, it's un-translatable. You have to render it on some page and then clear your cache and search in "{you-domain}/admin/config/regional/translate/translate" interface.
> 1 votes

---
Tags: taxonomy-terms, i18n-l10n
---


# Question
Title: How to see #default_values in multiselect form
I've done a custom form that is a multiselect type form. When I edit the node, the options that were previously selected are not shown in the selected options part.

This is the code that I've done:

```
 foreach ($node->field_tem_tica[LANGUAGE_NONE] as $delta => $value) {
    $term2 = taxonomy_term_load($value['tid']);
 }

  $query2 = "SELECT name, tid FROM taxonomy_term_data WHERE vid=4 AND language = '$language_url';";
  $result = db_query($query2);
  foreach ($result as $row2) {
     $options3[$row2->tid] = t($row2->name);
  }

  $form['group_config']['tematicas'] = array(
     '#type' => 'multiselect',
     '#title' => t('Temáticas'),
     '#options' => $options3,
     '#required' => TRUE,
     '#multiple'=>TRUE,
     '#default_value'=> $term2,
     '#prefix' => '<p><br>',
     '#suffix' => '</p>',
     '#size'=>20,
  );

```

Does anybody see a mistake? Is there any way to see the default\_values?

Thank you.

# Answer
The default value needs to be the *key* of the options array, so assuming the rest of your code is correct, this should work:

```
$form['group_config']['tematicas'] = array(
  '#type' => 'multiselect',
  '#title' => t('Temáticas'),
  '#options' => $options3,
  '#required' => TRUE,
  '#multiple'=>TRUE,
  '#default_value'=> $term2->tid,
  '#prefix' => '<p><br>',
  '#suffix' => '</p>',
  '#size'=>20,
);

```
> 0 votes

---
Tags: forms
---


# Question
Title: Select List value in an If statement - Computed Field
I have created a select list field in my Entity Form.

```
Select List : none||none and AM||AM and PM||PM

```

In my computed field, I want to know what did the user chose by using IF STATEMENT

example:

```
if($halfday == 'AM')
{
//action
}

```

I tried to use array\_pop (example code :

`$halfday = array_pop(field_get_items($entity_type,$entity,'field_halfday'));)`

but it does not work for me. What PHP code should I use? Any suggestions?

# Answer
Write the following code under **Computed Code (PHP) texarea** in computed filed settings

```
$calc =  $entity-> field_sample['und'][0]['value'];

if($calc == 'AM')
{
 //action
$entity_field[0]['value'] = 'After Meridian';
}

elseif($calc == 'PM')
{
//action
$entity_field[0]['value'] = 'Prime Meridian';
}

```

This is a sample tested code which prints the selected item at output of computed field.

Note: replace `filed_sample` with your select list field machine name.
> 1 votes

---
Tags: entities
---


title: Disable download images colorbox popup

text:
# Question
Title: Disable download images colorbox popup
How can I disable "right click" in colorbox Popup so the visitor could not directly download images.

# Answer
> 0 votes
You can use Copy Prevention module.

This module will Place transparent image above all your images - this will protect your real images from being saved using context menu or drag-and-drop to desktop

More from module page:

> Anything you put out there in the Internet (public pages) is available for anyone else to copy and save/re-use. So if you really want your content to be safe and protected - do not put it online.
>
> But if you want you can try to protect your content/images and prevent/disable at least the most simple ways to copy it. In fact, anyone can "view source", check the browser cache for images, use "Print Screen" or "site copy" software, etc. - these things can't be disabled, but they require additional knowledge and skills than just selecting the content and copying it or dragging an image from browser window to the desktop.
>
> This module includes several different technical ways/methods to make copying/stealing information/images from your site harder than it usually is:
>
> This module includes several different technical ways/methods to make copying/stealing information/images from your site harder than it usually is:
>
> * Disable text selection
> * Disable copy to clipboard
> * Disable right-click context menu on all site content
> * Disable right-click context menu only on images ( tag)
> * **Place transparent image above all your images - this will protect your real images from being saved using context menu or drag-and-drop to desktop**
> * Protect/hide your images from search engine indexes so that your images don't show up in image searches - add "noimageindex" robots tag and disallow image files indexing in robots.txt

---
Tags: views, javascript
---


# Question
Title: Is it OK to remove field values or revisions by deleting individual lines from the field table in the database?
I have been testing my site (with revisions enabled) for several days now and I have noticed that my field related database tables are filling up with revision info. Can I simply delete these line items from the field table or are there other entries that I need to be aware of?

# Answer
> 4 votes
It is better to Use the Node Revision Delete module to delete and manage your revisions.

> The Node Revision Delete module allows you to manage the revisions of the Node according to your choice. It helps you to keep the specific number of revisions for the node. This module provides you the flexibility for applying the revision delete for the specific content type and run it on the specific time. You can manage your settings from the Node Revision Delete Administration Page.

---
Tags: 7, entities, database, nodes
---


title: Field collections data not being saved

text:
# Question
Title: Field collections data not being saved
I am working on a website which has many Entity forms and some of the Entity form has field collection with few fields in it and it allows multiple items "Unlimited". When you save the node, the data does not save. When you click 'add new item', it also doesn't save the data, it just creates a new set of empty fields and has a 'remove' button.

after pressing submit button the form save all the data apart from data which is in Field collection.

After some research I come to know that Entity forms is not a good option for forms which has more them 100 Fields, because after 100 Fields the form creation become very slow.

one of the Entity forms in website has 180 Fields I am not sure if it is causing the problem.

There is no error message in logs, server error log and Firbug.

# Answer
> 1 votes
After some research I come to know that is not a good option for a big project due to performance, Field collection can be quite annoying from a performance perspective.

There are alternative ways to achieve a better result.

1 - Composed Field worked for me and improved system performance

2 - Creating a new content type to represent collection and then using Inline Entity Form to allow creation of the collection inside of the content type referencing it.

3- Using Multifield. however data extract could be a pain.

---
Tags: entities
---


# Question
Title: why node ref not saved in hook_node_presave
I have a node reference in my custom content type, It can get some content type as reference in unlimited , I want to programmatically add nodes to it ,

some part of my code is

```
function mymodule_node_presave($node) {
.....

$nid_res=_convert_smarttag($body, 2);
ym($node,'message');
foreach($nid_res as $i=>$val ){
      $node->field_news_tags['und'][$i]=$val->nid;
      // ym($i .'=='.$val->nid,'message');
        }
ym($node,'message');
.....
}

```

before my `foreach`

in my foreach

and after foreach

I check this nid , it's type checked to be referenced in this field. **but I dont know why this not saved finally !!!where is my problem?**

# Answer
> 1 votes
I found my mistake ,maybe useful for others that want save nid programmatically

```
foreach($nid_res as $i=>$val ){
      $node->field_news_tags['und'][$i]['nid']=$val->nid;
      // ym($i .'=='.$val->nid,'message');
        }

```

---
Tags: nodes
---


# Question
Title: Custom Mult-Step Form remove next button
I have built a Multi-Step form using forms example module as a base:

https://api.drupal.org/api/examples/form\_example!form\_example\_wizard.inc/function/form\_example\_wizard/7

I have a function that takes the user-inputted location on the first form and returns data for presentation on the 2nd form. If no data if returned back from the first form I want to hide the Next button. How can I do this?

# Answer
> 0 votes
You could try something like this on the second form:

```
if (empty($form_state['values']['location']) {
    $form['next']['#access'] = FALSE
}

```

---
Tags: 7, forms
---


# Question
Title: Include the user history visibility settings in a feature
I have two view modes for the user profiles, the default one and a custom view mode called "Header". In the default view mode I have chosen to show the user history information ("Member for...") but in the Header view mode it shouldn't be shown.

I have included the user account settings in a feature in order to be able to export them. Everything else is fine but I don't find how to include the history visibility settings in it. When I reinstall the site with my feature, the "Member for..." information is shown in both of the view modes. I can manually hide it in the configuration page, but I must find how to export it into the code.

Does anyone know how this can be done?

# Answer
> 0 votes
If you've added a custom visibility option to User accounts. You'll need to figure out a way to export it to code. if they are just Fields then they should show up under export options for Fields when building a feature.

If on the other hand you've created a custom tab of sorts on the User Accounts page and have a bit of code managing some settings there -- you need to inform Drupal of those pieces of custom data.

Features Extras supports exporting visibility settings for blocks, and blocks in general.

> To export a block, install FE Block, edit your block, give it a "machine name," export it with Features. You can export block settings (region settings, visibility settings, ...) of any block, and the content of blocks created with the Block module from Drupal core.

I recommend looking at that module and seeing how they export these settings. If I had to guess I'd say they use the Ctools Export API. There is a drupal handbook page on how to get started exporting configuration for your module.

---
Tags: users, features
---


title: conditional fields in node creation

text:
# Question
Title: conditional fields in node creation
Well Im trying to use some conditional fields while creating some type of nodes. for example

I have a content type called "organization" this content type has

name, logo, and some other stuff

also has a select box field where the user selects the type of organization, depending of what the user selects I need to show other fields that depends of the type of the organization.

There is a module for this?

Thank you

# Answer
> 1 votes
You should look at Conditional Fields Module. Does exactly what you need.

You can also find nice tutorial here: CFM Tutorial

---
Tags: 7, nodes, entities, database
---


# Question
Title: Cannot modify language field in node form using hook_form_alter in drupal 7
I tried adding a description for the language field in a node form using hook\_form\_alter:

```
$form['language']['#description'] = t('Description');

```

The changes are not accepted, the language field stays as it is the description is not added. As far as i can tell this is not a problem with the hook, because changes to other fields work fine, only the language field does not change. Any ideas what i'm doing wrong.

# Answer
> 2 votes
Your code doesn't work because the node edit/create form sets `$form['language']` using the following code. (See node\_form().)

```
  // Basic node information.
  // These elements are just values so they are not even sent to the client.
  foreach (array('nid', 'vid', 'uid', 'created', 'type', 'language') as $key) {
    $form[$key] = array(
      '#type' => 'value',
      '#value' => isset($node->$key) ? $node->$key : NULL,
    );
  }

```

It's then the Locale module that changes the form field in locale\_form\_node\_form\_alter() using the following code.

```
  if (isset($form['#node']->type) && locale_multilingual_node_type($form['#node']->type)) {
    $form['language'] = array(
      '#type' => 'select',
      '#title' => t('Language'),
      '#default_value' => (isset($form['#node']->language) ? $form['#node']->language : ''),
      '#options' => array(LANGUAGE_NONE => t('Language neutral')) + locale_language_list('name'),
    );
  }
  // Node type without language selector: assign the default for new nodes
  elseif (!isset($form['#node']->nid)) {
    $default = language_default();
    $form['language'] = array(
      '#type' => 'value',
      '#value' => $default->language,
    );
  }

```

If your module is executed before the Locale module, its changes to the language form field are not retained, as the Locale module set `$form['language']` to a different array.

In order for your code to work, you need to change the weight of your module, or implement hook\_module\_implements\_alter() to alter the order hooks are executed.

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

```

This code changes also the order in which `hook_form_FORM_ID_alter()`, and `hook_form_BASE_FORM_ID_alter()` are executed.

# Answer
> 1 votes
@kiamlaluno: I don't think your approach works. Here a comment from the i18n module:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
 function i18n_node_form_node_form_alter(&$form, $form_state) {
 $node = $form['#node'];
 /**
  * i18n has to override locale.module
  * drupal_alter() fails to order modules correctly in some cases
  * for example specific hooks like hook_form_BASE_FORM_ID_alter
  *
  * its not possbile to reorder hook_form_BASE_FORM_ID_alter with
  * hook_module_implements_alter
  *
  * @see http://drupal.org/node/765860
  */

   // call a 'private' implemenation of i18n_node_form_node_form_alter()
   $form['#after_build'][] = '_i18n_node_form_node_form_alter';
  }

```

I used the '#pre\_render' property to solve this:

```
  function your_module_form_node_form_alter(&$form, &$form_state){
    $form['language']['#pre_render'][] = '_your_module_language_node_prerender';
   }

   function _your_module_language_node_prerender($element){
     // do something with $element
     return $element
   }

```

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


# Question
Title: How to hide 'add to cart' button on content type full view?
How to hide '**add to cart**' button, on full mode view of a specific content type? It has to be done on condition if product is purchased for this content type.

I tried to add custom field template but for add to cart button could not find the right template name. I also found out the field name which displays add to cart "field-product-ref" but the template field--field-product-ref.tpl.php is not working. Need help in either identifying correct template name or any other approach which is correct?

# Answer
You could use devel\_themer module. After enable the module, a checkbox appear on left bottom of the window then, select the checkbox now you could find the template name after click the add to cart button...
> 0 votes

# Answer
I manage to resolve it.
Now sharing back with the community.
**To hide the add-to-cart button on FULL view mode if product is purchased**

```
 1. Implement this solution in _theme_form_alter.
 2. Sql query to check if product id belongs to complete order list for particular user
     "$query = db_select('commerce_order', 'cord');
    $query->join('commerce_line_item', 'li', 'cord.order_id = li.order_id');
    $query->join('field_data_commerce_product', 'prod', 'li.line_item_id = prod.entity_id');
    $query->condition('cord.uid', $user->uid, '=')
          ->condition('cord.status', 'completed', '=')
          ->condition('commerce_product_product_id ',$prod_id,'=')
          ->fields('prod', array('commerce_product_product_id'));
    $result = $query->execute();
    $resultValue = $result->fetchColumn(0);"
 3. Hide add-to-cart button if product id matches query result

```
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Is there module to generate form and save into content type?
I find a module to create a form like Webform or Entityform and save this one directly into a node (specific content type or entity).

# Answer
Entity form creates entity instances called "Entity form submissions". So the answer to your question is "Entityform module."
> 0 votes

# Answer
Thank for your confirmation, but when i create a new Entityform with many submission. I don't understand where it's stored.

If i go to "/admin/structure/entity-type", there is no content in relation with "Entityform". And i want to access programmatically to this data in futur.

I have vanille drupal installation.

Do you have any ideas ?
> 0 votes

---
Tags: nodes, forms, webforms, entities
---


# Question
Title: file_usage_add: custom type for my module
I have a custom calendar module I've created. When a user creates an event they have the ability to attach a thumbnail image to it. I'm trying to make it use the managed\_file type. In the documentation it appears I need to use file\_usage\_add to keep it from throwing an error. The problem is I'm not sure what to put in the 'type' and 'id' parameters. The documentation lists these required parameters:

* $file: A file object.
* $module: The name of the module using the file.
* $type: The type of the object that contains the referenced file.
* $id: The unique, numeric ID of the object containing the referenced file.

$file and $module are easy. However, this module doesn't create a node or anything else. I have my own table structure for this information. Is there a way to define my table that events get stored in as a 'type' and pass that with the unique id from that table?

# Answer
> 4 votes
Yes, `type` just needs to be something unique within *your module's* types of file usage. The value of the string itself is arbitrary.

So if you have a module which stores pictures of cats and dogs, and you want to address those two different types of usage separately, you might use (contrived examples obviously):

```
$cat = MYMODULE_load_cat('whiskers');
file_usage_add($file, 'MYMODULE', 'cat_pictures', $cat->id);

$dog = MYMODULE_load_dog('fido');
file_usage_add($file, 'MYMODULE', 'dog_pictures', $dog->id);

```

But the `type` for those could just as easily be `cat_foo` and `dog_foo`, all that matters is that you (the module developer) know what they are, so they can be used appropriately with `file_usage_delete()`.

---
Tags: 7, files
---


# Question
Title: How can I reproduce a Drupal install without using an installation profile
I need to be able to re-create a Drupal install (as a sub-domain) using the minimal install profile, but I then need to:

1. Install and configure a few additional modules
2. Configure a few content types

As it stands, I have installed and enabled Views, Field UI, and a custom module in the sub-domain. How do I export the settings into something I can re-produce without having the user have to go through the process of the Drupal install?

What I plan on doing:

1. Create a fresh install with all modules enabled and configured as desired (Views, etc)
2. Export the SQL

But this doesn't address more bespoke problems...any suggestions?

Where do I even start?

It's important to note that I do not think I am looking for a profile install as the user will never know any of the details of the server (these are all generated automatically when user signs up).

# Answer
It's not possible to install Drupal without an installation profile but I don't think that's really what you're trying to achieve, maybe edit the question? A couple of ways to achieve what you're wanting:

1. You'd be best off using `drush site-install`:

This way you can pass database credentials, site name and site username/password all in one command.
2. Either that or you can import a copy of an already installed Drupal site and change all the configuration to match the new domain and database details. I don't have any information about this method except that I think it would be much more difficult and time consuming than using site-install.
> 1 votes

# Answer
* You can build the base install

Use backup and migrate module or myPHPAdmin to backup the site

Use Putty-SSH tar command to backup the fileset Create new database for new install

Use Putty-SSH tar command to restore/mirror the fileset

Rewrite/edit settings.php with database user/pw, conf\[\] variable options and perms

Use phpMySQL and restore the backup and migrate file created in step 1

Simplified but works. BASH Scripts to do this are the automated technique.
> 0 votes

---
Tags: installation
---


# Question
Title: How can I automate the site setup process during installation?
I have this client requirement:

> While installing Drupal, user needs to do most of the configuration himself.
>
> 1. Select the logo.
> 2. Select the theme.
> 3. Select the type of website he wants like blog, website, forum, eCommerce and when he does it, it should come along with its own configurations.

I know I need to use an installation profile. Is there any other way to do it? If an installation profile is the only way, then how can I meet all these requirements?

# Answer
I recommend you take a look at NodeStream for examples. With a combination of install profile and Features, you do a great deal of setup during the actual install. You could either build on top of that, which is what we do at work, or you could use it for examples.
> 2 votes

# Answer
As opposed to install profiles, what might serve is if you manage the settings.php file with conf\[\] variables.
> 0 votes

---
Tags: 7, installation, distributions
---


# Question
Title: Drupal 7: Views search not returning correct results for multiple term searches
I've inherited a search form built using Views. When searching for one term the results are correct, and when searching for multiple terms enclosed in quotes the results are correct (although with duplicate entries), but when searching for multiple terms without quotes the results are not as expected.

You can view the search form at http://texasfortstrail.com. Search for fort, fort concho, and "fort concho" for different result sets.

Thoughts on what could be causing the discrepancies? I'm using Drupal 7.14 and Views 7.x-3.5.

Here's the view:

```
$view = new view();
$view->name = 'search_results';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Search Results';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Search Results';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'mini';
$handler->display->display_options['pager']['options']['items_per_page'] = '25';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['style_options']['wrapper_class'] = '';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['default_field_elements'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['element_type'] = 'h3';
$handler->display->display_options['fields']['title']['element_class'] = 'title';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['title']['element_default_classes'] = FALSE;
/* Sort criterion: Domain Access: Domain ID */
$handler->display->display_options['sorts']['gid']['id'] = 'gid';
$handler->display->display_options['sorts']['gid']['table'] = 'domain_access';
$handler->display->display_options['sorts']['gid']['field'] = 'gid';
/* Sort criterion: Search: Score */
$handler->display->display_options['sorts']['score']['id'] = 'score';
$handler->display->display_options['sorts']['score']['table'] = 'search_index';
$handler->display->display_options['sorts']['score']['field'] = 'score';
$handler->display->display_options['sorts']['score']['order'] = 'DESC';
/* Contextual filter: Search: Search Terms */
$handler->display->display_options['arguments']['keys']['id'] = 'keys';
$handler->display->display_options['arguments']['keys']['table'] = 'search_index';
$handler->display->display_options['arguments']['keys']['field'] = 'keys';
$handler->display->display_options['arguments']['keys']['default_action'] = 'empty';
$handler->display->display_options['arguments']['keys']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['keys']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['keys']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['keys']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'about_us_home' => 'about_us_home',
  'about_us_page' => 'about_us_page',
  'city' => 'city',
  'event' => 'event',
  'home_page_content' => 'home_page_content',
  'our_stories' => 'our_stories',
  'our_stories_home' => 'our_stories_home',
  'page' => 'page',
  'partners' => 'partners',
  'partners_home' => 'partners_home',
  'pya_home' => 'pya_home',
  'pya_page' => 'pya_page',
  'site' => 'site',
  'thc_theme' => 'thc_theme',
);
/* Filter criterion: Domain Access: Available on current domain */
$handler->display->display_options['filters']['current_all']['id'] = 'current_all';
$handler->display->display_options['filters']['current_all']['table'] = 'domain_access';
$handler->display->display_options['filters']['current_all']['field'] = 'current_all';

/* Display: Search Results */
$handler = $view->new_display('page', 'Search Results', 'default_results');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['element_type'] = 'h3';
$handler->display->display_options['fields']['title']['element_class'] = 'title';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['title']['element_default_classes'] = FALSE;
/* Field: Content: Short Description */
$handler->display->display_options['fields']['field_desc_short']['id'] = 'field_desc_short';
$handler->display->display_options['fields']['field_desc_short']['table'] = 'field_data_field_desc_short';
$handler->display->display_options['fields']['field_desc_short']['field'] = 'field_desc_short';
$handler->display->display_options['fields']['field_desc_short']['label'] = '';
$handler->display->display_options['fields']['field_desc_short']['alter']['max_length'] = '100';
$handler->display->display_options['fields']['field_desc_short']['alter']['trim'] = TRUE;
$handler->display->display_options['fields']['field_desc_short']['element_type'] = 'p';
$handler->display->display_options['fields']['field_desc_short']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_desc_short']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['field_desc_short']['type'] = 'text_plain';
$handler->display->display_options['defaults']['sorts'] = FALSE;
/* Sort criterion: Search: Score */
$handler->display->display_options['sorts']['score']['id'] = 'score';
$handler->display->display_options['sorts']['score']['table'] = 'search_index';
$handler->display->display_options['sorts']['score']['field'] = 'score';
$handler->display->display_options['sorts']['score']['order'] = 'DESC';
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Domain Access: Available on current domain */
$handler->display->display_options['filters']['current_all']['id'] = 'current_all';
$handler->display->display_options['filters']['current_all']['table'] = 'domain_access';
$handler->display->display_options['filters']['current_all']['field'] = 'current_all';
$handler->display->display_options['filters']['current_all']['value'] = '1';
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'about_us_home' => 'about_us_home',
  'about_us_page' => 'about_us_page',
  'city' => 'city',
  'event' => 'event',
  'home_page_content' => 'home_page_content',
  'our_stories' => 'our_stories',
  'our_stories_home' => 'our_stories_home',
  'page' => 'page',
  'partners' => 'partners',
  'partners_home' => 'partners_home',
  'pya_home' => 'pya_home',
  'pya_page' => 'pya_page',
  'site' => 'site',
  'thc_theme' => 'thc_theme',
);
$handler->display->display_options['path'] = 'search/node/%';

/* Display: Other Domain Results */
$handler = $view->new_display('page', 'Other Domain Results', 'other_domain_results');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'mini';
$handler->display->display_options['pager']['options']['items_per_page'] = '25';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '1';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Link */
$handler->display->display_options['fields']['view_node']['id'] = 'view_node';
$handler->display->display_options['fields']['view_node']['table'] = 'views_entity_node';
$handler->display->display_options['fields']['view_node']['field'] = 'view_node';
$handler->display->display_options['fields']['view_node']['label'] = '';
$handler->display->display_options['fields']['view_node']['exclude'] = TRUE;
$handler->display->display_options['fields']['view_node']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['view_node']['element_default_classes'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['title']['alter']['path'] = '[view_node]';
$handler->display->display_options['fields']['title']['alter']['absolute'] = TRUE;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['strip_tags'] = TRUE;
$handler->display->display_options['fields']['title']['element_type'] = 'h3';
$handler->display->display_options['fields']['title']['element_class'] = 'title';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['title']['element_default_classes'] = FALSE;
/* Field: Content: Short Description */
$handler->display->display_options['fields']['field_desc_short']['id'] = 'field_desc_short';
$handler->display->display_options['fields']['field_desc_short']['table'] = 'field_data_field_desc_short';
$handler->display->display_options['fields']['field_desc_short']['field'] = 'field_desc_short';
$handler->display->display_options['fields']['field_desc_short']['label'] = '';
$handler->display->display_options['fields']['field_desc_short']['alter']['max_length'] = '100';
$handler->display->display_options['fields']['field_desc_short']['alter']['trim'] = TRUE;
$handler->display->display_options['fields']['field_desc_short']['element_type'] = 'p';
$handler->display->display_options['fields']['field_desc_short']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_desc_short']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['field_desc_short']['type'] = 'text_plain';
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'about_us_home' => 'about_us_home',
  'about_us_page' => 'about_us_page',
  'city' => 'city',
  'event' => 'event',
  'home_page_content' => 'home_page_content',
  'our_stories' => 'our_stories',
  'our_stories_home' => 'our_stories_home',
  'page' => 'page',
  'partners' => 'partners',
  'partners_home' => 'partners_home',
  'pya_home' => 'pya_home',
  'pya_page' => 'pya_page',
  'site' => 'site',
  'thc_theme' => 'thc_theme',
);
/* Filter criterion: Domain Access: Available on current domain */
$handler->display->display_options['filters']['current_all']['id'] = 'current_all';
$handler->display->display_options['filters']['current_all']['table'] = 'domain_access';
$handler->display->display_options['filters']['current_all']['field'] = 'current_all';
$handler->display->display_options['filters']['current_all']['value'] = '0';
/* Filter criterion: Domain Access: Domain ID */
$handler->display->display_options['filters']['gid']['id'] = 'gid';
$handler->display->display_options['filters']['gid']['table'] = 'domain_access';
$handler->display->display_options['filters']['gid']['field'] = 'gid';
$handler->display->display_options['filters']['gid']['operator'] = 'not in';
$handler->display->display_options['filters']['gid']['value'] = array(
  '***CURRENT_DOMAIN***' => '***CURRENT_DOMAIN***',
  1 => '1',
);
$handler->display->display_options['path'] = 'search/node/%';

```

# Answer
This appears to be a known issue:
> 1 votes

---
Tags: views, search
---


title: Rebuild all paths for a content type

text:
# Question
Title: Rebuild all paths for a content type
I want to change all paths for a given content type.

For example is would change all node of type "image" that are currently at

```
/[some_token]/[nid]

```

to

```
/photo/[nid]

```

I am using path auto and I have lots of node (70k), what would be the way to go ?

# Answer
One approach for solving this would be to add an update script, see hook\_update\_n(), to one of your custom modules and then execute it at update.php.

Within the update script, you could run an update query like

```
$ret = array();
$ret[] = update_sql("UPDATE {url_alias} a LEFT JOIN {node} n ON a.src = CONCAT('node/'. n.nid) SET a.dst = CONCAT('photo/', n.nid) WHERE n.type = 'image'");
return $ret;

```

This would update all existing URL aliases of nodes of type 'image'. I have not tested this query, so you should test it or confirm it locally before deploying it.
> 2 votes

# Answer
Like @alias suggested, you can Create an SQL query that will go over the url\_alias table and create whatever aliases you want.

Note: for a small number of nodes, the answer is much much simpler:

1. Go to admin/config/search/path/patterns to define the new URL pattern for that content type.
2. Open the admin/content page.
3. Filter by a specific node type.
4. Check the checkbox above the content item to select all the items of the certain type.
5. Select the 'update URL alias' operation.
6. Press 'Update'.

Two other options if you have a medium number of nodes:

3. Temporarily change the number of nodes per page hardcoded in core. This will allow you to use the option above with more then 20 nodes at a time.
4. Create a VBO content admin view to allow the user to select more then 20 nodes on a same time, then select which action to execute.
> 4 votes

# Answer
I think you can just use Pathauto for that. Rename the URL pattern and use the Bulk update function to regenerate all aliases. You can also do this through the content overview screen (/admin/content) by filtering out the content type "image", select all and choose "Update URL alias" from the drop down menu.
> 3 votes

# Answer
Though the query has been answered I'd like to share the methods which I've tried for building bulk url aliases with path auto module based on my experience hoping this serves of use to someone looking for a similar concern of aliasing content of huge magnitude in a generic manner:

**Drush method example to alias 1000 published nodes of specific type in loop of 50 nodes**

```
drush eval '$start=0;$limit_count=50;$break_at=1000;
while (1) { $resource = db_query("SELECT nid FROM node WHERE type=\"MY_NODE_TYPE_TO_UPDATE\" AND status=1 LIMIT $start, $limit_count");
while($result = db_fetch_object($resource)) $nodes[] = $result->nid;
pathauto_node_operations_update($nodes);
foreach ($nodes as $nid) print "\n $nid";
print "\n Completed aliasing set of $limit_count nodes";
unset($nodes);
$start += $limit_count;
if ($start >= $break_at) break;
}'

```

**Creating an auto-refresh page (by setting meta tag) to perform bulk aliasing refreshing itself every 10 seconds** Referenced from the drupal.org pathauto bulk generation page

```
<?php
  include_once './includes/bootstrap.inc';
  include_once './sites/all/modules/pathauto/pathauto.inc';
  include_once './sites/all/modules/pathauto/pathauto_node.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
?>

<html>

<head>
<meta http-equiv="refresh" content="10">
</head>

<body>
Created new URL aliases at <strong><?php print date('r') ?></strong> :: Restarting in 10 seconds ...
</body>

</html>
<?php
  variable_set('pathauto_max_bulk_update', 1000); // Or how many nodes you think you have :)
  variable_set('pathauto_transliterate', TRUE);
  node_pathauto_bulkupdate();
?>

```

While in my case the alias update was for approximately 100k nodes with some complex tokens created with my custom module (which resulted in a lot of tears) the drush method turned out to be extremely slow, while the meta tag method running in prolonged period appeared to choke the server.

Another method which seemed to work to a certain extent in a better manner was using Drupal's Batch API.

**Sample Batch API code to update all published MY\_NODE\_TYPE nodes**

```
/**
 * Callback function for regenerating MY_NODE_TYPE alias batch job
 */
function regenerate_MY_NODE_TYPE_alias_form() {
  $form = array();
  $form['#submit'][] = 'regenerate_MY_NODE_TYPE_alias_form_submit';
  $confirmation_question = 'Are you sure you wish to regenerate the alias of all MY_NODE_TYPE nodes?';
  return confirm_form($form, $confirmation_question, $path = 'admin', $description = NULL, $yes = "Confirm and Regenerate MY_NODE_TYPE Node alias", $no = "Cancel", $name = 'confirm_regeneration');
}

/**
 * form submit function for MY_NODE_TYPE alias generation batch job
 *
 * @see regenerate_MY_NODE_TYPE_alias_form()
 */
function regenerate_MY_NODE_TYPE_alias_form_submit() {
  $batch = array(
    'init_message' => t('Regeneration of MY_NODE_TYPE alias in progress'),
    'operations' => array(),
    'finished' => '_regenerate_MY_NODE_TYPE_node_alias_complete',
    'error_message' => t('MY_NODE_TYPE alias Batch has encountered an error.'),
    'title' => t('Rebuilding MY_NODE_TYPE alias'),
  );
  $batch['operations'][] = array('_regenerate_MY_NODE_TYPE_node_alias', array());
  watchdog("form_submit", "MY_NODE_TYPE alias batch array initialized, before calling batch_set");
  batch_set($batch);
}

/**
 * Function responsible for regeneration of MY_NODE_TYPE nodes' titles
 */
function _regenerate_MY_NODE_TYPE_node_alias(array &$context) {
  if (!isset($context['sandbox']['progress'])) {
    $context['results'][] = '';
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['start_value'] = 0;
    // select all published MY_NODE_TYPE nodes
    $context['sandbox']['max'] = db_result(db_query("SELECT COUNT(nid) FROM {node} WHERE `type` = '%s' AND `status` = 1", 'MY_NODE_TYPE'));
    watchdog("Alias max_value", "Alias Batch maximum value set " . $context['sandbox']['max']);
  }
  watchdog("alias regeneration", "Current progress value is " . $context['sandbox']['progress']);
  $fetch_limit = 100;
  $nid_rs = db_query_range("SELECT `nid` FROM {node} WHERE `type` = '%s' AND `status` = %d", $args = array('MY_NODE_TYPE', 1), $from = $context['sandbox']['progress'], $fetch_limit);

  while ($MY_NODE_TYPE_nid_arr = db_fetch_array($nid_rs)) {
    $context['results'][] = $MY_NODE_TYPE_nid_arr['nid'];
    $MY_NODE_TYPE_nodes[] = $MY_NODE_TYPE_nid_arr['nid'];
  }
  // call pathauto mass update method with the array of nodes retrieved
  pathauto_node_operations_update($MY_NODE_TYPE_nodes);
  $context['sandbox']['progress'] += 100;
  $context['message'] = t("Now processing node %nid. (%progress of %total)", array('%nid' => $MY_NODE_TYPE_nid_arr['nid'], '%progress' => $context['sandbox']['progress'], '%total' => $context['sandbox']['max']));
  if ($context['sandbox']['progress'] >= $context['sandbox']['max']) {
    $context['finished'] = 1;
  }
  else {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

/**
 * @function success handler for MY_NODE_TYPE alias generation
 */
function _regenerate_MY_NODE_TYPE_node_alias_complete($success, $results, $operations) {
  drupal_set_message("Completed batch operation");
  if ($success) {
    $message = count($results) . ' MY_NODE_TYPEs processed.';
    // $message .= theme('item_list', $results);  // lists all nodes that were processed
    drupal_set_message($message);
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
    watchdog('alias batch_error', $message);
    drupal_set_message($message, 'error');
  }
}

```
> 1 votes

# Answer
For Drupal 7, this is simple. You'll need the modules Views Bulk Operations, Administration Views. Tutorial here: https://drupal.org/node/1326928
> 0 votes

---
Tags: 6, path-aliases
---


# Question
Title: Login with a REST service (services module)
I work with Drupal 7 (services 3.x) to implement a REST service. When I test a login request with this script:

```
$service_url = 'https://dev.mysite.org/api/blog/user/login.xml'; // .xml asks for xml data in response
$post_data = array(
  'username' => 'admin',
    'password' => 'admin',
    );
$post_data = http_build_query($post_data, '', '&'); // Format post data as application/x-www-form-urlencoded
// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string
curl_setopt($curl, CURLOPT_POST, true);             // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // POST this data
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
print "RESPONSE:\n";
var_dump($response);
// parse the response
$xml = new SimpleXMLElement($response);
$session_cookie = $xml->session_name .'='. $xml->sessid;
print "SESSION_COOKIE: $session_cookie";
file_put_contents('session_cookie.txt', $session_cookie);

```

I receive this error:

```
* upload completely sent off: 29 out of 29 bytes
< HTTP/1.1 401 Unauthorized: Missing required argument name
< Date: Sun, 09 Feb 2014 02:39:45 GMT
* Server Apache/2.2.22 (Ubuntu) is not blacklisted
< Server: Apache/2.2.22 (Ubuntu)
< X-Powered-By: PHP/5.3.10-1ubuntu3.9
< Expires: Sun, 19 Nov 1978 05:00:00 GMT
< Last-Modified: Sun, 09 Feb 2014 02:39:45 +0000
< Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
< ETag: "1391913585"
< Set-Cookie: DRUPAL_UID=-1; expires=Tue, 04-Mar-2014 06:13:05 GMT; path=/; domain=.dev.labdoo.org; secure
< Vary: Accept-Encoding
< Content-Length: 0
< Content-Type: text/html
<
* Connection #0 to host dev.mysite.org left intact
RESPONSE:
string(0) ""
PHP Fatal error:  Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/myuser/Desktop/test.php:23
Stack trace:
#0 /home/myuser/Desktop/test.php(23): SimpleXMLElement->__construct('')
#1 {main}

```
* My REST service configuration is:

* I followed this example to test the service.
* It is activated the session authentication in the Services module.
* It is activated application/x-www-form-urlencoded, json, xml....

**UPDATE**

It seems which the code has multiple mistakes.... I replaced my post\_data variable for this:

```
$post_data = array(
  'name' => 'admin',
  'pass' => 'admin',
);

```

And now, I send the login request correctly ( I receive a 200 response), but now, I try to parse the response message to get the cookie-session, I don't receive any response message. I am getting an error like this:

```
* upload completely sent off: 21 out of 21 bytes
< HTTP/1.1 200 OK
< Date: Wed, 12 Feb 2014 21:35:36 GMT
* Server Apache/2.2.22 (Ubuntu) is not blacklisted
< Server: Apache/2.2.22 (Ubuntu)
< X-Powered-By: PHP/5.3.10-1ubuntu3.9
< Expires: Sun, 19 Nov 1978 05:00:00 GMT
< Last-Modified: Wed, 12 Feb 2014 21:35:36 +0000
< Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
< ETag: "1392240936"
< Set-Cookie: DRUPAL_UID=-1; expires=Sat, 08-Mar-2014 01:08:56 GMT; path=/; domain=.dev.mysite.org; secure
< Content-Length: 1316
< Content-Type: application/xml
<
* Connection #0 to host dev.mysite.org left intact
RESPONSE:
string(1316) "
Fatal error: Unsupported operand types in /var/www/lbd/profiles/labdoo/modules/contrib/services/includes/services.runtime.inc on line 417

Call Stack:
    0.0000     334912   1. {main}() /var/www/lbd/index.php:0
    0.0347    4175712   2. menu_execute_active_handler() /var/www/lbd/index.php:21
    0.0348    4176376   3. call_user_func_array() /var/www/lbd/includes/menu.inc:517
    0.0348    4176756   4. services_endpoint_callback() /var/www/lbd/includes/menu.inc:517
    0.0366    4343036   5. call_user_func() /var/www/lbd/profiles/labdoo/modules/contrib/services/services.module:218
    0.0366    4343036   6. rest_server_server() /var/www/lbd/profiles/labdoo/modules/contrib/services/services.module:218
    0.0385    4449312   7. RESTServer->handle() /var/www/lbd/profiles/labdoo/modules/contrib/services/servers/rest_server/rest_server.module:39
    0.0432    4532668   8. services_controller_execute() /var/www/lbd/profiles/labdoo/modules/contrib/services/servers/rest_server/includes/RESTServer.inc:46
    0.0436    4534132   9. _services_controller_execute_internals() /var/www/lbd/profiles/labdoo/modules/contrib/services/includes/services.runtime.inc:106
    0.0436    4534176  10. _services_authenticate_user() /var/www/lbd/profiles/labdoo/modules/contrib/services/includes/services.runtime.inc:162

```

**UPDATE 2**

I am trying to create a new user to check if my error is related to working with an admin account. I tried (now with the script postman for Chrome) to create a new user via REST... It would be easy... but I wasn't ( I tested username,name,email,mail)...

# Answer
Finally, I have fixed the problem. It was a bug in the Services module. I updated from `7.x-3.5` to the `7.x-3.7` version, I followed the @sibiru tutorial and it started to work well.
> 0 votes

# Answer
This is the important bit:

> HTTP/1.1 401 Unauthorized: Missing required argument name

Just change your payload to

```
$post_data = array(
  'name' => 'admin',
  'password' => 'admin',
);

```
> 2 votes

# Answer
Try watching this screencast, it helped me
> 2 votes

---
Tags: users, services, 8
---


# Question
Title: How do I get a field count from an executed query?
I'm sure this exists, but after a few dozen searches, I'm not any closer to an answer.

After I've executed a query in Drupal (for example)

```
$dbParts = db_select("parts", "p")
    ->fields("p")
    ->execute();

```

How can I get a count (or list) of fields without pulling this first record? With MySQL I was able to use "mysql\_num\_fields".

**UPDATE**

Just to give a little background... I have some old code (using mysql\_\* functions) that export data to the DBF format. In order to format the header of the DBF, I need to have a field count (and information about the fields) even if the record count is 0 in order to format a "blank" database.

# Answer
> 2 votes
Drupal uses PDO, whose equivalent function is `PDOStatement::columnCount()`:

> Returns the number of columns in the result set represented by the PDOStatement object. If there is no result set, PDOStatement::columnCount() returns 0.

So what you're looking for isn't totally possible these days. I can't see a Drupal equivalent of `columnCount()`, but you can always grab the PDO connection object with `Database::getConnection()`, and work with that directly if it'll help you get part of the way there.

To take a different approach, and assuming you've used the schema API to describe your table to Drupal, you can query that instead:

```
$table = drupal_get_schema_unprocessed('MYMODULE', 'table_name');
$fields = $table['fields'];

```

---
Tags: 7, database
---


# Question
Title: Drupal 6 - form submission data loss from empty required fields
Scenario: Content profile node-type has new required fields added after many users have already filled out their profile info. (this scenario can work for any node-type). They go back to update their profile, and don't see the need to fill in the required fields, submit the forms, miss seeing the error message, and walk away, thinking that their updates have been submitted successfully.

I've had various versions of this same scenario play out across different websites and situations. And have tried out various home-made solutions where I have data collected at the validation stage in a nodeapi hook implementation. But those solutions are painful and flawed.

Anyone know of a simple solution to this pervasive problem?

# Answer
This is the default behavior, but I agree that it would be a irritating issue.

Perhaps if you did something like a warning message at the top when the user loads a previously edited node that has empty fields that are now required? That would get them looking at it from the get go. `form_alter` could do this for you.

Adding some pretty CSS on the page to highlight the empty required fields would also help guide them to the fields where their input is required.
> 0 votes

---
Tags: 6, nodes
---


# Question
Title: Pre-populate a field based on another node's field value
I have several different fields attached to my user (user type) which are used to temporarily save settings for that user (most are node references, set by rules/flags/buttons) Is there a way to auto populate a new node's fields based on tokens or rules so that every time a user starts to create a node, some of the fields are pre-populated based on the vales stored in the user's user fields? Note: I would like to expose these values to the user during the node creation process.

# Answer
You should check out `hook_form_alter`. It would let you preload form values but still keep them editable.

Something like this would work to load something from the user's profile fields into the node form for new nodes.

```
<?php
  function custom_module_form_alter(&$form, $form_state, $form_id) {
    switch($form_id) {
      case 'NODETYPE_node_form':
        global $user;
        $current_user = user_load($user->uid);
        // Set only on nodes that haven't already been saved
        if (!isset($form['#node']->nid)) {
          $form['field_YOUR_FIELD_NAME'][LANGUAGE_NONE][0]['value']['#default_value'] =
            $current_user->field_YOUR_USER_FIELD[LANGUAGE_NONE][0]['safe_value'];
        }
      break;
    }
  }
?>

```
> 4 votes

---
Tags: entities, nodes, rules
---


title: How to hook into an attachment?

text:
# Question
Title: How to hook into an attachment?
I have a field loading hidden in an attachment view and I need to hook into that attachment to alter the output of the field.

It involves PHP and I'd rather hook into template.php rather than download some PHP module to store PHP code in my database.

I've tried hooking into theme\_views\_pre\_render but I can't find my attachment, I can only modify the $view-\>attachment\_before output.

That, plus I can't actually obtain the field values in this hook?

So how can I hook into a field value in an attachment?

# Answer
An attachment is just like any other view (except that it is attached to other views), and so can be manipulated as such:

In template.php:

```
function THEMENAME_preprocess_views_view_fields(&$vars) {
  if (isset($vars['view']->name) && $vars['view']->name == 'VIEW_NAME' && $vars['view']->current_display == 'ATTACHMENT_NAME') {
    foreach ($vars['fields'] as $id => $field) {
      if ($id == 'FIELD_NAME') {
        $vars['fields'][$id]->content = 'new value';
      }
    }
  }
}

```

Remember to clear your cache.
> 0 votes

---
Tags: views
---


# Question
Title: Using PHP namespace hybrid for Drupal modules
I've been getting into PHP namespaces and had a thought about how to clean things up a bit in my custom modules. I was thinking that for hooks I could use the traditional Drupal method of defining functions in the global namespace with the module name prefix but for all other functions and classes I could define them inside a PHP namespace. So, for my module "donut\_win" a file would look like this:

```
<?php
namespace {

function donut_win_menu()
{
  $items['donut/win/%'] = array(
     'title'           => 'Hey, there!'
    ,'description'     => "Eveyone wins when donut wins."
    ,'page callback'   => 'Donut\\Win\\render_page'
    ,'page arguments'  => array(1)
    ,'access callback' => true
    ,'type'            => MENU_CALLBACK
  );

  return $items;
}

function donut_win_cron()
{
  # magic!
}

} # namespace global

namespace Donut\Win {

function render_page ($bingo)
{
  # so much magic!
}

}

```

I'm interested in what potential pitfalls would be with this method and any other disadvantages or advantages. Is this a good idea or am I crazy?

# Answer
> 0 votes
It looks like there aren't any technical pitfalls. But, using PHP namespacing is not part of Drupal's coding standards. Clive sums it up nicely in a comment on the question:

> Drupal has it's own coding standards which it's best to follow, and namespacing functions isn't part of that. If you're not bothered about the Drupal conventions, then sure, do whatever works for you...but if you're looking to write a module to contribute back to the community, or want it to be understood easily by other Drupal devs in the future, it's best to stick to standards

---
Tags: 7
---


title: Print specific page of a paged node

text:
# Question
Title: Print specific page of a paged node
I am using Print module to print a Drupal node. Recently users have asked the ability to print a node in form of individual pages.

For example if a paged 'Drupal' article spans on 5 pages, user wants the ability to print only 2nd page.

I tried to analyze the `var_dump` of a node (by pro-grammatically loading it) to find any information related to paging but I did not have any luck.

I am thinking to do paging of a node pro-grammatically and load different paged content in an array.

How can I do this ?

Please let me know if I need to provide more information.

# Answer
I was able to get specific paged content using following code.

```
  $data = node_load($nid);
  $pages = explode('<!--pagebreak-->' , $data->body['und'][0]['value']);

```
> 0 votes

---
Tags: paging
---


# Question
Title: How do I display a history of messages between two users using the Privatemsg module?
Anyone knows how to display a list of all messages that two users had shared using the Privatemsg module for Drupal 7? Sort of a history of the conversation between the two users in a block or in a `template.tpl.php`?

Any help please.

# Answer
> 1 votes
The OP succeeded in doing this by creating a helper function in a custom module.

The function accepts two arguments, the sender uid and the recipient uid. It returns the list of messages.

Then one can call this function from anywhere to get the required list of messages.

Here is the function the OP created:

```
function get_message_history($sender_uid, $recipient_uid) {
  $query = db_query("SELECT * FROM pm_index, pm_message
    WHERE ((pm_index.recipient = $sender_uid AND pm_message.author = $recipient_uid)
      OR (pm_index.recipient = $recipient_uid AND pm_message.author = $sender_uid))
      AND pm_index.mid = pm_message.mid
    ORDER BY pm_message.timestamp DESC");
  $messages = $query->fetchAll();
  return $messages;
}

```

---
Tags: privatemsg
---


# Question
Title: How to add multiple havingCondition with OR operator?
I want to add havingCondition with OR operator

In normal sql query my having conditions are like:

```
group by n.nid
having comment_count!=0 OR viewed_count!=0 OR likes_count!=0;

```

With adding multiple havingConditions like:

```
$query->havingCondition('likes_count', 0, '!=');
$query->havingCondition('viewed_count', 0, '!=');
$query->havingCondition('comment_count', 0, '!=');

```

but It gives having condition with AND operator

Can any one please help me in.

# Answer
> 1 votes
Create OR conditions separately, in a variable, and then just use them:

```
$or = db_or()->condition('a', 0, '=')->condition('b', 0, '=')->condition('c', 0, '=');
$query->havingCondition($or);

```

For more details, read `db_or` documentation on Drupal API page. This should always be your first place to go, before you ask API-related questions.

---
Tags: database
---


# Question
Title: How can i make my comments field allow images as part of the comment? (drupal 7)
I would like to allow users to put images into their comments but I can't seem to find a module or anyone who has done such a thing.

# Answer
> 0 votes
Install CKEditor module. Using this module you can use pictures in comments also

> This module will allow Drupal to replace textarea fields with the CKEditor - a visual HTML editor, usually called a WYSIWYG editor. This HTML text editor brings many of the powerful WYSIWYG editing functions of known desktop editors like Word to the web. It's very fast and doesn't require any kind of installation on the client computer.

# Answer
> 0 votes
You can use IMCE! It's very easy to use. But let me tell you that this only works for inserting and formatting the image inside a comment. If you want images to be comments you'll have to create a custom module (I am working on this right now).

---
Tags: media, comments
---


# Question
Title: What to do if we want a input format for select options of a webform?
I have a web form with select option field whose value is quite long. I cannot use css to configure this. I need to use input format so that I can break this option using HTML code. Is there any module or something?

**Additional Info:** We don't have input format option in case of webform module's select fields. My value in select field option is quite long. I have three values like below:

```
  Session 1: PwC
  11:30am
  Sourcing Strategies for the Next Decade

  Presented by:
  Damon Paling, Partner, PwC China
  Anthony Tennariello, Partner, PwC New York
  Maytee Pereira, Director, PwC New York.

```

I would like show the user like this but this is not possible since we don't have input format (HTML) to select.

# Answer
> 0 votes
I recommend the chosen module.

https://drupal.org/project/chosen

Its goal is to make input element a little more user friendly.

See here: http://harvesthq.github.io/chosen/

---
Tags: webforms, theming
---


# Question
Title: on delete of one field delete other field too
I want to implement some logic using what I can define that one delete of one field delete other related field.

so is there any module available or anythings else using what I can define cascade delete.

# Answer
> 1 votes
You can use hook\_field\_delete to determine which field is removed, and if its "yours" - find out which field you need to delete next and delete it

```
function hook_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
   if ($field['field_name'] == 'YOUR_FIELD_NAME') {
       //do some stuff to determine which
       //field you need to delete
       //and delete it
       //how to remove the field - the link below
   }

}

```

how to remove the field

---
Tags: entities
---