# Question
Title: Change some charachter in All field before saving node
I want done a action (change some charachter) on every field in saving node.
I know for specified field can use `hook_node_presave` ,but I want do this on all field in all content type (proximity 300 field and 40 content types) with out specify one by one . Have drupal api for hook\_filed\_presave or something like it?

This is work for specified field

```
function custom_changes_node_presave($node){

    if ($node->type ==='designer_background_images'){

        $filename =$node->original->field_db_image['und']['0']['filename'];
        $uri       =$node->original->field_db_image['und']['0']['uri'];

        $filename    = str_replace (" ", "_", $filename);
        $uri        = str_replace (" ", "_", $uri);

        $node->original->field_db_image['und']['0']['filename']= $filename;
        $node->original->field_db_image['und']['0']['uri']       = $uri;

        //field_attach_presave('node', $node);

            // And the actual field change for the given node (e.g. entity).

        //field_attach_update('node', $node);

        // echo "<pre>";
            // print_r($node);
        // exit;
        // print $node->original->field_db_image['und']['0']['filename'];
        // print $node->original->field_db_image['und']['0']['uri'];
    }
}

```

# Answer
With this method you have access all fields used in your content types.
entity\_get\_info Doc and field\_info\_instances Doc take me idea how can I got them.

```
function custommodule_entity_presave($entity,$type) {
    $allFields=field_info_instances('node');
    $savedFields=$allFields[$entity->type];
    foreach($savedFields as $index=>$field) {
        /// this is just general answer and for perform this act I have to be more careful
        $entity->$field['und'][0] =my_custom_function ($entity->$field['und'][0]);
    }
}

```
> 2 votes

# Answer
You're probably looking for `hook_entity_presave()`:

> Act on an entity before it is about to be created or updated.

It's equivalent to `hook_node_presave()`, but as the name suggests is run for all entity types.

From there you can use the Field Info API functions to get a list of fields that should be attached to that entity, then loop through them and do the character replacement.
> 5 votes

# Answer
You can do it with this modules:

This 3 modules are a "must have" in every drupal projects with fields.

If they are all values, you should activated the "Retroactive update" to update all the old fields.

Oskar
> -1 votes

---
Tags: 7, entities
---


# Question
Title: How to add an image gallery to content type
What I need is to let the user add a few images in the content type, and after the user posts Title, Body message, these images should show as a gallery on the node.

I know how to do the gallery via views Gallerific, but how do you add this gallery to a node?

# Answer
This might be of interest to you. It uses a content type and views for each user. Add a gallery for every user in a block If you require further assistance please let me know. The answer is quite detailed and is broken up step by step. What version of Drupal are you using.
> 0 votes

---
Tags: nodes, media
---


title: Drupal 6 node_load with conditions

text:
# Question
Title: Drupal 6 node_load with conditions
Here is the situation:

I have two content types. Content type a has a CCK reference field for content type b.

Now I am trying to load all the nodes from content type a that are referenced to content type b.

Here is the code that I have.

```
$nidcur =  $fields['nid']->content;

$node = node_load(array("field_micselect" => $nidcur));

dpm($node);

```

So I would like to load all the nodes that are related to the nid $nidcur.

# Answer
This should work for you:

```
$referenced_nodes = db_query("SELECT `field_FIELD_NAME_nid` AS `nid` FROM {content_field_FIELD_NAME}");
while ($referenced_node = db_fetch_object($referenced_nodes)) {
  $node = node_load(array('nid' => $referenced_node->nid));
  // Do your stuff here
}

```
> 2 votes

---
Tags: 6, nodes, database
---


# Question
Title: How can I control access to group-private content based on organic groups roles?
I would like my groups to be able to create content that is not only private to a group, but also private to certain roles within the group. For example, a post that is only accessible by members of Group A that also have the "officer" role.

Ideally, I'd be able to make the roles group-specific because different groups should be able to create and assign roles to their members.

How can this be accomplished?

# Answer
> 1 votes
I needed somewhat similar functionality for a drupal 6 site and gave up on using OG for this. Instead I made a vocabulary that defined my groups and used tac\_lite for setting access. The setup is being ported to drupal 7 right now, and I haven't had any problems implementing the same functionality in d7 so far. Maybe tac\_lite is a solution for you? http://drupal.org/project/tac\_lite

# Answer
> 1 votes
One possibility, which would twist your idea but still offer the same functionality would be http://drupal.org/project/og\_subgroups (still in beta for D7 unfortunately).

# Answer
> 0 votes
OG User Roles allows group administrators of organic groups to grant additional user roles to individual members of a certain group.

# Answer
> 0 votes
To allow permissions and roles to be changeable for groups, you need to add that feature to the 'group entity' This can be achieved by using this example link. **http://yourwebsite/admin/config/group/fields**.

http://vimeo.com/34032652

---
Tags: 7, users, organic-groups
---


title: Get length of the teaser

text:
# Question
Title: Get length of the teaser
I need to get the setting on what length the teaser of a custom made content type is set.

I tried Google'ing for it, but so far I have ziltch results. I also tried looking in the database, in the field\_config\_instance, field\_config and the variable tables, but they couldn't give me a value either...

Now, I'm hoping you experts could help me to point me to the right direction? Would be appreciated. :-)

Thanks in advance.

# Answer
> 0 votes
Please check ReadMoreControl module, this might help you..By this module you can add Read more links to other supported view modes

---
Tags: nodes
---


# Question
Title: How to build links compatible with clean and "dirty" URLs?
I have a development site that doesn't support clean URLs, my production site does support them. If I build a link in the body of a node like:

```
<a href="view-something/4,7">View something</a>

```

This shows ok on my production site but gives a 404 while in development site. How do I build universally good URLs ?

# Answer
You should be able to define such Links with the menu\_hook

http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_menu/7

Especially lookt at the Wildcard options i used them recently to define own urls
> 0 votes

---
Tags: 7, navigation, uri
---


# Question
Title: Provide several download option for same image in Drupal 7
Would anybody have any idea of how to create several download option of the same image in Durpal 7.

The sample website is: http://www.travesto.com/content/101jpg-anime-animated where several download option is enabled.

I would like to create a similar option for my birthday photos. I think may be views module is used here. BUt not sure. If anybody have any idea of doing this. plz help me....

# Answer
Do you mean different resolutions? Simply, you have to upload them, and link the files.

Then there are the following modules:
> 1 votes

# Answer
You can create a content type like 'gallery' and you can insert a 'image' image field then you create a set of media image preset.
For example 'small-download', 'medium-download', 'big-download'.

Now, in your theme, you overwrite field--image--gallery.tpl.php some code like 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): ?>

          <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>

              //here you have to find [with print_r($item)] where in the $item
              //is stored the image url and put it in $url

              $image = array(
                'style_name' => 'thumb',
                'path' => $url
                );

              theme_image_style($image);

              l('Download small', image_style_url('small-download', $url));
              l('Download medium', image_style_url('medium-download', $url));
              l('Download big', image_style_url('big-download', $url));
          </div>

        <?php endforeach; ?>
      </div>
    </div>

```
> 0 votes

---
Tags: 7
---


title: Jquery toggle show/hide fields

text:
# Question
Title: Jquery toggle show/hide fields
Hi I would like to offer a toggle show/hide for some fields that are not mandatory. Is there is a modules for this or would it be a case of using a template and jquery.

# Answer
You can put the not mandatory field in a group installing Field Group. The group have a 'collapsible' option.
> 1 votes

# Answer
You can Put your fields toghether with Field Group Module ,and after it you can show/hide it(field groups) by custom jquery code.
> 1 votes

---
Tags: javascript
---


# Question
Title: How to enable Google analytics while site is in maintenance mode?
I want to know how many users visit my site that is currently in maintenance mode. I have installed the google analytics module, but it doesn't add google tracking codes to the maintenance page, so google analytics says "Tracking not installed".

How do I enable it while site is in maintenance mode?

# Answer
You'll have to do it manually unfortunately, the normal page building handler isn't called for the maintenance page so the analytics module never actually builds up the necessary javascript.

You can follow the instructions here to set up a custom maintenance page template, from there you'll just need to add the tracking code manually to the bottom of the site. It should start working instantly.
> 1 votes

---
Tags: 7, google-analytics, maintenance-mode
---


# Question
Title: Displaying uid on user/x/ and user/x/edit page
I want to display the **uid** (read-only) of the user on both the **user/x** and **user/x/edit** page.

By using the function below I managed to show the **uid** on the **user/x/edit** page.

```
function my_module_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
    if (arg(0) == 'user') {
        $form['uid_read_only'] = array(
            '#markup' => 'User id : ' . '<b>' . arg(1) . '</b>',
            '#weight' => -500,
            '#disabled' => TRUE,
        );
    }
}

```

How do I show the uid on the **user/x** page (view state)?

# Answer
Implement hook\_user\_view() to show the **uid** on the **user/x** page.
> 4 votes

# Answer
Start by copying drupal theme user-profile.tpl.php into your theme, make sure to keep the name as user-profile.tpl.php.

open the file and edit it the way you want, I usually use this to get the uid

```
global $user
$uid = $user->uid;

```

then maybe you want to do something like:

```
print $user->uid;

```

Dont forget to clear your cache.
> 0 votes

---
Tags: 7, users
---


title: Remove Hashtag from url

text:
# Question
Title: Remove Hashtag from url
In a Drupal site, I've a hashtag appended to my url. Example:

```
www.myUrl.com/content/node#.UFnCybLN9Nu

```

I don't know where it comes from and I don't know how to remove it. Any ideas?

# Answer
That is coming from the AddThis service (media sharing icons). You maybe copied a link from there or if you are using that module, you selected to track the shared links.

If it's your widget, you can disable it by removing a line in JS (there is something like `"track = true"` in the widget code).
> 5 votes

---
Tags: uri
---


# Question
Title: WHERE MySQL clause not working in Drupal 6
I am writing a Drupal Module and I have encountered a problem. This is my code:

```
$query3 = db_query("SELECT nid FROM {node} WHERE uid=19");
var_dump(db_result($query3));

```

It currently returns: `bool(false)`

Now when I run this query in phpmyadmin it returns the desired nid (47) - no problem.

What am I doing wrong?

# Answer
> 2 votes
Try

```
$query3 = db_query("SELECT nid FROM {node} WHERE uid = '%d'", 19);

```

this is the proper way to handle variables in the db\_query, as it prevents sql injection.

```
//grab the current user
global $user;
$query3 = db_query("SELECT nid FROM {node} WHERE uid = '%d'", $user->uid);

```

---
Tags: database
---


# Question
Title: Display number of times content is referenced in content
How would I go about implementing the following content types + fields

* Parent
    + Name
    + Description
    + Other fields (e.g. location, date)
    + Number of children
* Child
    + Name
    + Description
    + Other fields (e.g. location, date)
    + Parents (entity reference)

Children can have multiple parents.

Basically what I want to do is to create a new Child and "tag" a Parent in it. A View with a list of Parents would then display something like "\[Parent Name\] has x Children" for each Parent.

I'm very new to Drupal so if I'm going about this completely the wrong way, please let me know!

# Answer
This video series helped me an infinite amount: http://vimeo.com/33251051, http://vimeo.com/33252553.

1. Make sure Child has an entity reference to Parent.
2. Create a new view
3. In Filter Criteria, add a new Type (= Parent)
4. In Advanced\>Other, set Aggregation to YES
5. In Advanced\>Relationships, add a new relationship for "A bridge to the Content entity that is referencing Content via field\_parent" where field\_parent is your entity reference. Call this "Parents"
6. In Fields, add Content: Title and when prompted set its Aggregation type to Group results together
7. In Fields, add Field: Parents and when prompted set its Aggregation type to COUNT (Distinct)
8. Ta-da
> 5 votes

# Answer
You can use combination of Taxonomy and Content Types... Please follow below steps to complete the functionality....

1. Create a vocabulary called parent.
2. Add parent terms -- You can give term name & description.
3. Create a Content Type Called Children
4. Add Term Reference field and reference to Parent Vocabulary.
5. For above field give number of values as Unlimited so that Children can have multiple parents.
6. Use views module to create a new view with base table as taxonomy and show list of parent terms with number of nodes tagged using views aggregation functions.

It makes sense to create a content Type for parent also if you have many parents...

In views you can add a entity reference relationship and use aggregation setting and check you can able to pull off what you are trying to achieve i guess...

Optionally check this module if it solves the issue drupal.org/project/nodereference\_count....

If nothing works you can use views php module and write a single query to achieve the functionality...

Hope it resolves your problem.
> 0 votes

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


# Question
Title: Views: expose filter - filter out results between a specific set of dates
I have a views (content type = car, Create date filter"exposed" and some fields to display in the result in a table).

is there any way to display all the node not created in the date that selected using the filter?
Thanks

# Answer
You should be able to add a view filter that uses the operator of "Is not between" when referencing a date.

You can have multiple filters for the same value, so you could allow people to search for dates, but have a second filter that removes results between X and Y
> 1 votes

---
Tags: 7, views
---


# Question
Title: Display specific nodes on specific pages
How do I display specific nodes from a view on specific pages?

For example, I create a CCK field ("Display on node id:") for the content type *Ads*, and put there IDs of content type *Basic page* where I want display this *Ads*.

Is there to achieve this without additional modules?

# Answer
Create a block display mode for that view (the view that display ads) and place that block on basic page node types.

In the view you should add a Contextual filter (under Advanced settings) and validate it as the node ID from URL. Then add a filter that selects only ads for that node ID.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Adding to that list of display options that includes "Default" and "Teaser"
Under structure \> content types \> manage fields, there are display options in the upper right. The system-defined ones are "default" and "teaser" but I have seen "tokens" and "colorbox" added by contrib modules.

What hook or function do I use to give my modules access to create these new content type displays?

# Answer
You can either use the Entity View Mode module (which lets you define new view modes through the UI) or you can use `hook_entity_info_alter()` in a custom module to create them through code:

```
function MYMODULE_entity_info_alter(&$info) {
  $info['node']['view modes']['some_view_mode'] = array(
    'label' => t('Some View Mode'),
    'custom settings' => TRUE,
  );
}

```

The 'custom settings' bit is defined like this in the `hook_entity_info()` docs:

> A boolean specifying whether the view mode should by default use its own custom field display settings. If FALSE, entities displayed in this view mode will reuse the 'default' display settings by default (e.g. right after the module exposing the view mode is enabled), but administrators can later use the Field UI to apply custom display settings specific to the view mode.

Basically you want to set the to `TRUE` to have the view mode show up on the manage fields page.

Using either of those methods you should see your new view mode(s) pop up everywhere (the manage display form for nodes, in views, etc.)
> 3 votes

# Answer
You will have to use `hook_entity_info_alter` to add new view modes to existing entities. But if you creating new entity then you can do it in the `hook_entity_info` itself.

```
function MYMODULE_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['another_teaser'] = array(
    'label' => t('Another teaser'),
    'custom settings' => TRUE,
  );
}

```

Also have a look at `node_entity_info()` if you want to define it in your own entity type.
> 3 votes

---
Tags: entities, theming, nodes
---


# Question
Title: Drupal Installation running without settings.php (multisite)
What we intended to achieve was setup drupal.abcd.com as main installation of multisite setup, and abcd.com, xyz.com, pqrs.com as sub-sites of the multisite setup.

The main installation (drupal.abcd.com) should contain the default Drupal installation (with the Bartik theme), and abcd.com should have the ABCD theme with content.

drupal.abcd.com is automatically taking the settings.php file from abcd.com. So, when I make change in abcd.com (e.g. setting a different database) the same change is done for drupal.abcd.com.

I also tried deleting drupal.abcd.com/sites/default/settings.php, but I can visit drupal.abcd.com with same settings as abcd.com.

The installation and creation of folders were done by the customer; I don't know what mistake he did.

Could anyone please suggest me where things might have gone wrong, or what can be done to avoid this behavior, and run everything as normal?

# Answer
> 3 votes
Have a look at sites.php in your sites folder.

```
 $sites = array(
   'devexample.com' => 'example.com',
   'localhost.example' => 'example.com',
 );

```

> The above array will cause Drupal to look for a directory named "example.com" in the sites directory whenever a request comes from "example.com", "devexample.com", or "localhost/example".

So in your case you should have `'drupal.abcd.com' => 'default'`

The reason why its picking up settings file from abcd.com is because when a request comes for drupal.abcd.com it looks for folder drupal.abcd.com since that folder is not there it will look for next match like abcd.com and it picks it up from there.

I am not sure about Drupal 7 site set up but playing around with sites.php should fix it.

# Answer
> 0 votes
With **kantu's** help the problem is fixed now.

What I did was copying examples.sites.php, and creating the sites.php file.

Then, I uncommented the last two lines of sites.php, and re-wrote them as:

```
 $sites['drupal.abcd.com'] = 'default';
 $sites['abcd.com'] = 'abcd.com';

```

---
Tags: 7, multi-sites, configuration
---


# Question
Title: Can I override the title attributes on an H2 tag within a specific drupal region or block?
I have a region within a site theme I'm working on, and would like the H2 title attribute to be white as opposed to the rest of the theme which calls for a blue. Can I use CSS to assign specific font size and color attributes to the title tag for that specific region/s within the theme?

# Answer
You can use CSS to style the H2 tag inside a specific block.

Your block should have a unique ID, based on the name of the block.

Your CSS would look something like this:

```
<style>
#block-your-blockname h2 {
 color: white !important;
}
</style>

```

Note: you may not need "!important", and that CSS can go in your main CSS file if you want.
> 1 votes

---
Tags: theming
---


# Question
Title: How does Drupal know which Entity View Mode to use?
When Entity View Modes are defined, how does Drupal know which to use? Are they only useful with Views, or can they be used in the node display as well? If so, is that specified in the template, or somewhere else?

# Answer
> 4 votes
On the backend, the view mode is used everywhere `node_view($node, $view_mode);` is called. In general, the caller specifies which is needed. And since the system only knows about `"full"` and `"teaser"` by default, those are the ones that are baked into core. Code does have the option of reading all of the view modes when it wants to get rendered content.

Views are the most obvious place the view modes get used, and also the place I find the most helpful.

If you have a node reference, and set the display to "Rendered Node" you can choose the view mode, and it will pull from the list.

In Panels the view mode shows up in the settings for the "Node Being Viewed" content pane. This typically gets used in the node override page, and it the only way that I know of to specify the view mode for a `node/$nid` path.

I suspect there are other places, too, especially with modules that make use of CTools content types.

# Answer
> 5 votes
With a tiny bit of glue code you can use specific node template files for different view modes, so they can become pretty useful:

```
function MYMODULE_preprocess_node(&$vars) {
  if($vars['view_mode'] == 'some_type') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__some_type';
  }
}

```

That will allow you to use template files with names like `node--article--some-type.tpl.php` specifically targeted to that view mode.

Other than that MPD's answer has all of the other common cases covered.

---
Tags: views, nodes, entities
---


# Question
Title: Customizing a drupal webform for Drupal 6
I am working on a system that would require users to register online by filling out a membership application form. There used to be a PDF form that used to be filled out and sent for processing. The client wants the online form to be as close in appearance to this PDF form. Is it possible to customize a form created using webforms such that it can have some of these elements such as logos, images, etc.?

# Answer
> 1 votes
You can customize form's HTML markup using Drupal's form alter hooks:

1. hook\_form\_alter or hook\_form\_FORM\_ID\_alter
2. Form API Reference

after changing form's markup you should only styling form using CSS.

---
Tags: webforms
---


# Question
Title: Edit/View Tab in Region other than Content
I'm trying to set up two contexts for use with a sub-theme of Omega.

3 Column Context: Uses the regions Sidebar First, Content and Sidebar Second. Content is 6 columns wide. The Sidebar regions are each 3 columns wide. This works fine.

2 Column Context Uses "Content Second" (9 cols. wide) and Sidebar Second (3 cols. wide).

Content Second is an additional region added to the info file in the sub-theme. regions\[content\_2\] = Content Second

The problem that I'm having is getting the Edit/View tabs to display in that region, the way they do with region "Content".

I've added region--content\_2.tpl.php to my sub-themes folder which seems to be working but when I add:

```
<?php if ($tabs && !empty($tabs['#primary'])): ?><div class="tabs clearfix"><?php print render($tabs); ?></div><?php endif; ?>

```

I get a "Notice: Undefined variable: tabs in include() " refering to that code.

Is it possible to get the Edit/View tabs in any region other than "Content"?

# Answer
Have a look at the Delta Blocks module which is included in omega. It moves these tabs (and other things like Messages) into blocks.
> 0 votes

---
Tags: theming
---


title: Can I hook a form from a custom module?

text:
# Question
Title: Can I hook a form from a custom module?
I have a form function called `mymodule_join_form` in MyModule and `differentmodule_form_mymodule_join_form_alter` in DifferentModule. It's not being called, though (I put \`echo 'hello';die;)

I can get to it using `form_alter` with `if (form_id == 'mymodule_join_form')`, but shouldn't the first way work?

# Answer
> 0 votes
if it's a form alter you should take a look at http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_form\_alter/7

Also clear cache and look if you have enabled de módule.

Have you tray with a dpm('hello world') with devel module enabled?

oskar

---
Tags: 7, forms, hooks
---


title: drupal cache_set / cache_get expiration

text:
# Question
Title: drupal cache_set / cache_get expiration
I have a function:

```
function _dc_election_races_get_articles($search_term)
{
    $search_url = 'http://feeds.example.com/vote_up/search.php?search='.rawurlencode($search_term);

    if ($cached = cache_get($search_url, 'cache'))
    {
        $results = $cached->data;
    }
    else
    {
        $results = json_decode(file_get_contents($search_url));
        cache_set($search_url, $results, 'cache', 60*60*3); //3 hours
    }

    return $results;
}

```

I basically want the cache to expire after 3 hours and re-fetch the data from the url. The documentation on drupal made it seem like that it might not be removed from cache after 3 hours. Will cron cleanup caches?

# Answer
If you start chasing the code in `cache_get` you will eventually end up in `DrupalDatabaseCache::getMultiple`. If you look at the code, you will see a call to `DrupalDatabaseCache::garbageCollection` at the top. This will handle cache expiration before cron runs.

As part of `system_cron` you will see that `cache_clear_all` get called with `NULL` as the first parameter which

> $cid: If set, the cache ID to delete. Otherwise, all cache entries that can expire are deleted.

This cleans up the cache tables every time cron runs.

The Drupal 6 plumbing is different for pruning the cache (start reading `cache_get`, but the end result is essentially the same.

**TL;DR**, your cache TTL will always be honored when you get values, it's just the cache table cleanup that may not happen *exactly* when the TTL is up.
> 3 votes

---
Tags: caching
---


# Question
Title: Drupal Views: Create 3-Column Home Page with Taxonomy Terms
I am looking to create a 3-column home page design for my site that segregates 3 different items of a given taxonomy type (News, Training Alerts, and Advisories) into 3 separate columns. Each column shows not only the taxonomy term, but pulls the content associated with it (e.g. a teaser view of each item marked 'News').

I am not very familiar with Drupal themes, but currently I have been able to accomplish everything I've wanted with my site using the Bartik theme. Are there any ways I can accomplish this using Views and without having to change much about the Bartik theme? Or alternatively, is there a way to just create a table with PHP code that pulls the content associated with each taxonomy type into each column of a 3-column table?

# Answer
You can do that easily with your bartik theme. You can use Panels and page manager with views.

It's not easy to use but it's worth it. There is a great screencast series in nodeone.se.

To be short:

* In views: you'll make a `content pane` (not a block or page)
* With panel you can retrieve all the information from this pane and choose your layout and where you want to put all your fields inside it.
* In your case you can make `3 content pane`, each one with a specific taxonomy. After that you'll choose in which columns you'll want to put them.
> 0 votes

---
Tags: 7, views
---


title: What's the limit of drupal?

text:
# Question
Title: What's the limit of drupal?
I want to know what's the limit of drupal?:

1. Maximum number of nodes .
2. Maximum number of content type .
3. Maximum of files 's size .

And That without interruption of service . I am using Apache + mysql +redhat .
Thank you very much

# Answer
> 4 votes
I've worked with sites that:
\- have millions of nodes.
\- hundreds of thousands of files.
\- sites that deal with video (gb sized files).

In the above cases it's something that drupal is built on top of and not drupal it's self that can be an issue. Million of nodes; use a database that can handle a lot of I/O (read this blog). Hundreds of thousands of files; setup your directory structure so you have less than 5,000 files in a dir. Large file sizes; there are workarounds, this is a PHP limit not a drupal one.

# Answer
> 6 votes
That depends on a lot of factors: hardware, configuration of your LAMP stack, ...

The only real way to test this is to benchmark it yourself, on your hardware, under your circumstances.

There's no real answer to this question.

# Answer
> 1 votes
There are limits set both within Drupal's configuration and by the limitations of your server. For example, the PHP memory limit is set by the admin, and determines how much system memory Drupal can use up. The hard drive space of your system determines how many gigs of code, database contents, and files can be stored. There are many such limitations, some of them available for change as settings, and some inherent in the limitations of your hardware and software setup itself.

Because the performance-determining variables and their potential combinations are so numerous, it's more practical to do some in-situ benchmark testing with your particular site on your particular stack on your particular hardware using your particular internet connection than it is to try to predict the performance from some kind of calculation of every possible variable.

Even then, your metrics may be very different in a dev environment with just a few users making requests than they would be in production use, where traffic to your site could be dramatically more voluminous.

---
Tags: performance
---


# Question
Title: Can PHP pages be ported into Drupal "easily"?
If I have a php page, just a regular webpage that php retrieves database information from, dumps it out in tables, css, divs, all that. Is it extremely difficult to port to Drupal?

I ask because if I don't use drupal, then I have one page with all my content and presentation and model all mixed up. If I don't, then I've either got another framework I'm using, or I'm rolling my own.

Problem is that I need to build some pages now, but Drupal is not ready. I can't delay, so later I want to integrate them.

I was hoping for advice on at least the best way to write a page that I know will later be in Drupal.

edit: How do I write a php page in such a way that it is best prepared for later integration?

# Answer
Well, you don't really. If you are accessing the database in anyway you should be using the Drupal database API. There are a lot of things that you should do using Drupal API's if you are going to use Drupal. However, with that said, you can run any PHP you want in any Drupal node. So, there is nothing special you need to do in order to write your PHP code to work within Drupal. However, you really should think through your implementation before you being and determine which parts should use Drupal.

Also, it only takes about 3 minutes to setup a Drupal installation. So, you could just setup a dev site in no time flat and develop inside that. Even if you don't have a server you can download a few applications that will act as a server like XAMPP which will give you Apache, PHP and MySQL so that you can install Drupal and begin working.
> 1 votes

---
Tags: migrations
---


title: New user registration fields

text:
# Question
Title: New user registration fields
I have a site with about 30 members, but I just added a new mandatory field on the registration. I want the old members to be forced to fill this in as well. What would be the best way to do this?

# Answer
> 1 votes
Choose one:

1. Use the rules module to test whether the user has authenticated and the field value of the current user is empty. Redirect to `user/[uid]/edit` if this is the case.
2. Do the same test in a module during your implementation of hook\_init(). Call

```
drupal_goto('user/[uid]/edit')

```

to redirect to the user edit page.
3. Do the same test in a module during your implementation of hook\_init(). Call

```
menu_set_active_item('user/[uid]/edit');

```

to show the user edit page.

Replace `[uid]` by the user id of the currently logged in user.

In cases 1 and 2, you also have to make sure that you do not redirect from `'user/[uid]/edit'` back to `'user/[uid]/edit'`. This would create an infinite loop of redirections, because the POST data gets lost when redirecting.

Documentation:

---
Tags: 7, users
---


title: Speed up drupal 6 solr indexing

text:
# Question
Title: Speed up drupal 6 solr indexing
We have 90,000 nodes and it and we run cron every 10 minutes and do 200 documents per cron run. At this rate it will take just over 3 days to index all the content. It is also indexing older content first.

1. Is there a way to index newer content first
2. Is there a way to index more than 200 per cron run?

# Answer
You can change the settings at `admin/settings/apachesolr`.

If your server has enough capacity, I'd run the cron more often and increase the limit.

Check also this thread and be sure to disable core search indexing.

Not sure though about indexing newer nodes first.
> 1 votes

# Answer
Both of the questions can be answered in the affirmative. It's just that both of those things require custom code. So I sufgest you try the Elysia Cron or Drush routes first, as specified in the thread Ivanhoe123 linked to.

The point of indexing older content first, I believe, is that otherwise it might take a very long time for the indexer to reach the nodes that have been edited or inserted longest ago.
> 0 votes

---
Tags: search
---


title: Unable to add field to existing view

text:
# Question
Title: Unable to add field to existing view
I had previously created a view which is a list of nodes of type 'Banner'. I have added an extra field to the content type, and I have attempted to add this to the view, which seems as if it works ie. adds to the fields list, and reflects the changes in the live preview.

But then the live page doesn't reflect the changes, ie. the new text fields dont show up and the fields aren't populated in the `$row` or `$fields` variables in the views-view-fields.... theme files when debugging.

Also, when I go back to edit the view the new added fields are not there, so it seems as though they haven't been inserted into the database.

Does anyone have any idea why this would be?

# Answer
A couple of things to check:

1. Confirm you added the field to the right content type and save the changes
2. Make sure you added the field to right view "display" and save the changes
3. Clear the cache of the whole site
4. Make sure if you are using field permissions that they are properly set
5. If you are using a template file for the view make sure to add the new field.
> 0 votes

---
Tags: views, 6, entities
---


# Question
Title: Taxonomy Reference Based on Taxonomy Field
I have a taxonomy with a custom field: field\_uid

Users are able to create their own taxonomy terms, and when they do, field\_uid is set to their UID.

I also have a content type which allows users to select terms from a common vocabulary, however, I only want them to have access to terms that they themselves created (IE terms with field\_uid = current user's uid).

I've tried using entityreference and views to do this, but views seems unable to cope with taxonomy fields very well.

Thoughts?

# Answer
Two things come to my mind:

1. For the view make sure to do a taxonomy or user view and add a relationship to each other.
2. You can also use the private taxonomy module: http://drupal.org/project/private\_taxonomy
> 0 votes

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


title: content type "custom data"

text:
# Question
Title: content type "custom data"
I have created a content type that has a "number of accepts" field. I want to add a button, "accept", to the content type. When a user clicks it, it will temporarily store their username and etc. Depending on the number of accepts field, the content type will display "1/10 Accepts" for example. How would I be able to do this and have the number of accepts displayed in realtime. thanks!!

# Answer
You can create using hook\_form\_alter() and I get my button on the Add/Edit node form:

```
$form['actions']['accept_and_adduser'] = array(
  '#type' => 'submit',
  '#value' => 'Save & Add a Lesson',
  '#name' => 'op',
  '#submit' => array('mymodule_node_form_submit'), /* NEED this */
  '#weight' => 1000
);

```

But, clicking the button doesn't seem to hit hook\_node\_submit() or hook\_node\_insert(). I'm assuming I'm missing a hook or something in the button creation...anyone have any ideas?

Then added this function:

```
function mymodule_node_form_submit($form, &$form_state) {
  // Do stuff before saving the node, saving the data of users in some table and calculate it

  // Call this to save the node
  node_form_submit($form, $form_state);

  // Do stuff after saving the node
}

```
> 0 votes

---
Tags: views, ajax, nodes, javascript
---


title: hook_menu_alter() is not working

text:
# Question
Title: hook_menu_alter() is not working
I have implemented `hook_menu_alter()` in a module I have created. I have printed something inside that function call but nothing shows up, though the function `hook_init()` is executed from the same module. The output of `hook_init()` shows up in the page, but not from the `hook_menu_alter()` even after clearing the cache.

Does anybody have any idea regarding this issue?

```
function mymodule_init(){
print "here";
}

function mymodule_menu_alter(&$items) {
print "I am here";
return $items;
}

```

# Answer
`hook_menu()` and `hook_menu_alter()` are not always invoked; they are invoked only when Drupal rebuilds the menus, such as when a module is enabled, disabled, installed, or uninstalled, or when the Drupal cache is cleared.

Anatomy of hook\_menu reports the following sentence:

> `hook_menu()` is called rarely, such as when modules are enabled. If you edit a module’s `hook_menu()`, you must visit admin/build/modules for the changes to take effect.

The function that invokes the implementations of `hook_menu()` and `hook_menu_alter()` is `menu_router_build()`, which contains the following code (in Drupal 7).

```
$callbacks = array();
foreach (module_implements('menu') as $module) {
  $router_items = call_user_func($module . '_menu');
  if (isset($router_items) && is_array($router_items)) {
    foreach (array_keys($router_items) as $path) {
      $router_items[$path]['module'] = $module;
    }
    $callbacks = array_merge($callbacks, $router_items);
  }
}
drupal_alter('menu', $callbacks);
list($menu, $masks) = _menu_router_build($callbacks);
_menu_router_cache($menu);

return array($menu, $masks);

```

The function is called by `menu_rebuild()`, which is then called by:

`drupal_flush_all_caches()` is invoked by `system_modules_submit()`, which is the submission handler for the module page where modules are enabled, and disabled; every time a module is enable, or disabled, the menu is rebuilt, and both the menu hooks are invoked.
> 10 votes

# Answer
In short: It does.

A print will most like not be visible, because of the timing of the function call. If you use `drupal_set_message`, you should see a message displayed.

The reason is that the menu is rebuilt as part of the action on the form submit which happens before the page is actually rendered. `drupal_set_message` is instead stored in the users session, so it will persist a page refresh, much like error messages on form validation.

Also `hook_menu_alter` should not return anything, instead you change the referenced variable. This is how all drupal's `*_alter` hooks work.
> 3 votes

# Answer
in `*_alter` hooks the argument is passed by reference (in this case `$items`), so rather than returning anything just print directly from the alter function.

```
echo"<pre>";
print_r($items);

```

and clear cache.

You will able to see the whole array.
> 1 votes

---
Tags: routes, hooks
---


# Question
Title: Call internal pages with drupal_http_request
I'm writing a little module, and I need to call several pages of my site using `drupal_http_request()`, which accepts only absolute URLs. I don't want to add a variable to store the domain of the site, also because on my company we have proxy etc.

Which is the best way to add the domain of the site?

# Answer
Here is what I'm using in a similar situation, with $base\_url as Baysaa mentioned above.

```
$path_to_file = '/path/to/feed.xml';
$base_url = $GLOBALS['base_url']; // Not sure if this line is necessary.
$file_over_http = $base_url . $path_to_file;
$http_result = drupal_http_request($file_over_http);

```
> 3 votes

---
Tags: 7
---


# Question
Title: Unable to set a default value for a CCK field
I am trying to set a default value for a CCK Multi Select field tried with PHP code

```
return array(
  0 => array('value' => "ONE"),
  1 => array('value' => "TWO"),
);

```

and without PHP Code by just selecting the values (after adding to Allowed Values) with required ON & OFF but still nothing gets selected in select drop down.

# Answer
I upgraded CCK modules and this issue wasnt there in new module. May be it was a bug in the version that I used before.
> 0 votes

# Answer
Simply try by creating a new (text)field & choosing widget as select list. then put in allowed values 0|a 1|b 2|c (putting 0|a in one line,1|b in other so on..) & number of values to unlimited & save by editing, select default values from drop down & save. hope it helps..
> 0 votes

---
Tags: 6, entities
---


# Question
Title: How to redirect to another URL if visitor is anonymous when clicking a menu?
I used the following code to redirect anonymous visitor to a login page:

```
<?php
  global $user;
  if ($user->uid) {
    print "<a href='http://www.sourcecodester.com/submit'>Submit now...</a>";
  }
  else {
    print "<a href='http://www.sourcecodester.com/user?destination=submit'>Submit now...</a>";
  }
?>

```

But I can do this only in a block. What I want is put a Submit menu in the main menu and if anonymous visitor click the link he/she will be redirect to:

http://www.sourcecodester.com/user?destination=submit

after he/she login, he/she will be redirect again to the submit page as defined in the URL as "destination=submit".

Is this possible in main menu?

# Answer
you can use Menu per Role module:

> This module allows you to restrict access to menu items1 based on user roles. It depends on the Drupal core menu.module—just activate both modules and edit a menu item as usual. There will be a new fieldset that allows you to restrict access by role. The fieldset also appears in the node edit form.
> 2 votes

# Answer
You can use Rules if you want ... but sometimes large modules are overkill for simple things. Using a custom module you can essentially intercept the page click/load with your own hook\_menu() or hook\_menu\_alter() implementation:

```
// If this is just a simple drupal Page node or Article node for instance
// you would want to use "function mymodule_menu_alter($items) { ..." here.
//
// If this is a page you made programatically, you would do as below ...
function mymodule_menu() {
  // You have some generic "submit" page that you want the user
  // logged in 1st before they visit it. That is to say there
  // is a requirement that they be logged in.
  $items['submit']=array(
    'page callback' => 'mymodule_submitview',
     // We want to provide a custom check to be visitor is
     // logged in 1st.
    'access callback' => 'mymodule_submit_requires_login_callback',
  );
  return $items;
}

// Simple page output for example.
function mymodule_submitview() {
  return user_is_anonymous() ? 'I am anonymous.' : 'I am logged in.';
}

// Our custom 'access callback' function to perform or logic check.
function mymodule_submit_requires_login_callback() {
  if (!user_is_logged_in()) {
    // send the user to the login form and make that form redirect
    // submission to our custom submit page.
    drupal_goto("user/login?destination=submit");
    // implicit exit; here.
  }
  return TRUE;
}

```
> 1 votes

# Answer
Using Rules modules you can get this kind of behavior.
> 0 votes

# Answer
Maybe, you can try this:

```
function YOURMODULENAME__form_alter() {
  if ($form_id == 'user_login_block') {
    $form['#action'] = 'node?destination=YOURDESTINATION';
  }
}

```
> 0 votes

---
Tags: routes
---


# Question
Title: How to create forms similar to admin block forms
I want to create a form similar to Admin Block Settings form. So far I have created draggable table, how can I add Enable and Disable sections to the form ? I checked out Draggable Views module but it does not work out for me as I am creating a custom form.

# Answer
> 0 votes
Here you have two examples to learn how to build a custom module with drag and drop elements:

http://coffeeshopped.com/2010/09/drupal-drag-and-drop-tables-in-custom-modules

http://www.computerminds.co.uk/quick-guide-using-drupal-add-tabledrag-and-enjoying-jquery-drag-and-drop-loveliness

Oskar

---
Tags: 6, forms, blocks
---


# Question
Title: How to organize better the taxonomy-selection drop-down box in Views?
I made a View to list a series of items. Each item has been assigned a Taxonomy term.

My taxonomy terms go like this:

```
--- Main1
----- Sub1
----- Sub2
--- Main2
----- Sub3
----- Sub4
----- Sub5

```

So there's a main category and inside other terms.

In my view, you can filter the entries to only display items for a certain category. **But the dropdown menu is a mess**. It goes like Sub3, Main2, Sub1, Sub5...

So, is there a way to organize it in a way it appears as I listed it above? And also, is it possible to give some kind of indentation for the subterms in the dropdown? (So people can easily tell what is a main term and what's a sub-term).

# Answer
You can use Hierarchical Select module to manage taxonomy terms in select list.

See this discussion to implement hierarchical select with Views module : http://drupal.org/node/1170192
> 1 votes

# Answer
Check also Better exposed filters \- it allows you to display the filter in checkboxes/radios instead of dropdowns (which are horrible for end users) and then you can further style the output to group and divide main categories visually.

Here's a screenshot of something similar I did:
> 0 votes

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


# Question
Title: How can I manage site translations in code?
I have a site with multiple translations, including a heavily customized version of the default Drupal "English." (The use case requires that a lot of the help text and labels throughout Drupal be changed.)

I am using the Features module to manage deployment. However, I can't find a way to manage translations in code.

Currently, I visit the Languages page, click export, download the .po file for each type (built-in interface, node types, taxonomy) for each language, and then commit these downloaded files to code. This seems extremely inefficient compared to working with Features.

I looked for a Drush command to help but the 5.0-rc3 version which I'm using doesn't have any i18n-related commands.

How can I manage site translations efficiently in code?

# Answer
> 2 votes
I had the same problem and had a look at the module Features Translation. However, there were some downsides to it. Don't know exactly what is was. From what I can remember is that when I import a feature, for example the menu link labels are imported in the built in interface. So it doesn't help to import the translations for Menu Items because the source labels are not available there but in the Built In interface. But maybe I am wrong, tried so many things I can really recall what I did.

But you can have a look at it, maybe it works for you.

Tell us when you have found a suitable solution. I am curious.

# Answer
> 1 votes
Drush 5.x, at least as of right now, doesn't have anything to help in this area.

Instead, I used Selenium IDE to automate a workflow for an admin account of logging in and importing the translations for each language. Exports must still be performed manually, which is a pain, but at least it's slightly faster than before. (Selenium IDE cannot be used to handle the exports because it's impossible to take over the downloading of files with Javascript.)

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


title: Fail to install drush via pear

text:
# Question
Title: Fail to install drush via pear
I try to install drush using the following command:

```
pear install drush/drush

```

I get this error message:

> No releases available for package "pear.drush.org/drush" install failed.

Then I try with `sudo`:

```
sudo install drush/drush

```

I get this error message:

> downloading drush-5.4.0.tgz …
> Starting to download drush-5.4.0.tgz (398,652 bytes) done: 398,652 bytes
> Could not rename /usr/bin/.tmpdrush to /usr/bin/drush copy(/usr/bin/drush): failed to open stream: No such file or directory
> ERROR: commit failed.

I installed pear, and added the pear.drush.org channel. What is wrong?

---

I realize that my question was not very clear. I was trying to install drush using pear on OSX Mountain Lion and I got those errors. Anyway I managed to accomplish my task another way, by installing "homebrew" package manager and following a few steps from this tutorial (step 8 and 9).

Update: an even simpler way to install drush using homebrew:

```
brew install drush

```

That's it.

# Answer
Use the following commands:

```
sudo rm /usr/bin/drush
sudo pear install drush/drush
sudo drush --version

```
> 5 votes

---
Tags: drush
---


# Question
Title: Applying CSS to sub theme created by Omega
I am creating responsive theme. To create a theme I have created subtheme of Omega theme.

Until the creation of subtheme every thing was easy. Now after creating the subtheme I want to apply the CSS provided by the designer. But the problem is that designer has created different class name and div tags than Omega.

I am stuck now, I don't know from where should I start ?

What will be the best practice in such type of cases when subtheme and CSS provided by the designer has different class and divs

# Answer
Try to match up the original with the new if you can... Use something that can show you the class names like firebug, an add on for firefox (there is one for ie as well). It will take a while but that is usually what will pin point the classes if you can't get the original css. If you have the original css try to use it in your template directory. See which one was edited first, ( global.css, alpha... etc) then just drag the files to the new destination making sure your .info files are the same as well because it may be a relative region issue.
> 1 votes

# Answer
Two solutions:

1. rename in the CSS
2. rename in ALL .tpl.php file's theme

There are no other solutions.
> 1 votes

# Answer
@ZioBudda is right. The easiest will be #1: Rename all your CSS classes.

I would suggest using something like the Live CSS module to make the task more manageable.
> 1 votes

---
Tags: theming
---


title: Add url alias with parameter (?foo=bar)

text:
# Question
Title: Add url alias with parameter (?foo=bar)
I need to create urls aliases like this:

```
/mypath?foo=bar&foo2=bar2 (source) -> /foo/bar (alias)

```

via standard drupal alias url add (admin/config/search/path), but when I insert that link in the source path textfield I receive an error about not existent source path. But the path is correct (it works).

How can I resolve it? Only via direct db query?

# Answer
> 2 votes
The reason you get that error is that the form validation handler verifies the source entered in the form is a valid menu path, using drupal\_valid\_path().

Setting the path alias directly in the database would cause errors, as the source of the path alias is used to set `$GET['q']`, in drupal\_path\_initialize(), which contains the following code.

```
$_GET['q'] = drupal_get_normal_path($_GET['q']);

```

In your case, `$_GET['q']` would be set to mypath?foo=bar&foo2=bar2. All the functions that use `$_GET['q']` expect it to the in the format path/subpath; the presence of the query parameters would cause errors. See for example the code executed by menu\_get\_item().

Using a custom module, you could implement hook\_url\_inbound\_alter(), and hook\_url\_outbound\_alter(). The first would transform foo/bar in mypath, setting `$_GET['foo'] = 'bar'`, and `$_GET['foo2'] = 'bar2'`; the second would transform mypath in foo/bar, when `$_GET['foo'] == 'bar'`, and `$_GET['foo2'] == 'bar2'`.

---
Tags: 7, uri
---


# Question
Title: How I can intercept an image field upload and validate it?
I have a content type with an image field. I need to validate this field because I need to check if user upload a real image or only a file with image's extension (like jpg, gif, png etc). I have tried and readed 100+ things but none resolve my problem.

I have tried via "#upload\_validators" with this code:

```
foreach ($form['field_all_images'][$form['field_all_images']['#language']] as $k => $v) {
  if (!is_integer($k)) continue;

  $form['field_all_images'][$form['field_all_images']['#language']][$k]['#upload_validators']['check_image_correct'] = array();
}

```

where "check\_image\_correct()" is a my custom function that checks via `imagegetinfo()`. My problem, in this "try/case", is that the function works/is called only for the first image. I have tried to move this function from `hook_form_alter()` to an `#after_build` function, without result (only the first time it works).

# Answer
It looks like there a couple of very small bugs in that code that would stop it working properly, try this:

```
$lang = $form['field_all_images']['#language'];
foreach (element_children($form['field_all_images'][$lang]) as $key) {
  $form['field_all_images'][$lang][$key]['#upload_validators'][] = 'check_image_correct';
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Allow groups of users to edit a single Webform
I need to enable groups of users to edit one Webform so that they can collaboratively complete a questionnaire. I am not concerned with two people editing at the same really.

I've seen mentioned the Organic Groups module and the OG Webform module to enable this but as far as I can tell it isn't suited to what I want to achieve.

The other option seems to be to implement hooks in the Webform module to override the user authentication but I'm afraid I wouldn't know where to start with that. How would you define the groups of users and then allow access to the forms based on those groups?

Any help would be massively appreciated!

# Answer
> 0 votes
If you can group those users in a role, you can use the Content access module to allow them to edit the webform.

Furthermore you can set content access settings per node, so you can limit them to be able to edit only that one webform.

---
Tags: users, webforms, organic-groups
---


# Question
Title: Url Path Alias is not working with the "raw value from URL contextual filter"
I could really use some help with this one. Long story short, I have a contextual filter which pulls the taxonomy term from the url (2nd position).

For example: if I'm at walldamp/drupal/acoustics, it will pull all the nodes with the tag "acoustics".

Here's the problem: Drupal doesn't read path alias's. The actual address for walldamp/drupal/acoustics, is something like walldamp/node/59. So if I have an article tagged 59, it works.

I do not want to change all my tag's to the node number, because this needs to be really user friendly. How can I get my contextual filter to read the url displayed, or is there another work around?

Thank you.

# Answer
How have your configured your contextual filter? I have the following configuration and it's working fine for me:

1. ***Contextual filters***: Has taxonomy term ID You also need to specify `validation criteria` for this filter, my setting is:

a) Specify validation criteria = Taxonomy Term
b) Select the correct vocabulary.
c) Set `Filter value type` to `Term name converted to term ID`
2. ***Create a relationshiop*** of `Content: Taxonomy terms on node`

a) Select the correct vocabulary.
b) Set `Require this relationship` to true

You may also wan't to use `Has taxonomy term ID width depth` if you have nested terms in your vocabulary.
> 1 votes

---
Tags: views
---


title: Multistep Node Form

text:
# Question
Title: Multistep Node Form
Are there any examples of creating a multistep NODE form. I looked at the examples module, but there was only a regular multistep form.

What I am looking to do is have a spreadsheet be uploaded and parsed which then creates a 2nd step in the form which populates a field collection w/ unlimited cardinality of field of type/name.

Could this be done with AJAX instead? (Drupal 7.)

# Answer
> 2 votes
You could go with a regular multistep form, and create your node in the final submit function.

# Answer
> 0 votes
The Multistep module does this to node create/edit forms (and only to node create/edit forms, in fact). It saves the data entered on each step when the step is submitted, so if the process is interrupted the node is still created and can be further filled-in later.

---
Tags: 7, forms
---


# Question
Title: I want to create a new command for the nodes like the standard edit and delete
In drupal you have the standard commands edit and delete which you access typing :

```
node/99/edit
node/99/delete

```

I want to create some other commands like :

```
node/99/approve
node/99/test
...

```

Where do I hook to access the command and execute some code ?

# Answer
> 5 votes
You need to use `hook_menu()` to define the path, coupled with the `MENU_LOCAL_TASK` type, e.g.

```
function MYMODULE_menu() {
  $items['node/%node/approve'] = array(
    'title' => 'Approve',
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array('my custom args'),
    'page callback' => 'MYMODULE_approve_node_page',
    'page arguments' => array(1),
    'weight' => -1 // Controls the display order for the tab
  );

  return $items;
}

```

Then you just implement a callback function, which has the node passed as a parameter, and build up your page output:

```
function MYMODULE_approve_node_page($node) {
  // Do something with $node...
  $build = array(
    '#markup' => node_view($node, 'teaser')
  );

  return $build;
}

```

Once you clear Drupal's caches you should see the new tab appear alongside the View/Edit tabs on a node page, but only for those users who have the permission you define in your `access arguments`.

---
Tags: 7, nodes, hooks
---


# Question
Title: Jquery for form with multiple save/submit buttons
I have created a form using fields with two action buttons; one for the default submit functionality ('Save'), and the other one for custom submit functionality ('Submit').

When the user clicks the submit button a confirm box is displayed asking the user whether he wants to submit the form or not. If the user selects yes, the custom submit callback for the button should execute.

I am using the jquery-alerts plugin to display a customized confirm box on the click event of 'Submit' button. I used the following jquery code for this

```
$('#recommendation-letter-node-form #edit-save').click(function() {
  jConfirm("Once you submit the application, you will not be able to modify it any further. Are you sure you want to submit?", "Application Confirmation Dialog", function(confirm) {
    if (confirm) {
      $(this).submit();
    }
  });
  return false;
});

```

the `.submit()` function doesn't work for buttons other than default form submit button and I need that the other button submit callback should be triggered when the confirm value is true.

# Answer
> 1 votes
One approach I used to achieved this was using the same callback function. Then within this method, use $form\_state\['triggering\_element'\]\['#id'\] or something similar to execute the proper function... i.e.

```
function my_form_submit($form, &$form_state) {
  $id = $form_state['triggering_element']['#id'];

  switch ($id) {
    case 'edit-submit':
      submit_my_form($form, $form_state);
      break;
    case 'edit-save':
      save_my_form($form, $form_state);
      break;
  }
}

```

# Answer
> 1 votes
Your problem is `$(this)` refered to first button(**save button not submit button** ), you should change `$(this).submit()` to `$('#yourformid').submit();` .

---
Tags: 7, forms, javascript
---


# Question
Title: Where to find structure of objects that I can access in PHP snippets added to different parts of UI?
In views I can add PHP snippets for custom validation or when I want to provide default value for contextual filter. It is telling me that I can use $view or $argument - but where is documentation of these objects? Where can I read what are my possibilities in these areas (or how check this, by using debugger for example)?

# Answer
You can install the devel module and use the dpm function to check it out. You can check the whole list of devel functions at http://ratatosk.net/drupal/tutorials/debugging-drupal.html
> 1 votes

---
Tags: 7, views
---


# Question
Title: Set order / weight of user profile core fields against user profile custom fields
Is it possible to set the order of core fields against custom fields added on user profile page? I want to bring the status field to the bottom of the list. I'm trying the code below but without succes:

```
function MY_MODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['status']['#weight'] = 100;
}

```

I want something in the following order for example:

* Username (core)
* Password (core)
* Custom field 1
* Custom field 2
* Status (core)

Thanks in advance

# Answer
> 3 votes
You can just try and set the weight as follows

```
$form['status']['#weight'] = field_info_max_weight('user', 'user', 'form') + 10;

```

Have not tried it but I am pretty sure it will work. This will make sure the status will always be the last field.

Also it should be `$form['account']['status']['#weight']`

---
Tags: 7, entities
---


title: Make Hook in main-menu

text:
# Question
Title: Make Hook in main-menu
I created a module containing the following files:

* menu\_imoveis.info
* menu\_imoveis.module

The content of menu\_imoveis.info is the following.

```
    name = Menu Imoveis
    description = Adiciona imoveis ao menu.
    package = Imoveis
    core = 7.x
    version = 7.x-dev

    files[] = menu_imoveis.module

```

\**The content of menu\_imoveis.module is the following.

```
function menu_imoveis_menu() {
  $items['node/27'] = array(
    'title' => 'Example Page',
    'menu_name' => 'main-menu',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

```

The code I wrote doesn't work.

# Answer
Taken from this comment, written by zifiniti:

> I was having trouble getting a menu item to display with the following code:
>
> ```
> function mymodule_menu() {
>   $items['custom-page'] = array(
>     'title' => 'Custom Page',
>     'menu_name' => 'main-menu',
>     'access arguments' => array('access custom pages')
>   );
>
>   return $items;
> }
>
> ```
>
> It was continuously denying me access to the specified path in addition to not displaying the item in the menu. I discovered that the reason behind this is if you do not specify a page callback, then the access callback will acquire a value of 0 in the database and thus render that path/menu item inaccessible.
>
> Working code:
>
> ```
> function mymodule_menu() {
>   $items['custom-page'] = array(
>     'title' => 'Custom Page',
>     'menu_name' => 'main-menu',
>     'page callback' => 'mymodule_custom_page',
>     'access arguments' => array('access custom pages')
>   );
> }
>
> ```
> 1 votes

# Answer
Ok Looking at it you are trying to edit a menu item which is already created. So you need to use the HOOK\_menu\_alter function.

```
function  mymodule_menu_alter(&$items) {
  $items['node/27']['title'] = 'Something';
}

```

Also you might need to clear cache for this function to be triggered.
> 0 votes

---
Tags: routes
---


# Question
Title: When a node is created, automatically update data in a corresponding node
## Background (simplified)

We're collecting data for a study in which participants come in on several occasions to have health measures taken. We have two custom node types: `Participant` stores background data about a person, and `Visit` stores information from a single visit (e.g., their blood pressure that day). Each Visit is related to one Participant via a field created by the Node References module.

On each visit, a participant might qualify for a one-time reward. Visit nodes have a `reward_visit` field indicating whether the participant earned a reward on this visit, and Participant nodes have a `reward_ever` field indicating whether the participant has ever received a reward.

## Question

I'd like to set up the following behavior: If a Visit node is created where `reward_visit` was set to Yes, also set `reward_ever` to Yes in the corresponding Participant node.

Is there a way to make this happen automatically, using Node References or some other relations module? I could custom-code it using hook\_node\_insert() or something, but I'd like to know if there's already an accepted way.

# Answer
UPDATE: The answer to this question is "Rules". I hadn't learned about them at the time. With a rule, you can choose to trigger on saving or updating new content and use conditions to limit it to the content type in question. For the action, choose "set a data value" and the relation between the two nodes should allow you to select the relevant field on the node you just created as the source, and the relevant field on the related node as the value to set.

Original answer: I ended up writing a small custom module that implements `hook_node_insert` and `hook_node_alter` for visit nodes. It gets the nid of the related participant from the submission, gets it using `node_load()`, changes the relevant values, and saves it using `node_save()`. I still suspect there's a less kludgy solution, but this seems to work perfectly well.
> 0 votes

---
Tags: nodes
---


# Question
Title: Error message after using Internalization
I installed Internalization module and made my website Turkish as default. Now I receive this error message

# Answer
> 1 votes
This warning issued from file and directory permission. This issues maybe useful for you.
link1
link2

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


# Question
Title: Drupal views grouping: amount by grouping
I have created a view, I have two separate tables based on this view. I used "grouping" to get these two tables. For the pager its asks how many items I want to display. I want 10 total, the 5 most recent from each grouping. What it ends up doing is giving me the 10 most recent between the two groupings. So its uneven. I wanted 5 and 5, but Im getting 7 and 3 based on published date. Can I get 5 for each grouping?

thanks, M

# Answer
> 1 votes
The Views Grouping Row Limit module allows you to specify how many rows you want to display in each group, maybe it can help you.

---
Tags: views
---


title: Enter one thing but save the other

text:
# Question
Title: Enter one thing but save the other
I try to construct a field and I wonder how should I implement this process via Field API:

1. User enter some data to the field. Let's say, the data entered is a node title.
2. User hits the "Save" button, but what is actually saved in the database is the node ID of the node whose title has been entered by the user.

Something like this happens with the Entity Reference module: I enter the title of the entity (as I 'm getting assistance through autocomplete), but the module saves `target_id`, not the title I have actually entered.

How can I gain such behavior?

# Answer
> 1 votes
Create a module for example module name is rose. In that module implement hook\_node\_validate

```
function rose_node_validate($node, $form, &$form_state) {
       //Check to see if this is the node form data you want to change
    if ($form['#form_id'] == 'contentType_node_form') {
        //based on the value provided in
        $form_state['input']['field_name']['und'][0]['value'];
        $new_info_data = 'some logic'; //get the data you would like to save .
        variable_set('new_info', $new_info_data); //Save the data in a variable.
    }
}

```

Then implement a hook\_node\_presave. As per our example

```
function rose_node_presave($node) {
    //check if the node type is the one you want to change the value
    if ($node->type == 'content_type') {
        $new_info = variable_get('new_info'); //get the value which was set in validation variable_set()
        $node->field_name['und'][0]['value'] = $new_info;
    }
}

```

I have implemented this on Drupal 7. A user enters instagram user name and I get the instagram id from instagram api and save it. Let me know if more explanation is required.

In this implementation users enters only address I get the Lat and Lng based on the address provided and save it in the database.

# Answer
> 1 votes
ok.let's suppose your entity ref field name is `field_entity_ref`
you should to create anther field (text) field , name it `field_book_title`
in you custom module `hook_form_alter`

```
  function custommodule_form_alter($form, &$form_state,$form_id) {
     if ($form_id == 'yourcontetntpe_form_node') {
        $form['#submit'][] ='mycustom_function';
        // we must hide shadow field in view
        // first check #access=false if not work comment it and use hide
         $form['field_book_title']['#access'] = false;
        // or you can hide it
        // hide($form['field_book_title']);
       }
   }

```

and in `mycustom_function` function get nid of refrenced node , load node and save it's title in `field_book_title`.

```
function mycustom_function(form,&$form_state) {
  $node = node_load($form_state['values']['field_entity_ref']['und'][0]['target_id']);
  $form_state['values']['field_book_title']['und'][0]['value'] = $node->title;
 }

```

And finally in view of node (in your tpl or in views) use `field_book_title` instead of `field_entity_ref`

I hope this be useful for you.

---
Tags: entities
---


# Question
Title: Make either of 2 fields required but not both?
Ive added a file field to comments so users can upload a file in a comment as well as post text. How can I make it so one of the 2 fields is required to be filled in to create a comment (so you cant submit blank comments), but without making both fileds required?

# Answer
Check this thread and Conditional fields module.

If you're using D7 - the principle is the same as in the thread I linked. Basically you need to attach the name of your processing function to the validation array and there perform the checks.
> 1 votes

---
Tags: entities
---


# Question
Title: How to allow anonymous comments on one content type, but not all
I would like anonymous visitors to be able to comment on my 'Blog' content type, but only registered users comment on my 'Forum' content type.

It seems that if anonymous users have permission to comment, this applies to all content types with commenting enabled.

Am I missing a setting somewhere, or would I need to look at hiding/disabling the comment form if content type is 'Forum' and user is anonymous?

# Answer
Check out the Allow anonymous comments per node type
> 1 votes

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


title: Getting views data as a REST service

text:
# Question
Title: Getting views data as a REST service
I need a way to get the output of a view as a REST service in JSON format.

I read about the RestfulWS and the Services modules, but I didn't find enough documentation. Are these straight forward, or should I just go with a custom module?

# Answer
> 8 votes
Perhaps Services Views module could be of interest here:

> Views support for the Services module version 3.x and later.
>
> It has currently two features: \- Create view based resource creating Services display in a view \- Execute any view of the system via views resource call
>
> After enabling "views" resource in your services endpoint you can do GET request to:
>
> ```
> http://example.com/<endpoint path>/views/<view name>
>
> ```
>
> This will execute a view and pass results.

---
Tags: theming, 8, services
---


# Question
Title: Is there a base module that implements the slide in, slide out behaviour like the Admin module?
I am looking for a module that implements slide in and slide out on top functionality, similar to the way some websites slide out a contact form when you click the thingy at the side of the page. The Admin and Slidebox modules have that ability, but I am looking for some kind of container object that implements the slide in and out functionality.

PS. the tags are not the most accurate but are the nearest.

# Answer
Superfish is a great option for drop down menus, and you can customise the effects: http://drupal.org/project/superfish

or Nice Menus: http://drupal.org/project/nice\_menus

You can also customise the admin menu to add common tasks, by editing the actual links list.
> 1 votes

---
Tags: javascript
---


# Question
Title: I'm constantly getting logged out of my account
I have a weird issue on a test server where I get constantly logged out. What could cause that?

# Answer
A lot of different things can cause that, so there are several things to check. One common issue is not having the site direct traffic to either www.\[sitename\].com or \[sitename\].com - this causes users to have separate sessions for each version of the site. Solution here: Website saves separate sessions for "www.domain.com" and "domain.com"

Another possible issue is a misconfigured sites/default/settings.php file - this can happen if you copy the site from another location. Check uncommented lines pointing to urls other than your test location. I believe cookie domain can cause session problems if misconfigured.

Finally, since you mentioned that this is a test server, you might check that Drupal's MYSQL user has the correct permissions for its database. I've had strange things happen when it has some but not all of the necessary access permissions to the database.
> 3 votes

---
Tags: 7, users
---


# Question
Title: Check when the last time someone visited a specific node
I need to make sure my users are visiting a specific node. What could I accomplish this?

A counter would be nice (e.g. "viewed three times by User234 in the past week"). Would that be hard to implement?

# Answer
> 3 votes
The Statistics module that is part of Drupal already get that information. Its `hook_exit()` implementation contains the following code.

```
  if (variable_get('statistics_enable_access_log', 0)) {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

    // For anonymous users unicode.inc will not have been loaded.
    include_once DRUPAL_ROOT . '/includes/unicode.inc';
    // Log this page access.
    db_insert('accesslog')
      ->fields(array(
      'title' => truncate_utf8(strip_tags(drupal_get_title()), 255),
      'path' => truncate_utf8($_GET['q'], 255),
      'url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
      'hostname' => ip_address(),
      'uid' => $user->uid,
      'sid' => session_id(),
      'timer' => (int) timer_read('page'),
      'timestamp' => REQUEST_TIME,
    ))
      ->execute();
  }

```

The data contained in that table are reset after 72 hours. statistics\_cron() contains the following code.

```
  // Clean up expired access logs (if applicable).
  if (variable_get('statistics_flush_accesslog_timer', 259200) > 0) {
    db_delete('accesslog')
      ->condition('timestamp', REQUEST_TIME - variable_get('statistics_flush_accesslog_timer', 259200), '<')
      ->execute();
  }

```

The Statistics module has a setting page (admin/config/system/statistics) that allows you to decide when the access logs are discarded; you can choose to discard then when they are older than 1 week.

The Views module has code to expose in a view the data saved from the Statistics module; you can add a field to expose the number of times a node is viewed in a view.

Alternatively, you can create a custom module basing on the Statistics module's code. In this case, you would need to implement the code for integration with the Views module, if you need it.

As side note, `hook_exit()` is probably going to be removed from Drupal 8; if you are using it in a Drupal 7 module, you will need to change your code when porting it to Drupal 8.

# Answer
> 1 votes
Because you need per-node per-user counts, the easiest approach I can think of is a small custom module. There were a few advanced statistic modules for Drupal 6 that might be able to track this info, but I'm not aware of any that accomplish this in Drupal 7. Writing a small module to simply increment a view count paired with uid and node vid in a table using hook\_node\_view would be a relatively small job for a drupal module developer.

---
Tags: 7
---


title: How to use confirm_form

text:
# Question
Title: How to use confirm_form
OK this one is driving me nuts. I've read the other question posted on DrupalAnswers and several threads on the Internet, but I still can't work this out.

In my menu hook I have this:

```
$items['import'] = array(
    'title' => '',
    'type' => MENU_CALLBACK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('_my_module_form'),
    'access arguments' => array('access content'),
);

```

Then I have these functions:

```
function _my_module_form($form_state) {
 if(!isset($form_state['storage']['confirm'])) {

  $form ['some_textarea'] = array(
   '#type' => 'textarea',
   '#rows' => 25,
   '#cols' => 10,
  );

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

  return $form;
 } else {
  drupal_set_message('hello');
  return confirm_form($form);
 }
}

function _my_module_form_validate($form, &$form_state) {
 if(!isset($form_state['storage']['confirm'])) {
 }
}

function _my_module_form_submit($form, &$form_state) {
 if(!isset($form_state['storage']['confirm'])) {
  $form_state['storage']['confirm'] = TRUE;
  $form_state['rebuild'] = TRUE;
 } else {
  drupal_set_message('hello2');
 }
}

```

When I submit the form, nothing happens. I would expect to see the drupal message 'hello', but instead I just get the original form again. However, if I submit the form a second time, then I see a drupal message saying 'hello2'.

Why does the comfirm\_form bit not get executed? It seems to me like the form state is not being rebuilt so the 'else' part of the conditional never gets executed.

Note: I am pretty sure form\_validate is not needed, but I just put an empty definition in there in case.

# Answer
> 4 votes
Looks like my issue was here:

```
function _my_module_form($form_state) {

```

Should have been:

```
function _my_module_form($form, &$form_state) {

```

---
Tags: forms
---


# Question
Title: How do you create a block of fields to a second Profile2 using views?
I can create a list of profiles of a specific type. That works great. But what's stumping me is I need a view that has fields that pertain to a specific person. Say for instance you are on Bob's "personal" profile and there is a block that has information for bob's second "business" profile (or any other member's other profiles for that matter). How do I create a block for this profile with relative fields that only populates on demand?....

# Answer
**Using Configuration**

You can use the Views module to access the Profile2 fields.

Below is a quote from ltiong on Drupal.org regarding accessing fields from multiple profile types. The same process applies to accessing a single Profile2 type.

> * 5.1 create View (Show:User)
> * 5.2 add relationship, (User:Profile); give the Identifier a unique name ie 'MainProfile'; select a single checkbox for 'Profile type',
> in my case 'Main profile';
> * 5.3 add another relationship, (User:Profile); give the Identifier a unique name ie 'EducationProfile'; select the other checkbox for
> 'Profile type', in my case 'Education profile';
> * 5.4 add Fields to view; select Profile2 field items; use Relationship dropdown in 'Configure field' to associate w/ correct relationship;

You can output as a Block, and use the Page URL to retrieve the correct user ID to load. (For your views context)

**Using Code**

You can use the profile2\_load\_by\_user(); function to programmatically retrieve Profile2 data.

```
$profile_data = profile2_load_by_user($user->uid);

```

See also: profile2\_load\_multiple()
> 1 votes

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


title: Send mail to users

text:
# Question
Title: Send mail to users
I'm looking for an simple module to send mail to the users of our site. It should be able to send a mail to all users of a certain roll, with the ability to put in a send from e-mail address. Just a simple form with send from, subject and body. Nothing fancy.

An optional extra would be that i can select users in a view and send them a mail using bulk operations.

I tried modules like simplenews and mass contact but they provide many things except a simple mail form.

Any suggestions?

# Answer
> 1 votes
You can use Rules module to send email also. You can filter users from Role and send email to selected users.

# Answer
> 1 votes
You can use the http://drupal.org/project/views\_send module.It will gives you a lot of customization options even to set your own headers.

# Answer
> 0 votes
You can use Views Bulk Operations in a view filterable by role. I believe Send email is a default action available.

---
Tags: 7, users, emails
---


title: Drupal cannot write to /tmp folder

text:
# Question
Title: Drupal cannot write to /tmp folder
My Drupal 7 website has no layout (CSS and JS is messed up) and is getting the following error message:

> The specified file /tmp/filestW97L could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.

The /tmp/ directory at the root level has 777 permissions. I think the directory the error message is referring to, as there are files with similar names in it. I'm puzzled as to why Drupal cannot access that directory.

It does have 80,000 files in it. Could it be too full?

I'm assuming that /tmp/ is the "destination directory". Am I correct?

I'm on a VPS running Centos. The VPS has plenty of resources and I tried rebooting it in case that might help.

I don't think I did anything to cause this error, as it happened when I was not working on the website. Is it possible that a CPanel update from the past several days did it?

I cannot read the system log, as the admin user cannot log in (I get blocked by an anti-spam module that requires JavaScript enabled). Is the system log the same thing as the watchdog table?

---

I fixed the problem. I did several things. I think flushing the drupal cache was the solution that worked, but I am not 100% certain.

# Answer
> 2 votes
CSS and JS are stored in files/ folder. This folder must writable in order for Drupal to store the aggregated files.

---
Tags: files
---


title: Override the theme for the login page

text:
# Question
Title: Override the theme for the login page
How can I override theme for the user login page in Drupal 7? By default, that page takes the default theme style.

# Answer
You can separate template file for overriding the user-login page.

Just create a template file called **page--user--login.tpl.php** file for theming the login page.
> 4 votes

# Answer
To know all the possibility about functions, variables, and template files for a specific block, region, or page, install the Devel, and Theme developer modules.

In the bottom left corner of your page, you will find the checkbox that actives the Theme developer module. Enable it, and click on a point of your page: You will find all the information about how to theme that part of the page.
> 0 votes

---
Tags: theming, users
---


# Question
Title: is there a way to display a message for views if there are no results?
I am using user relationships and activity feed, which displays actions from a existing view. If no view exists, it means either they have no friends or their friends have no activity so is there a way to have a message displayed for no results?

# Answer
In "Basic settings," there's a field called "Empty Text" that is displayed if there are no results.

If you're using arguments, you can set "Display empty text" if the argument is not present.
> 10 votes

# Answer
For Drupal 7 / Views 3 the answer would be:

Check the "Advanced" Options on the right side. There you can add a "NO RESULTS BEHAVIOR".
> 13 votes

---
Tags: views
---


title: URLs defined in a hook broken

text:
# Question
Title: URLs defined in a hook broken
I have a content type that, on the node page, displays taxonomy term fields, which in turn link to the automatically generated taxonomy term view for that term.

I would like to overwrite the output of these links, which I have attempted to do in the code below.

The problem is that the URL comes out malformed as: `/our-work%3Ftid%3D4` rather than `/our-work?tid=4`. Note that the argument `4` is just an example.

What could be the solution here? Some thoughts:

* Am I using the right hook?
* `urlencode()` doesn't seem to work here.
* Using Drupal's `l()` function seems to output HTML, not a processed URL.
* Using Drupal's `url()` function doesn't seem to work either, I get the same output when I build the options array, etc.

```
function ep3_misc_node_view_alter(&$build) {
    if ($build['#bundle'] == 'work') {
    // We cycle through this array for just integer indexes, since there are also string indices.
        for ($i = 0; isset($build['field_tags'][$i]); $i++) {
            $tid = $build['field_tags'][$i]['#options']['entity']->tid;
            $build['field_tags'][$i]['#href'] = check_plain('our-work?tid=') . $tid;
        }
    }
}

```

# Answer
The function that you should use is url(). If you want to output an absolute URL you should use the following code:

```
function ep3_misc_node_view_alter(&$build) {
  if ($build['#bundle'] == 'work') {
    for ($i = 0; isset($build['field_tags'][$i]); $i++) {
      $tid = $build['field_tags'][$i]['#options']['entity']->tid;
      $build['field_tags'][$i]['#href'] = url('our-work', array('absolute' => TRUE, 'query' => array('tid'=> $tid)));
    }
  }
}

```

If you don't want an absolute URL, replace the call to `url()` with the following one:

```
url('our-work', array('query' => array('tid'=> $tid)))

```

`check_plain()` is never used to output a URL; in fact, `url()` doesn't use it.
> 3 votes

---
Tags: 7, taxonomy-terms, hooks, navigation
---


# Question
Title: Redirect after a new node is added but not edited
I have a custom redirect on node submit.

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
    $form['actions']['submit']['#submit'][] = 'custom_node_submit';
}

function custom_node_submit($form, &$form_state) {
    $form_state['redirect'] = 'request-sent';
}

```

However, I would like to redirect only when a new node is created but not updated. How do I check the action being executed on the node ?

# Answer
> 2 votes
```
function mymodule_form_alter(&$form, $form_state, $form_id) {
    $form['actions']['submit']['#submit'][] = 'custom_node_submit';
}

function custom_node_submit($form, &$form_state) {
    if (arg(2) != "edit") {
      $form_state['redirect'] = 'request-sent';
    }
}

```

---
Tags: 7, nodes, forms
---


# Question
Title: Get single edit field from a content type
I'm writing a module with a custom form. I would to add in this a form a field from an existent content type, with values.

For example: I've a content type "article" wth a node reference field "field\_ref".

In my custom form I want to get this "field\_ref" field, with values. Is it possible?

I think that I could get the entire form and then get only the field but I don't like this solution :)

# Answer
You can build a custom autocomplete text field to filter node reference results. Check this link http://timonweb.com/how-create-ajax-autocomplete-textfield-drupal-7 to build autocomplete text field.

You just need to change the query in above implementation.
> 1 votes

# Answer
Assuming your field is a list type, you can grab the allowed values from the field using the `field_info_field()` function:

```
$info = field_info_field('field_states');
$options = $info['settings']['allowed_values'];

$form['work_state'] = array(
  '#title' => t('Work State'),
  '#type' => 'select',
  '#options' => $options
);

```

I got hint from this link of Stack Overflow

Check this link again from stackoverflow. https://stackoverflow.com/questions/11225158/drupal-7-programmatic-field-definition

This allows you to create node reference field
> 1 votes

---
Tags: forms
---


# Question
Title: Improvements in Drupal Gardens way: How do I place an input filter selector in CKEditor?
I would like to know how to achieve two improvements in WYSIWYG in the same way Drupal Gardens does.

The first one is to place Input filters selector as a dropdown selector within the WYSIWYG toolbar, which saves a lot of space and looks cleaner.
The second one is to place two tabs in order to switch from HTML code and WYSIWG Editor.

I created a site and exported the file as to see which modules Drupal Gardens uses, but I didn't find the correct one.

# Answer
This is the code responsible for those modifications.

```
(function ($) {

Drupal.gardens_misc = Drupal.gardens_misc || {};

Drupal.behaviors.gardens_misc = {
  attach: function(context, settings) {
    if (typeof CKEDITOR != 'undefined') {
      // Bind events to handle enabling and disabling of the WYSIWYG.
      CKEDITOR.on('instanceReady', Drupal.behaviors.gardens_misc.instanceLoaded);
    }

    $('.wysiwyg', context).closest('.text-format-wrapper').once('wysiwyg-tabs', function() {
      var $tabs = $('<div class="wysiwyg-tab-wrapper"></div>').insertBefore($(this).find('.form-textarea-wrapper'));
      $('<div class="wysiwyg-tab enable first">' + Drupal.t('WYSIWYG') + '</div>')
        .bind('click', this, Drupal.behaviors.gardens_misc.tabToggle)
        .appendTo($tabs);
      $('<div class="wysiwyg-tab disable last">' + Drupal.t('HTML') + '</div>')
        .bind('click', this, Drupal.behaviors.gardens_misc.tabToggle)
        .appendTo($tabs);
    });
  },
  instanceLoaded: function(event) {
    var $wrapper = $(event.editor.container.$).closest('.text-format-wrapper');
    var $original = $wrapper.find('.wysiwyg');
    var $clone = $original.clone().val($original.val());
    $clone.bind('change', function(event) {
      $original.val($clone.val()).change();
    });
    $wrapper.find('.cke_toolbox').removeAttr('onmousedown').prepend($clone);
    $wrapper.find('.wysiwyg-tab.enable').addClass('wysiwyg-active');
    $wrapper.find('.wysiwyg-tab.disable').removeClass('wysiwyg-active');
  },
  tabToggle: function (event) {
    if (!$(this).hasClass('wysiwyg-active')) {
      $(this).closest('.text-format-wrapper').find('.wysiwyg-toggle-wrapper a').click();
    }
  }
};

/**
 * Overides the default attach behavior for text formats without an editor
 */
Drupal.wysiwyg.editor.attach.none = function(context, params, settings) {
  var $field = $('#' + params.field);
  var $original = $('#' + params.trigger);
  var $clone = $original.clone().val($original.val());
  var $container = $('<div class="wysiwyg-none-header"></div>');
  $container.append($clone).insertBefore($field);
  $clone.bind('change', function(event) {
    $original.val($clone.val()).change();
  });

  // @todo: Need to display the allowed tags here
  var tags = Drupal.settings.wysiwyg_formats[$original.val()];
  $('<span><b>' + Drupal.t('Allowed tags: ') + '</b>' + tags + '</span>').appendTo($container);

  // Original behavior
  if (params.resizable) {
    var $wrapper = $field.closest('.form-textarea-wrapper');
    $wrapper.addClass('resizable');
    if (Drupal.behaviors.textarea.attach) {
      Drupal.behaviors.textarea.attach();
    }
  }

  $field.closest('.text-format-wrapper').find('.wysiwyg-tab.enable').removeClass('wysiwyg-active');
  $field.closest('.text-format-wrapper').find('.wysiwyg-tab.disable').addClass('wysiwyg-active');
};

/**
 * Overides the default detach behavior for text formats without an editor
 */
Drupal.wysiwyg.editor.detach.none = function(context, params) {
  $('#' + params.field).siblings('.wysiwyg-none-header').remove();

  // Original behavior
  if (typeof params != 'undefined') {
    var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first');
    $wrapper.removeOnce('textarea').removeClass('.resizable-textarea')
      .find('.grippie').remove();
  }
};

})(jQuery);;

```

Save the above in its own file e.g. drupalgardens\_wysiwyg.js, then either add the script to the .info file of your theme/module or add the file on the relevant page(s) using drupal\_add\_js or via the #attached property of a form/render array.

To get this to work on a non-DrupalGardens site, I had to comment out the two lines below the @todo comment around line 53. You may need to further tweak the code depending on how you have your wysiwyg profiles configured.
> 1 votes

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


title: Ajax: how to prepend my callbacks?

text:
# Question
Title: Ajax: how to prepend my callbacks?
I have an e-commerce based on Drupal + Commerce module.

My `add to cart` form use Ajax to reload itself when the user make a choice (item attributes, like color, size, etc..); Everythings works just fine but i need to add an overlay that hide the form just before the Ajax request is sent to prevent the user to click another option before the request has completed (and the form reloaded).

Basically, I need to add my own callbacks in the `beforeSend` and `success` events, but I have no idea on how tell Drupal to invoke them for (and only for) this specific form.

**edit:** I need to add a Javascript Callback, not php.

Any help?

**Edit** Mathankumar's solution indeed works, something like:

```
$(document).ajaxSend(function(event, request, object){
    request.onloadstart = function(){
        $("form.commerce-add-to-cart").css({'opacity':0.5});
        $("form.commerce-add-to-cart input").attr("disabled", "disabled");
    };

    request.onloadend = function(){
        $("form.commerce-add-to-cart").css({'opacity':1});
        $("form.commerce-add-to-cart input").removeAttr("disabled");
    };
});

```

works **BUT** i dont like this thing to be run for every ajax call.

I digged the `event, request, object` parameters of ajaxSend, but i was not able to find nothing about the form\_id or something to tell the `add_to_cart_form` requests from others, any help is appreciated!

# Answer
> 0 votes
A bit tricky, but this works:

```
$(document).ajaxSend(function(event, request, object){
    var test = getParameterByName('form_id', object.data);

    if(test.indexOf('commerce_cart_add_to_cart_form'))
    {
        request.onloadstart = function(){
            // beforeSend
            $("form.commerce-add-to-cart").css({'opacity':0.5});
            $("form.commerce-add-to-cart input").attr("disabled", "disabled");
        };

        request.onloadend = function(){
            // ajax request has ended
            $("form.commerce-add-to-cart").css({'opacity':1});
            $("form.commerce-add-to-cart input").removeAttr("disabled");
        };
    }
});

    //@link http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values/5158301#5158301
function getParameterByName(name, durl)
{
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(durl);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

// We all remember about IE, doesnt we?
if(!Array.indexOf) {
    Array.prototype.indexOf = function (obj, start) {
        for (var i = (start || 0); i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

```

# Answer
> 1 votes
You can use the following snippet,

```
jQuery('body').ajaxSend(function((evt, request, settings)){
  if (settings.url == "<something>") {
    // Perform your operations
  }
});

```

However this function will be called for all the ajax requests, so you need to have perfect condition to determine the right URL.

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


title: link a calendar to another content type

text:
# Question
Title: link a calendar to another content type
I have a calendar in Drupal 7, and I want to link this calendar with other nodes.

How do I do this? Which module should I use?

I am using Drupal 7.

# Answer
You need to add a "date field" to the test content type.

And with views +date field + calendar you will be able to do it.
> 0 votes

---
Tags: views
---