# Question
Title: Taxomony menu - show all, vocabulary link are disabled
I have a custom vocabulary which looks something like this:

Shops (vocabulary name)

* Sporting Goods
* Auto Parts
* Computers
* Etc. (15 items in total, 1 level)

My goal is to create a menu link to Shops and a drop-down sub menu that lists different types of shops (example - Auto Parts). Shops link must be in the main menu.

I have PathAuto installed and all term have their aliases. My problem is that the exact two options from Taxonomy Menu module while editing my vocabulary are disabled:

Add item for vocabulary **(disabled)**

*Shows the vocabulary name as the top level menu item of the taxonomy menu.*

Use 'all' at the end of URL **(disabled)**

*This changes tid+tid+tid to "All" in term when Display descendants has been selected. Only used if Menu path type is "Default path". Works with default taxonomy page.*

Menu path type is set to Default.

Why are they disabled ? Is this the appropriate module for this kind of menu ? Should this be constructed with Views module (haven't got round to it)

Since I am just beginning to learn drupal, I'd like to use as few modules as necessary, since there is probably a module for everything, but they would only probably bloat the site and I wouldn't learn anything.

Bonus question: are there any simple, widely used D7 themes with built in drop-down menus (currently using Bartik)?

# Answer
> 0 votes
I am currently working on an ecomerce project and faced same issue. This helped https://www.youtube.com/watch?v=iBdVW7fC2Tg me so I recommend watching it, For the listing I have used drupal nice menus module. You can use it from https://drupal.org/project/nice\_menus. In my project, listing is now working fine and I have 4 different menu items with their respective sub-categories.

If you still face any issues I will be available to help!

---
Tags: navigation, taxonomy-terms
---


# Question
Title: Modify user submitted form data before it is saved an emails are sent
I am new to drupal but I do have php experience. I am trying to modify an existing custom module that handles some forms on our site. The form in question is used to send an email to the address that is included as a hidden item.

I need to change this email address based on an option the user chooses.

Here is an outline of what I need to happen

user goes to form (hidden email field is already set) user enters their options user clicks submit button check users options and modify email field accordingly save values to database send email to new modified email address

Below is the code I am working with now

```
function bp_bottled_water_redirect(&$form, &$form_state, $form_id){
$interest = $form_state['input']['submitted']['primary_interest'];
$email = $form['submitted']['dealer_e_mail']['#webform_component']['value'];
//drupal_set_message("email is " . $email);
//drupal_set_message("interest is " . $interest);

if($interest == "bottled_water" && $email == "info.minnetonka@culliganwater.com"){
    //$form_state['input']['submitted']['dealer_e_mail'] = "info.bottledwater@culliganwater.com";
    //$email = $form_state['input']['submitted']['dealer_e_mail'];
    $form_state['values']['dealer_e_mail'][LANGUAGE_NONE][0]['value'] = "info.bottledwater@culliganwater.com";
    drupal_set_message("changed email to: " . $form_state['values']['dealer_e_mail'][LANGUAGE_NONE][0]['value']);

}
else{
    $form['submitted']['dealer_e_mail']['#webform_component']['value'] = $email;
    drupal_set_message("email remains: " . $email);
    drupal_set_message("interest is " . $interest);
    }
}

/**
 * Implements hook_form_alter().
 */
function dealers_form_alter(&$form, &$form_state, $form_id) {
//drupal_set_message("Form ID is : " . $form_id);

if ($form_id == 'webform_client_form_960') {
//drupal_set_message("found form");
$form['#submit'][]='bp_bottled_water_redirect';

}

  // Act only on 'webforms'
  if (isset($form['#node']->type) && $form['#node']->type == 'webform') {

    $require_zip = FALSE;
    if (isset($form['#node']->field_form_display_options['und'])){
      foreach ($form['#node']->field_form_display_options['und'] as &$key) {
        if ($key['tid'] == 13) {
          $require_zip = TRUE;
        }
      }
    }
    switch($require_zip){
      case TRUE:
        $zip = _session_get('zip', '');
        if (dealers_is_local($zip) && $require_zip == TRUE && $zip !== '') {
          $zipinfo = json_decode(file_get_contents('http://zip.elevenbasetwo.com/'. $zip));
          $simplexml_obj = dealers_get_local($zip);
          $form['submitted']['5_digit_zip_code']['#default_value'] = $zip;
          // $form['submitted']['city']['#default_value'] = ucwords(strtolower($zipinfo->city));
          $form['submitted']['state']['#default_value'] = $zipinfo->state;
          $form['submitted']['dealer_e_mail']['#default_value'] = $simplexml_obj->DealerList->DealerRecord->EMail;
          $form['submitted']['dealer_e_mail']['#webform_component']['value'] = $simplexml_obj->DealerList->DealerRecord->EMail;
        }
        else {
          drupal_goto('dealers/'. substr($_SERVER['REQUEST_URI'], 1));
        }
        break;
    }
  }
}

```

The issue I am having is I can change the values according to the drupal\_set\_message. But it seems to be taking place after the data is saved. Because the email shown when viewing my submission is still the old one. I think my code may be running to late.

How can I modify the email address before the data is saved?

# Answer
You have to use hook\_webform\_submission\_presave hook.

Using that you can **Modify a Webform submission, prior to saving it in the database**

For more information go through the hook documentation.
> 0 votes

# Answer
You maybe able to add a submit handler or validate handler.

How do I add an additional submit handler in commerce checkout form?

https://stackoverflow.com/questions/15375616/how-to-use-form-validation-in-drupal-7

See the form examples \> https://api.drupal.org/api/examples/form\_example!form\_example\_tutorial.inc/7
> 0 votes

---
Tags: forms
---


# Question
Title: Username display overidden by customer profile name
If a user has a customer profile (i.e. ever filled out a shopping cart) the name in the profile is used everywhere their username is displayed.

This results in a lot of confusion for our moderators/admins. Because when they go to lookup a user in admin/people they're looking for the username that the user logs in with. But what's displayed is their "nice" name from their shipping address. I need to undo this override because it's way too confusing.

It doesn't look like anyone is doing this through theme\_username(). Where is this display override happening?

# Answer
> 2 votes
Found it!

`commerce_kickstart_user_username_alter()` is overwriting usernames with the name provided in their addressbook.

I implemented my own `hook_username_alter()` to simply return `$account->name`.

# Answer
> 0 votes
Consider using the Real Name module to configure how display names are shown. It's a bit overkill because you just want it to be back to the username.

You could write your own lightweight module to theme the username back to the actual username. via `theme_username`\`

> Returns HTML for a username, potentially linked to the user's page.

---
Tags: 7, commerce
---


# Question
Title: How to limit the number of nodes created using the Feeds module?
I want to limit the number of node created by the Feeds module, it hsould be limited to 5 each time.

I've added `$conf['feeds_process_limit'] = 5;` to the bottom of `sites/default/settings.php`

I've also changed `FEEDS_PROCESS_LIMIT` value in `plugins/FeedsProcessor.inc` to be `5`

But still Feeds trying to import more than 5.

Looks like I've missed something. Anybody any hints about it?

# Answer
> 1 votes
You'll also need to clear your **caches** after setting `$conf['feeds_process_limit'] = 50;`.

Alternatively, if you are just looking for a quick **limiter** (during development of a custom importer, for example) this trick worked for me: Limit number of feed items to import ($conf\['feeds\_process\_limit'\] not working) (an `active` issue in the Feeds issue queue).

# Answer
> 0 votes
Try setting $conf\['feeds\_node\_batch\_size'\] in your settings.php file. It looks like that is one of the variables that the feeds module looks at to determine how many items to process in each batch.

---
Tags: 7, feeds
---


# Question
Title: Output the total number of rows in a view
Does anyone know how to show the count of the results of a custom view?

# Answer
You can add a custom section to either the header or footer to do this.

* Edit the view / display.
* In the center section, click **Add** next to **Header** or **Footer**.
* Choose **Global: Result Summary**. Add it where you need it.
* Then, edit the textarea to be the format that you need. There are a bunch of tokens available for building up the numbers.
* Preview the view, and then **Save** if everything is OK.
> 2 votes

---
Tags: 7, views
---


# Question
Title: Add Checkboxes to a views listing of titles
I am looking to pull in a views listing of events by title into a entity form.

I need help figuring out how to add checkboxes to the views listing of title. This way if someone checks the box when the form submits it will show in the form submitted information that they are interested in that event. Then I need to add that listing to the form.

Thanks

# Answer
> 1 votes
It can be done. You have to build a view -\> Entity view and pull in your fields. Then in the form create a field -\> Entity Reference -\> Check boxes/radio buttons -- under Entity selection -\> Views: Filter by an entity reference view -- then pull in the view you created.

Easy Peesy when you figure it out.

---
Tags: views, forms
---


title: Disable responsive Omega

text:
# Question
Title: Disable responsive Omega
I am on Omega 4. How do I disable responsive web design for my sub-theme? i.e. fixed grid yet I can still use singularity or other goodies in Omega.

I was from Omega 3.

I would like to quickly get the website up without spending too much time tweaking for RWD.

# Answer
> 1 votes
1. Create a custom layout (https://drupal.org/node/1936980)
2. Comment (or remove) the "breakpoint" in the scss (or sass).

---
Tags: theming
---


title: Drupal 7 module - page layout changes

text:
# Question
Title: Drupal 7 module - page layout changes
I'm new to Drupal development and this question may have been asked and answered but I haven't found an answer that works for me yet.

I am developing a module that creates 4 paths using a menu\_hook. Three of the pages appear inside an iframe defined on a page. I'd like to prevent the header/sidebars/footer (and other regions other than content) from appearing on the iframed page. This must be done independent of the theme - I don't know or care what the theme is.

I'd like the iframed page to only contain the content tags. I want to do this programmatically without the help of any additional modules. The iframed page executes a js script (on load) that redirects (the parent) to a results page. It is during the redirect that I can see the loaded iframed page and then the redirection occurs. The transition is ugly.

I have tried using templates in the module directory; however, I don't think I've done them correctly and haven't yet encountered a good example of a template loaded and used from a module directory.

I have tried a hook\_page\_alter function to **unset** the regions (but the header and footer still appear on the page).

I've tried a theme\_hook function but I'm only interested in suppressing some of the regions the theme may be using and not interested in variables.

Because I don't know what the theme is and I don't know what the selector names or classes might be for the page divs I don't want to try and solve this with a few "display:none;" entries in a css file. Any help or ideas would be appreciated.

# Answer
**Module:**

* The Empty Page module is a simple empty page solution. It provides an interface that assists in managing "empty" menu callbacks, mostly used for pages that only consist of blocks.
* The Panels module allows a site administrator to create customized layouts for multiple uses.
* Context allows you to manage contextual conditions and reactions for different portions of your site. For each context, you can choose what blocks to show.

**Theming:**

* Template suggestions are alternate templates based on existing .tpl.php files. You can write in preprocess\_page , where put condition and if true, assign page template to page--empty.tpl.php - here you should remove all regions printing except content - so you will get empty page.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: How to hide the (-) sign from facet filter block?
I am displaying faceted blocks and current search block on the search page.

When I select a filter from any faceted block, it appears in the current search block and also in that faceted block with this sign `(-)`.

When I click on this sign it removes the filter from the search.

It is fine in current search block. But It should not appear in the faceted block.

Suppose If I select `category1` from the facet block. In the current search block and in its facet block it appears like this `(-) category1`.

And I want that in the current search block it should appear like `(-) category1` and in its facet block it should on display its name like `category1` without the `(-)` sign.

Any one who know how to hide this in the facet block?

# Answer
> 1 votes
There are a couple of theme functions you can use to work with the display of these filters.

theme\_facetapi\_deactivate\_widget($variables)

theme\_facetapi\_link\_active($variables)

In your case, you could place the following in your theme's template.php file to edit the display of the deactivation 'button' of your facet:

```
function THEME_facetapi_deactivate_widget($variables) {
  return '';
}

```

---
Tags: 7, search
---


# Question
Title: Search Taxonomy Term pages containing entity referenced nodes
So, I've got myself into a bit of a pickle here and was hoping that could point out a way through.

* Drupal 7
* Views
* Display Suite
* Entity Reference
* Inline Entity Reference
* Search API
* Database Search

I have been building a sort of hybrid traditional multi-page and single-page site within the Bootstrap framework. In order to meet these requirements I have used an inline entity reference field to group multiple different nodes (each representing a Display Suite layout, such as 50%-50%, 33%-33%-33% etc) into a content type called 'Subject'. These 'Subjects' are to form each distinct row in a single-page style layout.

This has worked well, and I now need to compile these 'Subjects' into pages.

Because I want to avoid too much complexity in the workflow I decided against nesting these 'Subjects' into yet another content type called 'Page' using more entity references. Instead I went for a taxonomy vocabulary called 'Sitemap' with a term for each page, which could be selected from a term reference field in the 'Subject' content type. I then use a view to spit out all of the referenced 'Subject' nodes associated with that term as rendered entities.

TL;DR - I have a series of taxonomy term pages full of referenced rendered entity nodes.

When looking at implementing search I just can't get my head around how to index and display results. I obviously need the contents of these term pages to be indexed, but I also need to ensure that results will only point to term pages (preferably deep linked) and not any of the original nodes referenced on the term page. Granted, I'm not very familiar with it, but looking at Search API I can't see how I could achieve that.

Is this just a really silly way to achieve this kind of structure?

# Answer
I stumbled upon a module called Search by Page Paths which swerves the above issue by indexing the front end of the site. This approach means that regardless of the source of my data and where it is placed, it will see anything rendered out onto a page as part of that page.

The main caveat is that one must specify paths to index, but in terms of my particular build this isn't a bad thing and means I have complete control over where a user ends up after searching.
> 0 votes

---
Tags: 7, taxonomy-terms, entities, search
---


# Question
Title: How can I change a field's widget type on its node edit page?
I have a node type that uses Fuploader image field widget. When a user creates new a node of this type, I want them to be able to use the fuploader widget to upload images. When the user edits that node at some point, I want to switch to the normal imagefield widget. How can I accomplish this?

# Answer
> -1 votes
Login in as super admin:

content management -\>content types -\> edit \[your content type\]-\>managefields

click on configure of that field and there you will see second button which named "Change basic Information"

Click on this button and will get the way to edit widget type.

# Answer
> -1 votes
I would suggest creating two different content types. One would be shown when the user creates something new, and the other when they want to edit. They could share most of the data using the Add Existing Field option, but I think you might need to run Rules after the new content is created, to create a duplicate node of the other content type, using the same information.

---
Tags: media, entities
---


title: Free-tagging user accounts

text:
# Question
Title: Free-tagging user accounts
Is it possible to free tag user accounts in Drupal 6? For example, a user with appropriate permissions would be able to add tags created on the fly to any user account. If I could limit which user roles could be tagged, that would be a bonus.

# Answer
> 1 votes
Eventually worked out how to do this: use Content Profile module to extend the user account with a node of a custom type, and then create a free tag for that node type.

---
Tags: 6, taxonomy-terms
---


# Question
Title: How to filter a view based on tags applied to
I'm working on an old (2009) Drupal 6 site that uses a custom module to add a field to the content creation pages for certain node types. That field lists a sub-set of the users of a certain user type.

Some of those users are now being free-tagged on the site. I'd like to be able to create a view that lists only the nodes that refer to users that have a specific tag.

If that sounds a bit complicated, here's an example. Imagine a D6 site that works as an intranet for a doctor's surgery. Each doctor has a user account on the site, as does each patient. A custom module lets patients be allocated to doctors. After every appointment, the doctor fills in a report. That report is a node type, and includes a field created by a custom module that allows the doctor to select the patient who had the appointment, from a list of all of the patients who are allocated to that doctor.

Now, imagine that each patient's account could be free-tagged, and tags such as "male", "female", "diabetic", "pregnant", etc. were added to the patients' user accounts. How would I go about building a view that would display all of the reports given to patients who are tagged as "pregnant"?

# Answer
So, shortly after posting this question I worked out how to do it.

When I built this site I included the facility to create a Views relationship that points at the "referred to" user (the "patient" in the above example). So, I created this relationship in the view that I built. I then created *another* relationship that was itself based on the first relationship but pointing at the node created by the Content Profile module.

Then, I created a filter based on the second relationship, that filtered based on the taxonomy term I'd created (i.e., the "diabetic", "pregnant" stuff above). That did the trick.
> 0 votes

---
Tags: views, 6
---


# Question
Title: How to specify image paths for Commerce feeds imports on xampp?
Been banging around with Commerce feeds and think I've wrapped my head around it. One thing which has been flummoxing is how to provide the path in the CSV file to the image(s) on my xampp install.

I put the folder in xampp/htdocs/drupal/sites/default/files/poster\_pics/XXX\_image.jpg

Do I provide the path to the root of the site? (IE htdocs/drupal/etc?) or do I provide the entire path to the file on the local machine? (IE C:/xampp/htdocs/drupal/ rest of the path? or something more elaborate like

file:///C:/xampp/htdocs/drupal/sites/default/files/poster\_pics/ANON0060.jpg

Many thanks in advance.

# Answer
It's possible that something like a drupal file system paths (`public://poster_pics/name.JPG`). There actual path: `http://example.com/sites/default/files/poster_pics/name.JPG` i.e place image or file here manually.
> 1 votes

---
Tags: commerce, feeds
---


title: Sort View by the order of the arguments

text:
# Question
Title: Sort View by the order of the arguments
I have a view that receives some arguments from a questionnaire. In the questionnaire I calculate a list of nodes that's sorted by how well they correlate with the questionnaire. Once my view receives these arguments it will just sort them by their node id, and not the custom ordering I already applied when sending the arguments.

Is there any module that will display my nodes in a view, in the same order the arguments are received from the previous page?

I already tried views\_arguments\_extra, but this cannot achieve what I'm trying to do.

An example:

in my questionnaire I have determined that the 5 following nodes have the highest correlation:

```
7: 86%
8: 83%
12: 82%
1: 80%
2: 79%

```

I will then send this top 5 as an argument to my view.

So I also want my view to have that order:

```
7
8
12
1
2

```

# Answer
> 2 votes
I dont know of anyway to sort a view buy the arguments it receives. So this may not be really what your looking for but currently there's no other answers here and hopefully one of these alternative suggestions will help you.

Suggestion 1)

On your questionnaire submit function use views\_get\_view\_result http://api.drupal.org/api/views/views.module/function/views\_get\_view\_result/7 send the arguments to your view as normal you'll get back your 5 top hits but not sorted correctly. You can then reorder the results and manipulate the order the results appear in and print out your manipulated view.

Suggestion 2)

Using Views PHP module http://drupal.org/project/views\_php you can create your own sorting with php. You can pass your view the data you need with url's or $\_POST get that data in your view and create the sorting using that.

In a nut shell, I dont know how to do what you want, heres a couple of avenues I would probably try..

# Answer
> 0 votes
The module that does this very thing is Views argument sort which now lives in Views argument extras.

---
Tags: 7, views
---


title: A really big database size

text:
# Question
Title: A really big database size
I'm dumping the database every 2 days, but I noticed that at some point last month the database jumped from around 500 MB to 4 GB!

What can be the cause of it?

# Answer
> 13 votes
One reasons that a database can grow w/o bound is when you don't have cron setup to run. Check your "Recent Log messages" at **/admin/reports/dblog** and filter for cron, and make sure it is running (nightly is a good start).

On of the things cron does is prune the cache, watchdog, and sessions tables. These can fill up quickly with data that isn't critical to Drupal running.

Occasionally, clearing these out can take too long for a cron run. If this is the case, running a manual query, such as

```
DELETE FROM watchdog;

```

may be needed. As mentioned above, you can run this on the `cache` and tables beginning with `cache_`, `watchdog`, and `sessions`. It is always best to take a backup first, before running `DELETE` queries.

# Answer
> 6 votes
Run

```
show table status;

```

on your database, and take a look at the "Data\_length" column. There you will see which tables take up the space. I don't know how you dump your data, but if you use Backup and Migrate, the cache tables are by default not included, saving quite a bit of space.

# Answer
> 0 votes
If you have drush installed, run drush cron followed by drush cc all. That should fix the problem. Just reduced my db size from 4.3G to 65M.

---
Tags: 6, database, backups
---


# Question
Title: button for boolean field during node display
I have a boolean field in my content type which takes values either 1 or 0. I want to provide a button instead of just displaying the value of field so that the user can click on it and toggle the value.

Is it possible to doing something like this ?

# Answer
> 3 votes
Maybe you should check out the Flag module. Out of the box this module will give you the boolean field, the ajax button on the node view, and rules integration.

The flag module integrates nicely with views. Here is some helpful documentation. http://drupal.org/documentation/modules/flag

You will no longer need the boolean field on your node though so, depending on existing content may require a migration.

It does have a very large user base too and it may save you some development.

# Answer
> 0 votes
If you want to submit a new value for the field on the actual toggle then you'll need to write a custom module with an ajax handler that saves that value for you.

If you just want to change the look of the field and can wait for the 'Save' button to be pressed to save the updated value you could probably do everything in CSS with maybe a bit of javascript if you want to make it look more slick.

# Answer
> 0 votes
The best answer to this is to Use the Button-Field module and use rules to create actions when the button is clicked. The module already has integration with rules.

# Answer
> 0 votes
Fasttoggle may be what you want.

> Speeds up common administration tasks like unpublishing or promoting nodes or blocking users through the use of AJAX callbacks. This saves lots of page loads. If JavaScript is not available, it degrades gracefully to a regular confirmation page.

---
Tags: views, nodes
---


# Question
Title: Post the same menu as two different blocks?
I have a menu called main-menu. I want to post it twice as a block: one block with a main-menu in the header, and one block with a main-menu in the footer. But Drupal 7 will not allow it. Drupal 7 only allows me to post the block once...either in the header or in the footer.

Is there another way? If not, I will use Javascript to clone the entire main-menu html node and append to footer node.

# Answer
The Menu Block module will do this.

> So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
>
> Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!
> 8 votes

# Answer
It seems that the MultiBlock module can do this.

> The MultiBlock module solves this problem by allowing you to create multiple block instances of already existing blocks.
> 3 votes

# Answer
You can do this with the Render API in Drupal 7 quite easily, specifically look at `hook_page_alter()`. The Render API is a lot like the Forms API, you create content as arrays that describe the content, rather than creating raw HTML. Blocks are now created using these *render arrays*, which makes them very easy to manipulate from the module or theme layer. You can check out the documentation on the Render API for more details. Also, I found some Drupalcon videos quite helpful: http://www.archive.org/details/drupalconchi\_day3\_the\_render\_api\_in\_drupal\_7 and http://www.archive.org/details/PageRenderDrillDownInDrupal7 are good ones.

In your specific case, you'd implement `hook_page_alter()` something like this assuming the block is called 'main-menu' and it's in the 'header' region of your page...

```
function mymodule_page_alter(&$page) {
  // get the block you're after from the $page array
  $menu_block = $page['header']['main-menu'];

  // copy the block to another location in the page array
  $page['footer']['main-menu'] = $menu_block;
}

```

This code grabs the definition of the 'main-menu' block and copies it to the footer region. This will cause Drupal to print the block twice. This specific example is also shown in at least one of the videos linked to above.
> 1 votes

# Answer
also you can print the menu block a second time through the template page.tpl.php file or the one what you want to modify... doing something like this...

```
<body>
      <div class="header">
            <?php print render($page['menu']); ?>
      </div>
      <div class="content">
            .....
            .....page content and content blocks
            .....
      </div>
      <div class="footer">
            <?php print render($page['menu']); ?>
      </div>
</body>

```

That should make it, and with css you can make the style Change if needed

```
.header > .menu{..styles menu header...}
.footer > .menu{..styles menu footer...}

```
> 1 votes

# Answer
**Menu clone** allows you to clone a menu, but adjust it as you like, before creating a block that you can add anywhere in your site. It's a bit more flexible than menu block.
> 0 votes

---
Tags: 7, routes, blocks
---


title: Attaching file to node field

text:
# Question
Title: Attaching file to node field
I have a problem. I'm trying to attach file to node field by this code

```
function calculator_page_form_validate($form, &$form_state) {
$file = file_save_upload('file', array(
    // Validate extensions.
    'file_validate_extensions' => array(),
    ));
    // If the file passed validation:
    if ($file)
    {
            // Move the file into the Drupal file system.
            if ($file = file_move($file, 'public://cunning_files', FILE_EXISTS_RENAME)) {
            // Save the file for use in the submit handler.
            $form_state['storage']['file'] = $file;
        }
        else
        {
            form_set_error('file', t("Failed to write the uploaded file to the site's file folder."));
        }
    }
    else
    {
        form_set_error('file', t('No file was uploaded.'));
    }
}
function calculator_page_form_submit($form, &$form_state)
    {
        $file = $form_state['storage']['file'];
        // We are done with the file, remove it from storage.
        unset($form_state['storage']['file']);
        // Make the storage of the file permanent.
        $file->status = FILE_STATUS_PERMANENT;
        // Save file status.
        file_save($file);
        $file->display = 1;
        $file->description = "";
        // Set a response to the user.
        drupal_set_message(t('The form has been submitted and the image has been saved, filename: @filename.', array('@filename' => $file->filename)));
        global $user;
        $node = new stdClass();
        $node->title = $file->filename;
        $node->type = "file";
        //node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
        $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
        $node->uid = $user->uid;
        $node->status = 1; //(1 or 0): published or not
        $node->promote = 0; //(1 or 0): promoted to front page
        $node->comment = 0; // 0 = comments disabled, 1 = read only, 2 = read/write
        // Term reference (taxonomy) field
        //$node->field_tag[$node->language][]['tag'] = $form_state['values']['tag'];
        add_terms_for_node($form_state['values']['tag'], &$node);
        $file->display = 1;
        $file->description = "";
        $node->field_file[$node->language][0] = (array)$file;
        // 'node' is default,
        // Other possible values are "user" and  "taxonomy_term"
        $node = node_submit($node); // Prepare node for saving
        node_save($node);
        //drupal_set_message( "Node with nid " . $node->nid . " saved!\n");
    }

```

What am i doing wrong? Thank you for help and sorry for my poor engrich it isn't my natural language.

# Answer
> 1 votes
I found mistake. I accidently named field\_file as field\_fiele. Damn it four houers from life. Code works correctly.

---
Tags: 7, nodes, entities, files
---


# Question
Title: Do I still need to add verifications if the site has been verified through Google Analytics?
I'm working my way through the items in the SEO Checklist module. One of them is the Site Verification module. We have already verified our domain name through a Google Analytics account. Do I still need to add a verification using the Site Verification module, or is it redundant at this point?

# Answer
> 1 votes
It's up to you, of course. from the module's page:

> This module is useful for the following search engine verifications:
>
> * Google Webmaster Tools
> * Google Apps
> * Bing Webmaster Central (formerly Live Search)
> * Yahoo! Site Explorer
> * Yandex.ru
> * Any search engine or web service that uses META tags or file upload to verify that you are the owner of a site.

You are the one to know if you will need or want assistance with verification against above tools.

---
Tags: 7
---


title: Link menu active on 2 pages

text:
# Question
Title: Link menu active on 2 pages
I have a menu like this:

The sidebar on the left is the `Main Menu` with links. The first link is `STOCKLIJST`, that will link to the page `stocklijst/aangeboden`. As you can see in the second sidebar (this is a menu in a block that will only be visible when page starts with `stocklijst/*`) the link is active.

But when I click on the second link in the second sidebar the `'STOCKLIJST'` in the first sidebar won't be selected anymore.

Why? : Because this is a link to the first link in the second sidebar ... .

How should I could make sure that the first link is active on multiple pages? Or is the easiest way to for this with JavaScript or PHP?

**UPDATE:**

I've tried the menu position and added a trigger like this:

But that doesn't do much. Something I do wrong?

# Answer
I think you can achieve that by one of the following modules

1)Menu Position

> Often times site builders want certain types of content to appear in a specific position in the navigational menu. The simplest solution, adding all of that content individually to the menu system, has performance and usability issues. (Imagine hundreds of menu items added to one spot in the menu.)
>
> This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

2) Menu Trail By Path

> Menu Trail By Path sets the active-trail on menu items according to the current url.
>
> For example if you are at yoursite.com/blog/category1/article1 Menu Items with these paths will get the active-trail class on them and expand accordingly.
>
> blog
>
> blog/category1
>
> blog/category1/article1
> 1 votes

---
Tags: 7, navigation, routes
---


# Question
Title: How do you set a default input text format per content type?
I want to be able to set a different default input text format per content type and per content field.

For example, the format type choices might be "*Plain text*" and "*Rich text editor*" and in some cases I want the format to default to "*Rich text editor*" but keep "*Plain text*" as a choice in the dropdown. I know that I can change the order of the text formats to make "*Rich text editor*" the first choice, but this method changes all of them, that's not what I want to do.

# Answer
> 9 votes
In the absence of a stable release of Better Formats module, you can create a custom module to do this for specific content types or fields.

Create a module (modulename.info and modulename.module, inside a folder 'modulename'). Example: default\_text\_format.module:

```
<?php
/**
* Implements hook_element_info_alter().
*
* Sets the text format processor to a custom callback function.
* This code is taken from the Better Formats module.
*/
function default_text_format_element_info_alter(&$type) {
  if (isset($type['text_format']['#process'])) {
    foreach ($type['text_format']['#process'] as &$callback) {
      if ($callback === 'filter_process_format') {
        $callback = 'default_text_format_filter_process_format';
      }
    }
  }
}

/**
* Callback for MODULENAME_element_info_alter().
*/
function default_text_format_filter_process_format($element) {
  $element = filter_process_format($element);
  // Change input format to "Filtered HTML" for body fields of article nodes
  if ($element['#bundle'] == 'article' && $element['#field_name'] == 'body') {
    $element['format']['format']['#default_value'] = 'filtered_html';
  }
  return $element;
}

```

And default\_text\_format.info:

```
name = Default text format
description = Adapt the module code to set a default format for a content type.
package = Custom modules
core = "7.x"

```

Put these files in a folder 'default\_text\_format' in sites/all/modules/custom.

Change bundle name as appropriate for your content type. And you can substitute 'body' with your own 'field\_contenttype\_fieldname'. (After this comment / better\_formats code.)

# Answer
> 3 votes
Use the Better Formats module:

Better formats is a module to add more flexibility to Drupal's core input format system. It will allow you to set the default format per content type and much more.

# Answer
> 3 votes
I just bumped into this problem myself, but I didn't want to use a beta module (Better Formats), and I had to extend the functionality and automate it, so that such settings are not hardcoded, but set from the back-office.

So I did the following:

* I added a setting on the Edit Settings form of the field that I need the default text format for
* I used the code provided the above and modified it slightly so that it gets sets the default text format as saved in the settings of the field
* I used Features to export the content type so that I have my settings preserved in code

**Field Edit Settings part**

```
/**
 * Implements hook_form_FIELD_UI_FIELD_EDIT_FORM_alter().
 */
function MY_MODULE_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
  if ($form['#field']['type'] == 'text_long') {
    $instance = $form['#instance'];
    // Fieldset for Default Formats settings.
    $filters = filter_formats();
    $options = array('_none' => t('None'));
    foreach ($filters as $key => $filter) {
      $options[$key] = $filter->name;
    }
    $form['instance']['settings']['default_filter'] = array(
      '#type' => 'fieldset',
      '#title' => t('Default Filter Settings'),
      '#collapsible' => FALSE,
      '#collapsed' => FALSE,
    );
    $form['instance']['settings']['default_filter']['wysiwyg_profile'] = array(
      '#type' => 'select',
      '#title' => t('Select a default format for this field'),
      '#description' => t('The selected text format will influence the button and plugin configuration of WYSIWYG.'),
      '#default_value' => isset($instance['settings']['default_filter']['wysiwyg_profile'])
          ? $instance['settings']['default_filter']['wysiwyg_profile'] : '_none',
      '#options' => $options,
    );
  }
}

```

So this part of the code should evident enough...it adds a fieldset and adds a select list in it, which is populated by the WYSIWYG profiles existing on your site. Those WYSIWYG profiles are tied to the text formats, so when someone selects a text format/filter, it actually selects the profile that is configured.

Now the 2nd part is the same code as provided above by another user, and which is taken from the Better Formats module.

```
/**
 * Implements hook_element_info_alter().
 *
 * Sets the text format processor to a custom callback function.
 * This code is taken from the Better Formats module.
 */
function MY_MODULE_element_info_alter(&$type) {
  if (isset($type['text_format']['#process'])) {
    foreach ($type['text_format']['#process'] as &$callback) {
      if ($callback === 'filter_process_format') {
        $callback = 'MY_MODULE_filter_process_format';
      }
    }
  }
}

/**
 * Callback for MY_MODULE_element_info_alter().
 *
 * Alters the default text format of fields.
 */
function MY_MODULE_filter_process_format($element) {
  $element = filter_process_format($element);
  // Configuration array that specifies the fields that need to be altered.
  $field_info = field_info_instance($element['#entity_type'],
                                    $element['#field_name'],
                                    $element['#bundle']);
  // Change input format to configured value.
  if (isset($field_info['settings']['default_filter']['wysiwyg_profile']) && $field_info['settings']['default_filter']['wysiwyg_profile'] != '_none') {
    $element['format']['format']['#default_value'] = $field_info['settings']['default_filter']['wysiwyg_profile'];
  }
  return $element;
}

```

So the settings are saved, therefore Features Export is possible or whatever method you use to save your settings.

I hope this helps anyone else who encountered this problem!

---
Tags: 7, entities, nodes, input-formats
---


# Question
Title: Drupal 7 multilanguage front page using templates
I need to have 2 separate front page tpl pages for a multilanguage site I'm building, one for the english layout and one for the chinese layout. If the default language is zh-hans, I would like it to serve the custom tpl page-cnfront.tpl.php.

I managed to find an answer to my question for Drupal 6, which provided the following code:

```
function mytheme_preprocess_page(&$variables) {
  global $language;
  if (drupal_is_front_page() && $language->language == 'en') {
    $variables['template_file'] = 'page-customfront';
  }
}

```

I tried to modify it for my site in Drupal 7 like so:

```
function mytheme_preprocess_page(&$vars) {
  global $language;
  if (drupal_is_front_page() && $language->language == 'zh-hans') {
    $vars['theme_hook_suggestions'] = 'page__cnfront';
  }
}

```

but I think something is wrong, because I get a WSOD when I add this to my template.php. What is the correct way to do this?

# Answer
> 0 votes
I would suggest you to install the Variable translation (i18n\_variable) from the Internationalization module. This allows you to specify a front page per language under /admin/config/system/site-information.

# Answer
> 1 votes
theme\_hook\_suggestions is array

```
$vars['theme_hook_suggestions'] = array('page__cnfront');

```

---
Tags: theming, i18n-l10n
---


# Question
Title: custom field in product type not showing in line item drupal
ive created custom fields in my product type.

then i have this code under my custom module

```
global $user;
$order = commerce_cart_order_load($user->uid);
if($order) {
     $line_item_list = $order->commerce_line_items["und"];
     foreach ($line_item_list as $key => $value) {
         $line_item = commerce_line_item_load($value["line_item_id"]);
         drupal_set_message('<pre>' . print_r($line_item, TRUE) . '</pre>');
     }
}

```

i tried to print per line item to, but i cant see my custom field in the print...

anyone experienced this?

# Answer
You added the fields to the commerce product entity (`commerce_product`), not the line item entity (`commerce_line_item`).

That is why the fields don't show on your line item entity.

The line item entity contains a product reference field (`commerce_product`) referencing the associated product, you will need to inspect that to get the fields from the product.

e.g:

```
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
// Get product field value from line item
foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  // If line item is a commerce product type
  if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
    // Fetch duration value on product.
    $duration = $line_item_wrapper->commerce_product->field_subscription_duration_2->value();
    // Get raw values
    // $duration = $line_item_wrapper->commerce_product->field_subscription_duration_2->raw();
    drupal_set_message($duration);
  }
}

```
> 1 votes

---
Tags: commerce
---


title: Views Custom Contextual filter

text:
# Question
Title: Views Custom Contextual filter
How to create custom contextual filter for views using views api.

I have a custom table which is having some statistics data about the user. The user id is also stored in the table.

I managed to get the results using views api, Now I would like to use the contextual filter on the logged-in user, this is where I got interrupted. The contextual links are empty, its not showing any filters I can use of. How do I get contextual filters working using views api?

# Answer
did you implement hook\_views\_data and then defined you table there? if yes then did you define relation for uid? you can copy code from views/modules/node.views.inc

```
  // uid field
  $data['node']['uid'] = array(
    'title' => t('Author uid'),
    'help' => t('The user authoring the content. If you need more fields than the uid add the content: author relationship'),
    'relationship' => array(
      'title' => t('Author'),
      'help' => t('Relate content to the user who created it.'),
      'handler' => 'views_handler_relationship',
      'base' => 'users',
      'field' => 'uid',
      'label' => t('author'),
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_user_name',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_numeric',
    ),
    'field' => array(
      'handler' => 'views_handler_field_user',
    ),
  );

```
> 4 votes

---
Tags: 7, views
---


# Question
Title: How to prevent Migrate from creating null fields?
I'm writing some migrations classes using Migrate module. Some of my source fields does not have data for migration but the Migrate module creates Drupal fields with `null` values anyway. How to prevent that? I only want to create fields if there are non-null values for them.

This comment suggests that it should be enough to just unset field from source row (for example inside `prepareRow`), but that doesn't work for me - the field with `null` value is created anyway.

# Answer
> 1 votes
Apparently this feature was added to Migrate 2.6 and for now is available only when you're using dev version. For those who want to try it out, there is RC1 version available.

For older Migrate module versions, the empty field needs to be unset in **`prepare`** function, **not** inside `prepareRow` as the comment from drupal docs page suggested. Here is an example:

```
function prepare($entity, $row) {
  // Assuming that 'year' maps to 'field_year'
  if (!isset($row->year) || $row->year === null)
    unset($entity->field_year);

  // Assuming that 'gender' maps to 'field_gender'
  if (!isset($row->gender) || $row->gender === null)
    unset($entity->field_gender);
}

```

There is also a more *"generic"* solution prosed in one of the comments on drupal.org (pasting it here for future reference):

```
/**
 * Removes empty values prior to migrating.
 * @see http://drupal.org/node/1665332
 * @see http://drupal.org/node/1792894
 */
function mymodule_remove_empties($destination, $entity) {
  if ($destination instanceof MigrateDestinationEntity) {
    $entity_type = $destination->getEntityType();
    $form = $form_state = array();
    _field_invoke_default('submit', $entity_type, $entity, $form, $form_state);
  }
}

```

And in each of your Migrate classes:

```
public function prepare($entity, stdClass $source_row) {
  mymodule_remove_empties($this->destination, $entity);
}

```

---
Tags: 7, migrations
---


# Question
Title: Display custom URLs for individual tabs of quick tab
I need to display seperate URL(Deep linking) for individual tabs in a quick tab. I found a javascript fix in this link . The URL that is displayed has the quicktab name and tab number. It looks something like /test-quicktab-page?qt-test\_quicktab=2. I need a more meaningful url to be displayed. For example /test-quicktab-page/world or /test-quicktab-page/local . How can this be done?

I tried creating a URL alias but that didn't help.

# Answer
> 0 votes
Add jquery in external : This is used for you

```
jQuery(document).ready(function(){
  var quicktab = jQuery('ul.quicktabs-tabs.quicktabs-style-excel li  a').each(function() {
      var url  = 'test-quicktab-page?qt-test_quicktab=2';
      var href = jQuery(this).attr('href');
      var arr = href.split('/');
      alert(arr['2']);  /* rechange the index value as your url path */
      if(url == arr['2']) {
        jQuery(this).removeAttr('href');
        jQuery(this).attr('href','/test-quicktab-page/world');
      }
    });
});

```

---
Tags: uri, blocks
---


# Question
Title: Confirmation Email from Webform Submission
How would I send a confirmation email to the email address entered in a Contact Us form created with the Webform module?

# Answer
> 5 votes
This functionality is available out of the box with Webform.

1. On the webform node page, click on the "Webform" tab
2. From the webform tab, click on the "E-mails" tab
3. Click on the "Component value" radio button and select the component of the webform that captures the email address.
4. Click on the "Add" button
5. On the next page, you can set the Subject, From Address, From Name, and E-mail contents.

# Answer
> 1 votes
Step1: On the webform node page, click on the "Webform" tab

Step2: Click on the "E-mails" tab

Step3: Click on the "Component value" radio button and select the component of the webform select the email address component (the field the submitter will use to add his email address.

Step4: Select custom under E-mail subject and in the custom field write thank you for your submission.

Step5: Select custom under E-mail from address and use appropriate email like info@mywebsite.com

Step6: Step5: Select custom under E-mail from name and use appropriate name like the name of the company or website

Now select custom template under E-mail template and in field below add your message like

Thank you for submitting your message. You will be contacted should a suitable asap. Please do not respond to this email as this is an automated response.

Step:7 Click on the save button

# Answer
> 0 votes
There is a module available for this purpose; Webform Confirm Email Address

> webform\_confirm\_email is a simple addon module for the webform module.
>
> If you define an email in webform (eg. mydomain.net/node/9999/webform/emails) this email/these emails will be send immediately when the user clicked the webform submit button.

*Even without this module, we can send confirmation email to users. Important thing to note here is while creating the email component, we have to select **Email as webform's Type**. Go to the Email section of the webform. From there you can select the the email component as 'to'. Then add from, subject and template of the email to be sent.*

---
Tags: webforms, emails
---


# Question
Title: Where can I find in database that page (panel) is disabled?
I am using Panels module. If I go to structure -\> pages menu link, I will see my pages list.

I can disable/enable those pages. But how does this work under the hood? Where is it marked in the database that some specific page is disabled?

# Answer
Panel pages requires Page Manager module which comes with Ctools Module.... Below function in page\_manager/page\_manager.admin.inc is responsible for enable / disable action...

```
function page_manager_enable_page($disable, $js, $page) {
  if (!isset($_GET['token']) || !drupal_valid_token($_GET['token'], $page->task_name)) {
    return MENU_ACCESS_DENIED;
  }
  if ($page->locked) {
    if ($disable) {
      drupal_set_message(t('Unable to disable due to lock.'));
    }
    else {
      drupal_set_message(t('Unable to enable due to lock.'));
    }
  }
  else {
    if ($function = ctools_plugin_get_function($page->subtask, 'enable callback')) {
      dpm($function);
      $result = $function($page, $disable);
      menu_rebuild();

      // We want to re-cache this if it's changed so that status is properly
      // updated on the changed form.
      if (!empty($page->changed)) {
        page_manager_set_page_cache($page);
      }
    }
  }

  // For now $js is not actually in use on this.
  drupal_goto('admin/structure/pages');
}

```

When a panel page (Custom Created , Not default pages that comes with module) is enabled or disabled below function is called in ctools/page\_manager/plugins/tasks/page.inc...

```
/**
 * Callback to enable/disable the page from the UI.
 */
function page_manager_page_enable(&$cache, $status) {
  $page = &$cache->subtask['subtask'];
  ctools_include('export');
  ctools_export_set_object_status($page, $status);

  $page->disabled = FALSE;
}

```

You can find panel pages details inside variable table under the variable

> default\_page\_manager\_pages

When Disabled

```
a:1:{s:15:"test_panel_page";b:1;}

```

When Enabled

```
a:0:{}

```

Default pages that comes with module enable / disable status also stored in variables table...
> 2 votes

---
Tags: panels
---


# Question
Title: How to programmatically create views in Drupal 7
How do I programmatically create views in Drupal 7?

I would like to create a custom module that would output data as a view.

Is there any documentation on how to output views from a custom module?

# Answer
> 5 votes
My first guess was to create a desired view using UI, export it and paste the generated code into own module. And I guess this is how admin\_menu installs their admin views. You could install the module just for testing and see the contents of `/admin_menu/admin_views/views_default/`. At any rate, you would have to resort to writing a custom module and adhere to views' hooks syntax.

# Answer
> 0 votes
There is a very good step-by-step tutorial here: http://www.packtpub.com/article/creating-views-3-programmatically

---
Tags: 7, views
---


# Question
Title: Removing all "/node/$id" urls from xml sitemap plugin
In my project pages are implemented using Panels module and contain lot of nodes.

I've set up xml sitemap module, generated xml, and currently i can see many "/node/$id" urls, but:

1. That are not actual pages themselves, but parts of pages (or even parts of menus, etc)
2. Pages have aliases, that should be used, but not "/node/$id" urls.

How it is possible to remove "/node/$id" urls from sitemap and leave just pages with aliases?

# Answer
> 0 votes
To implement this with pages, implemented with Panels, it is necessary to manage pages urls manually with Xml Sitemap Custom subplugin: https://drupal.org/node/1235804

---
Tags: xml-sitemap
---


# Question
Title: What is the SQL query to filter og Admin Accounts?
I currently have the following SQL statement that gives me a list of all of my og nodes and their associated owner. I am having trouble nesting my JOIN statements to add the name of the owner from the users table. Any hints? Thanks

```
SELECT
    label AS `Group Name`,
    gid AS `Group ID`,
    etid AS `Node ID`,
    type AS `Type`,
    b.nid AS `Owner ID`
    FROM `prefix_og` a
        LEFT JOIN `prefix_node` b
            ON a.etid=b.nid

```

# Answer
This worked nicely... how can I make this available in a view?:

```
SELECT
a.label AS `Group Name`,
a.gid AS `Group ID`,
a.etid AS `Node ID`,
b.type AS `Type`,
b.uid AS `Owner ID`,
c.name AS `Owner Username`,
d.realname AS `Owner Realname`,
e.rid AS `OG Role ID`
FROM `prefix_og` a
LEFT JOIN `prefix_node` b
ON a.etid=b.nid
LEFT JOIN `prefix_users` c
ON b.uid=c.uid
LEFT JOIN `prefix_realname` d
ON b.uid=d.uid
LEFT JOIN `prefix_og_users_roles` e
ON b.uid=e.uid

```
> 0 votes

---
Tags: views, organic-groups, database
---


# Question
Title: How to change the order of content types
How would one go about changing the order of the content types list on a multilingual site or non-english site?

For example, by adding a content type named Émission (with accentuated É), we see the following list on admin/structure/types page:

* Article
* Page
* Émission

Same goes when translating a content type name (E.g.: Show =\> Émission) and changing language.

# Answer
The function `node_type_get_names()` calls the utility function `_node_types_build()`. If you look at the source, there is a call to `asort()` at the bottom.

If you read the documentation for `asort()`, you will see that it isn't called with it's second parameter, `$sort_flags`. This means that it will be called with the default, which is "normal" rules. In this case, I am prety sure normal rules means ordering based on the value of the code point, which places the English alphabet first, then "specials".

To take your characters with diacriticals into account, you would have have a proper locale defined, and then call `asort()` with the `SORT_LOCALE_STRING` option. For example,

```
$types = array('Émission', 'Page', 'Article');
print_r($types);

sort($types);
print_r($types);

setlocale(LC_ALL, 'fr');
sort($types, SORT_LOCALE_STRING);
print_r($types);

```

results in

```
Array
(
    [0] => Émission
    [1] => Page
    [2] => Article
)
Array
(
    [0] => Article
    [1] => Page
    [2] => Émission
)
Array
(
    [0] => Article
    [1] => Émission
    [2] => Page
)

```

That explains why the ordering isn't what you expect. A quick look through the Drupal source only reveals a single call to `setlocale(LC_ALL, 'C');` (it's in the bootstrap). See https://stackoverflow.com/questions/5231620/what-does-set-localelc-ctype-c-actually-do for what this does.

All of this means that without doing a `hook_menu_alter()` on the 'admin/structure/types' to change the page callback to be your own, or to `hook_pager_alter()` the render array for the page, you can't change the ordering.

As a stupid American :) who doesn't really understand all of the implications of localization and internationalization, I cann't comment whether the Drupal behavior is by-design or is a bug.
> 2 votes

---
Tags: i18n-l10n
---


# Question
Title: What is the best practice to upgrade Drupal core without breaking the Git repo and the production website
I've got a Git repository in which all my code is in the master branch, and I was previously just ignoring all the Drupal files, so that I kept a strict separation between code that I wrote (or modified or might modify) and code that could be generated with Drush or whatever.

This seemed like a good strategy until I had to upgrade Drupal. I realized I want to be able to roll back if things went poorly, and what better tool to use than Git to do that. I thought to myself this would be the perfect situation for a feature branch, so I made a `drupal-7.14` branch, gave it its own `.gitignore` to ignore all my code and settings files and pay attention to only files that are part of the Drupal install which I wouldn't be touching. I did an upgrade by hand (download, unzip, untar, copy), sorting through borderline cases like robots.txt and .htaccess, and overwriting Drupal's .gitignore with my own. I fixed some settings that worked with 7.14 but not with 7.15, to recover from a 500 error, and then everything seemed perfect. I renamed the branch to `drupal-7.15` and was about to go happily on my way.

Until I realized what I had inadvertently done: files that were previously untracked by my master branch but left in the working directory were now removed from the working directory when I checked out master, since they were no longer untracked files! ***D'oh!***

If I merge the `drupal-7.15` branch with master I'll lose the separation of code.

There's probably some way to convert a branch to a submodule. Assuming that's possible, that might be the best strategy. I knew before I did this that submodules were the "right" solution, but since I didn't realize the side effect of using branches for previously untracked files, I decided to cut corners and go that route. (Also, all the approaches I've seen to using submodules with Drupal assume that you're starting a new project and Drupal will be the master branch. It is undesirable to me to make someone else's code the master branch, and I already had a repo with a master branch. This looked like it would be unnecessarily complicated just to do an upgrade.)

There may be some other solution that I haven't thought of.

How can I best recover from this with the fewest possible downsides?

***UPDATE***: This is in development (in a Linux VM on my laptop), and has not gone to production yet. By the time we go to production I plan to have everything wrapped up in feature modules, but that's not in place yet.

***UPDATE 2***: Submodules *may* not work. According to Pro Git, "Submodules allow you to keep a Git repository as a subdirectory of another Git repository". Drupal doesn't provide any such a nice separation. Instead of all Drupal code being in a subdirectory, the relationship is more or less inverted, but there's still no clean separation, since you may be editing your .htaccess and robots.txt, so your code and the Drupal repo are mixed together. I'm looking for a workaround to this problem.

# Answer
It seems from discussion above that your question isn't about fixing your git repo, but about maintaining a Drupal site in git, and how that works with core updates.

I think that standard practice is in fact keeping all files in your repository, including Drupal core. The separation of Drupal code from custom code seems like a nice idea, but I don't think it's necessary, and I don't see what advantages it gives you. It also seems to assume that you will never want to patch core (or have to do it as a part of your deploy), which, while it isn't best practice, is definitely something you want to be able to do if something breaks in production. Keeping your commits nice and focused also helps to get this kind of separation.

The solution I've used is to keep all code in the same repository, put as much as possible in Features or other kinds of exports/code/configuration, and maintain a list of patches that need to be applied to out-of-the-box core and contrib.

When you update core, start in your dev environment:

* Make sure working directory is clean
* Dump latest database (`drush sql-dump`). Either make a commit with the dump or save it somewhere safe.
* Update core (`drush up drupal`)
* Commit all changes.
* Check patches file. If any patches need to be applied, apply them, and make another commit
* Run update.php if necessary (already done if you used drush for the update)
* Test your dev site. If everything is fine, push code to production. Run `drush updb` on production.
* If there's a problem and you need to revert, either revert or reset your repo (`git reset --hard HEAD~2` should do it), or revert the two commits if you want to keep the history. Replace your database with the dump.

The database dump is necessary because you otherwise can't undo changes made to the database by updates. You can also do the updating in a branch, in which case reverting just means checking out master. It's slightly inadvisable if you're working on one dev site because you can't really switch back to master and keep working there in parallel because of the database.

Using this more simple git-side workflow will allow you to use git's full power when you need it without the complication of submodules, etc. If this doesn't seem adequate, could you explain why you need further separation of code?
> 10 votes

# Answer
From my comments above, this question you have is about maintaining a Drupal site **files** with git, and how that works with core updates. You didn't mention anything about backing up and upgrading the database. I will try not to copy anything from goron answer.

I have created a blog post about this issue Upgrading Drupal core on your website with Git

Alternative Methods

> 1. Run Drush command `drush up drupal`
> 2. Apply a patch of the differences between the versions. See http://drupal.org/node/359234 & http://fuerstnet.de/en/drupal-upgrade-easier

You didn't state this, but if you are interested in tracking the changes between Drupal versions, I would do this by using *tags* instead of *branches*. Once you are done with your upgrade commit to *master*, tag your code as 7.x.
> 0 votes

# Answer
I'm running the setup with two branches just like the OP: one branch with my custom code only, and one branch that has both my custom and core files. I ran into the same situation: the ignored core files are removed when switching between branches.

I ended up having two identical git directories: \- one for working on my custom code, with the core files present but ignored, and I would never switch to the "full" branch in this directory \- one for performing merges, so that I would perform the branch switching and merging inside this directory only.

The reason that I choose this two-branches setup is because I want to easily track all local commits to core files, it's easier to examine and re-apply core mods when upgrading core files.
> 0 votes

---
Tags: version-control, upgrading
---


title: How do I uninstall the Relation module?

text:
# Question
Title: How do I uninstall the Relation module?
I am trying to uninstall the modules that are part of the Relation module, after I tested it on my test site.

The Relation Endpoints Field module is not selectable because Drupal says the field implemented by that module is being used.

When I click on the "Field list" link, I get the following list of fields currently used.

None of the reported fields is implemented by that module; they are standard Drupal fields.

What should I do, in such cases? The content type that used that field has been already deleted.

# Answer
This happened to me with a couple of modules last week; the solution was simply to run cron, allowing the fields marked for deletion to actually be deleted. After that I could uninstall the module in question without issue.
> 9 votes

# Answer
If you have access to phpMyAdmin for the site in question, the easiest way to solve this problem is to run the following query:

DELETE FROM `field_config` WHERE `field_config`.`deleted` = 1;

This is a problem caused by "fields pending deletion" in one of the core tables. Even after the field is deleted from all content types using the field, it isn't dropped from the field\_config table properly.

Some people suggest running cron "an arbitrary number of times" or waiting "an arbitrary period of time" but neither of these seems to work consistently or have a defined number. The only reliable solution I've found thus far is to run the query above when needed.

As soon as that query has been executed, you will be able to disable the module and uninstall as desired.

For more information see:
> 0 votes

---
Tags: entities, installation
---


title: My events are not displayed in calendar

text:
# Question
Title: My events are not displayed in calendar
Here I have a problem with Views and Calendar modules. I created test events with a date field.

I configured a view for Calendar with the date field, but no events are displayed ...

How to?

And if possible, how to remove the link on the month names?

thank you very much

# Answer
> 0 votes
Hi you could use event\_calendar module.. The calendar module only display calendars value. It is not display any event on it... So we are going for event calendar module. It gives various option for display the events and also provide the event content type..

---
Tags: views, datetime
---


title: Issue in posting a comment

text:
# Question
Title: Issue in posting a comment
When I post a comment, I get the following error on Drupal 7:

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'comment-28-0-0-und' for key 'PRIMARY': INSERT INTO {field\_data\_comment\_body} (entity\_type, entity\_id, revision\_id, bundle, delta, language, comment\_body\_value, comment\_body\_format) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7); Array ( \[:db\_insert\_placeholder\_0\] =\> comment \[:db\_insert\_placeholder\_1\] =\> 28 \[:db\_insert\_placeholder\_2\] =\> 28 \[:db\_insert\_placeholder\_3\] =\> comment\_node\_multi\_discussion\_theme \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> und \[:db\_insert\_placeholder\_6\] =\> test \[:db\_insert\_placeholder\_7\] =\> ) in field\_sql\_storage\_field\_storage\_write() (line 451 of /ftphome/dev\_itf\_events/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module).

What could be the cause?

# Answer
> 1 votes
Hi you have to remove the row from field\_data\_comment\_body table where entity id is 28 ..

---
Tags: 7, comments, database
---


# Question
Title: Hide or remove the "Remove" button, "Quantity" box, and Price for specific product/SKU on cart page of Ubercart
I have a zero-dollar product that, once added to the cart, should never be removed until checkout is completed. Currently, that product has the "Remove" button, "Quantity" field, and Price that all products are displayed with in the cart. How can I remove those three items just for this one product/SKU?

Thanks!

# Answer
You could achive this with hook\_form\_alter() and hide the field with $form\['field\_name'\]\['#access'\] = FALSE;
> 1 votes

---
Tags: 7, ubercart
---


# Question
Title: File attachments in /files/ disappearing
I'm having an issue on my site with uploaded file attachments disappearing. As an example, on our blog, we have images uploaded into the blog post with images added by using the file attachment. I've recently found them being deleted from the server resulting in an image placeholder. Yet the record of the file being attached is there and the source code within is correctly pointing.

Does anyone have any suggestions on how to diagnose this?

Our server is hostgator if that makes any difference. I'm not certain it's a Drupal problem.

# Answer
We are having a similar issue (http://deepcarbon.net), and it is intermittent. Most of the time it all works. But sometimes the images simply disappear. They were in the database, they were in the file system. Then all of a sudden they were not. Wondering if there's anything new on this topic.

So I know that the files table in the database has a status column. If the status is 0 (temporary) then the file will be removed the next time the cron runs. The other status is 1 (permanent).

I'm also curious about what jdu says "I would suggest bootstrapping drupal and manually running some of drupal's image functions to test it out". Can you explain that more? What functions?

So our current solution is to run a cron every night to determine if any files have been removed from the filesystem since the night before. And we archive the files directory, so we can restore them if need be. At least until the real problem

We've also turned on creating revisions for every change for every content type, so we know when someone does something in a node.

So far we have not had the problem again over the last 3 weeks, so debugging this issue is on hold.
> 1 votes

---
Tags: media, files
---


# Question
Title: Changes made in hook_node_view() are not applied?
I wanted to change the title of a node field on the node display page.

I have implemented `hook_node_view()` and changed the title in code using following code:

```
$node->content['my_field']['#title'] = t('Field Name');

```

When I `dpm()` the `$node` object I can see that above code has been successfully executed, but on node display page I still don't see the field name changed.

I also did a `dpm()` of `$content` from tpl file and found out that `$content['my_field']['#title']` has been set to 'Field Name' as per above code. But it still displays the older title.

Whay may be causing this to happen?

# Answer
Hi you have added extra fields in the content variable so you have to override the old title
> 0 votes

---
Tags: nodes
---


# Question
Title: Allow people to administer only on certain content type?
Under "admin/people/permissions" there is a permission that allows users to administer all the content types.

I want to create a role that can only administer an "Article" content type. How can I achieve this?

# Answer
> 6 votes
The menu callback for "admin/structure/types/manage/%node\_type" is defined in node\_menu() using the following array item:

```
  $items['admin/structure/types/manage/%node_type'] = array(
    'title' => 'Edit content type',
    'title callback' => 'node_type_page_title',
    'title arguments' => array(4),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_type_form', 4),
    'access arguments' => array('administer content types'),
    'file' => 'content_types.inc',
  );

```

There are other two menu items that follow it, but they depend from that menu item for the access callback.

```
  $items['admin/structure/types/manage/%node_type/edit'] = array(
    'title' => 'Edit',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/structure/types/manage/%node_type/delete'] = array(
    'title' => 'Delete',
    'page arguments' => array('node_type_delete_confirm', 4),
    'access arguments' => array('administer content types'),
    'file' => 'content_types.inc',
  );

```

Once you change the access callback for the first menu item, the other two will use the same access callback.

The first step, for the custom module I would implement to achieve what you want is to implement `hook_permission()`. node\_permission() is useful as guideline to write the code you need.

```
function mymodule_permission() {
  $perms = array();

  foreach (node_type_get_types() as $type => $info) {
    $perms["administer $type content type"] = array(
      'title' => t('%type_name: administer content type', array('%type_name' => $info->name)),
    );
  }

  return $perms;
}

```

The `foreach()` part could be rewritten as the following code:

```
  foreach (node_permissions_get_configured_types() as $type) {
    $info = node_type_get_type($type);

    $perms["administer $type content type"] = array(
      'title' => t('%type_name: administer content type', array('%type_name' => $info->name)),
    );
  }

```

The difference is that node\_permissions\_get\_configured\_types() is using some Drupal variables that are set in a settings page. The function is used also from the Node module when creating the list of the permissions associated to a node of a content type. The documentation for the function reports the following text:

> To exclude a specific node from getting permissions defined for it, set the `"node_permissions_$type"` variable to 0. Core does not provide an interface for doing so; however, contrib modules may exclude their own nodes in `hook_install()`. Alternatively, contrib modules may configure all node types at once, or decide to apply some other `hook_node_access()` implementation to some or all node types.

The second step is to alter the menu item already defined by the Node module.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['admin/structure/types/manage/%node_type']) {
    $items['admin/structure/types/manage/%node_type']['access callback'] = '_mymodule_content_type_access';
    $items['admin/structure/types/manage/%node_type']['access arguments'] = array(4);
  }
}

```

`_mymodule_content_type_access()` should contain code similar to the following one:

```
function _mymodule_content_type_access($type) {
  return user_access("administer {$type->type} content type");
}

```

# Answer
> 4 votes
The easiest way I can think would be to provide a new separate permission for each available content type which you can assign to arbitrary roles, then override the `access callback` for the content type edit form to use this new permission:

```
// Implements hook_permission()
function MYMODULE_permission() {
  $permissions = array();
  // Build up a permission for each content type
  foreach (node_type_get_types() as $type) {
    // Get the permission key
    $permission_string = _MYMODULE_permission_string($type->type);

    // Add the new permission
    $permissions[$permission_string] = array(
      'title' => 'Administer ' . $type->name . ' Content Type',
      'restrict access' => TRUE
    );
  }

  return $permissions;
}

// Implements hook_menu_alter()
function MYMODULE_menu_alter(&$items) {
  // Override the access callback
  $items['admin/structure/types/manage/%node_type']['access callback'] = 'MYMODULE_content_type_access';

  // Override the access arguments so we receive the content type object
  // rather than the standard permission name.
  $items['admin/structure/types/manage/%node_type']['access arguments'] = array(4);
}

// Access callback function
function MYMODULE_content_type_access($content_type, $account = NULL) {
  // If no account object is provided use the logged in user
  if (!$account) {
    global $user;
    $account = $user;
  }

  // If the user has access to edit all content types then we should return
  // TRUE.
  if (user_access('administer content types', $account)) {
    return TRUE;
  }

  // Otherwise create a permission string based on the provided content type.
  $permission_string = _MYMODULE_permission_string($content_type->type);

  // Return access based on the permission string
  return user_access($permission_string, $account);
}

// Helper function to build up a standardised permission string
function _MYMODULE_permission_string($type_name) {
  return 'administer ' . $type_name . ' content type';
}

```

# Answer
> 1 votes
You also have, on permissions, for each role:

* Article: Create new content
* Article: Edit own content
* Article: Edit any content
* Article: Delete own content
* Article: Delete any content.

What else do you need?

# Answer
> 0 votes
Workbench module can also help here. Different roles can have access to steps in Workbench, ie you can have different roles access different steps in workbench.

---
Tags: users
---


# Question
Title: Select Images from a Multiple Images Field
I have a multi-valued image field that gets populated automatically with several images per entity. I need to add a manual "approval" step where one or more of the images is selected to be used later. What is a clean way to implement the approval process for existing images?

# Answer
> 0 votes
Use field\_collection module to build a field that has an image and a boolean.

Copy existing multi-image fields into the new field\_collection like this:

```
/**
 * Copy a multi-image field into a multi-field_collection with an image field
 *
 * This function requires a patch for field_collection 7.x-1.0-beta7 like this:
 * wget https://drupal.org/files/1937866-field_collection-metadata-setter.patch
 * patch -p1 < 1937866-field_collection-metadata-setter.patch
 *
 * @param $nid  The node to update
 * @param $multi_image_source Name of the existing multiple-images field
 * @param $dest_field_collection Name of the new field_collection that will get the photos
 * @param $dest_field Name of the image field inside the field_collection
 */
function _copy_images_to_selectable_field($nid, $multi_image_source, $dest_field_collection, $dest_field) {

  $entity = entity_load_single('node', $nid);
  $wrapper = entity_metadata_wrapper('node', $entity);

  if ($wrapper->$dest_field_collection->value() != null) {
    drupal_set_message("skipping node with existing destination field ".$nid);
    return;
  }

  $photos = $wrapper->$multi_image_source->value();

  $collections = array();

  foreach ($photos as $photo) {

    $fc = entity_create('field_collection_item', array('field_name' => $dest_field_collection, 'revision_id' => 1));
    $fc->setHostEntity('node', $entity);

    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc);

    $fc_wrapper->$dest_field->set($photo);

    $fc->save(TRUE);
    $collections[] = $fc;
  }

  $wrapper->$dest_field_collection->set($collections);

  $wrapper->save();
}

```

\**NOTE: This function requires a patch for field\_collection 7.x-1.0-beta7. Download and apply the patch from the field\_collection module's folder like this:

```
wget https://drupal.org/files/1937866-field_collection-metadata-setter.patch
patch -p1 < 1937866-field_collection-metadata-setter.patch

```

---
Tags: 7, media
---


title: Allowing comments on Entityform

text:
# Question
Title: Allowing comments on Entityform
My current project requires the use of comments on submitted data on entityform. I believe this functionality is built in drupal 7 node. By any chance, is it possible to implement it also on Entityform? if not is there a possible workaround to meet my project requirements?

# Answer
Comments in Drupal 7 are tied to Nodes. You could try the Reply module but it is still a dev project.

Usually though in situation like this though if a project needs some functionality that is built into Nodes in Drupal core I think it might be case where Nodes should really be used.
> 0 votes

---
Tags: 7, comments, entities
---


title: Send content in mail + Rules

text:
# Question
Title: Send content in mail + Rules
When a user registers an account I would like to create an invoice (this is a content type) and send it as a pdf to the user. But I have no clue how I can send the invoice to the user... .

I know you can send a mail, but how to include the invoice I have no idea.

I've searched on the internet but no luck ... .

# Answer
I just had to implement this on a site in a similar fashion. You can use MIME Mail and it's submodule MIME Mail Attachments along with the Print and the Rules Download module. It will allow you to create a rule and email (with attachment.
> 0 votes

---
Tags: users, rules, nodes, emails, commerce
---


# Question
Title: How do I overwrite Facet API tokens for active items?
I'm using "Facet API" and "Search facets" modules on Drupal 7. I'm trying to change the values of the active items' tokens provided in the search blocks (especially the \[facetapi\_active:facet-label\] token) , I tried to use the "Facet API Bonus" module and the function hook\_facet\_items\_alter with no success, could someone help me? Thanks!

# Answer
> 1 votes
I didn't need the "Facet API Bonus" module, I wrote a module to implement THEME\_facetapi\_link\_active (included in facetapi.theme.inc) then i simply replaced the label's text using the function `str_replace` like this:

```
$variables['text']=str_replace("Price » Amount (decimal)","Price",$variables['text']);

```

---
Tags: tokens, search
---


# Question
Title: Adding View to Content Type already existing to combine fields
I have a content type that is loaded with 1000's of records. These are not shown through any custom view as of right now. I have multiple fields I would like to combine into a single field.

For example:

**field\_one, field\_two, field\_three**

...combine above into single field:

**field\_combined**

I don't need to do any calculations, I would just like to combine them into one field when the content type page is displayed.

# Answer
To do what you want, one way is to create a new view, something like this should work I think:

* Create a new view of the content type you wish to include
* Set display format to Table
* Add the fields you want combined to the Fields section
* Arrange them in the order in which you want them displayed
* Under format: Table | Settings, choose which column you want ALL of these fields to appear in and select that for each

This should present a new view with all of those fields in one column, and any other data as you see fit in other columns. You may need to adjust some styling to get them to format properly - for example, text is inline, so to have it appear on a separate line, you will need to wrap it a DIV or something like.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How do I render a Twig template and load a CSS file from a controller?
Is this considered a good practice for rendering a Twig template and loading a CSS file from a controller?

### DefaultController.php

```
namespace Drupal\acme\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Template\TwigEnvironment;

class DefaultController extends ControllerBase implements ContainerInjectionInterface
{
  /**
  * @var Drupal\Core\Template\TwigEnvironment
  */
  protected $twig;

  public function __construct(TwigEnvironment $twig)
  {
    $this->twig = $twig;
  }

  public static function create(ContainerInterface $container)
  {
    return new static(
      $container->get('twig')
    );
  }

  /**
   * hello
   * @param  string $name
   * @return string
   */
  public function hello($name)
  {

    $template = $this->twig->loadTemplate(
      drupal_get_path('module', 'acme') . '/templates/hello.html.twig'
    );

    $markup = [
      '#markup' => $template->render([ 'name' => $name ]),
      '#attached' => [ 'css' => [
          drupal_get_path('module', 'acme') . '/assets/css/acme.css'
        ]
      ]
    ];

    return drupal_render($markup);
  }
}

```

### acme.routing.yml

```
acme_hello:
  path: '/acme/hello/{name}'
  defaults:
    _content: '\Drupal\acme\Controller\DefaultController::hello'
    _title: 'acme Title'
  requirements:
    _permission: 'access content'

```

### hello.html.twig

```
<div class="acme-hello-text">
  <h1>Hello {{ name }}!</h1>
</div>

```

# Answer
> 5 votes
As far as I understand, the controller should just contain the following code.

```
class DefaultController implements ControllerInterface {
  public function hello($name) {
    $twig = $this->container->get('twig');
    $path = $this->templateDir . 'hello.html.twig';
    $template = $twig->loadTemplate($path);

    return [
      '#markup' => $template->render(['name' => $name]),
    ];
  }
}

```

See also Drupal 8: An Introduction to the New Production.

I still have to find a reason to do this, thought. `hook_theme()` is still supported by Drupal 8, and it doesn't seem it is getting deprecated, at this time. The only difference is that in Drupal 8, `theme()` has been renamed `_theme()`; as such, it should not be called directly.
Since you are asking if your code is considered good practice, I would say no: You should do as you did with Drupal 7, defining a theme function in `hook_theme()` that uses a template. Then return markup similar to the following one in your controller method.

```
[
  '#theme' => $your_theme_function,
  '#name' => $name,
];

```

Replace `$your_theme_function` with the theme function ID, and `#name` with the array index used for `'variables'`.
Actually, there is a difference between Drupal 7 and Drupal 8: While Drupal 7 allows you to attach JavaScript and CSS, Drupal 8 allows you to attach just libraries, which are a set of JavaScript and CSS files with dependencies.

# Answer
> 3 votes
I refactored my code as follow, removing code from the controller class and updating the method hello

**DefaultController.php**

```

namespace Drupal\acme\Controller;

use Drupal\Core\Controller\ControllerBase;

class DefaultController extends ControllerBase
{

  /**
   * hello
   * @param  string $name
   * @return string
   */
    public function hello($name)
  {
    return [
      '#theme' => 'hello_page',
      '#name' => $name,
      '#attached' => [
        'css' => [
          drupal_get_path('module', 'acme') . '/assets/css/acme.css'
        ]
      ]
    ];
  }
}

```

And also adding a new function to

**acme.module**

```

  function acme_theme() {
    $theme['hello_page'] = [
      'variables' => ['name' => NULL],
      'template' => 'hello'
    ];

    return $theme;
  }

```

If interested you can see a gist containing all of the files and code here https://gist.github.com/jmolivas/d29065493a91f16f35b2

---
Tags: 8, theming
---


title: How do I get the path for public://

text:
# Question
Title: How do I get the path for public://
I need to get the path for public:// at runtime. Is there a function I can use to get it?

# Answer
> 38 votes
You can use the following code, to obtain the real path of public://.

```
if ($wrapper = file_stream_wrapper_get_instance_by_uri('public://')) {
  $realpath = $wrapper->realpath();
  // ...
}

```

This code is the simplified version of the code used by `file_create_url()`, with the following differences:

* It doesn't allow third-party modules to alter the URL, since the OP is asking for the path associated with public://
* It doesn't check the URI contains ://, since this is clearly true
* It doesn't check the URI is a root-relative URI, since this is clearly false for public://
* It doesn't check the URI is protocol relative, since this is clearly false in the OP's case
* It doesn't check the URI is not a properly formatted stream, since public:// is a properly formatted stream
* It doesn't check if the scheme is http or https, since in this case is public
* It doesn't call `$wrapper->getExternalUrl()` since the OP is asking for the path, not for the URL

If the OP wanted the URL for public://, I would have used the following code, which is still a simplified version of the code used by the Drupal function, which needs to be more generic.

```
if ($wrapper = file_stream_wrapper_get_instance_by_uri('public://')) {
  $url = $wrapper->getExternalUrl();
}

```

# Answer
> 42 votes
You can use the file\_create\_url function.

```
$uri = 'public://';
$path= file_create_url($uri)

```

# Answer
> 24 votes
In case if you are using only local files (**not remote!**) you can also try drupal\_realpath()

```
$path = 'public://custom_map';
drupal_realpath($path);

```

It will return:

```
D:\Work\OpenServer\domains\local.testsite.com\sites\default\files\custom_map

```

# Answer
> 3 votes
See the following examples:

```
$scheme = file_uri_scheme($file);

if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
  $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
  $path = $wrapper->getLocalPath($file);
}

```

or:

```
$wrapper = file_stream_wrapper_get_instance_by_uri($uri);
$path = $wrapper->getDirectoryPath() . "/" . file_uri_target($uri);
print $path;

```

Check API for `DrupalPublicStreamWrapper`.

Using `file_create_url()` doesn't work in all cases (as the other answers suggest), because the returned URL doesn't have to be on the same server. And using `$_SERVER['DOCUMENT_ROOT']` works only for certain server configurations.

If you don't want to use stream wrappers, you may try simpler solution:

```
$path = variable_get('file_public_path', conf_path() . '/files') . '/' . file_uri_target($uri);

```

Otherwise if you need something that works more generally, check @hannanxp's solution:

```
$wrapper = file_stream_wrapper_get_instance_by_uri($uri);
if ($wrapper instanceof DrupalLocalStreamWrapper) {
  $path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
}
else {
  // This does not appear to be a local file so there's no such thing as
  // a relative path; do appropriate error handling here.
}

```

Read more: How can I convert a file uri to relative path?

---

Related:

---
Tags: 7, files
---


title: How do I put a block in a form?

text:
# Question
Title: How do I put a block in a form?
How do I put a block in a form?

My searches on this site and on google only have lead to questions of putting a form in a block. I want the opposite. I have a form definition array in a module, and I want to add in an existing block.

# Answer
> 1 votes
```
  $block = module_invoke('module_name', 'block_view', 'block_id');

  $form['block'] = array(
    '#markup' => render($block),
  );

```

---
Tags: forms, blocks
---


# Question
Title: New node created on one site automatically created on others?
Say I have a parent site where all my content is created: nodes and taxonomy terms, but I want that same content to be created - or to appear at least - automatically on multiple child sites. What ways could this functionality be achieved? The solution could be a custom module or a a contrib module, if one exists to perform this task.

# Answer
> 0 votes
Isovera wrote a good article on how to do this "Syndicate content between Drupal"

You'll need Views and Feeds at a minimum to get started.

In views you'd create an RSS feed (there are several views modules available to help with this) for the data you'd like to share between sites. You would then set up Feeds to import your newly created RSS feed. You can map each field from your feed to the content type you'd like to import into. Feeds can be configured to run on cron, allowing content to be imported from one site to another.

# Answer
> 0 votes
The Domain Access module and associated sub-modules will allow you to share content (nodes, taxonomy terms, blocks, etc) across multiple sites as well as select which sites you would like X or Y content to be visible on.

Each domain/site has the ability to have its own content as well as share content across all other domains.

---
Tags: nodes
---


# Question
Title: How can you compute grand totals in an aggregate view
I have a aggregate view in D7 that is working great. The only thing is, I want to add a grand total line to the view. What is the best way to add a grand total to the view? Here is a sample of my data.

```
Dept  Squad    # of Rpts   # Vols   # of Hours  Value of Hours
AK     AK-11        3          6        124.00           2,745.36
FL    FL-893       24         41        664.50          14,712.04

```

What I would like to do is the above plus a grand total line like:

```
Dept  Squad    # of Rpts   # Vols   # of Hours  Value of Hours
AK     AK-11        3          6        124.00           2,745.36
FL    FL-893       24         41        664.50          14,712.04

  Grand total      27         47        789.50          17,457.40

```

Any suggestions?

Thanks for you help.

Dennis

# Answer
You have to use Views Calc module.

The project page says:

> This module adds simple calculations to a views table. Requires the Views module.
>
> You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

For more information go through the module documentation.
> 0 votes

---
Tags: 7, views
---


# Question
Title: my articles publish even when I deselect publish
I'm an admin user type with publisher priveges as well. When I save an article, it is always save as "published". Even when I uncheck "published" under "publishing options" it saves as published.

In other words, I make sure "published" is deselected, and when I save and edit the article, the "published" select box is ticked.

My goal here is to save the content as unpublished, but I can't even when manually deselecting "published".

Drupal version 6.30. Fresh install. No whacky modules added.

# Answer
This is what I did to fix the problem:

1. I disabled all except the core modules.
2. I then tested to see if I could unpublish content, and I could.
3. I then re-enabled each module until I found the culprit. In this case, it was the "rules" module.
> 1 votes

---
Tags: nodes
---


# Question
Title: Drupal Commerce Paypal WPP Programatically Create a Transaction
I stumbled on a thread over at: https://drupal.org/node/1867768 and I am trying to do a similar integration with a "one page checkout" where the customer selects the product, puts in shipping information and cc information all on one page and I'm capturing that info using drupal's form api submit callback. I can programmatically create the order, add the profile type to the order but I'm getting a little stuck when it comes to the transaction. By the looks of it Ryan had mentioned that each payment gateway has a different way of declaring the transaction. I'm using Paypal Payments pro also know and Website Payments Pro (WPP) and was wondering how to go about creating a WPP transaction programmatically and seeing if anyone had dealt with this before?

Thanks,

# Answer
> 0 votes
I was able to solve this issue. Instead of retyping it, the answer can be found on drupal.org at this link: https://drupal.org/node/1867768#comment-8755925

---
Tags: commerce, payment-gateways
---


# Question
Title: Correct way to add custom column to user table?
I'm looking to add a column called 'updated' directly to the users table.

The Field API and Joins are not an option for me in this case due to external constraints.

How can I safely modify the user\_schema to add the 'updated' column in a custom module and safely clean it up when the module is removed?

Here is the layout of the 'updated' column based on the Schema API:

```
  $field = array(
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Timestamp for last time user was updated.',
  );

```

Currently my attempts using hook\_install are not working as I believe they should.

# Answer
> 5 votes
It seems that I was missing hook\_schema\_alter(). This fixed my issues with drupal\_write\_record() and views. Thank you @Clive for your comment here.

**Overview of what you need to do:**

**Actual Code:**

Here is how I accomplished this. The code below belongs in your module.install file.

```
function hook_install() {
  $field = array(
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Timestamp for last time user was updated.',
  );
  $index = array(
      'indexes' => array(
          'updated' => array('updated')
      ),
  );
  db_add_field('users', 'updated', $field, $index);
}
function hook_schema_alter(&$schema) {
  $schema['users']['fields']['updated'] = array(
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Timestamp for last time user was updated.',
  );
}

function hook_uninstall() {
  db_drop_field('users', 'updated');
}

```

---
Tags: 7, database
---