# Question
Title: path alias for 'edit' not loading correct page under 'admin/'
I have a content page that just editors need to see. So I set the pathauto to something like `'admin/page-title'`. The edit-path is `'admin/page-title/edit'` accordingly.

When trying to open the node in edit mode however, the first page of admin section is displayed instead of the edit form – as found under `'admin/'`.

This basically is not really a problem – just took me some time to figure out that actually the '*admin*' part of the URL is causing the problem. I would however really like to keep that URL structure since it would make the path consistent to the actual internal content structure. Any suggestion how I could get this work? Any pointers would be gladly appreciated.

# Answer
> 1 votes
It happens because paths defined through `hook_menu()` implementations have the precedence over path aliases. The System module defines the admin menu item, which is a *catch-them-all*, since Drupal, for a non existing path like node/1/not-defined-from-any-module, will show node/1. This also happens for not existing path aliases that partially match a path defined from a module; if you try to access admin/not-existing-alias, Drupal will return the page at admin.
Notice that in the case of a non existing alias that partially matches an existing one (e.g. path-alias/sub-path-alias/not-existing-sub-path versus path-alias/sub-path-alias), Drupal will not show the page at the path for the existing alias (in my example, path-alias/sub-path-alias).

Also, the Pathauto module doesn't define path aliases for node/1/edit; for that, you need the Sub-pathauto (Sub-path URL Aliases) module.

> The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
>
> For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.

---
Tags: 7, path-aliases
---


# Question
Title: How do you convert an existing order into a shopping cart order?
I would like to be able to have an existing order that has already been checked out back into a user's shopping cart. From what I have read from the documentation, a shopping cart is just an order for a user.

This is relevant because when my user's checkout the order, it only does an authorize only transaction, which means the funds have not been transferred yet. I want to allow my user's a window of time to change their order.

So, I figured the best way to do this was to take the order that they want to edit, void it out, and then put it back into their shopping cart.

I can't seem to find an api call for this. I saw `hook_commerce_cart_order_is_cart_alter` in the commerce\_cart API, but I couldn't figure out when this was called or if this was a use case for this API call.

# Answer
As you mentioned a shopping cart is nothing more than an order with the `state` of `cart`.

So all you need to do is to update the `state` of $order to `cart` using commerce\_order\_status\_update() function:

```
<?php
$log = t('Reverting back to Cart state so the customer can modify items.');
commerce_order_status_update($order, 'cart', $skip_save = FALSE, $revision = TRUE, $log);

```

Alternatively if you are using rules, you can use the rule: **"Set order status : Cart"** which comes with commerce module out of the box.
> 2 votes

---
Tags: commerce
---


# Question
Title: How can we do open a popup for login facebook and after complete it will close?
I want a popup that will open when anybody wants to sign-in using facebook or any social site login. The box pops up and will close after successful login or cancel

This is code I am using for this and I know something missing please give me some hint---

```
<a href="https://www.facebook.com/dialog/oauth?client_id=MYCLIENTID&redirect_uri=http%3A//www.MYWEBSITE.COM/fboauth/connect&scope=email" class="facebook-action-connect" onclick="window.open(this.href,'popupwindow','width=700,height=500,scrollbar,resizable'); return false;"  target="_self" style="color: White; font-weight: bolder; cursor: hand; text-decoration: none">

```

# Answer
You should try ulogin... I hope this will solve your whole problem. :)

Description:- uLogin service allows your users to login using their accounts at:

Facebook, Twitter, Google, Windows Live ID, LinkedIn and various open id.
> 1 votes

# Answer
I had the same problem that turned out to be the "External Links" module enabled. It saw the facebook url as external, and promptly added target="\_blank", causing all clicks to open in a new window.
> 0 votes

---
Tags: users, social-network
---


# Question
Title: Load fields from a node which reference an entity
I have a node with a entity reference field (more precisely a product reference). How do I access the fields of the referenced entity from the node?

(I’m trying to do it through a code field in the Display Suite, so I have access to the $entity object, not sure if that helps)

To explain better I would like to be able to do something like these tokens:

```
[node:field-products:0:field-flow-rate]
[node:field-products:1:field-flow-rate]
[node:field-products:2:field-flow-rate]

```

but with PHP, so I can cycle through the index.

# Answer
> 2 votes
You can use `entity_metadata_wrapper()` to easily get referenced entities, their field and much more.

```
$node_wrapper = entity_metadata_wrapper('node', $entity);

foreach ($node_wrapper->field_products as $product_wrapper) {
  // You can print or do whatever you like with the value of the fields
  // of the referenced entity like below:
  print $product_wrapper->field_flow_rate->value();
}

```

# Answer
> 1 votes
I'm not sure of the exact structure of your node object (use `dpm($node)` or `print_r($node)` if you don't have a debugger). But assuming the entity\_ref field is called field\_products then you would do something like this:

```
foreach ($node->field_products as $nid) {
  $child = node_load($nid); // might be $nid[0], use dpm to find out
  $flow_rate = $child->flow_rate;
}

```

---
Tags: commerce, entities
---


# Question
Title: Toggle CCK field visibility with CCK radio buttons
I have a content type with three cck fields

1 radio button, 1 text field, and 1 integer field.

What I am trying to do is by default have the text field and integer field hidden, and only show them dependent on the state of the radio button.

Example:

Two radio buttons, one which says *text* and one which says *integer*. When the *text* radio box is checked, then the text box shows and the integer box is hidden and vice versa.

# Answer
There is a contrib module written for just this: Conditional Fields. Here is a quote about it (from the module's project page):

> ... allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
>
> When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API. You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.
> 1 votes

# Answer
You can use client-side javascript for this. For example, the jQuery show/hide functions can be used to expose your text and integer fields depending on the value of the radio button.
> 0 votes

# Answer
If you're happy doing a very small amount of coding, then this can be achieved in a way that is far more lightweight than using the conditional fields module.

In a custom module you can implement hook\_form\_alter() or hook\_form\_FORM\_ID\_alter() and use the states api to add the visibility rules. You don't actually need to program the logic for hiding / displaying the fields, just define which values to use:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULENAME_form_CONTENTTYPENAME_node_form_alter(&$form, &$form_state) {
  $form['text_field']['#states'] = array(
    'visible' => array(
      ':input[name="radio_field"]' => array('value' => 'value_of_textfield_option'),
    ),
  );

  $form['integar_field']['#states'] = array(
    'visible' => array(
      ':input[name="radio_field"]' => array('value' => 'value_of_integarfield_option'),
    ),
  );
}

```
> 0 votes

---
Tags: nodes, entities, 6
---


title: Theming blocks in Panels

text:
# Question
Title: Theming blocks in Panels
Does anyone know of a module or some other way to allow users to customize blocks or panes (or even regions) in a panel on their profile page (i.e.: the authenticated user could change the color background of the block, or add a picture to the background, could change the color of the borders and font, etc?)

That means the same blocks could be themed differently by all users.

Ideally each block / pane would have a tab with some kind of a drop-down allowing the user to select options to add HTML and CSS on a per block basis.

The site uses Bartik (D7.)

Any feedback on this would be greatly appreciated. :)

# Answer
> 1 votes
Just some ideas:

I use the Fieldable Panels Panes a lot on smaller web page to add direct content to the Panel pane instead of having to create content for it first. FPP are entities. Maybe you can use for a user to add images (and text, files, etc.) to their profile page? Honestly, I've only used it on site building level.

I know about this module Classy Panel styles, but never used it. Maybe you can also set the permissions that users can use the pre-defined styles.

There is also a widget type module (as used in Atrium) where a user can move blocks (Panel panes) around. I don't have a link for that.

---
Tags: theming, blocks, panels
---


# Question
Title: Best practices for copying data (only) back from production site to testing site after exporting views as features to prod?
After building/testing a Drupal 7 site, I deployed it to prod server, exporting all views as features. Now the views are all 'in database' on test site, but 'in code' on live site - on the theory that no views editing should be done in prod. Now if I want to copy my prod database (but not code) back to my testing site for a new phase of development, what's the best way to avoid overwriting (or wiping out) views 'in database' on my dev site?

1. Should I have renamed the views when creating features?
2. do I export/import the views, either from/to testing or from prod to testing?
3. is there some other way to selectively preserve views in the testing db when copying back an sqldump?

Thanks much!

# Answer
> 1 votes
We have the following:

* DEV code base. (dev-code)
* DEV database. (dev-db)
* PROD code base. (prod-code)
* PROD database. (prod-db)

Here is a simple dev flow to change a view, deploy to prod and then continue development:

1. `[dev-db]` Create a new view or modify an existing view.
2. `[dev-code]` Create a feature module out of that view or re-create an existing one.
3. `[dev-db]` Enable the feature module on DEV.
4. `[prod-code]` Commit the change and push it to PROD or upload the changes to PROD.
5. `[prod-db]` Enable or Revert the feature on PROD.
6. `[prod-db]` Export database from PROD (and preferably sanitize it to remove sensitive data)
7. `[dev-db]` Import the database dump to DEV.
8. `[dev-code]` Continue development!

You shouldn't have any problem if you are following this flow.

# Answer
> 0 votes
1. Before synchronizing the database back to TEST environment, you should export all your views into code in your TEST environment, overriding the previous code.
2. Then revert your views to code.
3. Then synchronize the DB from DEV to TEST.

---
Tags: views, database, version-control
---


title: Hide url in subdirectory install?

text:
# Question
Title: Hide url in subdirectory install?
in my site I use version 7 of Drupal and Linux OS on the server, and need to hide the subdirectory of the installation when access by LINK ... explaining better: Current link: www.site.com/folder I want to change for only: www.site.com I searched in various forums, websites and how is an old subject, I believe that there was a change in the code to hide / delete the symbolic url paste ... In the folder / root .htaccess I created left like this:

`Options + FollowSymlinks
RewriteEngine On
RewriteRule ^ (. *) $ Folder / $ 1 [L]`

Thus, to access the site, only the index remains without the folder ... I want the whole site be without referencing the subfolder where it was installed ... How do I do this? thank you

# Answer
Add this rewrite rule in your .htaccess file:

```
RewriteEngine On
RewriteRule ^/subfolder/(.*)$ http://www.example.com/$1 [L,R=301]

```

Change `subfolder` and `www.example.com`.

Also, you can try with this:

```
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [NE,R=301,L]

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule !^subfolder/ /subfolder%{REQUEST_URI}  [L]

```

Again change you domain and subfolder name.
> 0 votes

---
Tags: 7, .htaccess
---


# Question
Title: Drupal custom page template based on the title of the page
I have the following page:

```
About us

```

Whose path is:

```
site.com/node/6

```

Theme suggestions for the template files are:

```
page--node--6.tpl.php
page--node.tpl.php

```

You should already know that it is too weird to create custom template files based on the node's id, thus I like to have my custom page template based on the page's title (of course, converted to machine name, for instance "About us" to be "about-s"). What should I do?

# Answer
I don't think this is an optimal solution at all, because node titles can easily be changed (and duplicated), but here you go:

```
function MY_THEME_preprocess_node(&$vars) {
  // This assumes that you are using Pathauto for generating clean URLs.
  // Get the "clean" title.
  $title = pathauto_cleanstring($vars['node']->title);
  // Replace all dashes with underscores. This is necessary for recognizing the
  // template filenames.
  $title = str_replace('-', '_', $title);
  // Add new template variation.
  $vars['theme_hook_suggestions'][] = 'node__' . $title;
}

```

Note: to make this bulletproof for different languages, alphabets and special characters, make sure you have the Transliteration module installed and set to transliterate strings prior to creating URL aliases. This way if a node title has non-standard character (e.g. `Č`) it will be transliterated to Latin alphabet (in this case `C`).
> 4 votes

---
Tags: theming
---


# Question
Title: How to hide comment section present in render array?
I have generated an array in Drupal 8 which is created by using viewbuilder in this manner:

```
 $content = $this->entityManager()->getViewBuilder($entity->getEntityTypeId())>view($entity, 'hardcopy');

```

And now I want to hide comment section present in this array.

Any idea on how to do this?

# Answer
The result that you get there is only prepared, the actual rendered content is not set there, you can't remove it there.

The comments are a field, you can hide/show them in the manage view display UI like any other files.

Define a view mode/display for your use case if the default ones don't work for you and then configure it there.

Doing it in code is only possibly in indirect ways. You'd need to set a flag in $content and then implement hook\_node\_view() alter and remove it there.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Can I map to Body Summary in Feeds Importer?
I'm setting up a Feeds Importer to pull in content form a previous CMS. To keep things manageable I'm setting up MySQL exports saved to CSV files per Content Type. In a content type of News we're using the Body for full content display and the Body Teaser for the views listing.

In the source CSV file I have two separate columns: one for Body Content and another destined for Body Summary.

But in the *Mapping for Node Processor* Feed Importer, I don't have an option to place the `teaser` column in `Body Summary`.

## Follow up:

I did the dummy field option. Once I had that, three lines of SQL saved the day.

```
UPDATE field_data_body f, field_data_field_news_teaser_summary_holdin ff
SET f.`body_summary` = ff.`field_news_teaser_summary_holdin_value`
WHERE  ff.`entity_id`= f.`entity_id` AND f.`revision_id`= ff.`revision_id`

```

# Answer
> 7 votes
Couple of ways of doing this using a dummy field. Create a dummy text field on the content type you are importing to. Then you could:

a. Use rules to move the dummy field into the body summary.

or

b. (preferred) Use the feeds presave hook in your own module to set the summary AND set the dummy field blank.

```
/**
 * Invoked before a feed item is saved.
 *
 * @param $source
 *  FeedsSource object that describes the source that is being imported.
 * @param $entity
 *   The entity object.
 * @param $item
 *   The parser result for this entity.
 */
function [YOUR_MODULE_NAME]_feeds_presave(FeedsSource $source, $entity, $item) {
  if ($entity->feeds_item->entity_type == 'node' && isset($entity->field_temp_summary['und'][0]['value'])) {
    $entity->body['und'][0]['summary'] = $entity->field_temp_summary['und'][0]['value'];
    unset($entity->field_temp_summary);
  }
}

```

# Answer
> 1 votes
This is already added to feeds dev you can use the dev feeds module or get the patch from issue\[962912\]

---
Tags: migrations, nodes
---


# Question
Title: How do I know which Drupal 8 modules are supported by Drupal 8 versions?
How do I know which Drupal 8 modules are supported by Drupal 8 versions?

For example is Page Manager 8.x-1.0-alpha8 module supported in every Drupal 8 version? And if not how do I know which Drupal 8 version supports some module?

Which version of Drupal 8 supports Paragraphs 8.x-1.0-alpha2 module?

# Answer
Unfortunately, you can only see which modules have a release that was at one point compatible with a pre-release of Drupal 8; you can't tell whether a module is actually still compatible without testing it - **unless** the maintainer explicitly mentioned it on the page.

For example, the Paragraphs project you asked for states:

> the alpha2 version is working with Drupal 8 beta 4. We try to keep the 8.x-1.x-dev branch compatible with the Drupal 8 HEAD.

You can make a good guess, though, using the module's activity and the core release cycle: The older a module is, the more likely it is to be broken by a major API change. For example, the .info -\> YAML switch (early 2013) broke all modules. The hook\_menu() -\> YAML switch (late 2013 / early 2014) broke all modules that have menu paths. Other APIs have been changed even more recently.

For example, the Page Manager project you asked about was last pushed yesterday, and the last alpha was released the same day as the last core beta. You have very good odds there.

> how do i know which Drupal 8 version supports some module?

Sorry to be blunt, but knowing this wouldn't really help you (unless you're working on porting the module, and need to know what to change). If the module isn't supported by the latest beta, then the last version that *did* support it is presumably an outdated and unstable pre-release. ;-)
> 2 votes

# Answer
> How do i know which drupal 8 modules are supported by Drupal 8 versions?

You can't.

Specific projects might release alpha/beta versions in sync with core but if that's so and which version requires which version is something you have to figure out for each project separately.

You can try to get guess based on the release date, check if a release came out before or after a beta version. But it might be that an older release still works.

No contrib project that I've seen so far explicitly defines version specific dependencies, and it's actually not really possible, because you don't know yet when you release whether the module is going to be compatible with the next beta or not and when something will break it.

That said, there should be fewer and fewer API changes that break contrib modules from now on.
> 3 votes

---
Tags: 8
---


# Question
Title: Print just field data from a view into a block?
I'm trying to get a variable from a view to display on a block. For example "We have 200 blog posts" (200 being the variable). Right now I'm using the views\_embed\_view method. The problem is the view includes a bunch of mark up I don't need/want (the container, theme, etc)

Is it possible to just call the field I want? I know I could create a whole custom theme for the view without markup but I'm hoping there is an easier way.

# Answer
> 1 votes
You can use Views UI to strip out the extra layers of styling for list/rows/fields if you're using an unordered list view. For list/rows, there's the `settings` link that allows you to toggle off row elements and field wrappers.

For fields, there's the `Style Settings` fieldset that lets you customize your field wrapper markup.

# Answer
> 2 votes
If what you're trying to get is the number of results returned from the view then your best bet might be to call views\_get\_view\_result():

```
$result = views_get_view_result($name, $display_id);
$num_blogposts = count($result);

```

However, if that's what you're trying to achieve then it might be better from a performance point of view to bypass views entirely and get the count with an EntityFieldQuery.

-- EDIT --

**Option 2:**

You could override the various templates that make up the view, removing any unnecessary markup from each.

To do this, Click on "Theme: Information" in the "Advanced" section of the view edit page (bottom right) and you'll see a list of templates used. Click each one in turn and create a new file in your theme folder and copy in the contents before removing any unnecessary markup.

What you name the file is important, back on the list of templates, note that each one has a large number of filename suggestions, ranging from very generic to very specific. Choose the name with the the most appropriate degree of specificity and name your file that. note that for example calling your Display Output template file "views-view.tpl.php" will mean that your override will have effect on every single view across your site, so a more specific filename should lock it down to a specific view/display/etc.

Once you've done this, you'll need to flush the theme registry cache before you'll see the change. The easiest way to do that is by clicking "Rescan template files" at the bottom of the theme information dialogue.

Finally note that these updates won't change what you see in the views preview unless you also make these changes for the admin theme.

note that if you are also rendering the view normally (in addition to the views\_embed\_view) where you want to see the original markup then you should probably use a new display of the view for this and make sure your template names only target the correct display.

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


# Question
Title: How to create a custom exposed filter in views?
I have to do an exposed filter that when a person write something it is going to show only the rows that have that.

The problem is that I can't do an exposed PHP Filter because there is no option to do it like the tohers that you can choose "Expose this filter to visitors, to allow them to change it".

The only way that I can get data of the webform submissions is using the Views PHP module, but I can't do an exposed PHP filter.

Is it is possible or not? If so, how?

# Answer
> 0 votes
If you construct field output with ViewsPHP you can try to use that field with Global: Combine fields filter.

# Answer
> 0 votes
With Webform version 4.x you should be able to work directly with Webform submission data (as in the actual fields, not just the `metadata`) without having to use Views PHP.

You have to set up some relationships to the field data before you can start working with it. Here is a tutorial that shows you how to do a similar task but the aim there is to sort on the field data and set up a contextual filter based on it. However, I'd have to guess that if you can do that then you can almost certainly set up an exposed filter as well.

---
Tags: webforms, views
---


# Question
Title: Content node migration to user profile in Drupal 6
I have Drupal 6.x installed where we a custom node type for author data. We are implementing a new design that designates users as authors and now assigning various roles such as author.

We have some 600 authors nodes which we wish to migrate to the user base so that we can assign the users to articles again.

What is the best method for accomplishing this?

# Answer
I'm assuming you're wanting to create new user accounts with these profile nodes, not migrate existing users linked to these profiles. Since you're using a custom node type and not core profile or Content Profile, there are many pre-existing solutions not available.

If these author nodes are constantly changing and you need to maintain periodic synchronization before you're ready to launch, you can set a custom class with the Migration framework. This requires some work so it might be overkill here.

More than likely, I'd say the best solution is probably the User Import module with data fed in via Views Data Export from your existing D6 site. You can create a view of your profile nodes, export it to CSV, and use that as a base to create all your new user accounts with the User Import module.
> 0 votes

---
Tags: nodes, users
---


title: How to call site name in PHP block?

text:
# Question
Title: How to call site name in PHP block?
I have a block in my footer that I currently use to display a copyright message using PHP, like so:

```
Copyright © <?php echo date("Y"); ?>

```

I'd like to add the site name to that code snippet, dynamically instead of typing the name. How can I do so?

So the end result would be:

```
Copyright © <?php echo date("Y"); ?> [[[php code to display site name goes here]]]

```

Thanks!

# Answer
> 5 votes
You can use `variable_get()` to get the site name, but you shouldn't use it directly in the template file or you could break caching.

Instead, define a preprocess function in your theme's template.php file:

```
function MYTHEME_preprocess_page(&$vars) {
  $vars['site_name'] = variable_get('site_name', 'Default');
}

```

Then you can use this in the template file:

```
Copyright © <?php echo date("Y"); ?> <?php echo $site_name; ?>

```

Before doing that, though, check whether you already have `$site_name` available in page.tpl.php. Some themes add it for you, some don't.

# Answer
> 1 votes
As an alternative to creating a pre-process function in your template, you can print the value of the site name variable in a block using this php snippet in your block

```
<?php
$site_name = variable_get('site_name');
echo $site_name;
?>

```

So, to print a copyright notice that includes your site name, it would look something like:

```
©copyright <?php echo date('Y');?><?php $site_name = variable_get('site_name'); echo "&nbsp"; echo $site_name; echo", "; ?> All Rights Reserved.

```

---
Tags: 7, blocks
---


# Question
Title: Does hook_node_info() have to be in .module or can it be in .install?
due to some code sharing it would help me quite a bit if I could put hook\_node\_info() to a .install file instead of a .module file. Now, from what I've tested it doesn't seem that it could be a problem but then every tutorial says you have to put it in .module file.

And the official documentation is silent in regards to this problem. So my question is, can I do it without braking something?

# Answer
> 0 votes
`hook_node_info` should be in the .module file. However, you could implement the hook in the module file and then just call `module_load_install` from there to include another function in the .install file, if that helps. Another option is to export the content type using a module such as Features instead.

---
Tags: 7, installation, nodes
---


# Question
Title: Profile 2 Not showing fields on user edit page
I install Profile 2 module and create separate registration page. after login with this user not showing that fields on edit user page Can any one help me in this

# Answer
> 5 votes
Give the permission "\[PROFILETYPE\]Edit own profile" under "Profile2" section to the respective user roles.

And the fields will be appeared on edit user page.

# Answer
> 3 votes
@theBraveDave - THANK YOU THANK YOU THANK YOU!! - I don't have enough "points" to vote-up your answer, but that fixed my problem with profile2.

Specifically:

1. If you're using Panels, check the admin/structure/pages admin page has the /user/%user/edit turned off
2. When editing the profile type (from admin/structure/profiles), make sure "Provide a separate page for editing profiles" is turned off

Then suddenly it started working again. (I'd recently done a Drupal core update plus ctools plus other key modules and suddenly profile2 had stopped working. It appears that somehow the user/edit page was turned back on again and it was as simple as turning it back off ("simple" once I read @theBraveDave's post - thank you!)

-Tom

# Answer
> 1 votes
Using profile2, the first 'main' profile you set up needs to have the box 'Provide a separate page for editing profiles' unchecked on the administration page before it will display on user/\[id\]/edit forms.

Admin form at /admin/structure/profiles

# Answer
> 1 votes
I was having the problem where I would be on my user edit page and I could see my profile2 profile buttons on the top right. Clicking on them though would just load the same drupal core user/edit page. The profile link was highlighted like I was on that particular profile2 profile edit page, but only the standard core user edit form fields were showing.

I then remembered I was toying around with Drupal Panels and found that I had enabled the Drupal Panels Page- User edit template /user/%user/edit

I disabled this panel page and then when I clicked on my profile2 profile button from the standard Drupal core user/edit page my Profile2 profile loaded properly. Hope this helps someone.

---
Tags: users
---


# Question
Title: How to get date values from field collection to a node?
I am trying to print the values from a field collection using following code in Drupal 7 node.But the date values are not getting.

```
$wrapper = entity_metadata_wrapper('node', $node);
 $formtype = field_get_items('node', $node, 'field_latest_schedules');
 foreach($formtype as $itemid) {

 $item = field_collection_field_get_entity($itemid);

 print $item->field_course_starts_on['und'][0]['safe_value'];
 print $item->field_course_ends_on['und'][0]['safe_value'];

 }

```

How can i print the date from a filed collection?

# Answer
> 0 votes
I suppose that `field_course_starts_on` and `field_course_starts_on` are fields that represent date and you want to print it as date. Correct me if I'm wrong.

So you can print those fields as date like:

```
print date('d F, Y', $item->field_course_starts_on['und'][0]['safe_value']);
print date('d F, Y', $item->field_course_ends_on['und'][0]['safe_value']);

```

The part `'d F, Y'` is a date format. Take a look at PHP Documentation to see all options for format parameter.

## **Update**

First you have to load the ids of the field collection fields of the node:

```
$formtype = field_get_items('node', $node, 'field_latest_schedules');

// Extract the field collection item ids
$ids = array_column($formtype, 'value');
foreach ($formtype as $ft_field) {
    $ids[] = $ft_field['value'];
}

```

To iterate over all fields you can use the following code:

```
//Get the entities
$collections = field_collection_item_load_multiple($ids);

//Loop over the array - if you have more than one entity
for ($i = 1; $i <= sizeof($collections); $i++) {
    $collection = $collections [$i];

    //Iterate over all member vars of the FieldCollectionItemEntity object
    foreach($collection as $key => $value) {
        //Look for fields - there are some other class vars, too.
        if (strpos ($key, 'field') !== false) {
            //Search for textfields
            if (isset($value['und']) && is_array($value ['und']) && isset($value['und'][0]['value'])) {
                print "Field ".$key." ".$value['und'][0]['value'];
            }
        }
    }
}

```

And than debug, target wanted fields and print those fields' values.

# Answer
> 0 votes
This is working for me....thanks for the helps....

```
<?php

if (isset($content['field_latest_schedules']['#items'])) {

    foreach ($node->field_latest_schedules['und'] as $key => $value) {
    $field_collection = entity_load('field_collection_item', array($value['value']));
    $idx = $value['value'];

    print $field_collection[$idx]->field_course_starts_on['und'][0]['value'];
    print $field_collection[$idx]->field_course_ends_on['und'][0]['value'];
}
?>

```

---
Tags: datetime, entities
---


# Question
Title: How do you get a node ID from an order in ubercart?
How do you get a node ID from any of the products in an ubercart order?

I'm trying to get the product author's (uid) from the order as shown below

The order will only contain nodes/products by the same author so a node ID from any of the products in the order will do.

$sid = db\_query("SELECT uid FROM {node} WHERE nid = :nid", array(':nid' =\> $product-\>nid))-\>fetchField();

$seller = user\_load($sid);

# Answer
> 0 votes
I should have been clearer, its ubercart marketplace.

I got it to work this way:

$items = uc\_cart\_get\_contents(); foreach ($items as $item) { $product = node\_load($item-\>nid); }

---
Tags: database, ubercart
---


# Question
Title: How to make an external database available to Views?
There's a lot of discussion here and in other places about using external databases in Drupal. What I've figured out from that is:

* The best way to work with data in a database table is to use the Views module. I've installed that and started using it and found it's great for working with a table that I've added to the site's database.
* The easy way to get Views to work with a table that was not created by Drupal is with the Data module. This module treats any table in the site database that is not in use by Drupal as an "orphan table" and allows it to be "adopted" at the click of a button.
* The module "Table Wizard" apparently provides a way to do that with tables that are not in the site's database. But that module is not available for Drupal 7.
* The "settings.php" file, in the section on "Database settings," has detailed documentation on how to define additional databases that the site can work with. But when a database is defined in that way, its tables do not show up in the list of orphan tables in the Data module.

The change that I've made to the database definition in the “settings.php” file of one of my sites is:

`$databases = array (
 'default' => array ('default' => array (
 'database' => 'db_local',
 'username' => 'db_local',
 'password' => '_________',
 'host' => 'localhost',
 'port' => '',
 'driver' => 'mysql',
 'prefix' => '',
 ), ),
 'extra' => array ('default' => array (
 'database' => 'db__extra',
 'username' => 'db_admin',
 'password' => '_________,
 'host' => 'localhost',
 'port' => '',
 'driver' => 'mysql',
 'prefix' => '',
 ), ), );`

I have a table that I want to use in more than one site in my multi-site installation. This means I need to have the table in a database that is accessible to each site. According to the reading I've done, my options for doing that are:

1. **Best, if it's possible:** Find out that there's a way to get the Data module to recognize tables in the additional database defined in "settings.php", so it can adopt them.
2. Use table prefixes to allow all the sites to use one database.
3. The module “Forena Reports” seemed to do exactly what I need, but when I installed it, I couldn’t get it to work. I submitted issue 2475645 and can’t do much more there unless there’s a fix for that problem.
4. Write my own module to give Views access to the additional database defined in "settings.php".
5. Install Drupal 6 with Table Wizard and use that to get Views to see my external table, and then somehow take the result of that and put it into Drupal 7. (This has been suggested in some posts.)
6. Follow the procedure in https://drupal.stackexchange.com/a/3321/45991 , which starts with installing a patch and seems to also require creating my own module.
7. I’ve also looked at the modules Feeds, Feeds SQL, Views XML Backend, and Migrate, but none of them say they can connect an external db to Views. Am I missing something? Is one of them the right solution?

Option 2 is not practical because it would result in a huge database with hundreds of tables that would be very difficult to manage. I’ve been making great progress in getting started on Drupal, but I don’t feel up to the task of 4, 5, or 6. Is there any possibility of something like option 1 working? Or is there any other way to get Views to work with a table outside the site database without being able to write my own module?

Two additional details: The first table I need to work with is pretty large, over 6,000 rows and about 20 columns. There is no intention to give visitors to the site access to the database except for information drawn from it for page content.

Thanks for your help.

# Answer
> 2 votes
I think the Forena module does indeed *exactly what you need*. Your setup issue is only a support request I think, not something that requires a "fix". After you get that resolved, you will even have a choice to yes or no use its views integration also.

The Forena issue you created is very well documented (great work!). But nowhere it says anything about **permissions** you granted (which makes me believe you might be missing some of the required permissions). So here is an attempt to address that:

* Can you briefly explain which of the (required) Forena related permissions you granted?
* The required Forena permissions are explained in the Setup Guide that comes with Forena? FYI: here is a quote of (part of) it:

> Forena allows for a lot of granularity as it comes to reporting related authorizations, by using the standard Drupal administration facilities to grant permissions to roles. The list of Forena related Drupal permissions that can be granted may be a bit overwhelming at first. Because there are 3 entries for each defined data source, and vanilla Forena already comes with 3 data sources.

To retrieve this guide in your own site, just navigate to /reports/help.setup

Those permissions to access the "data" are originally withheld. That's by design, because Forena is also pretty sensitive to anything that relates to granting access to data via Forena. What you wouldn't want to happen is that by simply installing and configuring Forena (without permissions admin), you can use it as a workaround to access secured data.

Also note that apart from permissions at the level of an entire data source, you have an option to further refine required permissions for specific data blocks (= custom SQL queries). To do so, just specify such required (Drupal) permissions within the SQL statement (syntax details are included in the Forena guides). A typical usecase for this, is to secure access to columns with sensitive data in it.

Disclosure: I'm a **co**-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.

# Answer
> 2 votes
I've done this successfully a couple of different ways:

**Use a SQL View to create a virtual table in `db_local` that refers to the corresponding table in `db__extra`.** The query to create that would look something like this:

`USE db_local;
 CREATE VIEW some_table AS
 SELECT * FROM db__extra.some_table;`

You can then refer to this SQL View as if it were a native table in your Drupal database, and you don't even need to add the external database at all in settings.php. Note that this might not be compatible with Data module (see https://www.drupal.org/node/1973806), but you should be able to describe the SQL View to the Drupal Views module by implementing `hook_views_data()`, and stop using Data module.

Here's another possibility: **use selective table prefixes to trick Drupal into rewriting {some\_table} to db\__extra.some\_table.** This is not the same as prefixing your Drupal tables.

Your `$databases` setting would look like this:

`$databases = array (
 'default' => array ('default' => array (
 'database' => 'db_local',
 'username' => 'db_local',
 'password' => '_________',
 'host' => 'localhost',
 'port' => '',
 'driver' => 'mysql',
 'prefix' => array(
 'some_table' => 'db__extra.',
 ),
 ))
);`

Again, I'm not sure if this is compatible with Data module, since I don't use it. But it should work with Views if you implement `hook_views_data()` yourself.

---
Tags: database
---


title: Which file should my style be in

text:
# Question
Title: Which file should my style be in
I'm putting this question in the Drupal forum rather than a CSS forum as I don't know if I just have a CSS issue or if the issue is more Drupal, maybe how I'm using the .info file.

I'm using Drupal 7 with UberCart and the AT Commerce sub-theme of Adaptivethemes. If I put my CSS in styles.base.css they take effect. However, it I put my CSS in a separate CSS then they do not.

I edited at\_commerce.info so I have this

```
// CSS
stylesheets[all][] = css/styles.custom.css
stylesheets[all][] = css/styles.base.css
stylesheets[all][] = css/styles.modules.css
stylesheets[all][] = css/styles.settings.css
stylesheets[all][] = color/colors.css
stylesheets[all][] = css/uc_product.css

```

I tried styles.custom.css as the first in the list as shown above and the last in the list and it make no difference. styles.custom.css is empty except for the 2 styles I'm trying to put there. When I put the 2 styles in styles.base.css I am putting them at the bottom of the file.

# Answer
> 1 votes
Just to eliminate a possible cause of your problem: **if** you have enabled CSS aggregation **then** you must clear the cache before changes to CSS files become active.

---
Tags: theming
---


# Question
Title: EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids()
I created a node called "Tutorial". When I preview the post before saving it, I received the following error:

> EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7693 of /var/www/clients/client1/web2/web/includes/common.inc).

However, the error when submitting a blog (a node created by drupal) is different. Here it is:

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1: SELECT nid FROM {node} WHERE uid = ; Array ( ) in eval() (line 10 of /var/www/clients/client1/web2/web/modules/php/php.module(80) : eval()'d code).

and

> Notice: Trying to get property of non-object in eval() (line 8 of /var/www/clients/client1/web2/web/modules/php/php.module(80) : eval()'d code).

Any help please...

# Answer
> 2 votes
I had similar issue. In my case I was using following line in node.tpl

```
$field = field_get_items('node', $node, 'field_foo');
$sponsored = field_view_value('node', $node, 'field_foo', $field[0]);

```

And field\_foo was not in all content type. In Drupal 6 or 5 approach was different to get field values. That's why it was not happening.

Solution was:

```
if($node->type=='story'){
 $field = field_get_items('node', $node, 'field_foo');
 $sponsored = field_view_value('node', $node, 'field_foo', $field[0]);
}

```

# Answer
> 1 votes
In my case: file \includes\common.inc

```
function entity_extract_ids($entity_type, $entity) { ...

-  if (!empty($info['entity keys']['bundle'])) {
+  if (!empty($entity->{$info['entity keys']['bundle']})) {

```

fixing error.

# Answer
> 0 votes
Just want to share the solution on my problem.

I am using Display Suite and the error is caused by this line:

```
if (arg(0) == 'node') {

```

After changing it to this code:

```
if (arg(0) == 'node' && is_numeric(arg(1))) {

```

The error has gone.

# Answer
> 0 votes
Regarding your: EntityMalformedException it seems to me that it's to do with Drupal asking for information that is not available at the time.

I had this error when I had a view that was displaying fields from a node that didn't have those fields. I hadn't stipulated the content type that was to be viewed so Drupal assumed that it was all types and when if found a content type that didn't have the fields I wanted to display it crashed(!?) that page and displayed an error similar to yours.

It seems that it's been a persistent error that has not been resolved. I've noticed in the issue queue of many modules and much to the confusion of many people this error occurs.

# Answer
> 0 votes
You must see in the content type if the fields data type matches with the information type you save. I mean, if you have a field that is integer type you can't insert a text.

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


title: How to know if who created the order

text:
# Question
Title: How to know if who created the order
Is it possible to determine who created the order? I've installed the entity reference module, then added a entity reference field in the order, but I'm not sure if this will work.

I've used the `hook_form_alter()` to get the current user id and set the current username as a default value.

How to check and save the current user who created the order upon saving the order? Will only set the default value on first save, then it won't change anymore in the next save.

Below is my code:

```
$user = $GLOBALS['user'];
if ($user->uid) {
  $form['field_order_created_by'][LANGUAGE_NONE][0]['target_id']['#default_value'] = $user->name;
}

```

# Answer
What you can do is you can create a small table which keeps your order id, user id and anything else you want. Whenever the order is saved you can check whether a record exists for the particular order id. If there is no you add the record otherwise you don't change the current record. For that you can use hook\_commerce\_order\_presave(). Inside this hook you can use your code l

option 1

```
function yourmodule_commerce_order_presave($order){
    if(!db_result(db_query('SELECT * FROM {your_table} WHERE orderid = %d', $order->id)))
        $user = $GLOBALS['user'];
        if ($user->uid) {
            $form['field_order_created_by'][LANGUAGE_NONE][0]['target_id']['#default_value'] =       $user->name;

        //add new record to yuor table
    }

}

```

option 2

```
function yourmodule_commerce_order_presave($order){
    if(!check_record_exists($order->id))
        $user = $GLOBALS['user'];
        if ($user->uid) {
        $form['field_order_created_by'][LANGUAGE_NONE][0]['target_id']['#default_value'] =       $user->name;
    //add new record to your table
}

function check_record_exists($oid){
    $exists = db_result(db_query('SELECT * FROM {your_table} WHERE orderid = %d', $oid));
}

```
> 1 votes

---
Tags: commerce, users, entities
---


# Question
Title: Avoid sql-drop or sql-sync drush commands in a particular environment
I'm syncronizing databases form stage to local environments with drush commands like:

```
drush @dev sql-drop
drush @stage @dev sql-sync

```

How can I protected that the @stage server reject to drop or sync its database like:

```
drush @dev @stage sql-sync
drush @dev sql-drop

```

I think this is a common problem, maybe there is some params that can be set in drushrc.php file. How can I manage that? Thanks!

# Answer
This is best done with a policy file. See policy.drush.inc, which has an example policy prohibiting overwriting a production server.

The example could be expanded to perhaps check for patterns in the destination parameter (any alias containing 'prod'), etc.
> 4 votes

---
Tags: 7, drush
---


# Question
Title: Add query parameter from url to all links on the page
How to Add query parameter from url to all links on the page? Basically I want to get the Query parameter from url and then attach that on all the links on the page. JQuery or PHP, Any solutions?

Please suggest. Thanks in Advance!

# Answer
> 0 votes
You can do it easily in a custom module, implementing **hook\_url\_outbound\_alter()**.

```
function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  $param = $_GET['q'];
  $path = 'build-path-as-desired.';
}

```

That should do it for you. The hook serves, basically, to alter outbound urls. You can look at the documentation for it in the system.api.php file, and I suggest you do that, as there are a couple of things to take into account when altering urls through it, but it's definitely an easy way of doing what you want to do.

EDIT: Online documentation for the hook - https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_url\_outbound\_alter/7

EDIT 2: Additional functions to work with the path being requested: drupal\_get\_query\_parameters() and drupal\_get\_path\_alias($path).

---
Tags: javascript
---


# Question
Title: Acquia Desktop & MAMP: No Drupal site found, only 'drush' cache was cleared
Usually I use MAMP for my local development server which already has all of my shortcuts and stuff configured the way I like it.

A client was on Acquia Cloud and to prevent conflicts with other developers we are all using the Acquia Dev Desktop for local. Acquia Dev Desktop comes with Drush within its own package.

When running my drush cc all I was getting the following error: No Drupal site found, only 'drush' cache was cleared

After running drush status I noticed that Drush was trying to use my MAMP version of drush and thus resulting in no site found.

# Answer
> 3 votes
To fix this answer I created a new Alias called adrush which points to the Acquia DevDesktop Version.

In my .bash\_profile file in my home directory I added

alias adrush='/Applications/DevDesktop/drush/drush'

now when running drush commands for sites that are in my Acquia DevDesktop environment I enter adrush cc all

---
Tags: drush, acquia-dev-desktop
---


# Question
Title: What happened to array-shift.com (Drupal Stackoverflow Clone)
It's interesting that there is no (recent) Drupal implementation of SO-like features. I (and others) have a need to have an SO clone that has areas for private data (corporate owned), so we cannot use SO or the StackExchange engine. I had high hopes for http://drupal.org/project/arrayshift, but it's fallen into disuse (and the demo site has been down for months).

Any suggested alternatives? We've looked at OSQA and Question2Answer, and both seem like an annoying integration mess for user profile information.

# Answer
> 13 votes
What "happened" is what commonly happens to an idea that is generally solid but not (yet) popular: it's not being used and therefore not being actively maintained.

The best way to combat "disuse" is to use it. Create your own sandbox copy and start improving it. Ask Eaton for permission to take over the module and he'll give it to you.

# Answer
> 7 votes
A fair portion of the functionality in arrayshift has been implemented by the Answers project.

drupal.org/project/answers

# Answer
> 2 votes
I set up a site with the ArrayShift modules. I had to go through at least two or three cycles of updating a few of them, and although it created views to display most recent/unanswered/hot/etc questions, it didn't automatically install a new node type for them. It was frustrating trying to figure that out. (The correct type/machine-readable name for the content type is *question*.)

There's no link in the banner menu to allow you to ask a question like the SE sites have (set in the primary links), but that's aping the SE look and feel too much.

It switches the description for titles on forms for creating content to *What's your programming question? Be descriptive.* regardless if it's actually a question or not.

A book page. *What's your programming question? Be descriptive.*

A blog entry. *What's your programming question? Be descriptive.*

A forum topic. *What's your programming question? Be descriptive.*

It's a tad annoying.

But anyway I've just started playing around with it and the basic functionality is there. There's some things I'll change to suit my preferences for a Q&A site, but I'll say ArrayShift looks pretty useful (once modules are updated) so far.

**EDIT:** Putting in a few questions & trying to answer them, it seems that answers are given using Drupal's comment system, rather than a separate *answer* node. While you have comments for answers in that the comment system permits threading and what-not, it doesn't keep comments for the *?* (which are often necessary as you can see in the typical SE *?*) together with them, visually expressing their relationship.

Also, I haven't been able to figure out how to activate the markdown editor.

# Answer
> 1 votes
Update about the " it's fallen into disuse" (related to ArrayShift) in the question here: the ArrayShift distribution has been in a kind of unsupported status until just recently. However its maintenance status has been changed to "actively maintained" again.

And I recently did as suggested by @greggles, and Eaton accepted indeed.

The project page now contains a roadmap which includes, among others, these items that I believe are the most urgent to be addressed:

* resolve the current security messages on the project page (for D6).
* provide support for D7 (and D8 later on).

The issues mentioned in the answer from @Huperniketes to this question, should get resolved soon now. Don't hesitate to use the issue queue on D.O for reporting bugs, feature requests, etc, as I am also planning to do to publish all sorts of feature requests I have in mind. As an alternative use Drupal.SE for similar support requests (and ping me about such questions in case I might not have noticed them).

Note: I'm interested in finding out more about the usage, purpose, etc of **array-shift.com**. I've been doing some research on that, but nothing seems to exist anymore. So any feedback on that would be appreciated.

Disclosure: I'm the (new) maintainer of this distribution,
I hope this does not violate the site's policy on self-promotion.

---
Tags: community-official-site
---


title: Dynamically indented text display

text:
# Question
Title: Dynamically indented text display
I'm happy to say that I've succeeded in importing an Access database into MySQL and getting a table from it to show up in Views. Progress! Thank you for all the help I’ve been getting here to overcome the hurdles along the way.

So now, the first webpage I'm working on has a rather unusual HTML table on it that’s a bit of a hack and I wonder if Views is capable of making it or if I need to find a different way.

You could call what I’m trying to do a “dynamically indented text display.”

On the current website, the javascript that builds the main part of the HTML table looks like this: `'
' + (nLevel == 0 ? '' : ' 	') +
 '' +
 (sHeading == '' ? '' : sHeading + ' ') +
 (sParty == '' ? '' : '' + sParty + ': ') +
 (sURL == '' ? '' : '' + sLinkText + '') +
 (sNotes == '' ? '' : sNotes) +
 '	' +
 '
'` In the data table, every row has (a) a value of nLevel between 0 and 12, inclusive, and (b) either a value of sHeading or a value of one or more of the other text variables. Therefore, every row of the HTML table has either a heading or a text block, and whichever it is is indented by an amount controlled by nLevel.

Two elements of simple logical processing stand out there:

* The numeric variable, nLevel, determines the level of indentation by a pair of \ tags in which the sum of the “ColSpan” parameters is 13. So there are 13 levels of indentation (from 0 to 12) across the page. (On the current page, the width of the indentations is set by 12 repetitions of “\ \” in the first row of the table.)
* A link is constructed from the variables sURL and sLinkText.

I see that Views allows for the calculation of a math expression in the construction of a table, but I don’t see anything that allows for this kind of programming there. So I’m thinking a Views table won’t work, unless there’s something I don’t know.

It’s possible that an HTML list could work if Views allows for nesting of lists, which would control the indentation. When nLevel increases from one row to the next, it always increases by one, so this gives the same behavior as “\
” (plus a bullet, which I could live with). But still, I would have to be guiding Views programmatically in its placement of “\
” and “\
” tags, and I don’t see how I would do that.

Maybe now you can see why I was originally thinking of just translating the code from javascript to PhP and putting that directly on the page. The code is pretty simple, so that would be easy. (The part that I still don’t know how to do is how to connect to the database with a query to get the values of the variables above.) But when I posted my question about whether this was a good idea, I got some strongly worded advice that it’s usually a very bad idea to put PhP code directly on the page.

So what is the right way to get Drupal to do the kind of dynamically indented text display described above?

Thanks for your help.

# Answer
depending on you exact set up (which you may be able to modify to suit), you could look into Views Tree module:

> This module provides a tree-based style plugin for Views. It is equivalent to the tree-based style template from Views 1.
>
> It is based off of the list style. Although it generates a nested view, there is still only a single query run for the view making it quite performant.
> 0 votes

# Answer
I think you should consider using the Forena module to address this question. It would be straight forward to transform your HTML table into an equivaent "FRX" file in Forena.

Here is an example of an FRX file (which is an XHTML file):

```
  <head>
    <title>My custom report title</title>
    <frx:category>Articles related Reports</frx:category>
    <frx:options skin="My_Skin_File_With_CSS_And_JS_To_Beaf_Up_My_Rpt"/>
  </head>
  <body>
    <table frx:block="MyDatabaseConnection/MySqlQuery">
      <tr frx:foreach="*">
      <td>{title}</td>
      <td>{body}</td>
      </tr>
    </table>
  </body>

```

The documentation that comes with Forena (after you install it), contains all the details you'd need. Here are a few pointers to the demo version of the FRX Reporting Reference (which also gets installed in your own site as part of the Forena installation) that should help:

I wouldn't be surprised if the Report Skins would come in handy also for all sorts of JS and/or CSS requirements you might have also.

Disclosure: I'm a **co**-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.
> 0 votes

---
Tags: views
---


# Question
Title: Register User with Services (JSON) with Custom Fields
I am trying to register a new user on Drupal7 via services with JSON. Actually I am posting info from JAVA (android) with JSON format to the server with services module enabled. A sample successful JSON post is:

```
    {
    "name": "erfan",
    "pass": "1234",
    "mail": "erfan@example.com",
    "status": "1"
     }

```

> **URL:** \[siteURL\]/\[endpoint\]/user/register

I was successful creating users with basic info such as name,email,status.

I have added custom fields like `field_address`, `field_phone`, etc to the web site and want to send them via JSON to the server.

The problem is I can not figure out how to post these data to the server and couldn't find any documentation about it. My trial and error approach was not successful too, because I am not good in PHP coding. So please help me. Thanks.

# Answer
> 4 votes
Hope this will help you,

In Drupal 7 you can use the below **JSON format** to add custom fields(`field_user_image`)

```
{
    "name": "test",
    "pass": "password",
    "mail": "test@gmail.com",
    "field_user_image": {
        "und": [{
            "fid": "2"
        }]
    }
}

```

I have tried in my local and it is working fine.

* Created new field **UUID**
* Calling the Service using **Firefox poster** add-on
* Code

```

  {
    "name": "testuser123",
    "pass": "testuser123",
    "mail": "testuser123@gmail.com",
    "field_register_uuid":
      { "und":
        [{
          "value": "65C7DCA4-8F03-473C-9E8F-08B3F29E91AE"
        }]
      }
  }

```

I can able to create new user with the custom field

References

# Answer
> 2 votes
This should be a comment, but I haven't enough reputation ...
When you create a user, you can only pass the fields that are shown in the registration form. Otherwise you'll need first to register the user and then update it with the new fields, as @paul-m said in his comment.

To show a field in the registration form go to

> configuration-\>people-\>account settings-\> manage fields
> click the edit link of the desired field and check "Display on user registration form."

# Answer
> 2 votes
The field value may have to be "flattened" in order for the user registration to work. In the example below, the field is a `List (text)` field with **radio buttons** for the widget.

* **POST** `?q=[my-endpoint]/user/register.json`
* **Content-Type**: `application/json`

JSON data to *POST*:

```
{
  "name":"bob",
  "mail":"bob@gmail.com",
  "conf_mail":"bob@gmail.com",
  "pass":"secret",
  "pass2":"secret",
  "field_choices":"2"
}

```

This also works for radio buttons:

```
"field_choices":{"und":"a"}

```

However, when we use a **select list** widget on this same field, the JSON is formed like this:

```
"field_choices":{"und":[{"value":"2"}]}

```

The JSON above will not work for radio buttons, you'll get a `406 - Not Acceptable An illegal choice has been detected. Please contact the site administrator`. This is a lesson and reminder that the Services module can sometimes be dependant on your field's widget when it comes to the JSON it expects.

---
Tags: 7, users, services
---


# Question
Title: Display No Results Text for Individual Field Groups in View
I have a drupal view set up to show links to certain documents. These documents are grouped by department in a Grid layout and then sorted by date. What I want to do is if there are no results available for a particular group in the grid layout, display a no results text line for that. I am willing to just put php generated text in the header or footer if that is an option. I do not want to generate a page of non-sense content titled "No Results" to inject it in the grid (that's what we're doing now)...I'm trying to get it to handle itself. Hopefully this layout will demonstrate it better if it's hard to understand:

> **Department Documents**
>
> **Department 1**
>
> 04/25/2015 \<--(These dates are rewritten to link to documents)
>
> 04/26/2016
>
> **Department 2**
>
> No results
>
> ...

**Edit**

I would rather not make this behavior global for all Grid views, if possible. I have other grid views where I do not want to display this, it is only on this one view.

# Answer
> 0 votes
I was kind of overthinking this a good bit...I actually found a way to do this with no hand written php involved. This way, I could also change the styling from grid to html list or whatever I wanted with no trouble. The way I've done it may not be the best way, but since there are usually only a handful of entries shown (no more than 2 or 3 for each department for 4 departments), performance shouldn't be an issue.

What I did is set up a view page for each department. I overrode the filtering in each and only filtered those pages to get results for that one department. I wrote a no results behavior for each individual page. Then, I set up a master view. In the header of that, I displayed alternating titles that linked to the individual lists if people wanted to view only those (as text areas) and then the view content after each (view areas). The image below shows what that looked like in the view config. There were a lot of overrides to do, but this got me the exact list-like style I was looking for.

# Answer
> 0 votes
The best to do this is using theme layer. In your case,`views-view-grid.tpl.php` is used to display the results.

There are different ways to alter that.

**Solution A: Using template preprocessors**

Add this function to `template.php` in your theme folder.

```
<?php
/**
 * Implements hook_preprocess_views_view_grid().
 *
 * Check if there is no result for this group and provide an appropraite message.
 *
 */
function phptemplate_preprocess_views_view_grid(&$variables) {
    $view = $variables['view'];
    if ($view->name == 'YOUR_VIEW_NAME') { // Only do this for a specific view
        if (empty($variables['rows'])) {
            $variables['caption'] = t('No results.');
        }
    }
}

```

**Solution B: Overriding the template file**

Copy `views-view-grid.tpl.php` to your theme folder and then modify it. You may also want to rename the template file so it would only apply to a specific view. (Learn how to find the appropriate template file name for Views).

```
<?php

/**
 * @file
 * Default simple view template to display a rows in a grid.
 *
 * - $rows contains a nested array of rows. Each row contains an array of
 *   columns.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)) : ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>

<?php // We check if there is no result we print a meesage ?>
<?php if (empty($rows)) : ?>
  <?php print t('No results.'); ?>
<?php endif; ?>

<table class="<?php print $class; ?>"<?php print $attributes; ?>>
  <?php if (!empty($caption)) : ?>
    <caption><?php print $caption; ?></caption>
  <?php endif; ?>

  <tbody>
    <?php foreach ($rows as $row_number => $columns): ?>
      <tr <?php if ($row_classes[$row_number]) { print 'class="' . $row_classes[$row_number] .'"';  } ?>>
        <?php foreach ($columns as $column_number => $item): ?>
          <td <?php if ($column_classes[$row_number][$column_number]) { print 'class="' . $column_classes[$row_number][$column_number] .'"';  } ?>>
            <?php print $item; ?>
          </td>
        <?php endforeach; ?>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

```

---
Tags: views
---


# Question
Title: How-to display a product variation field twice (or more)?
I want simply display a field of a *product variation* type (commerce) two times with different render settings.

I have tried with a dynamic field (display\_suite) but it not working... I would prefer to know a **programmatically** solution to accomplish this task and I want use the (Drupal core) ***Display Manager*** for designate my layout (not a template file) :)

**Note:** This product field do automatically refresh (ajax) like other when a different product variation is selected.

See this related "issue": https://www.drupal.org/node/1494192#comment-7031370

# Answer
You should be able to use `template_preprocess_node()` to duplicate a field.

I've not run this code and just written it from memory but something like this should suffice:

```
function template_preprocess_node(&$variables) {

  // Check this is the node type for commerce products
  if($variables['node']['#type'] == 'product') {

    // Copy the existing field to a new item
    $variables['content']['YOUR_FIELD_2'] = $variables['content']['YOUR_FIELD'];

    // Now make any changes to how you want to render the duplicate field
  }

}

```
> 1 votes

---
Tags: 7, commerce, display-suite
---


# Question
Title: View Field, Insert View, View Reference, Block Reference, Insert Block: which to choose to embed a view in a page
I have a view I would like to embed in a page with some other content. The page is for logged-in users only. I could make a page or a block version of the view. I could make a new content type or not for the page- it's not a big deal. So I could use Viewfield, Insert View, View Reference, Block Reference, Insert Block, EVA, and maybe some others to embed the view. I could even code a page template up with `views_embed_view()`, though I would prefer to use an existing module for ease of future maintenance. Using the view's header and footer fields is inadequate in this case, because I want the surrounding content to be easily editable?

Are there technical reasons to choose one of these modules over the others? For instance, do any of them have issues with caching or permissions? Or, for instance, Is there a reason not to use the view as a block?

# Answer
**Option 1:**

Just create a page for the view.

You can set which permission or role should have access to the page.

If you need to display content above or below the view use the header and footer.

**Option 2**

Use `hook_node_view()` and `views_embed_view()` to add the view as a field to the node you want to target:

```
function hook_node_view($node, $view_mode, $langcode) {

  // Add whatever logic you want here to only target the nodes you want
  if($some_check == TRUE) {
    // Add a new field to the content array
    $node->content['view_field'] = array(
      // Render you view
      "#markup"=> views_embed_view('view_name', 'view_display'),
    );
  }
}

```

You say it's better to not write PHP for maintenance reasons. I would argue the exact opposite - it's much easier to version control code than it is configuration stored in the DB.
> 1 votes

---
Tags: views
---


# Question
Title: Request a page - as admin - via command line to build up cache
Folks:

I have a pretty hefty view page which has been overridden with template files to produce a custom gantt chart for a long list of users. For each row of gantt data - the outputted html is cached to speed things up..

I've written a function which I call via drush that deletes the cached key:values from my custom cache table.

`drush eval 'custom_tweaks_clear_cache_codes()'`

The plan is to 1) flush the cache every morning via cron using this drush command. Then, 2) 'warm the cache' essentially request this page via command line to build the cache table up again.

The **issue** is, I could leave it and let the first user who views the page, take the hit so the cache gets built - but I can't allow this, the user needs to be an admin..

Essentially: I need a way to hit the page but as admin - which doesn't involve me loading the page every morning manually before the day starts.

Has anyone got any ideas?

# Answer
> 3 votes
Load the page via the cron (maybe 5 mins after deleting the cache) using wget. You'll need to set this up on the server as opposed to through the Drupal UI.

This won't hit the page as admin but I'm not sure what value that adds. You just need the caches to be built so hitting as an anonymous user will do this.

Also checkout `hook_drush_command()` for creating your own Drush functions (good tutorial here).

---
Tags: caching, cron
---


# Question
Title: Masking event title if marked as "private" (Views, Pathauto…)
I'm creating a calendar in D7 using an Event content type, which will include a Private checkbox. If it's set:

* Users with the appropriate permission will see the node title as it was entered.
* Everybody else will see "Private event" as the node title.

How would you approach this? (A code-based solution is fine.) Immediate concerns are ensuring "Private title" gets substituted in regular node displays, views -- and also pathauto URLs. Thanks!

---

Edit -- **Alternate strategy:**

1. Leave the node title alone (as "Private event" if the event is private), which will enable desired pathauto functionality without any changes.
2. Add a "private title" text field. This is where admin users would enter the actual name of the event, for internal reference.
3. On *display,* if the current user has admin permissions, alter the node title to display the private title value.

This seems like it would be a much simpler strategy. What do you think?

# Answer
> 0 votes
`hook_node_load()` should be suitable for changing the title based on the private status and current user.

Changing the path will be the hard bit.

Pathauto can only have 1 configuration per bundle so you'll need to use `hook_node_insert()` and `hook_node_update()` to act on events being added or altered to set the *private* path alias. `path_save()` can be used to actually save the new alias, but you will need to code the logic to come up with the alias yourself. This post on drupal.org may help.

Once the additional alias is set you will need to make sure to use the correct alias when building links to the content based on the current users permissions.

---
Tags: nodes, path-aliases
---


title: Drupal 8 different layouts in theme

text:
# Question
Title: Drupal 8 different layouts in theme
How do i create theme that has different regions for every node?

For example i want my frontpage to have different regions than some other page that represents content.

# Answer
You don't want different regions for *every* node.

Regions should be as generic and re-usable as possible.

However you don't have to include *all* regions in *all* templates.

Your `page--front.html.twig`could have a different set of regions to `page.html.twig`

Maybe checkout the Drupal 8 theming guide.
> 2 votes

---
Tags: theming, 8
---


# Question
Title: How to theme a field group (with div output and css class set)?
I would like to theme a group of fields that belong to a content type. For example to position all of them at a certain area in the page.

I want to do this in conjunction with the field\_group module

I know that it is possible to theme an individual field, by overriding `field.tpl.php` in your own theme, along with CSS as required. And I have done this successfully.

However I'd like to know if there is something like `field-group.tpl.php` which I can override in my own theme, similar to how I have done for field.tpl.php.

When editing the field group settings in the Content Type, `<div>` can be specified for a field group, as well as CSS classes. So I create a field group and specify these things and then add some fields to belong to my field group. However, when I look at the html source output for content of this content type, I cannot see anywhere this extra div is defined nor its groupname. Therefore I don't know how to theme it. Please advise.

# Answer
> 2 votes
I know you mentioned wanting to use the field\_group module, but I don't immediately see the need.

If the goal is to position a set of fields all together, why not override your `node.tpl.php` file, calling it `node--my-content-type.tpl.php` and then somewhere within it do something along the lines of:

```
<div id="field-group">
  <?php print render($content['my_field1']); ?>
  <?php print render($content['my_field2']); ?>
  <?php print render($content['my_field2']); ?>
</div>

```

That way they can A) be positioned by positioning `#field-group`, as well as allowing you to theme each field in their own `field.tpl.php` file.

# Answer
> 0 votes
First check: make sure your putting these field groups in on the "Manage Display" tab of your content type, not the "Manage Fields". "Manage Fields" only affects the node edit form, "Manage Display" field groups should show up on the page with your specified class/wrapper etc.

Second check: Are you looking at the right view\_mode? Field groups will show up on whatever view mode you have them set on.

Last thing I'd look at, if you're doing any preprocessing of the $content variable it can muck up settings you put into the "Manage Display" tab where the field\_groups are. You can dpm($variables\['content'\]); in your node\_preprocessor at different points to see if anything is messing with it.

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


title: Rewrite product title select list

text:
# Question
Title: Rewrite product title select list
I run a popular Drupal website that caters for the clubbing market. I retail events on my site using Drupal Commerce

To create an event(product) I have set up these fields :

* Event Title
* Event Date
* Event Price

When creating events, each event is a separate product with a different date.

Now on the node that lists that particular event, I title my products in a way so when select the event from the drop down select list it reads;

**==Product Title(Event Name)==Event date==**

eg

* Boat Party - 12/07/15
* Boat Party - 13/07/15
* Boat Party - 14/07/15
* Boat Party - 15/07/15
* Boat Party - 16/07/15

What I need is rewrite function:

Instead of adding the date in the product title every time, is the correct function to rewrite the product title in the drop down as to include the date variable and price like as follows;

**==Day,Month==Product Title(event title)==Price**

eg;

* 14th, May -- Boat Party -- £10
* 15th, May -- Boat Party -- £10
* 16th, May -- Boat Party -- £10
* 17th, May -- Boat Party -- £10
* 18th, May -- Boat Party -- £10

Thank you.

# Answer
Use `hook_form_alter()` to loop over the `#options` for the select field.

From memory I think the value of each option will be the commerce product ID so then you can use `commerce_product_load()` to load the event details and build the new title.
> 1 votes

---
Tags: commerce
---


title: Print view in email notification

text:
# Question
Title: Print view in email notification
I have created View and that is with edit node from admin side, and I want to send same view by printing in email and I am using code to print view in email like this

```
$items['user/%user/display']['access callback'] = false;
$viewName = 'example_view_1';
print views_embed_view($viewName);

```

But there is edit node link also whenever I see from admin side,but whenever I got same view in email then it will not show edit link of node, Let me know if anyone have solution.

# Answer
Finally I have done this reminder this way.

```
module_load_include('inc', 'webform', 'includes/webform.submissions');
$submissions = webform_get_submissions(nodeid);

```

and checked roles while printing node data in loop and get edit link through `$base_url;` and print into simple tabular format. Let me know if any query in it.

Thanks for the support.
> 0 votes

---
Tags: views, emails
---


# Question
Title: How do I reset Drupal Commerce orders, profiles, carts etc?
I have a heavily customized commerce site that I have just completed and I need to hand it over to the client. It has a ton of test orders, profiles etc. How can I reset all of the orders, profiles (revisions), carts auto increments etc so that it's scrubbed and can start over?

There is a similar question asked here, but it only covers orders. How to reset the id of the orders generated by Commerce module

On a side note, I would imaging this would make a great contrib module as I would imagine many other would require this.

Note: Uninstalling and reinstalling commerce is not an option as there are a ton of other configs and commerce contrib modules already set.

# Answer
I don't recommend truncating database tables, because you also have to consider field data / revision tables - that can get nice and tricky if you've used the same field on entities that you want to delete and on those you want to keep. There also may be other contributed modules on the site that have stored data related to these entities. Without using the API to delete these entities properly, you'll end up with this stale data laying around that may or may not cause problems later.

If I had to do this I'd either do as the other answer recommended - go through each list and use the delete links - or in the case of large data sets, I'd add Views Bulk Operations to the Views so I could delete them en masse. VBO is one of Drupal's best kept secrets - great for automating routine tasks like this.

When deleting Commerce entities, I'd start with payment transactions then orders then products and customer profiles. You need to delete both complete orders and shopping cart orders, otherwise referenced products / customer profiles will not be deletable.
> 4 votes

# Answer
Just contributed a module called Commerce Reset.

This module will allow you to.

1. Delete orders and reset order number.
2. Delete payment transactions.
3. Delete customer profiles.
4. Delete product variations

Check it out here Commerce reset
> 3 votes

# Answer
I recently ran into a scenario like this. I am not aware of any module that can do this so I think you might have the same 2 options that I did:

* Manually go through each section, orders, profiles, etc., and delete the entries. Might not be a viable solution if you have thousands on entries.
* Truncate the appropriate databases using SQL. I would backup the database first before you try this but the schema is relatively easy to figure out if you either profile the database or browse through the Commerce code base.

I personally went with the second option and it worked out quite nicely for me.
> 1 votes

---
Tags: commerce
---


# Question
Title: Reload a View with AJAX on a click event
I have a view displaying a table of related nodes that is embedded on another node's page. The info displayed in embedded view is periodically changing, I want to allow the user to refresh the view by clicking a "Refresh View" link or button without reloading the entire page.

I've checked out the views-hacks module which provides the auto-reload feature, but that doesn't do exactly what I need it to do.

# Answer
I'm afraid you won't do without a bit of coding here. What first comes to mind is a combination of

1. Form API for the refresh button,
2. views\_embed\_view() for retrieving the current version of the view.
3. AHAH javascript replacement for the view output replacing, and

Modules Views Auto-refresh mentioned by you or Ajax Views Refresh may not do exactly what you're after, but their code could be a source of inspiration when implementing views refreshing.

I also recommend having a look at the code of the Drupal core's *Poll* module, mainly the functions poll\_choice\_js (the callback function for the path `poll/js`) and poll\_form (`$form['choice_wrapper']['poll_more']`)
> 1 votes

# Answer
You need to use Drupal.behaviors.
For lack of time, I haven't tested the code, but this is basically the logic...

```
    Drupal.behaviors.myViewsRefresh = {
      attach: function( context , settings) {

        var viewName = 'the-name-of-your-views';

        // Your views should be Ajax enabled,
        // then it will be available as a property of the Drupal object
        // like so...
        var instances = Drupal.views.instances;
        var yourViews;

        // then you simply need to iterate thru the various
        // views instances name to find your views
        $.each( instances , function getInstance( index, element){
              if(element.settings.view_name == viewName ){
                  yourViews = '.view-dom-id-' + element.settings.view_dom_id;
              }
        });

        // Define your button click here...
        $('.yourButtonClass').click( function(){

            if(typeof yourViews !== 'undefined'){
              $(yourViews).trigger('RefreshView');
            }

        });
      }
    }

```
> 1 votes

# Answer
Create an exposed filter. View the html with firebug or a similar extension, then copy the html for the form that submits the exposed filter. Remove all the selection options so you're left with just the submit button, and rename it to something like "Refresh view". Take this html and put it into a header (make sure to set the mode to full html). Voila, Refresh on Demand Form.
> 0 votes

---
Tags: views, 6, ajax
---


# Question
Title: Site name div selectively in an h1 tag, affects markup and css
So, the position of my site title and logo have been moving around on different pages.

I was pulling my hair out until I compared the html outputs of the pages where the logo moves and it appears that on some pages my site name div is given an h1 tag and on other pages it doesn't have and is just in a regular div. Two of my pages have the h1 tags, but I just learned that this should only be the front page.

I had played with wrangling the positions with CSS but I want to know what is causing this change in my markup, so I can squash this CSS bug for good. Any ideas why this happens? and or suggestions on what to do? Here's the markup with what's close to what I want: Site name with no h1 tag Here's my site with the mystery h1 tags site name no h1 tag.

For clarification, I'm using a bartik subtheme, basically just added a css overrides CSS file. Here is my page.tpl.php

My question is 1) why did some pages have the h1, not just the front page; and 2) how do I stick an h1 tag on all the pages?

```
    ?>
<div id="page-wrapper"><div id="page">

  <div id="header" class="<?php print $secondary_menu ? 'with-secondary-menu': 'without-secondary-menu'; ?>"><div class="section clearfix">

    <?php if ($logo): ?>
      <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
        <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
      </a>
    <?php endif; ?>

    <?php if ($site_name || $site_slogan): ?>
      <div id="name-and-slogan"<?php if ($hide_site_name && $hide_site_slogan) { print ' class="element-invisible"'; } ?>>

        <?php if ($site_name): ?>
          <?php if ($title): ?>
            <div id="site-name"<?php if ($hide_site_name) { print ' class="element-invisible"'; } ?>>
              <strong>
                <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
              </strong>
            </div>
          <?php else: /* Use h1 when the content title is empty */ ?>
            <h1 id="site-name"<?php if ($hide_site_name) { print ' class="element-invisible"'; } ?>>
              <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
            </h1>
          <?php endif; ?>
        <?php endif; ?>

        <?php if ($site_slogan): ?>
          <div id="site-slogan"<?php if ($hide_site_slogan) { print ' class="element-invisible"'; } ?>>
            <?php print $site_slogan; ?>
          </div>
        <?php endif; ?>

      </div> <!-- /#name-and-slogan -->
    <?php endif; ?>

    <?php print render($page['header']); ?>

    <?php if ($main_menu): ?>
      <div id="main-menu" class="navigation">
        <?php print theme('links__system_main_menu', array(
          'links' => $main_menu,
          'attributes' => array(
            'id' => 'main-menu-links',
            'class' => array('links', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Main menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>
      </div> <!-- /#main-menu -->
    <?php endif; ?>

    <?php if ($secondary_menu): ?>
      <div id="secondary-menu" class="navigation">
        <?php print theme('links__system_secondary_menu', array(
          'links' => $secondary_menu,
          'attributes' => array(
            'id' => 'secondary-menu-links',
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Secondary menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>
      </div> <!-- /#secondary-menu -->
    <?php endif; ?>

  </div></div> <!-- /.section, /#header -->

  <?php if ($messages): ?>
    <div id="messages"><div class="section clearfix">
      <?php print $messages; ?>
    </div></div> <!-- /.section, /#messages -->
  <?php endif; ?>

  <?php if ($page['featured']): ?>
    <div id="featured"><div class="section clearfix">
      <?php print render($page['featured']); ?>
    </div></div> <!-- /.section, /#featured -->
  <?php endif; ?>

  <div id="main-wrapper" class="clearfix"><div id="main" class="clearfix">

    <?php if ($breadcrumb): ?>
      <div id="breadcrumb"><?php print $breadcrumb; ?></div>
    <?php endif; ?>

    <?php if ($page['sidebar_first']): ?>
      <div id="sidebar-first" class="column sidebar"><div class="section">
        <?php print render($page['sidebar_first']); ?>
      </div></div> <!-- /.section, /#sidebar-first -->
    <?php endif; ?>

    <div id="content" class="column"><div class="section">
      <?php if ($page['highlighted']): ?><div id="highlighted"><?php print render($page['highlighted']); ?></div><?php endif; ?>
      <a id="main-content"></a>
      <?php print render($title_prefix); ?>
      <?php if ($title): ?>
        <h1 class="title" id="page-title">
          <?php print $title; ?>
        </h1>
      <?php endif; ?>
      <?php print render($title_suffix); ?>
      <?php if ($tabs): ?>
        <div class="tabs">
          <?php print render($tabs); ?>
        </div>
      <?php endif; ?>
      <?php print render($page['help']); ?>
      <?php if ($action_links): ?>
        <ul class="action-links">
          <?php print render($action_links); ?>
        </ul>
      <?php endif; ?>
      <?php print render($page['content']); ?>
      <?php print $feed_icons; ?>

    </div></div> <!-- /.section, /#content -->

    <?php if ($page['sidebar_second']): ?>
      <div id="sidebar-second" class="column sidebar"><div class="section">
        <?php print render($page['sidebar_second']); ?>
      </div></div> <!-- /.section, /#sidebar-second -->
    <?php endif; ?>

  </div></div> <!-- /#main, /#main-wrapper -->

  <?php if ($page['triptych_first'] || $page['triptych_middle'] || $page['triptych_last']): ?>
    <div id="triptych-wrapper"><div id="triptych" class="clearfix">
      <?php print render($page['triptych_first']); ?>
      <?php print render($page['triptych_middle']); ?>
      <?php print render($page['triptych_last']); ?>
    </div></div> <!-- /#triptych, /#triptych-wrapper -->
  <?php endif; ?>

  <div id="footer-wrapper"><div class="section">

    <?php if ($page['footer_firstcolumn'] || $page['footer_secondcolumn'] || $page['footer_thirdcolumn'] || $page['footer_fourthcolumn']): ?>
      <div id="footer-columns" class="clearfix">
        <?php print render($page['footer_firstcolumn']); ?>
        <?php print render($page['footer_secondcolumn']); ?>
        <?php print render($page['footer_thirdcolumn']); ?>
        <?php print render($page['footer_fourthcolumn']); ?>
      </div> <!-- /#footer-columns -->
    <?php endif; ?>

    <?php if ($page['footer']): ?>
      <div id="footer" class="clearfix">
        <?php print render($page['footer']); ?>
      </div> <!-- /#footer -->
    <?php endif; ?>

  </div></div> <!-- /.section, /#footer-wrapper -->

</div></div> <!-- /#page, /#page-wrapper -->

```

# Answer
The rationale here is that for SEO best practices, every page should have a single H1 tag (OK so that's not strictly true with HTML5 but it was when Bartik was conceived). When a page has no title set there would otherwise not be a H1 tag which is often the case on the homepage.

To get around this you can do one of two things...

**1. Prevent the H! from being applied to the site name**

Change the following

```
<?php if ($site_name): ?>
  <?php if ($title): ?>
    <div id="site-name"<?php if ($hide_site_name) { print ' class="element-invisible"'; } ?>>
      <strong>
        <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
      </strong>
    </div>
  <?php else: /* Use h1 when the content title is empty */ ?>
    <h1 id="site-name"<?php if ($hide_site_name) { print ' class="element-invisible"'; } ?>>
      <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
    </h1>
  <?php endif; ?>
<?php endif; ?>

```

To...

```
<?php if ($site_name): ?>
  <div id="site-name"<?php if ($hide_site_name) { print ' class="element-invisible"'; } ?>>
    <strong>
      <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
    </strong>
  </div>
<?php endif; ?>

```

**2. Don't style the site name based on it's tag type**

Do all of you styling for the site name based on the "#site-name" selector, including resetting any default H1 styling.

--- Edit ---

Just seen that you were looking at having the H1 on the site name on all pages. In that case you can change the code in the template mentioned above to:

```
<?php if ($site_name): ?>
  <h1 id="site-name"<?php if ($hide_site_name) { print ' class="element-invisible"'; } ?>>
    <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
  </h1>
<?php endif; ?>

```

However, this will cause you to have two H1 tags on most pages which while not technically invalid anymore if you're using an HTML5 doctype (which if you're using Bartik you're probably not), it will have the effect of diluting you keywords, i.e. if you have a page about a given subject, instead of having the H1 tag telling search engines that the page is all about that subject, it will tell them that the page is really about your site name and contains a section about that subject and it won't rank as highly for that subject.
> 2 votes

---
Tags: theming
---


title: drush cannot find omega help commands

text:
# Question
Title: drush cannot find omega help commands
I've installed Omega 4 but drush cannot find the omega help set or the omega command set -- nor can I. Where are these supposed to be located? Without them, I cannot easily create a subtheme with drush, or do any of the drush goodies in omega 4.

# Answer
Drush can only find additional commands in themes and modules if it knows where your Drupal site is. There are several ways you can do this; cd to the directory that contains your settings.php file, or pass --root and --uri on the commandline to point at the Drupal Root and site uri (e.g. mysite.com), or define a site alias and pass @alias on the command line. See the Drush README file on the github project page for more information.
> 3 votes

# Answer
Had the same problem because I've placed my themes in profile folder, it works good If I move them back to sites/all/themes/
> 0 votes

---
Tags: drush, theming
---


title: Get logged in user id in api calls

text:
# Question
Title: Get logged in user id in api calls
I am working on an existing site where it has exposed api's via a custom module.

There's a new requirement where an api should only be accessed by authenticated user. For that theres a login api provided.

How can I make sure to add login information such that drupal recognises which user is making the call.

Does keeping SESSIONID in header will make drupal identify the user.

Note the API calls are made from android/ios app.

# Answer
> 0 votes
If the user is not logged into your app and if you don't let anonymous users to access the API, how can you let them to log in without accessing API?

What you can do is you can maintain a API key for your application. You should call the API using the key all the time. That should be your first check point. Then you should add that API key validation for accessing the API. Then you can give access to your login API function using that key.

Once user is successfully login to the system you can return a dynamically genarated(random) session key to your APP so that the user login to the app and he/she has a session key. From that point call the API using the session key and add validation method to validate both session key and API key.

So all API functions are accessed by logged in users only. When the user logs out from the app call a session key function to remove your key.

I think you are looking for this kind of a solution.

---
Tags: 7, database
---


title: Disabling CKEditor in comments

text:
# Question
Title: Disabling CKEditor in comments
Does anyone know of a way to force plain text mode in comments for all roles?

Edit: is it in any way possible to do so through CSS? Thanks!

# Answer
> 5 votes
Take a look at `admin/settings/ckeditor/editg`. There you can change the visibility settings by field path (something like `content_type@path.element_id`). That should work.

# Answer
> 6 votes
Try

```
function MYMODULE_form_alter (&$form, &$form_state, $form_id)
{
  // comments
  // http://api.drupal.org/api/drupal/modules--comment--comment.module/function/comment_form/6

  if ($form['#id'] == 'comment-form') {
    $form['comment_filter']['format'] = array(); // nuke wysiwyg from comments
  }
}

```

# Answer
> 2 votes
For Drupal 6, I would recommend the Better Formats module to control this. It allows to set a default input format on comments, but also allows different defaults per role and per content type. The Drupal 7 version is in development, but its status is a bit unclear at the moment because some of the features are now in core.

# Answer
> 2 votes
I had the same problem in D7. To fix it I changed the default input format of comments to Plain Text (ckeditor did not have a profile for that input format). This removed ckeditor from comments.

To remove the input format hints I installed the better formats module.

**Update:** I just noticed that your question was how to force plain text mode for all roles. To simplify I would just change the way the input format process text from "filtered text" to "plain text".

# Answer
> 1 votes
I did it this way. I fixed input format to a non wysiwyg one and denied access of it.

```
/**
 * Implements hook_comment_form_alter().
 */
function comment_form_alter(&$form, &$form_state, &$form_id) {
  $form['comment_body']['#after_build'][] = 'MYMODULE_customize_comment_form';
}

/**
 * Comment body after-build function.
 */
function MYMODULE_customize_comment_form(&$form) {
  // Hide text-format selector in comment form and fix format to filtered_html
  $form[LANGUAGE_NONE][0]['format']['format']['#value'] = 'filtered_html';
  $form[LANGUAGE_NONE][0]['format']['format']['#access'] = FALSE;
}

```

---
Tags: 7, comments, wysiwyg
---


# Question
Title: Calendar view doesn't display node titles upon first view, but will after Prev/Next are pressed
Our calendar is doing some strange stuff. At first, all of the node title are missing.

But by pressing Prev/Next, they then appear

I can't think of what might be causing this issue.

# Answer
> 0 votes
Well, I did a comparison between our development server and production server via `drush pml | grep Enabled | grep -i views` on each server. I noticed that for some reason I left views\_rss enabled on production but not development. After `drush dis -y views_rss` and `drush cc all && drush cron`, things appeared as normal.

---
Tags: views, datetime
---