# Question
Title: How to assign a confirmed user role upon email confirmation without logintoboggan?
Is there a way to assign an confirmed user role upon account **validation/email confirmation**?

there is this possibility mentioning logintoboggan:

How do I assign a role to a user after the user's email is confirmed?

My problem is that I am using email registration and genpass (so the user only needs to enter his email) and the modules don't work together.

I'm fairly good with rules and started looking into development. I'm not a programmer though and I don't know how I should implement a corresponding rules condition that checks whether the user has validated his account.

Any suggestions?

# Answer
If you're only allowing the user to login once they validate their email (which would make sense if you're using email confirmations) then you could just create a rule that assigns the role to the user when the user logs in:

```
{ "rules_add_user_role_at_login" : {
    "LABEL" : "Add user role at login",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "DO" : [
      { "user_add_role" : { "account" : [ "account" ], "roles" : { "value" : { "5" : "5" } } } },
      { "entity_save" : { "data" : [ "account" ], "immediate" : "1" } }
    ]
  }
}

```

Now, if you're allowing a user to login without having to validate their email (which makes less sense) then you'll need to write a bit of code that hooks into the user reset form and adds the role to the user when that form submits.
> 0 votes

---
Tags: 7, rules, emails
---


# Question
Title: Can I add Vertical Tab on a Node Edit Page in admin
I am hoping to add a custom Vertical Tab in node edit page. Is it possible?

As an example, someone did it like this:-

Thanks

# Answer
You can achieve this with hook\_form\_alter. Similar example can be found in the Examples for Developers module. Take a look at this after you are done with your form tabs, add a custom submit handler like `$form[#submit][] = 'my_custom_submit';` and then save the data in submit handler using `variable_set()` method like this:

```
variable_set('MYMODULE_' . $form_state['values']['your_value'] . '_special_option', $values);

```

**Note**: put it in `template.php` or in a custom module.
> 1 votes

# Answer
You can use this module to add groups and 1 of the options is vertical tabs:

https://www.drupal.org/project/field\_group
> 1 votes

---
Tags: nodes, forms
---


title: Add Library to Footer

text:
# Question
Title: Add Library to Footer
If I am using the Libraries API module to add a javascript library in my module, is it possible to have the library load in the footer instead of the header?

If not is there an alternative method?

# Answer
Instead of running the libraries\_load() function:

```
$library = libraries_load('easyzoom');

```

I just used the libraries\_get\_path() function to get the path and attached to the element and added scope of footer.

```
$easyzoom_library_path = libraries_get_path('easyzoom');

$element['#attached']['js'] = array(
  $easyzoom_library_path . '/dist/easyzoom.js' => array('scope' => 'footer'),
);

```
> 1 votes

# Answer
You can use scope parameter of drupal\_add\_js to specify the location of your script.

```
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
    array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
  );

```

Follow this for more details and examples of drupal\_add\_js
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Simplenews does not apply templates and does not resend
I have a strange issue. Simplenews sends ok html formatted emails but it does not read the extra info I write in template. It actually doesn read them at all.

The second issue it doesn't resend no matter how much I try.

# Answer
About You Second Issue - Here is a "dirty" solution.

* Go to phpMyAdmin and find simplenews\_newsletters table
* Edit that table and change **s\_status** on the newsletter you want from 2 to 0.

s\_status - 2 Newsletter has been sent

s\_status - 0 Newsletter has not been sent

s\_status - 1 Sending Newsletter
> 2 votes

# Answer
Attention for the mailing items that may be present in the table "simplenews\_mail\_spool". In this table the remaining recipients are present for the mailing in status "pending". they will be send out the next time the cron-job starts.
> 0 votes

---
Tags: emails
---


# Question
Title: Fetching user account additional field in views global php
I want to fetch the additional account field by using `global php` in `Views`. The additional account is shown below:

The code I use in `Global PHP` output:

```
<?php
global $user;
$namepsm = strtoupper(str_replace("_"," ",$row->value));
print ($namepsm .  ' ' . $user->field_id_number) ;
?>

```

I have an error

> Notice: Undefined property: stdClass::$field\_id\_number in \__lambda\_func() (line 4

I can use other standard account fields, for example `$user->name` or `$user->$mail`.

How can I **print** the additional account field (field\_id\_number)?

# Answer
> 3 votes
Use `user_load` function to load your account, like so:

```
$logged_in_user = user_load($user->uid);

```

Then `dpm($logged_in_user)` or `print_r($logged_in_user)` you will see you have access to the field you added.

---
Tags: views
---


# Question
Title: How to display the node id as a field (with label)
This question is really simple, i need to use the node id as an identifier and so i need to display it whenever a certain content type is shown. What's the best way to do this? i need to display the node with label and so on, i just don't want to make a custom field for something that's already a field.

# Answer
> 3 votes
You could add a hook\_node\_load() hook and copy the nid into a field like structure.

something like (*untested*)

```
function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->nid_field['und']['value'] = $node->nid;
  }
}

```

# Answer
> 4 votes
Create a template for the content type and use `<?php print $node->nid; ?>`

Make a copy of node.tpl.php from modules/system and paste in your theme directory. Copy the code from inside node.tpl.php and create a new file called "node--YOURTYPE.tpl.php" (replace YOURTYPE with the name of the content type).

Inside that file you can place `<?php print $node->nid; ?>` wherever you want the nid to be seen. You can add a label, wrap it in HTML to style it, whatever you like. Save the file and clear the cache to see the changes. Take a look at a node of that content type and you will see the node's nid.

# Answer
> 2 votes
1. download display suite module.
2. add a custom code field
3. select token and the code is \[node:nid\]

---
Tags: 7, entities
---


# Question
Title: How to check if an article is referenced from a collection?
I have a `collection` content type which is just a list of `EntityReferences` to articles.

When I am loading an `article`, how can I use the `Entity API` to check if it belongs to one or more collections?

Previously I would query the `DB`, but I wonder if there is a more idiomatic way?

# Answer
> 1 votes
To load all collection id's, which have a reference to $article\_id:

```
$collection_ids = \Drupal::entityQuery('node')
  ->condition('type', 'collection')
  ->condition('field_article_ref', $article_id)
  ->execute();
if ( count($collection_ids) > 0 ) {
  echo "the article $article_id is referenced in one or more collections";
}

```

---
Tags: 8, entities
---


# Question
Title: How can I rewrite a date field "End Date" to be "present" if no value is entered?
I have a `date` field for an item in which I am entering a `range of years`. I have created a view which displays the **start date and end date** as individual fields. Typical output looks like this:

> Title: Pop Art
> Start Date: 1958
> End Date: 1970

However, there are several items which do not have an end date because they are ongoing. Even though for the *end date* field's "No Results Behavior" I have "No results text" set to the word *present* it renders the start date in place of my rewrite text:

> Title: Contemporary Art
> Start Date: 1970
> End Date: 1970

I want it to do output like this:

> Title: Contemporary Art
> Start Date: 1970
> End Date: present

**How can I get the end date to render as the word "present" when no end date is specified?**

*Note: in my final view I will output the date range as, "1970-present." Above, I formatted my examples as "label: value" for clarity.*

# Answer
When there is no end date specified for a node it takes both the dates same. The module consider it a one day event.

However, in your case you are making it ongoing by not mentioning the end\_date so no results behavior is not going to work. I would suggest to use some global php like this

```
<?php
if($row->field_date == $row->field_date_1) {
   echo "Present";
} else {
  echo $row->field_date_1;
}
?>

```

Make sure to include this php field after both start and end date fields, and make the end date fields hidden.
> 4 votes

# Answer
Shabir A.'s answer got me on the right track. However `$row->field_date` returns nothing for me in Views PHP. I've come across this before and the solution was to use the $data variable. Here's the code I ended up using (my date field is 'field\_art\_year' the extra `field_` is not a typo):

```
<?php
$startdate = date("Y", strtotime($data->field_field_art_year[0]['raw']['value']));
$enddate = date("Y", strtotime($data->field_field_art_year[0]['raw']['value2']));

if($startdate == $enddate) {
  print $startdate . "–present";
} else {
  print $startdate . "–" . $enddate;
}
?>

```

**Addendum**: Should wrap this code in `if (isset($data->field_field_art_year[0]) { }` or else you get errors in the log.
> 2 votes

---
Tags: views, datetime
---


title: EntityQuery group by clause

text:
# Question
Title: EntityQuery group by clause
Using the EntityQuery API I am trying to add a group by clause to the query, however, it doesn't seem that one exists. The EntityQuery API does not have a groupBy() method.

Current Code:

```
$nodes = Drupal::entityQuery('node')
    ->condition('type', 'thing')
    ->condition('field_num_1', 'value', '=')
    ->condition('field_num_2', 'value', '=')
    ->range(0, 10)
    ->sort('title', 'ASC')
    ->execute();

```

Ideal Code:

```
$nodes = Drupal::entityQuery('node')
    ->condition('type', 'thing')
    ->condition('field_num_1', 'value', '=')
    ->condition('field_num_2', 'value', '=')
    ->groupBy('field_num_3')
    ->range(0, 10)
    ->sort('title', 'ASC')
    ->execute();

```

# Answer
> 12 votes
For aggregate queries, you need to use the separate method, from https://www.drupal.org/node/1918702:

```
$query = Drupal::entityQueryAggregate('node');

$result = $query
  ->groupBy('type')
  ->aggregate('nid', 'COUNT')
  ->execute();

```

groupBY() alone doesn't do anything. The normal entity query returns entity ID's. Always. It makes no sense to group by a field or anything else. Only in combination with aggregate.

---
Tags: entities, 8
---


# Question
Title: How do I use custom marker icons with Gmap?
I want to show markers like on this map here http://demo.symphonythemes.com/drupal7/bizreview/ which are obviously custom.

How do I go about this? I'm either searching for the wrong thing or something.

# Answer
Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:
>
> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).
>
> And the Set my location block allows your visitors to locate themselves on the map, either automagically --via the Wifi/GPS device on their mobile-- or by typing an address or landmark, like "Eiffel tower" (bottom screenshot, upper left corner, click to enlarge).
>
> Follow this step-by-step tutorial to create a handy store locator with proximity search, from a list of addresses in a spreadsheet. You'll learn about the Feeds and Display Suite modules too!
>
> Finally IPGV&M provides a set of visitor location retrieval technologies, both IP and HTML5-based, so that you can track where past visits came from and where current visitors are located, superimposing their moving positions as markers on your maps.

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here).
> 1 votes

---
Tags: google-maps
---


# Question
Title: Search result to show link to the page not to the pdf file
I am using the Search file attachments module (which searches for text from pdf files after they are indexed), and everything works fine.

But I would like in Search result to **display link** to the content (where I uploaded the file) not **link to the PDF** itself, so that the user goes to that page and from there he can choose to see the PDF.

I am still new to Drupal, but from what I have read that I have to alter `$search_results` in `search-results.tpl.php` and use `template_preprocess_search_results()` to display what I want (*not sure if this is the right way*) or is there another way to this?

**EDIT:**

I found that I could edit `search_file_attacments.module` and there is the link attribute in `$results[]` I just have to figure out how to get nid (so I can get the url) from fid

# Answer
First, I can't install the Search File Attachments module at this moment, but you can read at the module's page:

> The module is based on the core search and no other module is required.

And I don't see any template page inside the module.

As in the `search-result.tpl.php` you will only have access to the `$snippet` variable, this is not a solution for you, because `$snippet` is a string, see the code inside `search-result.tpl.php`:

```
<?php if ($snippet): ?>
  <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?></p>
<?php endif; ?>

```

So your best bet should be implement the `template_preprocess_search_results()` in the template.php file of your theme.

See this example:

```
function THEME_preprocess_search_result(&$variables) {
    dpm($variables); //you need devel module to use dpm
}

```

Inside `$variables['result']` you will have the values that you need to make your modification. See the `dpm()` output:

If you want modify the `$snippet` variable then change the value inside the function like this:

```
function THEME_preprocess_search_result(&$variables) {
  //searching the info that you need
  $variables['snippet'] = 'The new value';
}

```
> 3 votes

---
Tags: 7, search
---


title: How to use DI with simple objects?

text:
# Question
Title: How to use DI with simple objects?
I have a simple class to which I am providing some values via constructor and I would like to use DI. This class has no relation to Drupal(not a plugin, form, entity,...).

It serves as a wrapper for dataset where I need to do some data manipulation by using few services.

I wanted to use the ContainerInjectionInterface but it only has the create() method and it does not look like it can be used for this purpose.

Can the DI in D8 even be used for this purpose?

# Answer
> 2 votes
Yes. Just require the services you need in your constructor, and wherever you create your object, pass them in.

That *is* the very definition of dependency injection.

The container/services are just a way to describe your dependencies to the environment/Drupal so it can do that automatically but that is in no way a requirement.

What you probably want to do is to use the factory pattern, so that you have a factory, which you can define a service, which offers a method to get your value object with the necessary services injected. Drupal 8 has various examples for the, for example KeyValueDatabaseFactory (keyvalue.database), which has a get($collection) method. Each call creates a new object, passes the dependencies that object needs to it and then returns it.

# Answer
> 0 votes
Yes, DI can be used for that purpose, but you don't deal with the `ContainerInjectionInterface` interface in any way: You just define a service, which could use any class, such as the class you already have (if it can be used), a wrapper around that class, or a class that instantiate objects of that class; in any case, you don't have to implement a specific interface. Since you normally create a service when you want to allows other modules to implement alternatives to the service, the class normally implements an interface you make public.

For example, Drupal defines the http\_client service, which by default implementation uses the `\GuzzleHttp\Client` class; it also defines the email.validator service, which by default uses the `\Egulias\EmailValidator\EmailValidator` class.

---
Tags: 8
---


title: Field modification using PHP

text:
# Question
Title: Field modification using PHP
I have a content type which contains field\_state. The nodes of this content type store the two letter abbreviation for the state in each node using field\_state. OH is Ohio, CA is California and so forth. I need to render this field with the full spelling of the state name. I have a PHP Array that contains all of the 50 mappings that I need like -- $state\['CA'\] = 'California'; This data structure is wrapped in a PHP function state\_full\_name($abbreviation).

I created a View which creates a block of everything I need -- except the full spelling of the state name. I know how to apply a PHP functions to a specific Views field in both D6 and D7. The solution in D8 has been elusive for me. I believe I need to use a Views plugin in some fashion. Can you help? Thanks!

# Answer
> 5 votes
A configurable or a base field? Either way, that's a perfect use case for using a list (string) field type, then you tell Drupal what the allowed values and its keys and labels are. Views will use that when displaying he field and everything will just work.

If you define your field in Code, instead of hardcoding the list in there, you can also specify a callback that will call your PHP function, in case you expect the list to change or if it is dynamic (`allowed_values_function` in the field storage settings). Although you can also turn that around and treat that field configuration as the canonical source for your information and if you need it in PHP, read it out from there.

If that is for some reason not an option, then you can implement a Views field Plugin and expose it to views using `hook_views_data()` hook. That's very likely a lot more complicated than using the right field Type for your use case, though.

---
Tags: views, entities, 8, plugins
---


title: Where is Update translation?

text:
# Question
Title: Where is Update translation?
In `admin/config/regional/translate/update` I found the following message:

> If there are available updates you can click on "**Update translation**" for them to be downloaded and imported now or you can edit the configuration for them to be updated automatically on the Update settings page

The following screenshot reveals more:

I could not able to find **Update translation** anywhere. What is missing?

# Answer
I suggest you the installation of Localization update module.

From the module's page:

> Automatically downloads and updates your translations by fetching them from localize.drupal.org or any other Localization server.

I use this module in all my projects, you can also have the `.po` files in the local server.
> 3 votes

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


# Question
Title: Cloned site pointing to original site's database - can this cause problems?
**Can pointing a cloned site to the original site's database cause problems?**

I'm running a Drupal 7 site with a MySQL database sitting on a separate server.

I pulled a clone of the site's codebase repository onto a seperate development server, then imported a very recent backup of the database into a fresh database. The site ran correctly, from a different domain.

However, I forgot to update the `local.settings.php` file, so the cloned DEV site pointed to the PROD database. This file was incorrect for about 16 hours, overnight, and I've since updated it to point to the correct database.

While the DEV sit pointed to PROD, I did not create, edit or delete any content on the DEV site. My only change was to disable 'aggregating CSS/JS files' under performance settings. The CRON would have run many times overnight.

I've since cleared all caches and purged all cached URLs from Varnish, but for political reasons I cannot simply restore an earlier backup of the site.

Could this database crossover cause any problems now or in the future?

# Answer
> 0 votes
The only way this could cause problems would be if the filesystem became out of sync. Since you didn't create, edit, or delete any content, this shouldn't be the case. If you have anything running on a cron hook which creates files you may see 404s in your logs. An example of this would be something like boost or advagg which create cached html/css in the files dir. Even if this is the case however you will be fine once cron has run again from the live codebase.

---
Tags: 7, database
---


title: Service module contextual filter

text:
# Question
Title: Service module contextual filter
This answer from 2 years ago (to which I am not allowed to comment) to the question "How send argument to Services Module (Views+Contextual filters)" contains something about passing contextual filter value to the service module. It is about this URL:

```
http://test.url/endpoint/path?uid=123

```

My question here: what exactly is that "path"? Is that machine name of the view?

# Answer
To resolve your issue: make sure when the view is created there is no other page or block.

It seems something setup in your MASTER page was causing it to not work. i.e `localhost/extra/api/views/service.json?tag=11584`
> 0 votes

---
Tags: views, services
---


title: Views tag filter

text:
# Question
Title: Views tag filter
I can't seem to get my tags to filter the way I intended them to work. What I'm trying to do:

I have a vocabulary created via the tags field attached to the articles content type.

I have a content type Foo which I'm creating a view in to list 'Articles' with the tag corresponding to Foo's title

Ex: Article Type: 1 - Tag: 'Yay You' 2- Tag: 'Yay Me'

Foo Type 1 - Title: 'Yay You'

would have a view showing data from Article 'Yay You'

I've already tried every conceivable way to apply contextual filters to this but can't seem to get it to pull any data unless I remove all contextual filters so that it's just showing my teasers of Articles.

The one I spent a large chunk of time on that seemed promising was the tag/taxonomy term filters attempting to pull the taxonomy term from the url since it's in the format site.com/articles/hyphenated-article-title but that didn't end up getting me anywhere.

# Answer
> 0 votes
I think in your logical data structure your second content type "Foo" is not really a content type, but a taxonomy term, as the identical title "Yay You" suggests. The taxonomy terms are fieldable and you can fill them with content the same way as any entity. So you don't need the second content type. To show the taxonomy term you can use the default view for taxonomy:

```
/admin/structure/views/view/taxonomy_term

```

To modify the diplay to show the new fields:

```
/admin/structure/taxonomy/manage/tags/overview/display/full

```

# Answer
> 0 votes
If you really want Foo to be a content type - presumably so you can add extra information to each Foo page, beyond the listing of Articles with tags that match the Foo title - then consider the Viewfield module which has a preliminary D8 port.

This will enable you to

* create a field on Foo that references a particular view
* set a default argument using Foo's title by token, which is passed through to the view and can be used as a contextual filter in the view
* optionally choose to "force the default" so that users with permission to edit Foo cannot necessarily change the reference and arguments to this view.

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


# Question
Title: Adding Rules to Canada Post and UPS (Ship-by-weight)
I've a site with Drupal Commerce. I'm utilizing both the Commerce UPS and Commerce Canada Post modules. However, these modules are pulling the shipping cost directly from *Canada Post* and *UPS* using their API's.

I want to implement a rule that does the following:

```
Per Ounce
Base Charge: $13.35
Minimum Amount: $0.00
+  $0.00  per ounce on weight less than  21 oz (pivot-weight)
+  $0.30  per ounce on weight greater than 21.00 oz

```

How do I do this within the Commerce Canada Post and Commerce UPS modules?

# Answer
I doubt you'll be able to "create a rule" using either Commerce Canada Post or Commerce UPS (as in your question). Because *creating rules* is mostly commonly done with the module ... euh ... Rules.

Even though I'm a fan of Rules, I'd rather first try a NOT commonly known/used solution to answer this question, i.e. the Math Field module. It is a fairly new D7 module, released only this year. Some more details about this module (from its project page):

> The Math Field module defines a new field type to dynamically calculate values on entity forms. **This is an alternative to Computed Field that does not require the use of PHP Filter.**
>
> Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

The reason why I think the Math Field module might be a solution (or at least worth giving it a try), is because of the various fields that appear to be used (as a prereq) for using either Commerce Canada Post or Commerce UPS.
> 0 votes

---
Tags: commerce
---


# Question
Title: Is using nodes for a notification system a performance concern?
I am building a user activity notification system whereby each new notification message is created as a new node which is displayed by Views. To prevent an infinite number of nodes being created there is a system in place to delete notification nodes once they have reached a certain age.

This still begs the question however of whether using nodes in this way is a good idea for future performance. If a single user gets 20 notifications in a day, that is 20 nodes; now if there are potentially several hundred to a thousand users that is a lot of nodes in a short period of time. The main reason I use nodes is because they are easy to access and manipulate using Rules and also are very flexible when used with Views.

Therefore is it worth considering an alternative to nodes and if so what? The Messaging module comes to mind, but since each new Message is a new entity I'm not quite sure whether in terms of performance this would be any different to using nodes. Is there a module that offers the same flexibility of nodes but also has better performance?

# Answer
There can be some performance issues because all your messages will be stored in the node table along with the other nodes. This will slow down any node loading or any kind of node type handling. I would suggest creating your own entity which would result in these being in their own table. They can also be referenced via entity reference and into views. Check out how to create entities and check out my entity feature on github.
> 3 votes

# Answer
I would go with Messaging. Dedicated Entity (if implement properly) is always faster than Node. I participated in the big D7 project and we were happy with Message API. By using a custom entity you can switch to custom storage, like: https://www.drupal.org/project/mongo\_entity

This can be helpful for D8:

https://drupalwatchdog.com/blog/2015/3/entity-storage-drupal-8-way
> 4 votes

---
Tags: nodes, performance, notifications
---


title: How do I get full CKEditor working?

text:
# Question
Title: How do I get full CKEditor working?
I'm trying to get the full CKEditor working in Drupal 8, but I only see the standard toolbar. I've downloaded the full zip file and unzipped it into core/modules/ckeditor, uninstalled/reinstalled ckeditor but still it's the standard toolbar.

How do I enable the full toolbar?

# Answer
There's more interaction and integration between core and CKEditor's plugins than we see in D7. In fact, in researching your question, I've learned that Drupal and the CKEditor team are actively collaborating, which is cool to know. But let's first note that the ckeditor js libraries and plugins (version 4.5.5 as of Drupal 8.0.1) live at `core/assets/vendor/ckeditor`, not `core/modules/ckeditor`. Also note that enabling ckeditor plugins requires explicit supporting code, such as noted here and here.

So, rather than "the kitchen sink" approach — it might be better to identify which CKEditor plugins you need enabled, that are not in core, and use the code examples in the URLS above to implement them. FWIW, it's much easier to manage such projects after delivery anyhow, even with D7.

Finally, as a nag, I presume kittens still get it bad when you overwrite drupal-managed code with your own code. In other words, I'd figure how to extend Drupal without changing code in `core/` so that when I perform a later core update, I won't loose those changes.
> 1 votes

---
Tags: 8, wysiwyg
---


# Question
Title: How to modify comment-wrapper.tpl.php to change the comment form layout?
I am trying to change the layout of my comment form. Unfortunately, when I print only fields that I need and the submit button, I can't use the button, nothing happens when I press on it.

I used following code in comment-wrapper.tpl.php:

```
<div id="comment-rating">
    <?php print render($content['comment_form']['field_cuisine']); ?>
    <?php print render($content['comment_form']['field_service']); ?>
    <?php print render($content['comment_form']['field_ambiance']); ?>
    <?php print render($content['comment_form']['field_accueil']); ?>
    <?php print render($content['comment_form']['field_qualit_']); ?>
  </div>

  <div id="comment-text">
    <?php print render($content['comment_form']['field_nom']); ?>
    <?php print render($content['comment_form']['field_n_de_carte']); ?>
    <?php print render($content['comment_form']['field_e_mail']); ?>
    <?php print render($content['comment_form']['field_t_l_phone_']); ?>
    <?php print render($content['comment_form']['comment_body']); ?>
  </div>
  <?php print render($content['comment_form']['actions']); ?>

```

Everything is displayed as expected, but i can't submit the form.

I also tried something like:

```
<div id="comment-rating">
    <?php print render($content['comment_form']['field_cuisine']); ?>
    <?php print render($content['comment_form']['field_service']); ?>
    <?php print render($content['comment_form']['field_ambiance']); ?>
    <?php print render($content['comment_form']['field_accueil']); ?>
    <?php print render($content['comment_form']['field_qualit_']); ?>
  </div>

  <div id="comment-text">
    <?php print render($content['comment_form']['field_nom']); ?>
    <?php print render($content['comment_form']['field_n_de_carte']); ?>
    <?php print render($content['comment_form']['field_e_mail']); ?>
    <?php print render($content['comment_form']['field_t_l_phone_']); ?>
    <?php print render($content['comment_form']['comment_body']); ?>
  </div>
  <?php print render($content['comment_form']); ?>

```

Like that I can submit the form by pressing on button, but the content of fields are not taken in consideration.

# Answer
> 2 votes
# The best solution:

This is the default `comment-wrapper.tpl.php`:

```
  <?php if ($content['comment_form']): ?>
    <h2 class="title comment-form"><?php print t('Add new comment'); ?></h2>
    <?php print render($content['comment_form']); ?>
  <?php endif; ?>

```

If you want to modify the form elements by overriding the template file, here is **the best known way**:

```
  <?php if ($content['comment_form']): ?>
    <h2 class="title comment-form"><?php print t('Add new comment'); ?></h2>

    <?php
    // 1. Create a custom markup
    $form_custom_markup = '';
    $form_custom_markup .= '<div style="background-color: red;">';
    $form_custom_markup .= render($content['comment_form']['author']);
    $form_custom_markup .= '</div>';
    $form_custom_markup .= '<div style="background-color: blue;">';
    $form_custom_markup .= render($content['comment_form']['comment_body']);
    $form_custom_markup .= '</div>';

    // 2. Attach the custom markup to the form
    $content['comment_form']['custom_markup'] = array(
      '#type' => 'markup',
      '#markup' => $form_custom_markup
    );
    ?>

    <?php print render($content['comment_form']); ?>
  <?php endif; ?>

```

In this example we make the Author field appear in red background and the comment body in blue background!

You could simply modify the sample above to re-arrange any form element in your form.

# Why the normal way didn't work?

To understand this solution and other solutions first we need to understand why `forms` behave differently than other `render arrays`.

To start let us have a look at the function that renders a form:

```
<?php
// form.inc

function theme_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  }
  element_set_attributes($element, array('method', 'id'));
  if (empty($element['#attributes']['accept-charset'])) {
    $element['#attributes']['accept-charset'] = "UTF-8";
  }
  // Anonymous DIV to satisfy XHTML compliance.
  return '<form' . drupal_attributes($element['#attributes']) . '><div>' . $element['#children'] . '</div></form>';
}

```

As you see, when you `render($form)` it wraps it with ''. It means that any elements that have been rendered before will be out of `<form>`. That was why when you render `render($form['actions'])` before `render($form)` even buttons stop working, because they are out of the `<form>` element!

# What are other solutions?

## Using HOOK\_preprocess\_hook()

As you could see we modified $content\['comment\_form'\]. You could do the same thing by using the `template preprocess function`:

```
/**
 * Implements HOOK_preprocess_hook()
 * Preprocess variables for comment-wrapper.tpl.php
 */
function THEME_preprocess_comment_wrapper(&$vars) {
  if ($vars['node']->type == 'article') {

    $form_custom_markup = '';
    $form_custom_markup .= '<div style="background-color: green;">';
    $form_custom_markup .= render($vars['content']['comment_form']['author']);
    $form_custom_markup .= '</div>';
    $form_custom_markup .= '<div style="background-color: red;">';
    $form_custom_markup .= render($vars['content']['comment_form']['comment_body']);
    $form_custom_markup .= '</div>';

    // Attach the custom markup to the form
    $vars['content']['comment_form']['custom_markup'] = array(
      '#type' => 'markup',
      '#markup' => $form_custom_markup
    );
  }
}

```

This example overrides form elements of comment form on `article` pages.

**Tip:** You should replace `THEME` with your theme name and put this function in `template.php` in you theme folder.

## Using HOOK\_preprocess\_hook()

If you trace where the element is actually generated you will get to this lines in `comment.module`:

```
$build = drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid));
$additions['comment_form'] = $build;

```

We can see this is a form with the `form_id` of `comment_node_NODE_TYPE_form`. So we could use `hook_form_alter` to alter form elements:

```
/**
 * Implements hook_form_alter()
 */
function THEME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'comment_node_article_form') {
    // Play around with $form
  }
}

```

In this example we are altering the comment form for `article` nodes.

**Tip:** Generally using `form_alter` to change the display of the form is not recommended because it also affects the `form_submit()` and `form_validate()` and may cause unwanted issues in future or conflict with other modules.

---
Tags: theming, comments
---


# Question
Title: How do I change the order of the Views row fields programmatically?
How do I change the order of the Views row fields (programmatically) not by Views UI?

E.g: the last field should come up first in the list.

Any hooks available?

**Note**: I can not use the Views UI, as I don't own the code for feature re-create, so I'm looking for some hooks.

# Answer
Go with one of Views API hooks, e.g: hook\_views\_pre\_render

You can access Views rows by `$views->result`.
> 1 votes

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


# Question
Title: How to redirect a user to a personal area of page once logged in?
I want to allow users to login to their area 'personal' and view their uploaded images/posts (basically creating an instance of the page) which is different to every user that logs in to my website --- similar to Facebook profile page which has the same layout for every user but different content in it.

So far, I have created a role called 'subscriber' (which are members of the page) and I have enabled front page module to re-direct subscribers to the 'personal' page.

I have read that the Views module is useful but I am stuck on how to do this.

# Answer
> 4 votes
From what I understand you need to redirect the user to its profile page, I mean `www.example.com/user/[USERNAME]` page.

simply install rules module and add a new rule and use this configuration for it:

In the **EVENT** select `User has logged in` and in the **Action** select this

and this is the **action** configuration

# Answer
> 5 votes
You can create a View to show the infomation that you need and with the help of the LoginToboggan module you can redirect the users to the view's url.

> The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:
>
> * Optionally redirect the user to a specific page when using the 'immediate login' feature.
> * Optionally redirect the user to a specific page upon validation of their e-mail address.

For more info about creating Views, you can read:

>

# Answer
> 3 votes
You can use hook\_user\_login to redirect different users based on a role. You will get complete user object in **$account parameter**. Check the role and redirect the user.

```
$edit['redirect'] = 'your_page_path';

```

# Answer
> 3 votes
Are you wanting to show a user all content that they have created (similar to the Facebook wall)? Or are you wanting to create a more timeline display of all content that a user's friends have created? Regardless, you're almost definitely going to want to research the heartbeat module.

If you wanted a lighter weight alternative, you could look into the flag\_friend module, plus a view that shows content for all users who are your friends.

I haven't used the D7 of these modules recently, but there are lots of tutorials about using these to create Facebook-like results.

**EDIT:** An even lighter (but not nearly as robust) option is just using views.

* For your own list of content: create a page display and add a filter by the currently logged in user.
* For content others have created: you'd probably have to add the flag module, create another page display for this list, and add a relationship and filter that uses the flag. This should show the currently logged in user only content by people they've flagged (or "liked", or "friended").

But I still think heartbeat is the way to go if you're looking for the full blown Facebook experience.

**EDIT:** For the redirect after login, LoginToboggan is the way to go.

# Answer
> 2 votes
These kind of redirect-after-login cases are typically implement using the Rules module. Have a look at the answers to these questions:

Pick the scenario that's closest to what you're trying to do, import the rule(s) (in Rules export format) that are included in these answers and tweak them a very little bit to create your own variation of it. Should take less then 5 mins or so to get the job done and (only requires site building skills).

---
Tags: redirection
---


title: Load “my blog entries” on profile pages

text:
# Question
Title: Load “my blog entries” on profile pages
I have created the view “my blog entries” which should be displayed on a user’s profile page. In terms of displaying not all but only the currently viewed user’s blog entries I have added the *Contextual Filter* called *Content: Author uid.*

In a second step I created a block, which is only present on listed pages: “profile/\*”

So now I can go to a user’s profile page (root/profile/3) and the block is enabled, the view is loaded and will load only entries from that very user.

In terms of improving SEO I used URL-Aliases to get something like this: root/profile/the-actual-user-name

For obvious reasons my view won’t work anymore. How to get it work again without the user-ID in the URL?

# Answer
For your contextual filter use **Provide default value, User ID From URL.** (this automatically extracts the uid from the url (page) and the uid does not need to be in the url).
> 3 votes

---
Tags: blocks, views
---


# Question
Title: Insert code in to field or center of content type that already has 1000's of nodes
So i'm trying to put Google Adsense in to the middle of a node of a few different content types and have tried does this in various ways but to no avail.

The latest method was to put the google adsense in to a block, which works and then use block reference module as a field, this bit works too which in turn shows the google adsense in the exact place I want it, above certain fields and next to the main body field. The problem with this method is that I want it to show on every node already created, which there are thousands of. I have used https://www.drupal.org/project/field\_defaults to select the block on that field and to force it to show on all already created nodes, but this last bit doesn't work. I still have to go through the nodes individually and add the block reference.

Another method I tried was to create a field called Google Ad Content and then add the default google adsense code, as above, this doesn't work because I have to preselect the text format to work with the google adsense code and also update all of the nodes and I end up with the same problem as above.

How else can I go about this?

# Answer
https://www.drupal.org/project/eba inserts a block in to the manage display area of each node or entity, this has allowed me to add a google ad in the middle of the content between any fields I want on any entity I want and to 1000s of already published nodes.
> 0 votes

---
Tags: nodes
---


# Question
Title: Problems getting Carousel jQuery plugin working
I am trying to get a Carousel on my site, but I am having problems.

I want to install http://www.jqueryscript.net/slider/Full-Width-Responsive-Carousel-with-jQuery-Bootstrap.html.

I have created a content item for testing this on http://xuzo.com/testing/node/26.

### *Method A*: my own stylesheets (not working)

I pasted the HTML from http://www.jqueryscript.net/slider/Full-Width-Responsive-Carousel-with-jQuery-Bootstrap.html and put it in my content item under FULL html format. I have tried to make it work with my own style sheets that I copied from the website above, I put them into my info file, and uploaded them to the server.

```
stylesheets[all][] = carrousel/bootstrap.min.css
stylesheets[all][] = carrousel/jquerysctipttop.css
scripts[all][] = carrousel/bootstrap.min.js
scripts[all][] = carrousel/jquery.min.js

```

Since I have the style sheets, I am not sure I had to use CSS injector and JS injector or not.

### *Method B*: external CDN JS styles sheets + my own style sheets (not working)

I put my own style sheets that I copied from the website above into my .info file.

```
stylesheets[all][] = carrousel/bootstrap.min.css
stylesheets[all][] = carrousel/jquerysctipttop.css

```

I linked the external CDN files in template.php.

```
 drupal_add_js('//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', 'external');
drupal_add_js('//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js', 'external');

```

The page shows up with images, but it is not working.

In CSS injector I tried this code.

```
#jquery-script-menu {
  position: fixed;
  height: 90px;
  width: 100%;
  top: 0;
  left: 0;
  border-top: 5px solid #316594;
  background: #fff;
  -moz-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
  -webkit-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
  z-index: 999999;
  padding: 10px 0;
  -webkit-box-sizing:content-box;
  -moz-box-sizing:content-box;
  box-sizing:content-box;
}

.jquery-script-center {
  width: 960px;
  margin: 0 auto;
}

.jquery-script-center ul {
  width: 212px;
  float:left;
  line-height:45px;
  margin:0;
  padding:0;
  list-style:none;
}

.jquery-script-center a {
  text-decoration:none;
}

.jquery-script-ads {
  width: 728px;
  height:90px;
  float:right;
}

.jquery-script-clear {
  clear:both;
  height:0;
}

```

In JS injector I tried this code.

```
jQuery(document).ready(function($) {
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-36251023-1']);
  _gaq.push(['_setDomainName', 'jqueryscript.net']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
});

```

I know I am missing something, but what?

# Answer
I don't see that you have add html elements with bootstrap attributes like data-target and data-slide-to. When I inspect your page and replace this:

```
<ol><li> </li><li> </li><li> </li></ol>

```

with this: (example from plugin site)

```
<ol class="carousel-indicators"><li data-target="#my<ahref="http://www.jqueryscript.net/tags.php?/Carousel/">Carousel</a>" data-slide-to="0" class="active"></li><li data-target="#myCarousel" data-slide-to="1"></li><li data-target="#myCarousel" data-slide-to="2"></li></ol>

```

I get dots that actually work.
> 2 votes

# Answer
Try:

```
    (function ($) {
             $( document ).ready(function() {
              var _gaq = _gaq || [];
              _gaq.push(['_setAccount', 'UA-36251023-1']);
              _gaq.push(['_setDomainName', 'jqueryscript.net']);
              _gaq.push(['_trackPageview']);

               (function() {
                var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
              })();
            });
    })(jQuery);

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: A View listing Multiple Locations and each Location having it's Own Map
I am using Google Store Locator for to list a locations, I have a use case where some of the locations have special events. I want a small map next to each listing.

I've added some items to the Store Location content type to select if that location is having an event with some other fields relevant to the event.

With that, I've created a view that shows everything I need, except for a small map of the location next to the event listing. You can see what I'm going for here:

I'm stuck on how to add the map. I know I have the location information I need in the content type, but there doesn't seem to be any "map" format I can use in the view. I'm assuming I'll need another module or something custom.Looking at OpenLayers, it looks like it adds multiple markers to one map like a lot of the other solutions, anyone know if it can do what I'm asking?

The map doesn't need to be interactive, I'd take a static image that linked out the the location in Google maps.

# Answer
> 0 votes
I was able to use the Address Field Static Map module to get this taken care of.

Since I was already capturing the address in the content type, after installing the Address Field Static Map Module, I could add another 'location' field to my View and select the 'Address Field Static Map' field formatter and customize as needed from there. The module even provided an option for linking out to the location in Google Maps.

To use this, the Address Field Module is a dependency.

This gave me the exact thing I needed.

---
Tags: location, google-maps, views
---


# Question
Title: What is the entity ID for private messages?
I want to access some private messages using `entity_load()` but I don't know what the entity ID is to call them by. I have the message ID (mid) but that doesn't appear to work.

I'm attempting to load an individual message like this:

```
      $message_entity = entity_load('privatemsg_message', array($row['mid']));

```

And this is how Private Message declares `hook_entity_property_info()`.

```
/**
 * Implements hook_entity_property_info().
 */
function privatemsg_entity_property_info() {
  $info = array();
  // Add meta-data about the basic node properties.
  $properties = &$info['privatemsg_message']['properties'];
  $properties = array(
    'mid' => array(
      'type'  => 'integer',
      'label' => t('Private message ID'),
      'description' => t('Private message ID'),
    ),
    'thread_id' => array(
      'type'  => 'integer',
      'label' => t('Private message thread ID'),
      'description' => t('Private message thread ID'),
      'getter callback' => 'entity_property_verbatim_get',
    ),
    'author' => array(
      'type'  => 'user',
      'label' => t('Private message author'),
      'description' => t('Private message author'),
      'setter callback' => 'entity_property_verbatim_set',
    ),
    'subject' => array(
      'type'  => 'text',
      'label' => t('Private message subject'),
      'description' => t('Private message subject'),
      'setter callback' => 'entity_property_verbatim_set',
    ),
    'body' => array(
      'type'  => 'text',
      'label' => t('Private message body'),
      'description' => t('Private message body'),
      'setter callback' => 'entity_property_verbatim_set',
    ),
    'timestamp' => array(
      'type' => 'date',
      'label' => t('Private message sent date'),
      'description' => t('Private message sent date'),
    ),
  );
  return $info;
}

```

How do I get the entity ID for private messages? Is that different than the message ID (mid) or thread ID (thread\_id)?

# Answer
It turns out **mid** is correct, but for whatever reason `$row['mid']` was returning a string, not an int. Type-casting the string as an int solved the problem.
> 2 votes

---
Tags: 7, entities, privatemsg
---


title: Loop through all nodes with rules

text:
# Question
Title: Loop through all nodes with rules
I have a content type (called **Contact List**) and by using Rules module I want to check if there is a specific phone number in my nodes, I get the node id and use it in the other content type (called **Products** which has an *Entity Reference* field that point to the **contact list**).

if not and it can't find any entries I create a **contact list** node.

Certainly the phone number field is unique.

How can this be done with Action loop?

As in the picture depicted I need to add some functionality that check the Contact list existence to prevent duplication.

# Answer
> 2 votes
Sounds like a case for the Rules action:

"Fetch entity by property"

It will allow you to load another entity using a particular value, such as phone number.

---
Tags: 7, rules, entities
---


title: Get user ID for database insert

text:
# Question
Title: Get user ID for database insert
I have a form inserting into a database in Drupal 8. I would like to insert the user id. I have the following code:

```
$userCurrent = \Drupal::currentUser();
$uname = (int)User::load($userCurrent->id());

```

Without the (int) Drupal throws an error saying it cannot be converted into a string. With the (int) Drupal always returns 1. What am I doing wrong?

UPDATE: As stated I would like the user ID not the user name. Sorry if it doesn't make sense, I am very new to Drupal and there is not a lot of documentation for 8 yet.

# Answer
> 0 votes
Do you want to get the username, as the variable name suggests?

```
$uname = User::load($userCurrent->id())->name->value;

```

Your question does not make sense, why load the user with the id to get the id, you already have?

---
Tags: users, 8
---


# Question
Title: DB connection works from the CLI, but fails from within Drupal
I have set up a MySQL server on a machine with IP-address `192.0.2.9` (not the real address). The database user is named "drupal". Connecting to it using the CLI *mysql* command works just fine and the connection is accepted.

```
mysql -u drupal -p -h 192.0.2.9
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
...

```

However, when Drupal tries to connect to the *same* MySQL server from the *same* host, using the *same* credentials, I get this error:

```
PDOException: SQLSTATE[HY000] [2003] Can't connect to MySQL server on '192.0.2.9' (9)
in lock_may_be_available() (line 167 of /var/www/html/includes/lock.inc).

```

I have double checked that the correct database credentials and host are set in `settings.php`. I am at my wit's end, unable to figure out why this database connection works from the CLI, but not from within Drupal.

In case it matters: This is Drupal 7.41 and the OS on both machines is RHEL7.

# Answer
> 2 votes
Figured it out!

The client computer was running SELinux and was blocking outgoing connections over http. This pair of CLI command fixed it.

```
setsebool httpd_can_network_connect 1
setsebool -P httpd_can_network_connect 1

```

---
Tags: 7, database
---


title: Changing published revision

text:
# Question
Title: Changing published revision
I'm trying to published revision for a node, while saving. Currently D8 manage revisions, but the last revision is always the "published" revision.

I'm using hook\_entity\_presave, but I can't find a method to do this.

Some suggestions?

# Answer
The last revision is always the one that will be used throughout the site. So if it is published then it will be shown. You cannot have one revision published and working on another revision that is not published yet.

Although maybe you can edit an older revision(make sure you do not tick the "create new revision" option while editing) and then, via revision overview, make it the current revision.

If you want to change the status of node(not any entity, only node entity) programmatically than you can call the $node-\>setPublished(TRUE) or $node-\>setPublished(FALSE) methods.
> 0 votes

---
Tags: 8, nodes
---


title: "Global" List (Float)?

text:
# Question
Title: "Global" List (Float)?
Assume I have a content type with a list field (float) that can contain the following values: a, b, c. I created three nodes (A, B, C) with those field values.

Creating a new node, is there a way to *auto clear/remove* already existing values in older nodes?

For example, if I choose *a* in a new node, I want that in node *A* that value is removed.

The Unique Field module does the job of preventing duplicated values, but it doesn't allow to remove values from other nodes.

# Answer
I found a solution: use a field group (Field Group) of booleans and set them as exclusive values (Exclusive value).
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: Restrict what content can be added to a panel page (using panels & organic groups)
We are using Organic groups and Panels with Drupal 7.

We want each group to have one panel node (that is, a node which content type is "Panel"). The group administrator can then use different kind of layouts and display existing content.

I created two groups A and B. I also created panel node (a node which content type is "Panel") for each group and some nodes that belong to group A and some nodes that belong to group B

Now, when admin of group A edits the panel node's content (through a tab "Panel content") of group A and selects Existing node when adding content to a panel pane, he can choose nodes that belong to group B. Is there a way to make panels respect OG access control? So that group A admin could not select contents of group B to be displayed in a panel pane of group A.

The content in the groups still need to be public so that if anonymous user visits content belonging to each group he will be able to see them.

# Answer
> 1 votes
I guess that by:

> when admin of group A edits the panel page

you mean edit the group's node that is being viewed through a panel,and not that he can edit the panel's settings, and when you're saying

> selects Existing node when adding content to a panel pane

you mean that selects content through field (entity-reference). That said, you don't need to make panels respect OG permissions -I am not sure if that's possible- but to filter out the content showing in that field based on Group A or B. To achieve that you may use field\_get\_items, see the contents of the field and check which node belongs to which group (every node belonging to a group has a Group id (gid) by that gid you can node\_load the group node and access its fields) and configure set/unset the field's values accordingly or even you may use hook\_form\_alter to do so.

---
Tags: 7, panels, organic-groups
---


# Question
Title: Create a new personal page instance for each user
I have a content type named 'personal' and a node (page) also called 'personal' which is of that content type.

I want my users to have their own private 'personal' page on my website where every user can post their own private stuff. Like a blog page where the page layout is the same for everyone but each user has their own posts on their profile page.

I am trying to achieve something like www.mywebsite.com/personal/username (or www.mywebsite.com/username/personal)

I am using the Rules module but each user is still getting re-directed to the one and only 'personal' page I have created.

# Answer
> 2 votes
## You can create new Views page like this:

Let me explain underlined options:

**Path: personal/%** \- let you to create dynamic path. In addition "%" sign is a wildcard used by contextual filter;

**Relationships \> Content:author** \- this relationship is required by filters to show only nodes created by its author. Without this we would be able to filter only by user ID.

**Contextual Filters \> User:name** \- this is value of URL wildcard. It allow you to filter nodes by put any user name instead of % sign. For example: www.mywebsite.com/personal/john

**Filter Criteria \> Current User (Yes)** \- It shows only nodes created by current logged in user. Without this filter anyone can put any user name in url and see content created by this user.

Let me know if something is not clear to you.

---
Tags: nodes, rules, users, redirection, path-aliases
---


# Question
Title: Best way to keep local and remote sites synchronized?
I run the same drupal site on a local server (i.e. my mac with mamp) and on a remote server (i.e. my hosting provider). I want to keep the two sites synchronized. My hosting provider does not allow ssh keys. I have already tried the drush aliases way, but with no success at all - I keep getting the message "no alias record could be found for source @.... So please, my question is this: What is the best and easiest way to keep the two versions (local and remote) of the same site synchronized?

# Answer
> 0 votes
For your case (no SSH, no drush, no Git) I would suggest the following methods

* Configuration Management module.

> The configuration management module enables the ability to keep track of specific configurations on a Drupal site, provides the ability to move these configurations between different environments (local, dev, qa, prod), and also move configurations between completely different sites (migrate configurations) without the use of modules with all configuration being owned by the site.
* Backup and Migrate module.

> Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.

"Configuration Management" module is useful when you are testing and altering node types, fields, views etc. and you just want to send you final changes to production (and the reverse).

With the "Backup and Migrare" module you can backup-restore (and schedule that) the whole or parts of the database and files. You can also utilize the excellent free service NodeSquirrel. You create the backup profiles according to your needs, save to NodeSquirrel, just restore from NodeSquirrel on your local server (and the reverse).
*Beware: restoring a database with "Backup and Migrate" does not clean or drop the previous database tables issue*

In case you are codding custom modules and themes OR you are updating core / modules AND you want an easier way to upload only the updated / changed files: I would suggest the Beyond Compare software. It does a excellent and fast compare / diff job with local - remote FTP folders. \[1\]
*I am not in any way affiliated with the company. You can also try other comparing tools.*

Edit:

* You can also try the stage file proxy module suggested by @Saphyel
* \[1\] Since you are using a Mac, you can also try the free software Cyberduck or FileZilla which both have "compare folder" capabilities. They are not the same as a dedicated compare/diff tool but they are free to use and they may be good enough for what you need.

# Answer
> 0 votes
For executing drush commands on others server you should have access via SSH, and you only have access via FTP. Your best option I think is doing every day on production a backup and download it and then in your local machine: **drush sql-cli \< db.sql** or **mysql db \< db.sql**

Maybe you can use the module stage\_file\_proxy so you don't have to copy files

# Answer
> 0 votes
I have same situation I use

module Webservice and view Data Export or Feeds at local Mac when i create new content offline it stock in my database local. i use CURL to detect if i have connection internet to server web if my connection is ready my cron will post new content from local to my web site via webservice REST. when i create new content from my website. my local can receive via RSS or view data export

---
Tags: drush
---


title: display image inside a panel

text:
# Question
Title: display image inside a panel
I have a small `jpeg` image that I want to display in a panel.

I created a panel with the layout I desired but I am confused as how can I display an image inside one of the columns of the panel.

I tried adding a new custom content in which it presents a html text area. But not sure how would I add the correct `url` without hard coding the entire path (i.e: the host and sub directory etc).

Please enlighten me :)

# Answer
You can use custom content option in panel to add HTML...

Step 1 : Click on Add Content

Step 2 : Click on New Custom Content

Step 3 : Add HTML and select filter as Custom HTML

Step 4 : Save Changes
> 1 votes

# Answer
You can insert any kind of content within panels using fieldable panels panes module. It can be used to create custom fieldable entities which can be dropped inside panels. For example usage, check the Panopoly distribution.
> 0 votes

# Answer
Make a page-panel for localhost and add your content in the panel

Make a variant on the panel for Live and add your content in the panel.

Make use of a selection rule (e.g. php with string localhost) for selection the correct variant.
> 0 votes

# Answer
I had similar requirement but in addition to add an image, I needed an *Image Link*.

1. After having the entire *Panel* working, I installed Fieldable Panels Panes and Link Image Field modules.
2. Then I access the *Fieldable Panels Panes* configuration, choose the option *Panels Pane* and add an *Image Link field*.
3. Go to *Panels Page* and pick up the page that you want to add the *Image* or *Image Link*.
4. Access the *Content Page tab* and Add a content region. Choose the *Fieldable Pane* and add your image.

Hope this help.
> 0 votes

# Answer
make a contentype called 'image', add an image field to contentype, add a node type 'image', upload your image to your node, add a view displaying content and displaying fields, add your image field, filter by contenttype 'image' your node (only the image) will appear in the view, add the view in your panel. This way you can show your image in other panels also.
> 0 votes

# Answer
To add a single static image, you have to add a Custom Content Pane and using the `img` tag and provide the path of the image.

There is no need to add the absolute path of the image. You can give the path of the image as :

```
<img src="/sites/default/files/office.jpg" />

```

I hope this will work.
> 0 votes

---
Tags: media, panels
---


# Question
Title: How to Group fields, and duplicate them?
I'm trying to create a type of buzz feed website where you can make a list of items.

If you set the body field setting to unlimited. You get a "Add item" button.

You can duplicate the body field as many times as you want.

I want to duplicate a set of fields using the "Add item" button

title, image, description as one item.

How can I do this?

# Answer
> 2 votes
You can also go for the Multifield module. More details from its project page:

> This project seeks to provide a true compound field solution for Drupal 7. As much as I love Field collection, it still has to save actual entities, and can cause performance problems due to having to load all the referenced field collection entities on node, or parent entity load.

How to use multifield check listed links :

# Answer
> 1 votes
You can do it by using these modules:

Field Group

> Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.
>
> The field group project is a follow-up on the field group module in CCK. The release will only exist for Drupal 7 release and higher, so since the existence of the Fields API in core. By moving field group to a separate module, this may open some new perspectives.

Field Group Multiple

> This module extends the Field group module by displays and widgets which group multiple fields by there items.
>
> Grouping types:
>
> * Multiple fields container
> * Multiple fields table
> * Multiple fields as label-value

---
Tags: entities
---


title: How to list user flags in node

text:
# Question
Title: How to list user flags in node
I have a node that people can flag to indicate their attendance/interest in that node's activity. However, I would like to show a list of users who have flagged a given node on that node's page. While I can find a way to show a user's current flag state or a flag count for that node in a view, I can't find a way to do this for the node representation itself.

# Answer
> 5 votes
You can relatively easy do that by adding a views contextual filter for the node id (`nid`) with the following configuration:

* *When the filter value **is NOT in** the URL*: `Provide default value -> Content ID From URL`
* *When the filter value **is IN** the URL or a default is provided*: `Specify validation criteria ->` Your CTs list
* *Filter value format*: `Node ID`
* The flag relationship used should be: `by any user`

Of course you can use that view as a block and place it wherever you like.

# Answer
> 2 votes
As said by mchar, it can be done easily using views.

1) Create a view by selecting your content type.

2) Under Relationships in Advanced tab, select Flags (flag name) by any user and (flag)Flags:user

3) In fields tab, Add user name field and Flag user as relationship.

Hope it will work for you.

---
Tags: nodes, flags
---


# Question
Title: How to update custom user field on form submit
I want to create a basic page that has only one of my custom user account fields listed, and available to edit.

For example, I have a custom user account field: field\_companyname

Rather then directing the user to go to `www.example.com/?q=user/1/edit`, I want the user to go to a different page (i.e `www.example.com/node/5`). On this page, there should only be a single text input field, and a submit button to save the new data to the user account.

I'm pretty sure I need to implement `user_save()`, but I just don't know where to go from here.

```
// load user object
$existingUser = user_load('USERID');

// update some user property
$existingUser->some_property = 'foo';

// save existing user
user_save((object) array('uid' => $existingUser->uid), (array) $existingUser);

```

Any help or pointers would be much appreciated. Thanks for looking!

**EDIT: I was able to load the entire user account edit form onto a node using the following code:**

```
<?php
  module_load_include('pages.inc', 'user', 'user');
  global $user;
  $account = user_load($user->uid);
  $output = drupal_render(drupal_get_form('user_profile_form', $account));
  return $output;
?>

```

However, I still cannot figure out how to display ONLY my single custom field. Any help is greatly appreciated.

**EDIT #2: I used CSS to hide the other fields that I did not want to display. Seems like there should be a better way to do this. But I guess this will work for now, unless anyone else can chime in :-)**

Thanks again for looking.

# Answer
Use field\_attach\_form in your page with the field name and user object. You can use field\_attach\_form\_validate and field\_attach\_submit to validate and submit the values.
> 1 votes

# Answer
Use hide() function hide unnecessary fields. You can hide form field like:

```
hide($form['field_name']);

```

Implement hook\_form\_FORM\_ID\_alter() to do your magic with a hide() function
> 0 votes

---
Tags: 7, users
---


title: Truncate some part in URL field

text:
# Question
Title: Truncate some part in URL field
I have created a view that consist of *username* field and *URL* field. URL is like https://www.example.com/video/video\_id.

When I add the URL field, it shows the full URL; I want to display only the video\_id.

How can I do this?

# Answer
There are two possible solutions for this;

1. You can simply make a `.tpl` file of view and use following code to extract only *video\_id* from *URL* field.

```
$url = "YUOR_URL_FIELD";
$vid = explode('/',$url);
echo $vid[count($vid)-1];

```
2. Use the Views Php module and add a *php field* after the *URL* field, then use this code to just show the *video\_id* from *URL*.(It also needs token module to be enabled)

```
$url = "USE_YOUR_FIELD_TOKEN";`
$vid = explode('/',$url);
echo $vid[count($vid)-1];`

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to login to an external website after drupal-login?
I would like know how I can login my user to an external website after drupal-login please ?

I use :

```
    $xenAPI = new XenAPI('http://xen.dev/api.php', 'MY_API_KEY', 'MY_API_KEYSALT');
    $xenAPI->login('Kyna', 'secret_password', 'http://theming.dev');

```

The login work on all page when I use HOOK\_user\_load(), but if I use HOOK\_user\_login(), don't work. I don't have an error, but -\>login() create a redirection with an header and I think drupal-login overwrite my header on external script or create a redirection before my script.

# Answer
> 0 votes
Yes, the login form has a redirection(see the `\Drupal\user\Form\UserLoginForm::submitForm()`), so you need to remove that redirection with `$this->getRequest()->query->remove('destination')`.

---
Tags: 8, redirection
---


title: Assign role based on purchased products

text:
# Question
Title: Assign role based on purchased products
I'm using the Drupal Commerce, Checkout redirect and Auto assign role modules.

When a checkout is completed by an anonymous user on a Drupal Commerce website a Drupal account will be created.

If there is only one product everything is ok, but what happen when there are many products?

How can I make it so that:

* If a user buys "Product 1" I will be auto-assing a role "Role 1"
* If a user buys "Product 2" I will be auto-assing a role "Role 2"

Could anyone solve this question?

# Answer
> 0 votes
I needed something similar: user purchased an item (points) and depending on the purchased product a value (points) should be added to the user profile. The rule below is ready to accept (loop through) multiple products/lineItems. In my case I only need the first one:

```
 "value" : [ "commerce-order:commerce-line-items:0:line-item-id" ],
        "limit" : "1"

```

First I fetch the purchased products (line items) by property (line\_item\_id). The result is an array (list of purchased products).

Next you need to loop through this array/list and add the desired action to the individual/current purchased product. If you need a condition (product 1 -\> role 1) you can use conditional rules. It is an awesome rules addon that lets you insert IF conditions within loops (so you dont have to create a component that checks the product).

```
{ "rules_purchasing_points" : {
"LABEL" : "PURCHASE Points",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_payment" ],
"ON" : { "commerce_payment_order_paid_in_full" : [] },
"DO" : [
  { "entity_query" : {
      "USING" : {
        "type" : "commerce_line_item",
        "property" : "line_item_id",
        "value" : [ "commerce-order:commerce-line-items:0:line-item-id" ],
        "limit" : "1"
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "entity-fetched" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "data_convert" : {
            "USING" : { "type" : "decimal", "value" : [ "list-item:line-item-label" ] },
            "PROVIDE" : { "conversion_result" : { "conversion_result" : "Conversion result" } }
          }
        },
        { "component_rules_set_points" : {
            "recipient" : [ "site:current-user" ],
            "sender" : "1",
            "points" : [ "conversion-result" ]
          }
        },

```

---
Tags: commerce, redirection
---


title: Ajax function not returning any html

text:
# Question
Title: Ajax function not returning any html
I'm trying to develop an Ajax process in a Drupal Module. Here's the code :

```
function My_Module_menu() {
  $items = array();

  $items['route/to/ajax/%'] = array(
    'page callback' => '_MY_MODULE_processing',
    'page arguments' => array(3),
    'type'  => MENU_CALLBACK,
    'access arguments' => array('acces content'),
    'delivery callback' => '_MY_MODULE_listing'
  );

  return $items;
}

function _MY_MODULE_processing($region='110') {

  // Executing some operations to retrieve a list of NIDs
  // retrieving the nodes
  $nodes = node_load_multiple ($nidList);
  return ($nodes) ;
}
/**
 * Here is the templating part
 * @param unknown $nodes
 */
function _MY_MODULE_listing ($nodes){
  $build = array();
  $nodeList='';
  foreach ( $nodes as $node ) {
    $nodeList = $nodeList.'<option value='.$node->nid.'>'.$node->title.'</option>';
  }
    $build['content'][]=array(
      '#prefix'=>'',
      '#suffix'=>'',
      '#markup'=>$nodeList,
    );

  return ($nodeList);
}

```

I don't get any response with this. I've run debugging function and it goes inside every function. First `_MY_MODULE_processing` then `_MY_MODULE_listing`.

How can i return a correct response ?

# Answer
Got it. I returned the answer with ajax\_deliver :

```
function mij_add_aide_list_proposition($nodes){
    // Magic stuff goes here (construction of $nodeList)
    $build['content'][]=array(
      '#prefix'=>'',
      '#suffix'=>'',
      '#markup'=>$nodeList,
    );

  //$test=drupal_render($build);
  ajax_deliver($build);
}

```

If someone finds another way, I'm open to any change !
> 0 votes

---
Tags: ajax
---


# Question
Title: Can the Devel Generate module generate content for all possible permutations and combinations?
I love the Devel Generate module as it helps me to create test content very quickly. Random content that the module generates is sufficient most of the times.

But at times I would like to have content for all the permutations and combinations. For example let us say that a content type has three optional fields. So in total I would like to have 8 nodes of that type created that cover all the permutations.

Is this something that can be achieved with the Devel module?

# Answer
To my knowledge there is no such feature in the Devel Generate module.

Therefor, as an alternative, I recommend to use a (rather basic) custom module for creating such nodes (so without using Devel Generate).

The article about How to programmatically create nodes, comments and taxonomies in Drupal 7 contains great example of how to do so. Here is a summary of that article (about how to programmatically create a node):

> * Initialize a node object
> * Add body field
> * Add custom fields
> * Add file / image field
> * Add a term to a node
> * Save a node

You probably don't need the "add file" and "add term", and simply have to repeat the "add custom fields" a few times (for each of your 3 fields), and then "you" are in full control of which permutations/combinations you actually want.
> 3 votes

---
Tags: testing, debugging
---


# Question
Title: How to create a main menu with dropdown?
I want to create a main menu with dropdown. There will be collapsed links in each menu heading. When the user hovers over one heading, links accompanied by that header will be displayed in a box.

I first tried to add node and give them parent nodes. For example, I have created a node with title called "Lorem" and created another with title called "Ipsum". I have provided both of them a menu link. I have set the "Lorem" node as the parent node of "Ipsum". But it seems like "Ipsum" doesn't appear in "Lorem"'s content of its menu link.

Is there any way to look up the links' child elements? For example:

```
dpm($main_menu);

```

This doesn't yeild me neither the link that connected to "Ipsum" or the "Lorem"'s child links. How can I see the "Lorem"'s child link? Or where it is?

If I can find it, I can override the `theme_links` and create dropdowns.

# Answer
> 0 votes
You need to use any of this module

Nice Menus

> Nice Menus enables drop-down/right/left expandable menus. It uses only CSS for most browsers, with minimal Javascript for IE6.

Superfish Menu

> You will see several blocks called Superfish", move any of them to a region, use the "Configure" link of the block to configure it accordingly to your needs, and save.

Responsive Dropdown Menus

> > Responsive Dropdown Menus provides a new menu tree rendering to make responsive, drop-down enabled main menu possible on any theme.
>
> ```
> Provides new menu blocks for each menu.
> All module blocks add dropdown menu support and responsive menu toggles.
>
> ```

Megamenu

> Mega menus are a type of drop-down, which seeks to overcome some of the usability drawbacks of traditional drop-downs. Hierarchy of your navigation is made visible all at once and the amount of clicking, searching, and navigating is reduced.

---
Tags: navigation
---


# Question
Title: Ajax %-wildcard URL giving 404 error when setting a parameter
I have a page with a dropdown. When you click on that dropdown that content is loaded by Ajax. I would like to do the same for the **Breadcrumb**, so I created an Ajax-URL in my module:

```
function selectexamfeature_menu() {
  $items = array();
  $items['selectexamfeature/ajax-replace-breadcrumb/%'] = array(
      'title' => 'Ajax-Callback for replacing breadcrumb',
      'page callback' => 'selectexamfeature_ajax_callback',
      'page arguments' => array(2),
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK,
  );
  return $items;
}

function selectexamfeature_ajax_callback($url){
  $commands = array();
    // later on the $url will be used here for generating the breadcrumb html
  $ret = $url;
  $commands[] = ajax_command_html('.page-breadcrumb', $ret);
  $page = array('#type' => 'ajax', '#commands' => $commands);
  ajax_deliver($page);
}

```

and in my Javascript code I have:

```
  var custom_settings = {};
  custom_settings.url = '/selectexamfeature/ajax-replace-breadcrumb/SOMELINKASSTRING';
  custom_settings.keypress = false;
  custom_settings.prevent = false;
  Drupal.ajax['custom_ajax_action'] = new Drupal.ajax(null, $(document.body), custom_settings);

  Drupal.behaviors.selectexamfeature_ajax_replace_breadcrumb = {
    attach: function (context, settings) {
      $( "#edit-field-text-grade-tid" ).change(function() {
        // the event...
      });
    }
  };

```

So at the end I want to get the `SOMELINKASSTRING` in my `$ret` variable. But for now I just get a 404 error all the time:

> An AJAX HTTP error occurred. HTTP response code: 404 Debugg information follows: /selectexamfeature/ajax-replace-breadcrumb/SOMELINKASSTRING Statustext: Not Found...

I believe the issue is in the wildcard section. Somehow it does not replace it correctly.

If I leave the `%` away and also the `SOMELINKASSTRING` it works without issues. But I for sure need the parameter to know which page is requested.

Also watch this awesome article but it did not help either.

# Answer
I solved it with drupal hooks. So I use an already existing Ajax trigger.

```
function selectexamfeature_theme($existing, $type, $theme, $path) {
  return array(
    'breadcrumb' => array(
      'template' => 'breadcrumb',
    ),
  );
}

```

and

```
function selectexamfeature_views_ajax_data_alter(&$commands, $view) {
 ...
 // building the url variable
 ...
 $vars = array();
 themename_generate_breadcrumb($vars);
 $markup = theme('breadcrumb', array('breadcrumb' => drupal_get_breadcrumb()));
 $commands[] = ajax_command_replace('div.page-breadcrumb', $markup);
}

```

This works as intended.
> 0 votes

# Answer
If the form is part of a standard Drupal form, you can use Drupal's built in AJAX system. There is a detailed explanation here: Ajax Forms in Drupal 7. Basically it should look like this.

```
function hook_some_form($form, &$form_state) {
  // Create a frop down
  $form['some_select'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => $default,
    '#ajax' => array(
      'callback' => 'some_ajax_callback', // This is the php function to be called
      'wrapper' => 'some_wrapper', // The javascript #id to put content in.
      'method' => 'replace', // Content placement option
    ),
  );

  // Result contents container
  $form['some_wrapper'] = array(
    '#type' => 'item',
    '#id' => 'some_wrapper',
    '#tree' => TRUE,
  );
}

```

And for the PHP callback

```
function some_ajax_callback($form, $form_state) {
  // Fetch the value AJAX gave us.
  $value = $form_state['values']['some_select'];

  // Recreate the wrapper as we overwrite the old one.
  $form['some_wrapper'] = array(
    '#type' => 'item',
    '#id' => 'some_wrapper',
    '#tree' => TRUE,
  );

  // Append the value of the drop down to it.
  $form['some_wrapper']['value'] = array(
    '#type' => 'item',
    '#markup' => check_plain($value);
  );
  // Return everything to Javascript.
  return $form['some_wrapper']
}

```

This allows you to pass form values to PHP for processing.
> 2 votes

---
Tags: ajax, routes
---


# Question
Title: Using View to List a Member's Organic Group with Inherited membership
I am looking to create a view which will return any content a user has membership to.

Following steps from another post, I managed to return content which matches users membership. But this doesn't take into account content where membership is inherited. So a node which is linked to another node's audience doesn't appear in the view. Steps taken:

* Add new view. `Show -> OG membership` (***important!***)
* Then in some display add a contextual filter:

`OG membership: Entity id.`

Provide default value: `Type -> User ID` from logged in user
* Next to get the actual titles of the groups (as the base table is OG membership, not node),
* Add a relationship -\> `Group Node from OG membership`.
* Add a field -\> `Content: Title. Relationship` -\> Group node from OG membership.

Using Views to List a Member's Organic Groups (7.x-2.3)

# Answer
> 0 votes
After digging around in the default views, I found a work around for my problem.

I cloned the view **OG User groups (OG membership)** which is normally attached to the user profile. I then filtered content against some custom fields to resolve my problem.

Its a work around admittedly, but I would advise people to check some of the other default views or the og\_extras module for additional views.

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


# Question
Title: How to group facets (Facet API) by day for date fields?
How to group facets (Facet API) by day for date fields?

Currently I have a custom date field indexed by Search API Solr.

I want to group this values by day, for example:

> Friday 26 june
>
> -08:30
>
> -08:45
>
> Saturday 27 june
>
> -08:30
>
> Sunday 28 june
>
> -08:30

# Answer
> -1 votes
Use the numeric\_groups module. It is a sandbox project.

---
Tags: search
---


# Question
Title: How to expose Profile2 fields in Services?
Is there a good solution to CRUD a user's Profile2 fields via Services? I assume this can be done with Services Entity API, but I wonder if there is a more direct integration?

With Services Entity API, I enabled the `entity_profile2` resource and can load an index of profiles. I need to disable the ability to index the profiles but allow a user to retrieve their own profile.

From the docs, this URL should be able to find user with uid=296's profile:

`api/entity_profile2.json?parameters[uid]=296`

But the result is an empty page.

# Answer
> 1 votes
I found that I had to use pid: `/api/entity_profile2?parameters[pid]=1`

# Answer
> 0 votes
For anyone still looking for this, I had to enable the index option (not just retrieve), and create an alias (without a number in it) under entity\_profile2 for this to work.

# Answer
> 0 votes
Neither of the above answers worked for me. Hitting `api/entity_profile2.json`, whether you add query parameters or not, is going to get the index of profiles, which you will have switched off and therefore will return a 404 "resource not found" error. You need to hit the retrieve route with an id like with all other services, but you'll need to get the profile id first. You want to **`GET api/entity_profile2/1.json`**, where 1 is the profile id- not the user id.

It is possible of course to get the index and then filter down based on uid, but this isn't the best RESTy option and seems a bit convoluted. Also, a big issue is that when you hit `api/user/1.json` (for example), it doesn't give any details about user fields, including any associated profile2 profile ids.

I decided the best way was to hook into the service call postprocess in a custom module and add the profile2 data to it. You could either add just the profile ids to the user object, then from that use the entity\_profile service as mentioned above, or you can just tack the whole entity onto the user object and not have to even bother with services\_entity at all. Code as follows:

```
function mymodule_services_request_postprocess_alter($controller, $args, &$results) {
  if (isset($results->uid) && $results->uid > 0) {
    $profile2 = profile2_load_by_user($results);
    if ($profile2) {
      $results->profile2 = array_values(profile2_load_by_user($results));
    }
  }
}

```

... which results in something like this when getting `api/user/1.json`

```
{
  "uid": "1",
  "name": "admin",
  "mail": "admin@example.com",
  "theme": "",
  "signature": "",
  "signature_format": null,
  "created": "1441810121",
  "access": "1450698782",
  "login": "1450695398",
  "status": "1",
  "timezone": "UTC",
  "language": "",
  "picture": "0",
  "init": "admin@example.com",
  "data": false,
  "uuid": "82919e2f-e431-44e6-b4b1-8d13c5555c94",
  "roles": {
    "2": "authenticated user"
  },
  "profile2": [
    {
      "pid": "1",
      "type": "main",
      "label": "Main profile",
      "uid": "1",
      "created": "1450696479",
      "changed": "1450696479",
      "field_first_name": {
        "und": [
          {
            "value": "Matt",
            "format": null,
            "safe_value": "Matt"
          }
        ]
      },
      "field_last_name": {
        "und": [
          {
            "value": "Fletcher",
            "format": null,
            "safe_value": "Fletcher"
          }
        ]
      }
    }
  ]
}

```

How you format it is up to you of course, there are many ways of doing things; but this was the easiest method for me and doesn't require as many REST calls as other solutions :)

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


# Question
Title: Driver not specified for this database connection
I want to connect to external database:

```
$old_database = array (
        'default' =>    array (
                'database' => 'grantexpert_registration',
                'username' => 'grantexpert_usr',
                'password' => 'xxxxxx',
                'host' => '62.168.127.59',
                'port' => '5432',
                'driver' => 'pgsql',
                'prefix' => '',
        ),
);

Database::addConnectionInfo('olddatabase', 'default', $old_database);
db_set_active('olddatabase');

```

But Im getting an error:

> Driver not specified for this database connection: olddatabase in Database::openConnection()

All the examples show exactly this structure of array, but it's not working. Is smoething wrong here?

# Answer
You've already provided the target DB name with the second param to `addConnectionInfo()`, so you just need to remove the 'default' element from the array, and shift the connection params up:

```
$old_database = array (
  'database' => 'grantexpert_registration',
  'username' => 'grantexpert_usr',
  'password' => 'xxxxxx',
  'host' => '62.168.127.59',
  'port' => '5432',
  'driver' => 'pgsql',
  'prefix' => '',
);

Database::addConnectionInfo('olddatabase', 'default', $old_database);
db_set_active('olddatabase');

```
> 3 votes

---
Tags: database
---


title: convert 2 select in db_select

text:
# Question
Title: convert 2 select in db_select
I have this query in SQL

```
select *
from node n, node_collection_data nc
where n.nid = nc.nc_child_nid
and
nc.nc_parent_nid = (select nc_parent_nid
from node_collection_data
where nc_child_nid=17)

```

This is what I got so far:

```
 $query -> join('node_collection_data', 'nc', 'n.nid =
 nc.nc_child_nid'); $query->condition('type', $node->type)
       ->condition('status', 1)
       ->condition('n.nid', $node->nid, '!=')
       ->condition(db_or()
       ->condition('n.language', array($language->language, LANGUAGE_NONE), 'IN')
         ->condition('n.language', $node->language, '=')
       )
       // get nc_child_id
       //->join('node_collection_' . $sort, $sort, 'n.nid = ' . $sort . '.nc_child_id')
       ->fields('n', array('nid', 'title'))
       ->fields('nc',array('nc_parent_nid')) // select nc_parent_id

```

I am trying to convert the last part.

```
nc.nc_parent_nid = (select nc_parent_nid from node_collection_data where nc_child_nid = 17)

```

How can I convert it to `db_select()`?

# Answer
> 0 votes
You need to search for db\_select using subquery.

Look the below links to get some idea.

Using db\_select with subqueries

db\_select condition with subquery

# Answer
> 0 votes
Put your subquery in a variable like

```
$subquery = "(select nc_parent_nid from node_collection_data where nc_child_nid = 17)";

```

And then use it with addExpression function in your main query

```
$query->addExpression($subquery, 'sub_query');

```

Use the following debug function to check your query

```
dpm((string) $query);
dpm($query->arguments());

```

---
Tags: database
---


# Question
Title: How do I skip validation for node form element?
I have a content type having 10 fields that are all required. How do I skip validation for some fields? Is there any hook/function that allow me to do this?

# Answer
I consider that by

> How do I skip validation

you mean "make the fields not compulsory" (UI level)

If that is the case then you can use hook\_form\_alter and change the `['#required']` setting, for any form element, to `FALSE`.

Keep in mind that hook\_form\_alter is a generic hook invoked by any form in your site (performance issue) alternative you may use hook\_form\_FORM\_ID\_alter to "to talk" to a specific form. Hope that helps.

If you want to make the validation on a different level, you have to write your own validation handlers (`['#validate']`) or override Drupal's, like `node_form_validate`
> 1 votes

# Answer
For deciding and skipping some fields after submit follow the following steps.

Step 1: Perform HOOK\_form\_alter and add a custom function in **$form\['#validate\]** array, remember your custom validate function must add on 0th key of the array.

Step 2: Perform your calculation and find on which fields you want to perform the validations, and set them in **$form\['#limit\_validation\_errors'\]**.

I hope this will help you for the skipping validation.
> 1 votes

---
Tags: hooks, forms
---


# Question
Title: Implementing i18n string translation in a custom module?
I have a custom module I've built which essentially acts as a repository of custom CTools keywords that users can arbitrarily define. The issue I'm facing is I need to be able to translate these user-defined strings, so I think I need to implement string translation using the i18n\_string module.

I have never worked with translation or localization before, so I'm a bit lost with regards to going about how to implement this. I think I'm on the right path with i18n\_string though. Can someone experienced with i18n provide examples that I can look at so I can learn the proper way to implement this?

# Answer
Exactly, you can't wrap variables with `t()`. They will get printed, but they won't be translatable. I had a form that saves a user-defined string and wanted that string to be translatable from Drupal's translation interface.

Messed around quite a while with `i18n_string()` and its attribute `$name` (a `$textgroup` and a `$context` glued together with `:`).

Finally got it: You can provide your own `$textgroup` via `hook_i18n_string_info()` and later provide any other custom string as `$context` (maybe take your module's name to keep things clean).

If you have more than one string in your module pay attention to have every single one of them glued with another custom string to the prior context (textgroup:context:string\_1, textgroup:context:string\_2, ...).

Here comes a working example:

```
/**
 * Implements hook_i18n_string_info().
 *
 *   This is the most interesting thing here. You create a new
 *   textgroup your strings will be identified with. Here it's
 *   simply: Custom modules.
 *   When you set the i18n-string later you then only add another
 *   string as context like 'custommodules:any_other_string'.
 *   See the markup example in the form below.
 */
function MYMODULE_i18n_string_info() {

  $groups['custommodules'] = array(
    'title' => t('Custom modules'),
    'format' => FALSE,
    'list' => TRUE,
  );

  return $groups;
}

/**
 * Example form.
 */
function form_example() {

  // Just for testing, the first form element prints the translated
  // string, so you simply can test it after translation by switching
  // your page's language and see it working. This also demonstrates how
  // you will print the string everywhere else.
  $form['markup'] = array(
    '#markup' => i18n_string('custommodules:MYMODULE:string_1', variable_get('user_defined_string', 'Bempo Kohm'), array('update' => TRUE)),
  );

  $form['string'] = array(
    '#type' => 'textfield',
    '#title' => t('A beautiful and pure string'),
    '#default_value' => variable_get('user_defined_string', 'Bempo Kohm'),
  );

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

  return $form;
}

/**
 * Example form submit handler.
 */
function form_example_submit($form, &$form_state) {

  variable_set('user_defined_string', $form_state['values']['string']);
}

```
> 4 votes

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