# Question
Title: How to enable jEditable to perform updates?
I recently installed the jEditable inline content editing module on my Drupal 7 site, as an adjunct to the DataTables module.

We need the ability to perform updates on data presented in a DataTable View. I get an error that it cannot connect to the DB.

Does anyone have experience and success in making this work?

Or is there another module/jquery method I can use that does this?

**Note**: I cannot perform CRUD from a views interface (hence the name views) this would be a cool option though.

# Answer
> 0 votes
Consider looking at the Editable Views module for a possible alternative. Here is a quote about it from its project page:

> ... lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
>
> Editable fields can be added on the base entity as well as on entities brought into the View by a relationship. Other, non-editable fields may be added to the View, in which case they function normally.
>
> Currently, the following Views fields can be edited:
>
> * all FieldAPI fields
> * node title

---
Tags: 7, views
---


# Question
Title: Theme generic file link in node template
I want to change the text on a link to download a file in my node template. In **Manage Display** I have selected **Generic File** as the formatter which outputs this

but I want to change it to this

How can I do this?

# Answer
You can function theme\_file\_link() , you can change the file link title before html rendered for file link in your custom themes templete.php file.
> 0 votes

---
Tags: entities
---


# Question
Title: Show Field Collection fields together in same field item
I have a field collection with two fields - Image and Caption. How do I get the two fields to display in the same field item? Right now the HTML is:

```
<div class="ds-1col entity entity-field-collection-item field-collection-item-field-video-item view-mode-full clearfix">
<div class="field field-name-field-video-image field-type-image field-label-hidden">
    <div class="field-items">
        <div class="field-item even"><!-- image here --></div>
        <div class="field-item odd"><!-- image here --></div>
    </div>
</div>
<div class="field field-name-field-video-caption field-type-text field-label-hidden">
    <div class="field-items">
        <div class="field-item even"> <!-- image caption --></div>
        <div class="field-item odd"> <!-- image caption --></div>
    </div>
</div>

```

I need the HTML to be more like:

```
<div class="ds-1col entity entity-field-collection-item field-collection-item-field-video-item view-mode-full clearfix">
<div class="field-items">
    <div class="field-item even image">
    <!-- image field here -->
    </div>
    <div class="field-item odd caption">
    <!-- caption field here -->
    </div>
</div>

```

# Answer
> 0 votes
The problem was with how the field collection was set up. Originally, the field collection fields had unlimited values, while the field collection in the content type was limited to one value.

I reversed this so that the fields were limited to one value and the field collection has unlimited values.

---
Tags: 7, theming, entities, display-suite
---


title: Why would drush sql-sync fail to work?

text:
# Question
Title: Why would drush sql-sync fail to work?
I have a development server set up in my drush aliases as @dev, and a UAT server set up as @uat. I can successfully execute drush commands locally on both servers, and I can execute remote commands from UAT to the development server (e.g. `drush @dev cc all` or `drush @dev upc` or whatever). However, when from the UAT server I execute

```
drush sql-sync @uat @dev

```

it appears to work, but when I first make a change on UAT and then sync and then check the same page on dev is has not changed. I have tried `drush @dev cc all` afterward to make sure there is no caching problem, but this doesn't help.

What could I be missing? Or what could be failing? How can I troubleshoot this?

***UPDATE (corrected)***: If I log into *@dev* and execute the same command (in other words, having @dev pull data from @uat rather than having @uat push data to @dev) it works. But I'd still like to get it working when executed from @uat.

# Answer
> 9 votes
There's not enough here to tell what's wrong, but there are a couple of things you can do to isolate the problem. Start with `drush @uat sql-conf` and `drush @dev sql-conf`; this is what Drush will use to look up the database records for the two sites. If one of these fails to print the right information, that could cause sql-sync to fail. Next, try `drush sa --with-db @uat` and again for @dev, and see if the database record matches what you saw with sql-conf. If, for example, you copied a database record into your @dev alias and specified the wrong database (one different than the one specified in settings.php), then sql-sync might be successfully copying your production database to some other db on the dev machine.

If neither of these things work, you can try adding first -v (verbose output) and then -d (debug mode -- really a lot of output) and see if there is anything there that might help you find the problem.

**Update:** Did you make a typo in your update? drush sql-sync @dev @uat pushes dev to uat, which seems like the opposite operation. If `drush sql-sync @uat @dev` works on dev and not on uat, I would recommend carefully comparing your alias files on the two machines and see if there are any differences. Especially check your 'databases' record in your alias definition, if you have any, and run the diagnostic tests I recommend above. As a workaround, from uat you could run `drush @dev sql-sync @uat @dev`, which would remotely run `drush sql-sync @uat @dev` on the dev machine.

# Answer
> 2 votes
I had the same problem. My solution was to add the ending '--no-cache'

drush sql-sync @dev @local --no-cache

If you don't do that, drush takes the last saved sql-dump.

Cheers Stefan

# Answer
> 0 votes
I've solved my problem with sql-sync after I updated the drush version on my localhost. It was 5.7 on localhost and 6.0-rc4 on server. After update the drush version on localhost is 7.0-dev. sql-sync works well!

# Answer
> 0 votes
I had the same weird problem and after cleared @dev cache it worked.

# Answer
> 0 votes
When I encountered this issue, I used verbosity (--verbose) to find that I was getting a MYSQL error 2013 "Lost connection to MySQL server during query" in the last stage of the synch.

Turns out my packet size was too small so my end couldn't finish the job.

*That is not necessarily meant to be a double entendre.*

So I edited the my.cnf (mine was in /etc/mysql) and cranked it from 16M to 128M.

Also, had to use --no-cache.

---
Tags: drush
---


title: hook_form_alter based on path

text:
# Question
Title: hook_form_alter based on path
I don't know if this is possible but could I do something like

```
<?php

  $foo = current_path();
  print $foo;

?>

```

in page--foo.tpl, then something like

```
function MYMODULE_form_user_register_form_alter(&$form, &$form_state) {
    function name() {
        global $foo;
        if $foo == 'user/register/foo' {
            unset($form['account']['mail']);
    }
  }
}

```

in a custom module. I'm trying to make fields unique to roles without using profile2. Getting this error when I try it though:

> Parse error: syntax error, unexpected '$foo' (T\_VARIABLE), expecting '(' in /var/www/html/drupal/sites/all/modules/custom\_forms/custom\_forms.module on line 71

Using Auto Assign Role for the path.

# Answer
It looks like you have researched a few ideas and mixed them all. The page--foo.tpl is a theme template file, and the names there are often used with theme suggestions so you can change the regions and wrapping html for different pages in different ways. This is theme layer, and should be used for changing the appearance but not the processing.

The `Hook_form_id_alter()` is used to alter that specified form before it is passed to the theme layer, so that function will run before the print `$foo;` in the template.

So with what is in your question, the process would go like this:

> Check value of yet-to-be-set global `$foo` If foo is a specific page, remove field from form send form to theming get current page save current page to local `$foo` and ignore the global `$foo` that has already been checked. print out the value of local $foo into the html of the page

Also, I do not see roles touched anywhere in your question. If I have read it right, you dont need the tpl at all and you can do this all in the form\_alter.

```
function MYMODULE_form_user_register_form_alter(&$form, &$form_state) {
  global $user;
  if( current_path() == 'user/register/foo' ){
    // do what you want here
  }
}

```

Considerations. Since you are using `hook_form_ID_alter` instead of `hook_form_alter` it is pretty safe to assume that this will only fire on the registration form so checking the registration url is a little redundant. Since you are trying to define a function inside a function, you are used to javascript and the php scope handling is causing you some trouble; you should google for available drupal functions (like current\_path() ) to help you before trying to write your own helper functions.
> 4 votes

---
Tags: forms
---


# Question
Title: How can I create a table in which columns and rows get added dynamically?
I want to create table with **Tasks** as columns and **Users** as rows.

Here is a sample of how such a table should look like:

```
------------------------------------
|       | Task 1 | Task 2 | Task 3 |
------------------------------------
| User1 | 30%    | 0      |        |
| User2 | Done   | 100%   |        |
| User3 |        | 100%   | 10%    |
------------------------------------

```

I want to do it in the following way. When I create a new node with Node Type "Task" that has title "Task XX..." and some description, then the new column with "Task XX" label appears.

Users (User1,User2...) are just a group of drupal users. So probably I need a new Node Type like "User tasks track".

And when a new "Task XX" appears, probably Node Type "User tasks track" should be extended with a new field "Task XX".

I've checked a lot of modules (EditableViews, ViewsMatrix, QuickEdit, Datatables, AjaxTable, Footable, FiledCollections, SlickGrids), but I still can't see the whole solution. If these modules can provide the described behaviour. I can write custom module which plays with database, but I really don't want to invent the wheel, if there is the solution somewhere out there.

Please help me with you opinion, any references, architectural tricks/advice. Anything that can at least show me the directions to the solution.

# Answer
> 0 votes
I forgot that famous tagline from a recent president, but in French I would sound something like "Mais oui, c'est possible" ...

The question here seems like a variation of something I recently ran into, related to processing log messages. One of the challenges with recent log messages (watchdog), is that there might be quite a few PHP notices, warnings, and errors that are filling up your logs. So a good practice is to identify / address these problems in your site (which will reduce the required resources for your site also and will result in a faster site).

However digesting these messages is quite a challenge. That's why I've come up with my own "custom" report, as illustrated in this screenprint:

Within the "Report Execution Parameters" (collapsed in the screenprint above), I specify the search criteria of the log messages to be retrieved (like severity, User name, etc). And the red numbers are hyperlinks to get a drill down report of the specific messages for which I want more details (= to display the actual watchdog entries).

Some more details about the above table:

* Think of the columns (with headers starting with "Msg Type:...") as your "***Task XX***". While each row (= different message) is like your "***User1***", "***User2***", "***User3***".
* If there wouldn't have been any errors with (say) "Msg Type: Ajax" or "Msg Type: page not found", then the corresponding column wouldn't have been created.
* Some columns (like "Msg Type: Error" or "Msg type: PHP") contain a value for multiple rows.

Refer to my answer to "How to gets analyts and generate visual reports from sessions?" for more details about creating reports (tabular displays) as in the above screenprint.

Just in case anybody wonders "How did you do that?" (without checking out my answer in the above link): ***There's a module for it*** ... it's called Forena ... And the clue in this specific case is to use Forena to create a "Crosstab table".

**Bottomline**: no need to re-invent the wheel ...

Disclosure: I'm a co-maintainer of the Forena module.

---
Tags: views, theming
---


title: Edit values of a select list in a view

text:
# Question
Title: Edit values of a select list in a view
I have a select list in a `view` that filters the `view` by the team number.

Each team number will be displayed in the select list like: `2014-2015 - 01`, `2014-2015 - 02` and so forth.

All I want are the last two numbers to display on the view's table, so what I did was used a computed field to just grab the last two numbers so then only the team number shows up.

However, I can't use a computed field to automatically fill the contents of a select list, and when I create a team filter, the select list has `2014-2015 - 01` , `2014-2015 - 02`, and so forth.

**I want to edit the select list so it only shows `01, 02,` etc.**

I am really good with `JS injector` and prefer to do most things like this with that, but sadly the page is refreshed so many times it's not a good thing to use. Any thoughts?

# Answer
> 1 votes
I suggest you create a custom module and in `hook_form_alter` according to your expose filter module `form_id` get your form element,then you can change the value of your expose filter without change the value of them (as what you want) something like below code can help you

```
function yourmodule_form_alter(&$form,$form_state,$form_id){
   if ($form_id == "your_views_exposeform") {
            // first try dpm($fom); to see what you have there
            foreach($form['expose_your_field']['und']['#options'] as &$item){
            //  repalce label of select option items with what you want
            }
        }
        }

```

---
Tags: views
---


# Question
Title: Hide Content Type Default Pages from Search Results
I have multiple content types where users enter data that I consume in views and create pages from.

I want to exclude some of these default content type rendered pages from the search results, but do not want to exclude the content and the views page where the results are.

For example, I have Basic Page Content Type and want to see any basic page content. I also have Custom Page Content Type and want to see these fields, but not the default rendered page, just my View created page that consumes the Custom Page Content Type fields.

Where do I set this up or how do I set up search to handle this type of need?

# Answer
> 0 votes
You can use Custom Search module.

> This module alters the default search box in many ways. If you need to have options available like in advanced search, but directly in the search box, this module is for you. D8.x notes
>
> The module adds options to select:
>
> ```
> which content type(s) to search,
> which specific module search to use (node, help, user or any module that implements search),
> which input type to use (with Elements),
> advanced criteria
>
> ```
>
> For all these choices, there are options to switch between a select box, checkboxes or radio buttons, and also customize the selector label and the default - Any - text. Advanced options
>
> There are also options to:
>
> ```
> change the default search box label,
> add a default text in the search box,
> add advanced search criteria,
> change the default submit button text,
> use an image instead of the submit button,
> change the order of all the elements,
> include some elements in a popup block,
> add a filter to the results page,
> show/hide basic and/or advanced search in the results page,
> show/hide meta data in the results page,
> multiple search paths
>
> ```

---
Tags: 7, views, nodes, search
---


# Question
Title: Replacement pattern for one value of a multivalue field in views
Rewriting the results of a views field, I wonder if there is a way to use a replacement pattern for the first, second and third value of a multivalue field.

In my case, as example:

I have tried to use this rewritten tags field: \[field\_tagging:0\] \[field\_tagging:1\] \[field\_tagging:2\]

However, this is not rewritten/recognized as replacement patterns.

The result I need, is that in the views field has three tag links, which have a rewritten path (in this case it also uses !1 for the contextual value in the URL)

# Answer
> 0 votes
I had a similar problem, although not exactly the same. Here's what worked for me: 1. Enable the module entity\_token which is a sub-module of Entity. 2. Use field-tagging:0 (with a dash not an underscore). Depending on exactly what you are trying to do, you may need a further parameter such as field-tagging:0:url.

It seems that field\_tagging and field-tagging are two different things. The first one doesn't accept :0.

---
Tags: views, tokens
---


# Question
Title: Does backup and migrate include the users and login info?
I'm migrating from the test environment to the live environment, both of which have a separate set of users/logins/privileges.

How do I not overwrite this information when migrating from one site to another?

# Answer
If you want to move user data from a Drupal site to another, you need to use the Migrate module. The *Backup and migrate* module is for exporting and restoring database and files.
> 1 votes

# Answer
Assuming that you are using the Backup and Migrate module (as per your title), just use the feature to exclude selected tables, similar to what is described in the answer to the question about "Backup and Migrate exclusion recommendations?", which states:

> I have following tables to exclude data (**not** to exclude the table altogether):
>
> * all cache\_\* tables
> * ctools\_views\_cache
> * ctools\_object\_cache
> * flood
> * history
> * queue
> * semaphore
> * watchdog
> * search\_index
>
> Usually search\_index saves a lot of database size.

You may also want to look at these issues:

* How to backup and migrate just the user accounts?: even though it's the opposite of what your question is about, it does provide some interesting background info about this topic, i.e (quote from it):

> The exclude table features are there because not all db data needs to be backed up (cache tables, search index, etc) and not all tables in a db are necessarily drupal tables (you might have wordpress installed in the same db and not want to back up those tables). You'll notice that there is no option to backup just part of a table. There is no way to backup all users with uid \> x for example.
* Default tables/data to exclude, which includes an interesting list of tables to not be migrated (pick what fits for you), i.e. (quote from it):

> When creating a backup profile, the module by default sets the following tables to have their data excluded according to issue #209647: Exclude advice:
>
> + cache
>     + cache\_filter
>     + cache\_calendar\_ical
>     + cache\_menu
>     + cache\_page
>     + cache\_views
>     + sessions
>     + search\_dataset
>     + search\_index
>     + search\_keywords\_log
>     + search\_total
>     + watchdog
>     + accesslog
>     + devel\_queries
>     + devel\_times
* Entire site backup excludes default/settings.php file: just be aware that that is how it works (to avoid surprises after restore).
> 1 votes

---
Tags: users, backups
---


# Question
Title: meta tags don't display when not authenticated
I'm using Drupal 7, Meta Tags/Open Graph meta tags 7.x-1.0-alpha6.

When logged in, meta tags act as I would expect. I see the meta tags when I view the page source.

When not logged in, the meta tags are missing. What could cause this?

# Answer
You have a patch for this issue. There is a README.txt file updated.

All you need to do is to render meta tags in your `page--front.tpl.php`, add following in this file of your theme:

```
<?php
 render($page['content']['metatags']);
?>

```

Or you can try to add this in your `template.php` file of the theme:

```
<?php
function THEMENAME_preprocess_page(&$vars) {
  if (!empty($vars['is_front'])) {
    metatag_page_build($vars['page']);
  }
}
?>

```

Just replace `THEMENAME` with the name of your theme.
> 1 votes

# Answer
Check metatags permissions, be sure the anynomous user has the right permission to access metatags
> 0 votes

---
Tags: meta-tags
---


# Question
Title: How to override jQuery from contrib module
It's from editable fields that I want to override jQuery from. I tried to simply copy the function in question into my scripts.js and make it work but it obviously doesn't.

I'm sure my custom js file loads because I'm already using other code in it. Now, I just put a console.log statement in the beginning of my copied function that is supposed to fire at every `.blur();` but nothing's coming out.

I also checked that my custom js code got loaded *after* the editable fields code (In case I sound stupid: I don't know how far drupal takes care of it to do this by default.)

this is the function - originally from editablefields - that I would like to override

```
    (function ($) {
Drupal.behaviors.editablefields_submit = {
console.log('override check');
attach: function (context) {
    $('.editablefield-item').once('editablefield', function() {
      var $this = $(this);

      // There is only one editable field in that form, we can hide the submit
      // button.
      if ($this.find('input[type=text],textarea,select').length == 1) {
        $this.find('input.form-submit').hide();
        $this.find('input[type=text],textarea,select').change(function() {
            console.log('this out of override= ' + $this);
          $this.find('input.form-submit').triggerHandler('click');

        });
      }
    });
  }
};

```

# Answer
> 5 votes
To override the JavaScript file added to a page from a module, you need to implement hook\_js\_alter(). The example code shown for `hook_js_alter()` is the code used by the jQuery Update module uses to change the jQuery library used from Drupal.

```
  // Swap out jQuery to use an updated version of the library.
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';

```

In your case, if mymodule.module is the module that needs to change the JavaScript file, and the file added is script.js, then the following code can be used to achieve your task.

```
function mymodule_js_alter(&$javascript) {
  $javascript[drupal_get_path('module', 'editablefields') . '/editablefields.js']['data'] = drupal_get_path('module', 'mymodule') . '/script.js';
}

```

The same code works for a theme too. The difference is that instead of using `drupal_get_path('module', 'mymodule')`, the code should use `path_to_theme()`. *

Using `hook_js_alter()` would work also for JavaScript settings added by Drupal, external JavaScript files, and inline JavaScript code. What changes is how the array is structured in those cases.

* I didn't test the code I am suggesting to use for a theme.

# Answer
> 0 votes
The basic idea - but drupal behaviours are a bit hazy documentationwise - would be in your script.js to use the **`detach`** function and detach this behaviour (editablefields\_submit) and attach your own which would use the same jquery selectors for a different effect.

# Answer
> 0 votes
Doing the override in jQuery itself might be a better option in some cases.

Something like...

```
var myNewFunction = Drupal.behaviors.existingFunction();
Drupal.behaviors.myNewFunction = function() {
   // Do some stuff
   return myNewFunction.apply(this, arguments);
};

```

This way you are able extending the jQuery function instead of replacing it.

---
Tags: 7, javascript
---


# Question
Title: How can I avoid this markup is filtered out from my block?
I generated a widget on pinterest. The result is the following:

```
<a data-pin-do="embedPin" href="http://nl.pinterest.com/pin/1438168111370/"></a>
<!-- Please call pinit.js only once per page -->
<script type="text/javascript" async defer src="//assets.pinterest.com/js/pinit.js"></script>

```

`pinit.js` is included in the theme and is available in the page.

I added a block with the following code.

```
<a data-pin-do="embedPin" href="http://nl.pinterest.com/pin/1438168111370/"></a>

```

When I saved the block (I used CKEditor), it cleaned. Actually, I don't know if it is cleaned by **CKEditor** or the **full HTML** filter.

How can I find out which of those is cleaned out the markup?

* If it's due to **CKEditor**, how can I solve it? The `advanced content filter` is disabled.
* If it's due to **full HTML** filter, how can I configure it so that only this non compliant syntax is allowed?

**NOTE:** In the **full HTML** filter, the checkbox `Correct faulty` and chopped off `HTML` is NOT checked.

# Answer
I've had the same issue with CKEditor removing classes in the past, Full HTML is not the issue.

Add the below code to the end of your CKEditors config.js file, which is found within the CKEditor library code.

```
CKEDITOR.config.allowedContent = true;

```

You might find that the file is called ckeditor.config.js and that this is the file that needs to be changed rather than the default config.js. This file can be found in the root of the CKEditor module.
> 2 votes

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


# Question
Title: Custom grouping by taxonomy term in view
I made a view with taxonomy and nodes, groupped like this:

```
term 1
    subterm 1
        row
        row
term 2
    subterm 1
        row
        row
term 3
    subterm 1
        row
        row
    subterm 2
        row
        row
term 4
    subterm 1
        row
        row

```

But I need grouping by term like this:

```
term 1
    row
    row
term 2
    row
    row
term 3
    subterm 1
        row
        row
    subterm 2
        row
        row
term 4
    row
term 5
    row
    etc.

```

please any ideas, i wasted a lot of time to find the hook and tpl.php for this (tpl. or hooks - ?)

# Answer
> 1 votes
Groping things in view not that easy, and what i suggest you here to save your time to use views\_field\_view which allowed you to insert view inside view.

So simply make 3 displays each one for level and pass the argument between them, that should not take more than 5 min

---
Tags: taxonomy-terms
---


title: Entity reference link module

text:
# Question
Title: Entity reference link module
I am using entity reference field in a content type with select list widget allows you to add the title of a node in the content type, however the title dose not work as a link to the node. I would like to now how can i make the title work as a link to the node?

dose Entity Reference link module fits this purpose?? if yes how it works? if no is there any way to do this??

# Answer
Go to *Manage Display* of the content type that contains *field reference* field, Select *Rendered Entity* of *Format* of the field. I mean this

and using that widget you can select a custom *Display mode* and by that display mode you can choose what fields of the referenced content must be displayed (title or any other field).
> 0 votes

# Answer
Go to `Content types » [your_content_type] » Manage display` and select FORMAT as `Link label to the referenced entity` for your referenced field.
> 0 votes

---
Tags: navigation, entities
---


# Question
Title: Toggle Modules on or off at a certain time with Rules
I'm looking for a way to toggle a Module on or off based on the time of day using Rules. Ideally, the logic behind it would be something like:

```
IF

The time is between 1700 and 0900 AND Module X is turned OFF

THEN

Turn Module X ON

ELSE IF

The time is between 0900 and 1700 AND Module X is turned ON

Turn Module X OFF

ELSE

Turn Module X OFF

```

I'd like this to run with each CRON run (15 minutes). Is this achievable using Rules and without going into PHP?

# Answer
Since you run cron in every 15 minutes, you can use module\_disable or module\_enable in `hook_cron` of your module. Using

```
format_date(time(), 'custom', 'l j F Y');

```

you can get the current date and time. What is difficult for you to build such module?
> 0 votes

---
Tags: 7, rules
---


# Question
Title: How can I sort a view based on a rewritten field?
I have a view of a content type that contains two different date fields (one with date repeats and one multivalued single dates). Only one date field is filled out at any given time. In the view's display, I have combined the two fields by hiding the first date field and rewriting the second and including the replacement token of the first and second. Is there any way to now use the rewritten field to sort the view in ascending order based on this combined date field? It appears it sorts it based on the original value of the date field.

I have done my research and have only found old, somewhat-related, threads with dead-ends.

views sorting by rewritten field?

Table does not sort on rewritten field, but on original field

Views: custom field for sort criteria

Sort by global:custom text. Is it possible?

I was hoping there is a new or sneaky way of making this happen.

# Answer
If you don't want to go for the module route, this is one alternative:

1) install Computed Field module
2) add a computed field to your content type
3) in the field settings, in the Computed code (PHP) textarea, you can access the field data.

Get your date fields in your current langugage to a variable.

```
$repeating_dates = field_get_items($entity_type, $entity, 'field_repeating_date_example');
$multidates = field_get_items($entity_type, $entity, 'field_multidate_example');

```

Your date values can now be found in

```
$repeating_dates[0]['value'],
$repeating_dates[1]['value'],
$repeating_dates[2]['value'], etc.

$multidates[0]['value'],
$multidates[1]['value'],
$multidates[2]['value'], etc.

```

Do whatever logic you need with your date fields and assign the result to

```
$entity_field[0]['value']

```

Now you have a sortable field you can use in views, but first you have to update all the nodes as the computed field will only be computed and saved to the database at node save. There are many ways to do this, one is using Views Bulk Operations, it gives you an option to re-save nodes at admin/content.
> 4 votes

# Answer
I think you can do it with the Views Natural Sort . It have the option to sort the fields means - **Enable Sorting for Specific Fields** . If you follow this tutorial you will get an idea!!.
> 2 votes

# Answer
The only sneaky way of making this happen is if you do not use pagination, then you can use PHP sorting in a custom query override that doesn't rely on the database.

According to stevector,

> Pagination is what really stops us from sorting by computed fields because normally we need to say "Database! get me results 21-30 when sorting by the nid column".
>
> So you can't reliably get results 21-30 from the db if the db doesn't know how to define the 21-30 (like in the case of a computed field).

So the most practical and reliable solution is to use Computed Field as mentioned by Kari Kääriäinen.
> 1 votes

# Answer
This is a bit of a hacky way to do it, but it works and you don't need any additional modules.

Create a label for the field that you want to sort on and do NOT exclude it from display. Instead, rewrite the display as "blank" by adding an empty html `<!---->` comment as the rewrite value. Then add your other php/rewritten field as a child of this column.

This will display the table header for the correct column for sorting.
> 1 votes

---
Tags: views
---


title: How to get values after form submit

text:
# Question
Title: How to get values after form submit
I created on custom module to generate a form with this code

```
function report_page_form_form($form, &$form_state) {
    $meberArr = array();
    $form['field_member_org']=array(
        '#type'=>'select',
        '#options'=> $meberArr,
    );
    $form['field_start_date'] = array(
      '#date_format' => 'Y-m-d',
      '#type' => 'date_popup',
      '#weight'=>0,
    );
    $form['field_end_date'] = array(
      '#date_format' => 'Y-m-d',
      '#type' => 'date_popup',
      '#weight'=>0,
    );
// Provide a submit button.
          $form['submit'] = array(
            '#type' => 'submit',
            '#value' => 'Filter',
          );
return $form;
 }

```

In one of my `node--nid.tpl.php`, I am rendering this form as

```
 $arr = drupal_get_form('report_page_form_form');
 print drupal_render($arr);

```

I am writing an SQL query in the same `node--nid.tpl.php` file to fetch data from DB.

```
SELECT TITLE FROM REPORT WHERE ....

```

I need to pass form submitted values to this query. Can anyone help me to do it.

# Answer
You would get the values of the submitted form in `hook_form_submit`

```
function MY_MODULE_NAME_form_submit($form, &$form_state) {
         //your code here
        }

```

You would get all the required values in `$form_state['values']`
> 2 votes

---
Tags: forms
---


# Question
Title: Create path alias programatically when node is created
I have a custom content type that is created by a module. Is there a hook I can use to set the path alias of my custom content type when a node is created?

One of my fields is an alpha-numeric code, and I want to use that in the path. eg.: 'event/myc0d3'

I noticed that this function (path\_set\_alias) existed in 6, but I can't find the equivalent for 7. And do not know where I would call it.

# Answer
> 9 votes
hook\_node\_insert() wasn't working in my case, and with some searches I came up with this blog post. I implemented hook\_insert() in the same way and presto.

```
/**
 * Implements hook_insert().
 */
function mymodule_insert($node) {
    // Set the URL alias
    if (empty($node->path['alias'])) {
        $node->path['alias'] = 'slug/' . $node->nid;
    }
}

```

# Answer
> 12 votes
Instead of using hook, Pathauto module should be used where you can define specific pattern how aliases are generated per content type (at `/admin/config/search/path/patterns`). In there you can use replacement patterns or code your own. It's much cleaner approach.

Otherwise you can try `hook_node_presave($node)` and change the alias directly:

```
$node->path['pathauto'] = 0; // Required only if Pathauto is enabled.
$node->path['alias'] = "foo/bar";

```

or use the `path_save(&$path)` function directly as below:

```
$path = array('source' => "node/$node->nid", 'alias' => 'foo/bar');
path_save($path);

```

# Answer
> 9 votes
The function is now called path\_save(), see path\_taxonomy\_term\_insert() for an example.

# Answer
> 0 votes
Implement hook\_node\_insert().

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


# Question
Title: Unable to set placeholder on password input
```
function customization_form_user_register_form_alter(&$form, &$form_state, $form_id) {
 $form['account']['pass']['#attributes']['placeholder'] = t('Password');
}

```

I am trying to set placeholder on password field in registration form.

I seted placeholder on username and email, but on password field won't work...

Any help? Thank you!

# Answer
Wish I'd seen this sooner. You've probably moved on from this problem, but for the benefit of other people seeking an answer to this question: (obviously replace mymodule with the name of your module)

```
/**
* Implementation of hook_element_info_alter ()
*/
function mymodule_element_info_alter (& $type)
{
  if (isset($type['password_confirm']['#process'])) {
    $func = '_mymodule_process_password_confirm';

    $type['password_confirm']['#process'][] = $func;
  }

  return $type;
}

/**
 * Do a bit of processing for the password_confirm element.
 * Original processing happens in expand_password_confirm()
 */
function _mymodule_process_password_confirm ($element)
{
  // Use the element's title, or create a custom title with the t() function.
  $element['pass1']['#attributes']['placeholder'] = $element['pass1']['#title'];
  $element['pass2']['#attributes']['placeholder'] = $element['pass2']['#title'];

  // Remove these lines if you want to keep the field labels.
  $element['pass1']['#title_display'] = 'none';
  $element['pass2']['#title_display'] = 'none';

  return $element;
}

```
> 10 votes

# Answer
turibe solution is true. But you can save #title keys (do not remove), for compatibility with another modules.

```
/**
* Implementation of hook_element_info_alter ()
*/
function mymodule_element_info_alter (& $type)
{
  if (isset($type['password_confirm']['#process'])) {
    $func = '_mymodule_process_password_confirm';

    $type['password_confirm']['#process'][] = $func;
  }

  return $type;
}

/**
 * Do a bit of processing for the password_confirm element.
 * Original processing happens in expand_password_confirm()
 */
function _mymodule_process_password_confirm ($element)
{
  $element['pass1']['#attributes']['placeholder'] = t('Password');
  $element['pass2']['#attributes']['placeholder'] = t('Confirm password');

  // Remove these lines if you want to keep the field labels
  // Hide labels for pass fields
  $element['pass1']['#title_display'] = 'invisible';
  $element['pass2']['#title_display'] = 'invisible';

  return $element;
}

```
> 0 votes

---
Tags: users, input-formats
---


# Question
Title: How to call a function of one module in another module
How can I call a function of one module in another module? I want to call `uc_stock_adjust()` function of uc\_stock.module in my own custom module. Is it possible?

Here is my code so far:

```
function my_module_node_presave($node){
  if($node->type == 'add_stock') {
    $stock_value = $node->field_stock_value['und'][0]['value'];
    $sku = $node->field_sku['und'][0]['value'];
    if (module_exists('uc_stock') && function_exists('uc_stock_adjust')) {
      uc_stock_adjust($sku, $stock_value);
    }
  }
}

```

I want to add and delete stock of products by using reference `uc_stock_adjust()`, which is defined in uc\_stock.module, in my custom module. But when I try the above code, it doesn't work.

It giving an error, and the error is:

> Notice: Undefined variable: sku in my\_module\_node\_presave() (line 29 of \sites\all\modules\my\_module\my\_module.module)

# Answer
> 15 votes
To call the function of one module in another module:

1. If the function is not in the .module file, call module\_load\_include()

```
//Load node.admin.inc from the node module
module_load_include('inc', 'node', 'node.admin');

```
2. Call the function from the other module

```
function_you_want_to_call();

```

# Answer
> 0 votes
`Undefined variable: sku` means that you have not declared a value for the variable `$sku`. Have you done debugging to make sure that `$node->field_sku['und'][0]['value']` outputs a value?

# Answer
> 0 votes
See module\_invoke(). This calls a function (hook) in a specified module.

The given hook `uc_stock_adjust()` can thus be called by: `module_invoke('uc_stock', 'adjust');`. (Note that this is because the function follows Drupal conventions of module\_name\_function\_name).

If desired additional arguments can also be passed to a function's parameters with: `module_invoke('uc_stock', 'adjust', $first_param_to_pass, $second_param_to_pass, $etc);`

---
Tags: 7, hooks, ubercart
---


# Question
Title: How to enter text in a fieldset's summary?
Using the form api to create a fieldset:

```
$form['fieldset'] = array(
 '#title' => 'title',
 '#type' => 'fieldset',
 '#collapsible' => TRUE,
 '#description' => 'desc',
);

```

Drupal will output:

```
<fieldset class="collapsible form-wrapper collapse-processed" id="edit-fieldset">
  <legend>
    <span class="fieldset-legend">
      <a class="fieldset-title" href="#">
        <span class="fieldset-legend-prefix element-invisible">Hide</span>
         title
      </a>
      <span class="summary"></span>
    </span>
  </legend>
  <div class="fieldset-wrapper">
    <div class="form-item form-type-textfield form-item-testelement">
      <label for="edit-testelement">asdf </label>
      <input type="text" id="edit-testelement" name="testelement" value="" size="60" maxlength="128" class="form-text">
    </div>
  </div>
</fieldset>

```

The #title in the form array will be the `<a>` you click on to expand the fieldset. I want to put text in the `<span class="summary"></span>`, which puts additional, non linked text beside the title. I can't seem to do this with the form api, as #description will only put text within the fieldset that is hidden when it is closed.

What's the easiest way to do this?

# Answer
> 3 votes
See `vertical_tabs_example_form_alter()`, there it's written:

> Vertical tabs provide its most usable appearance when they are used to include a summary of the information contained in the fieldset. To do this, we attach additional JavaScript to handle changing the summary when form settings are changed.

```
  '#attached' => array(
    'js' => array(
      'vertical-tabs' => drupal_get_path('module', 'vertical_tabs_example') . '/vertical_tabs_example.js',
    ),
  ),

```

In `vertical_tabs_example.js` it then goes on like so:

> Use the fieldset class to identify the vertical tab element. Depending on the checkbox status, the settings will be customized, so update the summary with the custom setting textfield string or a use a default string.

```
$('fieldset#edit-vertical-tabs-example', context).drupalSetSummary(function (context) {
  if ($('#edit-vertical-tabs-example-enabled', context).attr('checked')) {
    return Drupal.checkPlain($('#edit-vertical-tabs-example-custom-setting', context).val());
  }
  else {
    return Drupal.t('Using default');
  }
});

```

# Answer
> -1 votes
I am looking to do something similar, setting a summary in a manually output collapsible fieldset.

I looked into the collapse.js where it is defining the collapse behavior (line 56 of /misc/collapse.js).

At line 70, It looks like it is pulling the summary text from $.fn.drupalGetSummary().

I am not 100% on this (since it doesn't appear to mention in the Form API docs), but from looking at source codes, I think it might do the trick if you add to your array an entry for

```
'#summary' => "This is my fieldset!",

```

Other things you could experiment with:

```
'#summary callback' => 'my_module_example_fieldset_summary',
'#summary arguments' => array('bar'),

```

and you would probably need to define the summary callback in a module...

```
function my_module_example_fieldset_summary($foo){
  return t("foo is ".$foo.".");
}

```

or maybe you could just use something simple like:

```
'#summary callback' => 't',
'#summary arguments' => array('foo is bar.'),

```

---
Tags: forms
---


title: form submit handler is not called

text:
# Question
Title: form submit handler is not called
I tried to mimic the multiple user deletion feature of user.module but for some reason the confirm form submit handler never get called. I don't know where the problem lies in. Following is a working sample of module except for the function delete\_multiple\_server\_confirm\_form\_submit which never gets executed.

```
function mymodule_menu() {

  $items['testservers'] = array(
    'title' => 'Manage Servers',
    'page callback' => 'display_servers_callback',
    'page arguments' => array('delete'),
    'access callback' => true,
  );

  return $items;
}

function display_servers_callback($args = '') {

  $op = isset($_POST['op']) ? $_POST['op'] : $args;
  $op = strtolower($op);
  $build_form = array();

  if (!empty($_POST['table']) && isset($_POST['operation']) && ($_POST['operation'] == 'delete')) {
    $options = $_POST['table'];
    $build_form['delete_multiple_server_confirm_form'] = drupal_get_form('delete_multiple_server_confirm_form', $options);
  }
  else {

    $build_form['display_servers_form'] = drupal_get_form('display_servers_form');
  }

  return $build_form;
}

function delete_multiple_server_confirm_form($form, &$form_state, $servers) {

  $path = current_path();

  return confirm_form($form, t('Are you sure you want to delete %title?'), $path, t('This action cannot be undone.'), t('Delete'), t('Cancel')
  );
}

function display_servers_form($form, $form_state) {

  $header = array(
    'server_name' => array('data' => t('Server Name')),
    'location' => array('data' => t('Location')),
    'protocols' => array('data' => t('Protocols')),
    'status' => array('data' => t('server status ')),
  );

  $servers = array(
    array('server_name' => 'us1', 'location' => 'us', 'protocols' => 'test', 'status' => 'ok'),
    array('server_name' => 'us2', 'location' => 'us', 'protocols' => 'test', 'status' => 'ok'),
    array('server_name' => 'us3', 'location' => 'us', 'protocols' => 'test', 'status' => 'ok'),
  );

  $options = array();

  for ($index = 0; $index < count($servers); $index++) {

    $options[$index] = array(
      'server_name' => $servers[$index]['server_name'],
      'location' => $servers[$index]['location'],
      'protocols' => $servers[$index]['protocols'],
      'status' => $servers[$index]['status'],
    );
  }

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No servers found'),
  );

  $options = array();
  $operations = array('delete' => array(
      'label' => t('delete servers'),
      'callback' => 'delete_multiples',
    ),
    'suspend' => array(
      'label' => t('suspend servers'),
    ),
  );

  foreach ($operations as $operation => $array) {
    $options[$operation] = $array['label'];
  }

  $form['options']['operation'] = array(
    '#type' => 'select',
    '#title' => t('Operation'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => 'delete',
  );

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

  return $form;
}

function delete_multiple_server_confirm_form_submit($form, &$form_state, $servers) {

  drupal_set_message('working');
}

```

# Answer
> 1 votes
After careful rereading of the user module, i realize that 2 more hidden form values need to be added so the same delete\_multiple\_server\_confirm\_form will get called again after confirming action,otherwise the display\_server\_form will be rendered.

```
$form['table'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
$form['operation'] = array('#type' => 'hidden', '#value' => 'delete');

 foreach($servers as $id) {

    $form['table'][$id] = array(
         '#type' => 'hidden',
         '#value' => $id,
         );
   }

```

# Answer
> 0 votes
What about:

```
$form['options']['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Update'),
  '#submit' => array('delete_multiple_server_confirm_form_submit'),
);

```

# Answer
> 0 votes
Change you function name from `delete_multiple_server_confirm_form_submit` to `display_servers_form_submit`

# Answer
> -1 votes
If you are rendering your form using form--anyformname.tpl.php template file then make sure in that template file you are rendering these three thing at the end:

```
    <div>
    <?php print render($form['form_id']); ?>
    <?php print render($form['form_build_id']);?>
    <?php print render($form['form_token']); ?>
    </div>

```

---
Tags: forms
---


title: Form submit handler not working

text:
# Question
Title: Form submit handler not working
I'm developing a pretty basic module `catalog_request` that creates a form. I'm replacing the form's default submit button `<input ..type="submit" />` with a `<button ...>click</button>` using following in form definition.

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

    /**
     * form fields here
     */

    $form['fieldset_submit']['the_submit_button'] = array(
       '#type' => 'markup',
       '#prefix' => '<button class="btn submit">',
       '#markup' => 'Send Request...',
       '#suffix' => '</button>',
    );

    /* ... */
}

```

and have defined other two form related functions

```
function catalog_request_form_validate($form, &$form_state) {
    drupal_set_message(t('The form was validated'));
}

function catalog_request_form_submit($form, &$form_state) {
    die('submitted');
    //drupal_set_message(t('The form was submitted'));
}

```

**The problem**

My submit function `catalog_request_form_submit` isn't being called. I've read numerous articles online but none resolved my issue. Following didn't work

1. Adding `'#submit' => 'catalog_request_form_submit',` to `the_submit_button` key
2. Adding `'$form['#submit'] => 'catalog_request_form_submit';` to end of `catalog_request_form` function
3. Adding `'$form['#submit'][] => 'catalog_request_form_submit';` to end of `catalog_request_form` function

I've read that adding something along the lines of `$form['actions']['#submit'][] = 'custom_function';` could solve the problem but I'm not sure how to adapt it for my form.

I know that having `'#type' => 'submit'` for the submit button makes the form work but I want a `button` tag.

My problem is exactly When altering the submit button, the form does not work but it doesn't have a *solution* (only an answer that ignores the question's point)

P.S. I do not develop for drupal frequently so I might be missing something very obvious.

Any help will be greatly appreciated. thanks

# Answer
> 2 votes
In order to add another submit handler you have to add something to `hook_form_alter()`: check for your particular form ID, and then add a submit handler in one of the following ways:

**OPTION 1:**

To add a submit handler that is called as the next callback *after* processing the default submit handler callback you can use this:

```
function mymodule_form_alter(&$form, &$form_state) {
  if ($form_id == 'form-id-of-your-form') {
    $form['actions']['submit']['#submit'][] = 'mymodule_whatever_function';
  }
}

```

**OPTION 2:**

If OPTION 1 is not working for you, replace the third line with this:

```
form['#submit'][1] = 'mymodule_whatever_function';

```

This will add a second submit handler, or replace the second one with yours if there is already more than one.

**OPTION 3:**

To remove the default submit handler completely (so that "nothing will happen" on submit, or so that you can replace it with your own), use code like this:

```
function mymodule_form_alter(&$form, &$form_state) {
  if ($form_id == 'form-id-of-your-form') {
    unset($form["actions"]['submit']);
  }
}

```

# Answer
> 0 votes
From the link you provided:

> "In order for the form to be submitted correctly the element needs to be a submit, button or image\_button type."

So maybe something like the following will work.

```
$form['fieldset_submit']['the_submit_button'] = array(
    '#type' => 'button',
    '#name' => 'name',
    '#value' => t('Submit'),
    '#executes_submit_callback' => TRUE,
);

```

# Answer
> 0 votes
https://api.drupal.org/api/drupal/includes!form.inc/function/theme\_button/7

You can write something like this in your theme

```
function THEMENAME_button($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled'])) {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

```

and change markup for you needs.

Internet Explorer 6-7 doesn't work with button value attribute.

**Update**

```
function THEMENAME_button($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled'])) {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }

  return '<button' . drupal_attributes($element['#attributes']) . '>'. $element['#attributes']['value'] .'</button>';
}

```

# Answer
> -3 votes
If you are rendering your form using form--anyformname.tpl.php template file then make sure in that template file you are rendering these three thing at the end:

```
    <div>
    <?php print render($form['form_id']); ?>
    <?php print render($form['form_build_id']);?>
    <?php print render($form['form_token']); ?>
    </div>

```

---
Tags: 7, forms
---


# Question
Title: Commerce Module allowing user to customize product
is **drupal commerce** able to allow user customization of products in the following way. Imagine your product is a bike. You want your user to:

* Change color of the bike (and therefore changing price, depending on chosen color)
* Change wheel type (and therefore price)
* Change type of break (brand for example)
* Further, the individual product should be saved (cookie for example) and one should be able to share a link to the individual product (here I saw many examples where sharing the product does not work - because you will always go to the default product)

I was looking out there but could not find many shops that solve the descriped tasks.

I used **commerce kickstart** on simplytest.me - https://ds64.ply.st/tops/guy-short-sleeve-tee to have a quick view. If I change the color, add it to the shopping cart, click on checkout and click on edit item again, I will end up at the standard configuration. Therefore the whole configurator does not make sense if I can not edit and save my individual customized product.

**Nice to have** a descriptive text that summerizes the chosen attributes and therefor for example a max. weight of the bike could be calculated...

Nike for example generates a url with a random id that can be used to share the customized product...

http://store.nike.com/us/en\_us/product/air-max-95-id/?piid=40361&pbid=166815001#?pbid=166815001

Thanks for your aswers in advance! Pedro

# Answer
> 1 votes
Yes, you can do something like this example:

https://drupalcommerce.org/videos/tutorials/customizable-products-pizza-store

Have to tweak a bit for the sharing part, probably would go with a custom module and hook\_entity\_view\_alter() using the variables from the url to adjust for the specific changes.

---
Tags: commerce
---


title: Display block on first login only

text:
# Question
Title: Display block on first login only
I want to display a block on first login only and never after that, is there any module or something possible for that? I have a block which is visible always on the first page, but what i need is to show the block only once and never ever after. That block contains a link to start a javascript on page for the tour(Joyride Module). The problem is, If i select "Play tour once", It plays the tour once for every session and as soon as user comes after some time, I will restart the tour. I want the tour to start only once after login. I have decided to do it by showing the link to manually start the tour in a block and that block would be visible only after first login. So, is it possible?

# Answer
First Login Module will do the job for you , this is some description about this module from its page :

> A simple utility module which enables the use of "first logins". With this module the site admin can enable content or do things that appear only on the first login for users by using modules like Context or Views. Couple useful functions are included for use in custom modules.
> 2 votes

# Answer
You can create a hidden field on the user profile, like a flag, default value as 0, in a custom module you load the block and then change the value of the field.
> 1 votes

# Answer
Check out the
user alert module

Here is description how to use this module:

> Enable User Alerts Set the appropriate permissions for selected roles Set the User Alert block in the appropriate region of your theme. Create a user alert node.
> 1 votes

# Answer
There are multiple ways to check if it is the first time user has logged in. You can create and assign a custom role with the name of `logged_in` for any user who logs in. the level of permissions is not important for this role.

Now if any user logs in and he/she has this role, it means it is not the first time he/she visits your site otherwise it is the first time and you must load the block programmatically and assign the role to it programmatically. You can implement this in `hook_user_login` as follow:

```
function THEME_user_login(&$edit, $account) {
     if (!in_array('logged_in', $account->roles)) {
     // assign the role to the user and load the block programmatically , it is her/his first login

            $uid = $account->uid;// User ID of user that logs in
            $role_name = 'logged_in'; // The name of the role to add.
            if ($role = user_role_load_by_name($role_name)) {
             user_multiple_role_edit(array($uid), 'add_role', $role->rid);
            }
            $block = module_invoke('module_name', 'block_view', 'block_id');
            print render ($block);
       }
}

```

**Don't forget not to load (or assign the block) on (to) any region by default**
> 0 votes

---
Tags: users, blocks
---


# Question
Title: Masonry effect not loaded in D7 Masonry Views
I had installed Masonry Views module, along with Masonry module in my Drupal 7 site. In my view, I can select format as "Masonry", and had updated the details such as column width. But the output still displays the view like unfomatted list.

In my status report, it shows
jQuery Masonry: 2.1.08
jQuery Update: jQuery 1.7.1 and jQuery UI 1.10.2

My js file is in: www/mydomain/sites/all/libraries/masonry/jquery.masonry.min.js

I had flushed cached, but the masonry effect still doesn't appear. Any idea what's the problem?

# Answer
> 0 votes
It's just because you are just updating a `Jquery` version in front end theme but not updating in `admin` theme. Because `views` opens in `admin` theme so you should also update `Jquery` version in it. For getting this work just goto `admin/config/development/jquery_update` and click on `configure` link in front of `admin` theme, then select the same version of `Jquery` as you selected in `front` theme. Now you can edit the `masonry views` as per your needs and check the result.

---
Tags: 7, views
---


# Question
Title: Module Webform won't send email to certain address
For some reason the **normal** contact form won't work. It doesn't send any mail to any address I request. Therefore, I used the module Webform for Drupal 7.

The problem I have is almost the same described in this thread.

However, for me the problem is even when the domain name is the same. Like `user1@domain.com` works, but `info@domain.com` doesn't.

When I do send to a gmail account, there also is no problem.
Basically, the `info@domain.com` doesn't seem to be 'supported'.
All the other email addresses do work.

The domain-email is hosted by Gmail. (A Google Business account)

What am I missing?

# Answer
> 0 votes
I found out that this problem occurs because the mail is sent to the same server as the mail is sent from. The server itself thinks it is smart enough to handle this itself. This means de mail message is never 'leaving' the server. So, it'll never reach de gmail services.

# Answer
> 1 votes
I was having this same issue. I contacted my host (Hostmonster) and found that there is a setting in your Zone Editor that can fix this issue.

Under MX (Mail Exchanger) I selected Remote Mail Exchanger and under the section that says "Points to" I put exchange.domain.com (replace domain with your domain name). I did this because we are running all of our email through an exchange server.

Try calling your host and explaining the problem.

I hope this helps!

---
Tags: 7, webforms, emails
---


# Question
Title: Conditionaly display fields of another node on a node page
I am a Drupal beginner, have some CMS and PHP knowledge. I am strugling with a case which intuitively seems like a thing that had to be been solved many times.

I have these **content type**:

* `Product` with 2 fields `description` and `company`.
* `Company` with various fields but the ones that matter here are `company_intro`, `company_address`.

When I create a `product` page, I fill in the description and choose a company from a list. When I present the product page to the user, I want it to start with "company\_intro" from the selected company, followed by the description and ending with the address.

Is that possible?

# Answer
At first you need to make a relation between Product and Company . to do that you have to install a reference module , Entity References or References . After enabling the module (No different which one you install) you need to modify your product content type , remove your company field and add a new field of type reference to a node , then refer it to your Content type Company .

till now you have made a relation between Product and Company , now to do the rest of the job you can use Panels and Page Manager (included in CTools) .

Check this tutorial if you are not familiar with panels : Learning Panels and Page Manger
> 0 votes

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


# Question
Title: Select options not loading when using callback function
I am creating the select box form element as following

```
$form['select-user-group'] = array(
       '#type' => 'select',
       '#title' => t('Select a group'),
       '#options' => select_user_dropdown_options(),
       '#description' => t('Select a group to send the mail.'))

```

and am trying load the options for select box like follwing

```
function select_user_dropdown_options(){
    db_set_active('drupal');
    $result = db_query("select * from {content_type_usergroup}");
    $record = db_fetch_object($result);
    $str = '<select><option>-- Select a user group--</option>';
    while ($obj = db_fetch_object($result)) {
        $str .= '<option>'+$obj->field_p_group_name_value+'</option>';
     }
     $str .='</select>';
     return $str;
}

```

> But its not loading options to the select box , please help

# Answer
> 0 votes
The call back function should be like follows :

```
function select_user_dropdown_options(){
    db_set_active('drupal');
    $result = db_query('select * from {users}');
    $options = array();
    $options[] = '-- Select a user  --';
    while ($row = db_fetch_object($result)) {
      $options[$row->uid] = $row->name;
    }
     return $options;
}

```

# Answer
> 1 votes
Your select\_user\_dropdown\_options() function needs to return an array of options, not a block of HTML. See the #options section of the Form API documentation -- you should find yourself re-reading that Form API page a lot.

Your array will be in the form

```
array(
  'group_1' => 'Group 1',
  'group_2' => 'Group 2',
);

```

A pedantic note -- I believe that's really a function call as opposed to a callback. That's fine; I mention it mostly because you don't include the parentheses when providing the names of callback functions.

---
Tags: 6
---


# Question
Title: avoid duplicated records with drupal_write_record
I want to test `drupal_write_record`, the insert part is ok, but this function seem to duplicate records.

How to make a condition for if new record is already stored ?

some like db\_merge with key

Thank you

# Answer
This function can take 3 arguments , in this situation the third argument acts as an array of primary keys and if we pass the third argument to the function (primary key), it will update the record, if don't pass - it will insert a new record .
> 0 votes

---
Tags: database
---


# Question
Title: Add a link in management menu for specific role
I can't find the way to display a link in the management menu for specific roles. The link shows up only for administrator, despite all the access callbacks I tried.

In the view displayed by the page callback I declared same path, menu and access callbacks. As I don't know who is called last between module code and the view (?), I also tried with no menu nor access settings in the view.

If you could have a look at my implementation to check where I'm wrong ? Thanks a lot

```
function vts_dashboard_menu() {

  $items['admin/backoffice/production'] = array(
    'title' => 'Production',
    'description' => 'Edit catalogue',
    'page callback' => 'vts_dashboard_backoff_circuits',
    'access callback' => 'vts_dashboard_user_has_role',
    'access arguments' =>  array('éditeur voyages', 'éditeur taxonomie', 'administrator'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'management',

    //2 alternative tests below. EVEN WITH TRUE, doesn't show up for non admin
    //'access callback' => TRUE,
    //OR ...
    //'access callback' => 'node_access',
    //'access arguments' => array('view', 1),
  );

  $items['admin/backoffice/production/circuits'] = array(
    'title' => 'Circuits',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
    'access callback' => 'vts_dashboard_user_has_role',
    'access arguments' =>  array('éditeur voyages', 'administrator'),
  );
  // ... more items...
);
//page callback function
function vts_dashboard_backoff_circuits(){
  $viewname = 'circuits_vts';
  $viewdisplay = 'backoffice_products_list';
  return views_embed_view($viewname, $viewdisplay);
}
//access callback function
function vts_dashboard_user_has_role() {
  global $user;
  $roles = func_get_args();
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}

```

**Precision** : these roles can see the pages/tabs called if they access directly to the path.

# Answer
Shame on me ! The solution relied of course in a single line of my code, shared below in case it could help somebody.

I aimed to block many admin pages access, from which the `admin` path, in a radical manner :

```
function vts_dashboard_menu_alter(&$items) {
   $items['admin']['access callback'] = 'vts_dashboard_admin_access_only';
  //more items ...
}
function vts_dashboard_admin_access_only() {
  global $user;
  if( !in_array('administrator', $user->roles)){
    return false;
  }
  return true;
}

```

But `$items['admin']['access callback']` blocks also descendant menus items... commented out and all's fine again !

Be what it is, if any enlightened Drupal guru can tell me how to restrict access to `foo` path but no `foo/bar`, he'll receive all my consideration !
> 0 votes

---
Tags: routes
---


# Question
Title: How to correctly get Form API single checkbox value variable from database?
I created an `additional_settings` fieldset for node type forms that holds a single checkbox:

```
$form['MY_SETTING']['enabled'] = array(
  '#type' => 'checkbox',
  '#title' => t('Enable'),
  '#default_value' => variable_get('MY_SETTING_' . $form['#node_type']->type, FALSE),
);

```

When I check the checkbox and save the node type form the value gets stored like that: `MY_SETTING_MY_NODETYPE[0] = 'enabled'`. The `#default_value` only understands `TRUE` and `FALSE` and doesn't work with `enabled`. I've sneaked in other modules (p.e. comments module) and have seen that they solved that with constants. But how to apply a constant in that form logic and let it be saved to the database?

# Answer
> 1 votes
You could use constants in place of string literals, sure, but that's not related to the issue you're having. That's simply a matter of converting the statement you already have to a boolean.

Which is as easy as:

```
$bool_enabled = variable_get('MY_SETTING_' . $form['#node_type']->type, 'disabled') == 'enabled';
$form['MY_SETTING']['#default_value'] = $bool_enabled;

```

Incidentally, the string "enabled" evaluates to `TRUE` in PHP, so it's not possible for it "not to work with `enabled`", it's just that 'disabled' also evaluates to `TRUE`, so you won't ever see a falsey value.

Personally I think the simplest solution is store the variable as an integer, 1 or 0. Then you can just assign it straight to the form element and let PHP's implicit integer -\> boolean conversion take over. That's how all core (and contrib, that I've seen) modules handle it.

---
Tags: 7, forms
---


title: t() function doesn't render HTML

text:
# Question
Title: t() function doesn't render HTML
It is the `t()` function and the way I assigned value to a `body` field

```
$my_body_content = t('!frequency new comment(s) sent to <a href="!url">!title</a>', array('!frequency ' => $frequency , '!url ' => $url , '!title ' => $title));
$ewrapper->field_body->set(array(
        'value' => $my_body_content
) );

```

the `$frequency`, `$title` and `$url` are already set. This is the configuration of the `body` field (it allows `a` tag)

But it is what I get

**Why it doesn't render the HTML ?**

---

# UPDATE :

I edited the `body` by UI like this

and it worked! sounds the problem is because of the *PHP* code

# Answer
> 0 votes
Ok, I found it. I should have add the `format` to `field_body` assignment as follow:

```
$ewrapper->field_body->set(array('value' => $my_body_content,'format'=>'full_html'));

```

# Answer
> 2 votes
This code should work for you

```
$link = l($title, $url);
$my_body_content = t('!frequency new comment(s) sent to !link', array('!frequency ' => $frequency , '!link' => $link));
$ewrapper->field_body->set(array(
    'value' => $my_body_content
) );

```

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


# Question
Title: Custom Entity API does not give individual fields in Views, only (sometimes information-less) rendered entities
---

note: I'm currently exploring hook\_entity\_property\_info\_alter and clearing the cache forcibly by truncating the cache table as I've had many iterations of work on this over the years. *(Though I wouldn't recommend you trying that and if you do, back up first!)*

---

I've defined entities in `hook_entity_info`. But when I have I get differing results and none of them work in Views as I was hoping.

*"Paid subs"* doesn't give me control of individual fields and therefore allow me to mix one field here with another of a joined entity there. But it does give fairly decent information.

This is its definition in `hook_entity_info`:

```
$info['paid_sub'] = array(
    'label' => t('Paid subscription'),
    'plural label' => t('Paid subscriptions'),
    'description' => t('company paid subscriptions (in theory
        this could be just postage or the full cover price etc.'),
    'base table' => 'company_paid_subs',
    'entity keys' => array(
        'id' => 'psid',
    ),
    'uri callback' => 'entity_class_uri',
    'entity class' => 'PaidSubEntity',
    'controller class' => 'PaidSubEntityController',
    'admin ui' => array(
        'path' => 'admin/paid-subs',
        'controller class' => 'PaidSubEntityUIController',
        'menu wildcard' => '%paidsubentity',
        'file' => 'paidsubentity.admin.inc',
    ),
    'module' => 'company_subs',
    'access callback' => 'paidsubentity_access_callback',
    'label callback' => 'paidsubentity_label_callback',
    'views controller class' => 'EntityDefaultViewsController',
);

```

## paid subscriptions

---

---

## Subscription

This one: "Subscription" doesn't do anything remotely useful.

`hook_entity_info` code:

```
$info['subscription'] = array(
    'label' => t('Subscription'),
    'plural label' => t('Subscriptions'),
    'description' => t('A subscription (as opposed to
        user registrations, paid recipients of magazines, promo readers etc.)'),
    'base table' => 'subscription',
    'entity keys' => array(
        'id' => 'sid',
        'revision' => 'revision_id',
    ),
    'entity class' => 'SubscriptionEntity',
    'controller class' => 'SubscriptionEntityController',
    'module' => 'company_subs',
    'access callback' => 'subscriptionentity_access_callback',
    'label callback' => 'susbcriptionentity_label_callback',
    'revision table' => 'subscription_revision',
);

```

Is it because I have been overriding default configurations? What's the cause? Ideally I'd like to be able to select individual fields within an entity rather than having to rely on a rendered entity because I'd like to be able to select one field from one entity and another from another entity by using joins in `hook_views_data_alter`, like this (which worked just fine until I stopped defining each field in `hook_views_data` and turned the bespoke tables into entities specifically to try and utilise the extra functionality of core and contrib modules etc.):

```
$data['subscription']['user_id']
['relationship']['handler'] = 'views_handler_relationship';
$data['subscription']['user_id']
['relationship']['base'] = 'users';
$data['subscription']['user_id']
['relationship']['base field'] = 'uid';

```

# Answer
> 0 votes
If you've tried conventional approaches and they haven't worked (like me) then you might find that there are a few things that you need to do:

Firstly for me was truncating the cache table just to get rid of a whole heap of old data from previous iterations of my designs. Then it was simply defining hook\_entity\_property\_info as suggested. To check if things are working you can debug and use hook\_views\_data\_alter(&$info) and check out the variables. You'll probably see views has two varieties (unless I'm still doing something wrong):

entity\_subscription and views\_entity\_subscription...

```
entity_subscription Array [3]
    table   Array [2]
        group   Subscription
        entity type subscription
    user_id Array [4]
        title   user id
        help    user id of registrant
        field   Array [2]
            handler entity_views_handler_field_entity
            type    user
        relationship    Array [5]
            handler entity_views_handler_relationship
            base    entity_user
            base field  uid
            relationship field  user_id
            label   user id
    magazine_id Array [4]
        title   magazine id
        help    magazine id of this subscription
        field   Array [2]
            handler entity_views_handler_field_entity
            type    magazine
        relationship    Array [5]
            handler entity_views_handler_relationship
            base    entity_magazine
            base field  mid
            relationship field  magazine_id
            label   magazine id
views_entity_subscription   Array [1]
    rendered_entity Array [3]
        title   Rendered Subscription
        help    The Subscription of the current relationship rendered using a view mode.
        field   Array [3]
            handler entity_views_handler_field_entity
            type    subscription
            real field  entity object

```

And then as is suggested a whole heap of different places, those fields will be available and if you go to "Relationships" in the Views config then you can also add other entities and their properties. For example 'user' as is the case with "entity\_subscription" above, defined by specifying "type" as "user".

Oh, and also - the views\_entity\_subscription was just a rendered entity, I presume this is for a direct entity/views use, for example when creating a view just of that entity type.

One final thing: the entity api module itself actually has, in the folder within that module called 'modules' (i.e. sites/all/modules/entity/modules/...) a whole heap of hook\_entity\_property\_info() for the main (core) Drupal entities. This means you can open user.info.inc for example and see how the module authors wrote the entity\_property\_info for the user entity.

---
Tags: views, entities
---


# Question
Title: How to send hidden field value to db on webform submit
I am using Drupal 7 webform api, have a created a field in my `_form_alter` hook in a custom module, but while on page load the hidden field contains the correct value, when I submit the form it does not save to the mysql table, and gives me an empty cell

```
$form['State'] = array(
  '#type' => 'hidden',
  '#value' => 'Unread',
  '#attributes' => array('id' => array('stateform')),
);

```

How can I make it save to the mysql table on submit?

UPDATE:

```
$form['State'] = array(
'#type' => 'hidden',
'#title' => t('Hidden'),
'#attributes' => array('id' => array('state')),
);
drupal_add_js(drupal_get_path('module','mymodule') . '/js/custom.js');

```

# Answer
> 1 votes
You also will need to write a hook\_form\_submit for your form. In the \_form\_submit() you will take the hidden value and store it where you like.

That is the simple answer for your question. If you provide more details there could be other ways of handling the data. What is your form action?

# Answer
> 0 votes
You do not need any hooks to do this. You can simply create an element via the webform UI of type "hidden." and it will save when the webform is submitted.

# Answer
> 0 votes
This value should be stored in

$form\_state\['values'\]

You can access that in your hook\_form\_submit. It wouldn't hurt to do a drupal\_set\_message on $form\_state\['values'\], so that you can see exactly what values are stored there.

---
Tags: 7, webforms
---


title: Is it possible to make path to /%?

text:
# Question
Title: Is it possible to make path to /%?
My question: Is it possible to make path to /% ?

I have path that goes categories/% and that works when I type categories/hats it returns me category hat with all product it's taged with.

I would like to be able to type url/hats and to have above explained functionality.

Is this possible and what do i change in view it is not possible to make path just /% ?

# Answer
> 1 votes
You can do that quite easily with the Views module and contextual filters.

The one thing that I don't suggest doing is using Taxonomy. I don't like using taxonomy because besides it being a non-indexed list of vocabulary, it allows for too much variance. For instance in taxonomy:

```
"hat" != "Hat" != "hAt"

```

So, if you tagged one page as "hat" and the other "Hat", you would have to search for both term to get the content to display.

It much better to use the existing functionality of Content Types to create your "taxonomy." Coupled with Views, Entity Reference, and Path Auto, you can do exactly what you are looking to do with a minimum of additional modules and "no taxonomy."

I would definitely suggest taking a look at the Relativity Data Model put out by Jay Epstien.

The Florida Drupal Camp website was redesigned with this model. The most important thing to notice is the speed at which things load.

I have also been using it quite extensively and can tell you that excluding content, my site is less than 5K in size; that's about the size of an iPhone app. This is accomplished mostly due to the fact I am running less than 20 modules total.

# Answer
> 0 votes
What you need to pass an argument from url to view is Contextual filter , in views you will find it below advanced section , add a contextual filter based on your taxonomy and you are done , here is a tutorial about that : Contextual Filter Tutorial

---
Tags: views, uri
---


title: Translating contextual filter nid value

text:
# Question
Title: Translating contextual filter nid value
On a multilingual site, the function named `language_negotiation_get_switch_links($type, $path)` looks up the content translation and enables user to switch to parallel content if available. What if the path comes from Views with contextual filter being the node ID? Say, in English it'd be `en/news/197` but in German `de/nachrichten/198`. Drupal/Views tend to leave the contextual filter untouched and produces invalid criss-cross paths such as `de/news/197`. There seems to be no way to translated the value into one that belongs to a given translation set.

Is there? Or maybe I'm approaching the problem in a wrong way...

# Answer
> 1 votes
The key was using two functions: `drupal_get_normal_path()` and `i18n_get_path_translations()`. Inside `hook_language_switch_links_alter()` you can modify the href attribute of each language switcher.

# Answer
> 0 votes
Implementing hook\_language\_switch\_links\_alter() is definitely the way to go. Here is the code along with two (2) helper functions, assuming there are display variants for each language.

```
/**
 * Implements hook_language_switch_links_alter().
 *
 * This is a workaround for Path Translation not supporting Views' contextual filters.
 * Alter the language switcher to switch between path/to/[term] and different
 * paths for different languages.
 */
function mymodule_language_switch_links_alter(array &$links, $type, $path) {

  // Load the current view if there is one.
  $view = views_get_page_view();

  // Act only if we're looking at the view in question.
  if (($type == "language_content") && isset($view) && ($view->name == 'myview')) {

    // Skip situations where there's no argument.  This is handled by Path Translatoon.
    if (isset($view->args[0]) && ($view->args[0] != mymodule_get_myview_view_all_term($view))) {

      // Iterate across all language links.
      $language_active = $GLOBALS['language']->language;
      $displays = mymodule_get_myview_view_language_displays();
      foreach ($links as $language_current => &$link) {

        // Skip the active language.
        if ($language_current == $language_active) {
          continue;
        }

        // Set the path for the current language.
        $path = $view->display[$displays[$language_current]]->display_options['path'];
        $link['href'] = strtok($path, '/') . '/' . $view->args[0];
      }
      // Break the foreach reference.
      unset($link);
    }
  }
}

/**
 * Returns the list of displays for the view in question, keyed by language.
 *
 * @return array
 *   The list of displays.
 */
function mymodule_get_myview_view_language_displays() {
  return array(
    'en' => 'page_myview_en',
    'fr' => 'page_myview_fr',
  );
}

/**
 * Get the language-specific term representing all items.
 *
 * @param view $view
 *   The previously loaded view in question.  Optional.
 * @return string
 *   The term.  If there's no translation in the current language, "all" is used.
 */
function mymodule_get_myview_view_all_term($view = NULL) {

  // Load the view if it wasn't provided.
  $view = (is_null($view) ? views_get_view('myview') : $view);

  // Get the current language and the display names for each defined language.
  $language = $GLOBALS['language']->language;
  $displays = mymodule_get_myview_view_language_displays();

  // Return the language's "all" term, or the default if there isn't one.
  if (isset($view->display[$displays[$language]]->display_options['arguments']['tid']['exception']['value'])) {
    return $view->display[$displays[$language]]->display_options['arguments']['tid']['exception']['value'];
  }
  else {
    return 'all';
  }
}

```

Note that this doesn't handle the translation of the term itself within the path, only the part of the path leading up to it. For now, that will always be in the default language. This is the separate issue Views contextual filter validation: Support ET-translated taxonomy term name.

---
Tags: nodes, views, i18n-l10n
---


# Question
Title: Term translations not working as View's path contextual filter
Let's say you have a taxonomy called `Animals` and you have terms like `Dog`, `Cat`, `Horse`, etc. Every term has its translation, so for example for dogs you have `Hund` and `Chien`. Now you want to make a View which generates a page that lists content tagged with the Animals term reference, contextually filtering the tag based on the URL part.

And this is the part I'm having difficulties with. The contextual filter I made works perfectly with source language values and converts properly to term ID. So I'm getting correct listing (both in preview pane and generated page) for `/animals/dog` but incorrect for `/tiere/hund`.

The contextual filter is set to `Content: Animal Genre (Translated)` and validation to `Localised term or synonym converted to term ID` (actually I tried perhaps every possible combination of i18n and non-i18n options here, no joy).

I trie out another solution - with `Content: Has taxonomy term ID` \+ relationship (as described here).

Is it something I'm not setting up correctly or is there a bug around i18n, Views, i18nviews...? I'd be grateful for any guidance

# Answer
Implementing hook\_language\_switch\_links\_alter() is definitely the way to go. Here is the code along with two (2) helper functions, assuming there are display variants for each language.

```
/**
 * Implements hook_language_switch_links_alter().
 *
 * This is a workaround for Path Translation not supporting Views' contextual filters.
 * Alter the language switcher to switch between path/to/[term] and different
 * paths for different languages.
 */
function mymodule_language_switch_links_alter(array &$links, $type, $path) {

  // Load the current view if there is one.
  $view = views_get_page_view();

  // Act only if we're looking at the view in question.
  if (($type == "language_content") && isset($view) && ($view->name == 'myview')) {

    // Skip situations where there's no argument.  This is handled by Path Translatoon.
    if (isset($view->args[0]) && ($view->args[0] != mymodule_get_myview_view_all_term($view))) {

      // Iterate across all language links.
      $language_active = $GLOBALS['language']->language;
      $displays = mymodule_get_myview_view_language_displays();
      foreach ($links as $language_current => &$link) {

        // Skip the active language.
        if ($language_current == $language_active) {
          continue;
        }

        // Set the path for the current language.
        $path = $view->display[$displays[$language_current]]->display_options['path'];
        $link['href'] = strtok($path, '/') . '/' . $view->args[0];
      }
      // Break the foreach reference.
      unset($link);
    }
  }
}

/**
 * Returns the list of displays for the view in question, keyed by language.
 *
 * @return array
 *   The list of displays.
 */
function mymodule_get_myview_view_language_displays() {
  return array(
    'en' => 'page_myview_en',
    'fr' => 'page_myview_fr',
  );
}

/**
 * Get the language-specific term representing all items.
 *
 * @param view $view
 *   The previously loaded view in question.  Optional.
 * @return string
 *   The term.  If there's no translation in the current language, "all" is used.
 */
function mymodule_get_myview_view_all_term($view = NULL) {

  // Load the view if it wasn't provided.
  $view = (is_null($view) ? views_get_view('myview') : $view);

  // Get the current language and the display names for each defined language.
  $language = $GLOBALS['language']->language;
  $displays = mymodule_get_myview_view_language_displays();

  // Return the language's "all" term, or the default if there isn't one.
  if (isset($view->display[$displays[$language]]->display_options['arguments']['tid']['exception']['value'])) {
    return $view->display[$displays[$language]]->display_options['arguments']['tid']['exception']['value'];
  }
  else {
    return 'all';
  }
}

```

Note that this doesn't handle the translation of the term itself within the path, only the part of the path leading up to it. For now, that will always be in the default language. This is the separate issue Views contextual filter validation: Support ET-translated taxonomy term name.
> 0 votes

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


title: Editing the front page template

text:
# Question
Title: Editing the front page template
I am trying to change the format of the content promoted to the front page. I want to move the display order of the `title` below the `image`. By default it's set to `title`, `image` and then `Read More`.

Editing the content type (manage field, manage displays) does not do anything in this regard.

Manage display: I've set the order from Image first then Body. (no effect)

Teaser: I've set it to only show the Image (body is hidden) (no effect)

I've read the docs to change the `page.tpl.php` to `page--front.tpl.php` but I don't see any options to move the title down below the image in this file. (I only see this code in node.tpl.php.)

I can move the title block under the content block and it works, but this affects all pages.

**How can I change this only for the front page, so it doesn't affect all pages?**

node.tpl.php

Title block

```
<?php print render($title_prefix); ?>
<?php if (!$page): ?>
 <h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>"><?php print $title; ?></a>
 </h2>
<?php endif; ?>
<?php print render($title_suffix); ?>

```

Content block

```
<div class="content clearfix"<?php print $content_attributes; ?>>
<?php
  // We hide the comments and links now so that we can render them later.
  hide($content['comments']);
  hide($content['links']);
  print render($content);
?>

```

# Answer
> 1 votes
There are many possible ways to customize your front page content.

One of the easiest would be to create a view with page display and set the field order as you like and give a path to the view. Now you can change your frontpage to the path of this view (Configuration \> Site Information - Default front page).

If you want to go with the standard front page and rearrange in the template as you described you could use drupal\_is\_front\_page() to have different parts of the template for frontpage and other pages.

# Answer
> 1 votes
The solution of Stefan Korn is good and simple.
If I'm not mistaken, there is an alternative solution, shown here, where it is recommended to use template\_preprocess\_node() in order to be able to work only on the file *node--front.tpl.php*, "while your original node.tpl.php will be used everywhere else." (quote)

# Answer
> 0 votes
Usually the content generated in front page has nothing to do with the `page--front.tpl.php`, basically the content is being rendered in `content` region, it is probably a list of rendered entity in your front page with `teaser` display or in some cases it might be a views list which I doubt it. unless you provide more info about what and how you already displaying your content, there's nothing much we can do to help you!

---
Tags: theming
---


title: set a id for a div class in drupal

text:
# Question
Title: set a id for a div class in drupal
Anyone help me how to set the id for a div class dynamically in code. Let suppose class name by group\_left

```
      <div class-"group_left article_left">

```

I have to add a id attribute for this class "group\_left article left"

I have used the java script to set the id but I can't.This is my code.

```
   var thediv = document.getElementByClassName(".group-left ");
    thediv.setAttribute("id", "pad_id");

```

There is any way API to add attribute id for a class in drupal.please help me.

# Answer
> 1 votes
You would be better off using jQuery:

```
(function($) {
  $(function() {
    // Grab the element with both group_left and article_left class and set an ID attribute.
    $('.group_left.article_left').attr('id', 'pad_id');
  });
})(jQuery);

```

It's worth checking that the element with both of those classes is unique on the page, if the same ID is added to more than one element then the document will become invalid and you might have problems with other javascript.

# Answer
> 1 votes
I just came across this too, I used a simple rewrite in my view. Here are the details.

You can also use a template override, see this example.

# Answer
> 1 votes
I needed to stamp teasers with named anchors so to provide a jump-to behavior - I think you might dig into the node or field template and do something like:

```
<?php print '<div id="node-' . $node->type . '-' . $node->nid . '"></div>'; ?>

```

# Answer
> 0 votes
Just wanted to add how I had to add an ID to a div.class element in drupal. I tried what Clive put in and it didn't work for me. The below add it for me just fine.

```
jQuery(document).ready(function($) {
  // Code that uses jQuery's $ can follow here.
  $('div.field-print-link').attr('id', 'newsletterPrint');
});

```

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


# Question
Title: Possible to require custom module dependancy on a specific dev version?
Is it possible for my custom module to enforce it's dependability on a specific dev version of a particular module?

E.g. my custom module, foo is dependant on variable module `7.x-1.1+26-dev`.

# Answer
Here is the info. Writing .info files (Drupal 7.x)

```
dependencies[] = exampleapi (1.x)

```

The above module requires any minor version of the module in the 1.x branch (1.0, 1.1, 1.2-beta4, etc.)

**The dependencies\[\] property in the .info file can also optionally specify operators:**

```
= or == equals (optional: equals is the default)
> greater than
< lesser than
>= greater than or equal to
<= lesser than or equal to
!= not equal to

```
> 4 votes

# Answer
Drupal 7.x does not support development dependencies as tagged by drupal.org's packaging system. A development identifier (`+XX-dev`) will be removed from the dependency before a version comparison. There are a couple surprises with the comparison, so it's worth detailing further.

## Dependency version parsing

The dependency's version, as found in a module's info file, is parsed by `drupal_parse_dependency()`. The version is separated into three parts via regular expressions.

```
$p_core = '(?:' . preg_quote(DRUPAL_CORE_COMPATIBILITY) . '-)?';
$p_major = '(?P<major>\d+)';
$p_minor = '(?P<minor>(?:\d+|x)(?:-[A-Za-z]+\d+)?)';

```

The minor part may include an identifier (*alpha*, *beta*, *rc*) as long as it is preceded by `-` and followed by one or more decimal digits. Drupal packaging development identifier, which uses a + as separator, won't match the minor's identifier regex and it's removed. For example, `7.x-1.1+10-dev` will be simplified to `7.x-1.1`1.

## Version comparison

The version comparison happens in `drupal_check_incompatibility()`, which uses two parameters:

* `$v`: The parsed dependency structure from `drupal_parse_dependency()`
* `$current_version`: The version to check against

The parsed `$v` will already have had any development identifiers removed, but `$current_version`, retrieved directly from the the module's .info file with the core (`7.x`) removed, may contain a development identifier. This doesn't typically cause problems because the actual version comparison, done by the internal PHP function `version_compare()`, converts the *+* separator to *.*:

> The function first replaces \_, - and + with a dot . in the version strings and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'. Then it compares the parts starting from left to right. If a part contains special version strings these are handled in the following order: any string not found in this list \< dev \< alpha = a \< beta = b \< RC = rc \< # \< pl = p. This way not only versions with different levels like '4.1' and '4.1.2' can be compared but also any PHP specific version containing development state.

Therefore, the development module's development identifier becomes a patch number2 with *dev* appended. For example, *1.1+10-dev* becomes *1.1.10.dev*.

Patch releases are greater than corresponding minor releases (*1.1.10.dev* \> *1.1(.0)*), and because most dependencies specify a greater or equal version, the development module is marked compatible.

For example, `(>=7.x-1.1)` will be compatible with a *7.x-1.1+10-dev* will be compatible because `version_compare()` consider *1.1.10.dev* higher or equal to *1.1*.

However, the dependency `(==7.x-1.1+10-dev)` won't be compatible with *7.x-1.1+10-dev*.

1 Technically, the core is also dropped and the actual comparison value would be *1.1*. I've retained the core for demonstrative purposes.

2 I mean the semantic versioning's major, minor, and patch.
> 1 votes

---
Tags: 7
---


# Question
Title: Programmatically render menu on search view
I'm trying to programmatically build a menu on my site, it works fine on all pages except a search view. This code I'm using is below:

```
        $config = array('menu_name' => $menu_name, 'level' => 2, 'depth' => 10, 'expanded' => true);
        $menu_tree = menu_build_tree($config);

```

When I do a var\_dump() of $menu\_tree it has a content key in the array which has all the menu items, but only if the page is a 'normal' node. If it's the search results view then that array key is empty.

Does anyone have any idea why this is?

I also have two custom functions to change the output of the menu however these don't seem to be called as if I do a var\_dump("test") at the start of them it has no affect. The two custom methods are:

```
THEME_menu_tree__menu_footer_links_1()
THEME_menu_link__menu_footer_links_1()

```

# Answer
> 0 votes
I worked it out, turns out the problem is different to what I thought.

Because the search view isn't in the menu structure I need to add different values to the $config array. Firstly I needed to add "parent\_mid" so it knew what menu item to use as the root for the menu tree & I needed to change the level to 1 to output the links I wanted. Although 2 was still outputting links, just the wrong ones for what I needed.

If you need to work out what the parent\_mid is go to Admin \> Structure \> Menus \> Your Menu & hover over the edit link for the menu item you want to be the root of the menu tree, the ID is in the URL. You can also get it programatically, like I did, using menu\_node\_get\_links().

---
Tags: 7, views, routes
---


title: How do I get the default user picture?

text:
# Question
Title: How do I get the default user picture?
I am using the following code to get the URL of the image associated to a user.

```
$user=\Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$picture=$user->get('user_picture')->entity->url();

```

If the user didn't upload a picture, this code doesn't return anything useful.

How can I get the URL for the default image?

# Answer
User pictures are no longer guaranteed to exist in Drupal 8. It is added by the standard profile, but not added if you use the minimal profile.

The user picture is simply a image field attached to the user bundle, so normal file field API's can be used. **To get the file path of the default image for the user picture field attached to the user bundle:**

```
<?php
$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::service('entity.repository')->loadEntityByUuid('file', $default_image['uuid']);
$file->getFileUri();
?>

```

I'm not sure what you are trying to achieve. If you are looking for better default avatars, then I encourage you to look at Avatar Kit for Drupal 8. *Disclaimer: I am the developer of Avatar Kit*.
> 5 votes

---
Tags: users, media
---