# Question
Title: How can I use exposed filter likes "views tree" in views of content?
I want to add exposed filter that shows taxonomy parents and children to views, this view's type is content. Clearly my goal isn't creating menu by taxonomy, my goal is creating exposed filter for content of views.

Like Below.

# Answer
The Taxonomy Menu module looks like just what you're after.

https://www.drupal.org/project/taxonomy\_menu
> 0 votes

# Answer
I think a better solution for this is Better Exposed Filters. Just add the exposed filter as you normally do and use Better Exposed Filter with checkboxes. That's it.
> 0 votes

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


# Question
Title: Theme's css and js files are not being loaded
I was trying to create a theme for Drupal 8.1.8. My CSS and JS files unfortunately cannot be loaded. I have checked if I used any tab characters, but I have used always 2 space characters for an indent.

I have read the documentation page at Drupal.org: https://www.drupal.org/theme-guide/8/assets. I was trying around 2 hours with all possible combination. Also I tried the google search, Drupal core code inspection.. I could not figure it out.

My theme is located at **themes/englishtrainer**. The css is located in **themes/englishtrainer/css** and the javascript files are in **themes/englishtrainer/js**. The theme can be enabled as a theme without problems.

The contents of my theme's files in the following.

**englishtrainer.info.yml:**

```
name: Englishtrainer
type: theme
version: 8.x-1.0
core: 8.x
package: Custom
# Scripts & Styles
libraries:
  - englishtrainer/global-styling

```

**englishtrainer.libraries.yml:**

```
global-styling:
  version: 1.x
  css:
    theme:
      css/css-test.css: {}
  js:
    js/js-test.js: {}

```

**css/css-test.css:**

```
body {
    background-color: red;
}

```

**js/js-test.js:**

```
alert('it is loaded!');

```

I was checking the html markup for any occurrences. The javascript console has been also checked. It does not contain any entries.

Do you have any idea?

# Answer
**englishtrainer.info.yml**:

```
name: Englishtrainer
type: theme
core: 8.x
version: '1.0.0'
libraries:
  - englishtrainer/base
regions:
  header: Header

```

No need for `package`

**englishtrainer.libraries.yml**:

```
base:
  version: VERSION
  css:
    theme:
      css/css-test.css: {}
  js:
    js/js-test.js: {}

```

Use `base` to start things off and the `VERSION` keyword will take the version info from **englishtrainer.info.yml**.
> 1 votes

# Answer
Solved it. My issue was, that I had a theme "and" a module with the same name. However the module did not implement any theming components. But this broke the theme. After I have uninstalled the module with the same name, the background was red (css worked) and the javascript alert appeared (javascript worked).

Thank you for your attention.
> 0 votes

---
Tags: theming, 8
---


title: Unable to change #markup

text:
# Question
Title: Unable to change #markup
I'm using Drupal 8, and I want to change the markup of `more_links` from `<a href="/node">more</a>` to something like `<a class="some class" href="/node">more</a>`. I have tried with `mytheme_preprocess_container(&$vars)` with the help of `kint` debug to analysis the `$vars` array. `$vars['element']['#markup']` returns `<a href="/node">more</a>`. However, setting it to a value does not applied.

```
function saidbakr_preprocess_container(&$vars){
 $vars['element']['#markup'] = 'HHHHHHHH';
}

```

I tried to use the `#children` but it has a protected property of markup and I don't know to how use the `create` method?

```
$vars['element']['#children']->create('HHHHH')

```

What's the problem here?

## Update:

I just have gotten a semi solution, I regard it *semi* because it depends on a direct `echo` from `template_preprocess_container` like the follwoing:

```
function saidbakr_preprocess_container(&$vars){
  $elem = $vars['element'];
  if ($elem['#type'] == 'more_link'){
    $vars['children'] ='';
    echo str_replace('<a','<a class="btn btn-primary" ', $vars['element']['#children']);
  }
}

```

I used `echo` because setting HTML tags string to `$vars['children']` leads them to be printed as entities on the page. i.e you see the HTML tag of the link instead of the actual link. Is there any concerns about using direct `echo` from the preprocess functions?

# Answer
You should be able to change the more variable in template\_preprocess\_views\_view, like:

```
function YOUR_THEME_preprocess_views_view(&$variables) {
  $variables['more'] = \Drupal\Core\Render\Markup::create('<a href="#">HHH</a>');
}

```
> 2 votes

# Answer
It's unclear, where you are. The template `container` has `children` as output, not `element`. Also in `views-view` there is no `element`. If you change variables, that are not used in the twig, then this will do nothing. Look in the comments at the top of the twig to see what you can change.

But to answer the question. `create()` is a static function and it is used when you create a new Markup object:

```
$vars['abc'] = \Drupal\Core\Render\Markup::create('abc');

```

I don't think Markup has a property or method to change it. You replace the old object with a new one.
> 0 votes

# Answer
As per my understanding you can change the url as well as text of the read more but you will have to implement **template\_preprocess\_links()**

Below is code snippet to achieve what you are looking for :

> use Drupal\Core\Url;

```
 function mytheme_preprocess_links(&$variables) {
      // some logic enclosing this block
       $variables['links']['node-readmore']['link']['#title'] = t('Custom text ');
$variables['links']['node-readmore']['link']['#url'] = Url::fromUri('base:' . 'node');
$variables['node']['#links']['node-readmore']['#attributes']['class'][]
= 'btn btn-primary';

    }

```
> 0 votes

---
Tags: views, theming
---


# Question
Title: Cron not working when called from SSH php curl - Elysia cron module activated
I have Elysia cron module activated, with some cron task scheduled.

I have a crontab pointing to an sh every \*/2 minutes. The sh executes a php with a curl call to `cron.php?cron_key=CRON-KEY`. It was working perfectly some weeks ago. Suddenly, it has stopped working. When I launch the same cron.php address by browser, it works perfectly, executes the cron with all the scheduled tasks in order as defined by Elysia config.

But when the same cron.php is called via the SSH php (console or just through the cron daemon), it does not work. It gives no error or hint, just does not do anything. I have tested curl in the same domain, with GET parameters, to a different php file, and it is working. I have no idea what can be happening, I have re-installed Elysia cron, and the same results. I cannot understand why Drupal knows that the script is called via a non-browser script and why it stops working.

# Answer
After much debugging (too much debugging, I am afraid), I discovered that the problem was in that the cron did not go through all the steps (bootstrap). The problem (which was not logged) was in the Domain Access module, in which I deleted the English language in one of the domain. IMHO, this is a bug, but not sure if of the module, the core or what. I cannot afford wasting 8 hours of my time looking for errors when I make a simple change that, in principle, should not affect the entire performance of Drupal. This is the kind of things that make Drupal not trustworthy.
> 0 votes

---
Tags: cron
---


# Question
Title: Can I pass file name as a parameter to menus page arguments?
I have a hyperlink, in that I am passing the dynamic foldernames and filenames as url like below.

```
 $data .= '<div><a href="'. $base_url.'/custom/delete/'.$foldnames.'/' .$filenames .'">' ."--". $filenames .'</a></div>';

```

When I click on this, it will go to the particular menu, in the menu I am calling a function to do delete functionality. Below is the menu implemetation

```
 $items = array();
    $items['/delete/%/%'] = array(
    'title' => "Delete Files",
    'page callback' => 'delete_public_files',
    'page arguments' => array($arg1, $arg2),
    'access arguments' => array('administer custom settings'),
   'type' => MENU_CALLBACK,
  );

```

I am getting confused while using the arguments here. Can anybody help me that how I have to hit this `sitename/custom/delete/foldnames/filenames` url. On the samy way how can call `delete_public_files` function with $foldnames and $filenames as arguments.

# Answer
**Example**

```
function mymodule_menu() {
  $items = array();
  $items['custom/delete/%/%'] = array(
    'title' => "Delete Files"
    'page callback' => 'delete_public_files',
    'page arguments' => array(2, 3),
    'access arguments' => array('administer custom settings'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

Please use integer in the array of `page arguments` to specify the value in url. The url is split in this format: `0/1/2/3`
> 0 votes

---
Tags: 7, hooks, files
---


# Question
Title: DS Views Block Field page visibility settings
I have a Views block *Sectors*. I have created a DS block field that renders this view and I have configured it to be available only for specific `bundle|view_mode`. It gets displayed on every `bundle|view_mode` page after that.

I wan't to configure this block to be visible only on a certain page(s) and not in all `bundle|view_mode` specified. Basically, I need a **Show block on specific pages** settings as in D7.

# Answer
Go to `/admin/structure/block` under the disabled region, click on `Place block` button and try searching for it on the search box, if you find it, place it and then `Configure`.
> 0 votes

---
Tags: 8, display-suite
---


# Question
Title: How do I change the admin password form PHPMyAdmin?
How do I change the admin password form PHPMyAdmin?

# Answer
> 1 votes
if you have the drush installed in your system . You can use the below command :

```
drush user-password USERNAME --password="SOMEPASSWORD"

```

For more reference refer this

# Answer
> 0 votes
You can change with going to users table

1 Run query

```
`UPDATE users SET name='admin', pass='$S$Drl0vgZ9yuU9uc4JyaTMHxMPriC7q/PsOUOx52fCrVQSTpI/Tu4x' WHERE uid = 1;`

```
1. change email address in users table getting the password reset link (only applicable for if password is foget ) checkout this link for more information

# Answer
> 0 votes
In phpmyadmin run this query.Then your username is "admin" and password is "admin".

```
   'UPDATE users SET name='admin', pass='$S$DUW/9/iT3a6vAzdFrjsXki9IHC.CjgW4yrsZlDTzMlKXdd5Wk.mb' WHERE uid = 1;'

```

# Answer
> 0 votes
By using drush you can do like this:

> drush uli or drush uli uid

drush uli provides link like this for admin(by default)

http://default/user/reset/1/1470735542/FAG2Elp2J\_eN4k6XMq\_KleQmBTmQ1Uoitl0Vs86JvdA Replace default with your site URL.

Refer this link.

---
Tags: 7
---


title: How to delete files from public folder?

text:
# Question
Title: How to delete files from public folder?
I am storing some files in public folder, programmatically I want to delete those files through the provided path. I tried using below code, but not worked.

```
function delete_public_files($arg1, $arg2){
  $uri = 'public://';
  $path= file_create_url($uri);
  $fullpath = $path.$arg1.'/'.$arg2;

  //file_unmanaged_delete($fullpath);

  $fid = db_query("SELECT fid FROM {file_managed} WHERE uri = :path", array(':path' => $fullpath))->fetchField();
  if ($fid) {
    $file = file_load($fid);
    file_delete($file);
  }
  else {
    file_unmanaged_delete($fullpath);
  }
}

```

These files are not recorded in the file\_managed table and file\_usage table also. So how can I delete these files. If I pass the path to `file_delete($fullpath);` It will says error that first argument should be object. So how can I achieve all these things. Thanks for any appreciation.

# Answer
> 2 votes
file\_delete deletes a file where it is located and its database record also.

First check file\_load whether it is rendering an object file.

```
// load the file
$file = file_load('YOUR_FILE_ID');

// delete file from disk and from database
file_delete($file);

```

The `file_delete()` also takes a second argument `$force` that if set to `TRUE` will remove the file even if it's reported as in use by the `file_usage` table.

use `drupal_unlink($fullpath)` if files are not recorded in the file\_managed table and file\_usage table.

See this

---
Tags: 7, hooks, files
---


title: Are the same node paths a problem?

text:
# Question
Title: Are the same node paths a problem?
I created a website with Drupal 8 in 4 languages. When I access a node in the default (English) language, I get to a page with a path of e.g. localhost/contact, just as it should be. Now, when I switch to Japanese, I would expect it to be localhost/jp/contact, but it is localhost/jp/node/13 (the page does display though). Both nodes have the same path listed (/contact) when I inspect them in the administration area.

For the record, my language detection methods are set in this order, in case it matters:

1. Account administration pages
2. URL *(note: URL path prefixes are configured)*
3. Session
4. User
5. Browser
6. Selected language

How can I achieve the expected state I mentioned above? That is, having the same (relative) paths set for each language variant of a node, while the language part of the URL would ensure displaying the proper language version of the node and while the URL would be human-readable and not just the node ID?

# Answer
> 2 votes
You either need to make your aliases not language specific (you can only do that in the alias administration page right now, not in the node edit form) or you need to create one for each language.

If the alias shows up for all languages, make sure you made the path field translatable in the content translation settings, maybe something doesn't work correctly otherwise.

See https://www.drupal.org/node/2775275 for an issue to allow language-unspecific aliases. You could also use tokens to get the original language with pathauto to work around it.

---
Tags: 8, i18n-l10n
---


# Question
Title: How to use a sub-domain for a specific content type?
I have a blog content type. My client would like the domain to be blog.example.com for only that content type. I would like to know the best way to approach this, whether it be a rewrite rule or using Domain Access Module.

I have installed the Domain Access module, and created my primary domain (example.com) and another domain (blog.example.com) for the blog - but am now not sure how to go about assigning that domain for my blog content type.

Any advice is much appreciated - please keep in mind this is for Drupal 8.

# Answer
> 0 votes
In hook\_ENTITY\_TYPE\_view\_alter you can check for your content type and redirect here. Lets give a try , maybe it will help

---
Tags: 8, domain-access, subsites
---


# Question
Title: How to use admin table theme with multistep form?
I have 1000 records of users with name and checkbox. I want to show the list of users in table theme. I have use

```
theme('table', array('header' => $header, 'rows' => $rows));

```

But how to use it with multistep form. Please find the below code.

```
function getForm() {
$form = array();
$step1 = array();

drupal_add_js("
function checkUncheckAll(theElement){
  var theForm = theElement.form, z = 0;
  for(z=0; z<theForm.length;z++){
    if(theForm[z].type == 'checkbox' && theForm[z].name != 'checkall'){
      theForm[z].checked = theElement.checked;
    }
  }
}", 'inline');

$step1['user'] = array(
   '#type' => 'container',
   '#tree' => TRUE,
   '#prefix' => '<div id="user">',
   '#suffix' => '</div>',
);
$results = db_query("SELECT* FROM {user_token} ut LEFT JOIN {users} u ON u.uid= ut.uid where u.status=1 and u.uid!=0 group by ut.uid ")->fetchAll();

foreach($results as $k=>$result)
{
  $user[$result->uid] = $result->name;
    $defaults = array_keys($user);
}

 $step1['checkall'] = array(
 '#type' => 'checkbox',
 '#title' => t('Select / Unselect all'),
 '#attributes' => array('onclick' => 'checkUncheckAll(this);'),
 '#weight' => -1,
 );

 $step1['user'] = array(
 '#type' => 'checkboxes',
 '#title' => t('Send message to listed users'),
 '#options' => $user,
 //'#default_value' => $defaults,
 '#attributes' => array('class' => array('check_notify_user'))
 );

 $step1['submit']=array(
     '#type'=>'submit',
     '#value'=>t('Next')
 );

$form[] = $step1;

$step2['message'] = array(
  '#type' => 'textarea',
  '#title' => 'Message',
  '#description' => t('No more than 250 words please!'),
  '#wysiwyg' => false,
  '#attributes' => array('maxlength' => 250),
);

$step2['prev'] = array(
  '#type' => 'submit',
  '#value' => t('Previous'),
  '#name' => 'prev',
  '#submit' => array('custom_previous_submit'),
);

$step2['submit']=array(
    '#type'=>'submit',
    '#value'=>t('Submit')
  );

$form[] = $step2;

return $form;

```

}

# Answer
I assume you know how to do the multi-step form. For the table, you can use Drupal's table theme function. If the table contains only markup, you can do something like this:

```
$form['table'] = array(
  '#theme' => 'table',
  '#rows' => $rows,
  '#empty' => 'Empty List - No Entries',
  '#header' => $header,
);

```

or

```
$form['table'] = array ('#value' => theme('table', $headers, $rows));

```

You can use this in multistep form also.

If the table contains actual form elements (such as selects, textfields, etc.), you can wrap them in a form element that calls a theme function, like so:

```
$form['table'] = array ('#theme' => 'output_table');

$form['table']['element_1'] = array (...);
$form['table']['element_2'] = array (...);

```

Within 'theme\_output\_table', generate your $headers and $rows to feed to 'theme\_table' by calling 'drupal\_render' on the relevant form elements that are children of $form\['table'\].
> 0 votes

---
Tags: users
---


# Question
Title: Why are links missing when using the Notify module?
I use the Notify module. When I select for Mail System (`admin/config/system/mailsystem`) the choice **DefaultMailSystem**, the mail is sent but change line in a small border like this

But when I select **HtmlMailSystem**, it sent in a line (like what I want) but the links disappear and it looks something like this:

The links only appear in Gmail. In the other mails (hotmail,yahoo) they do not.

Why does this happen?

How could it be correct? In a line with links?

# Answer
> 2 votes
Your question is pretty incomplete, so let me start with adding some crucial information that I think is missing in it:

1. Relative path `admin/config/system/mailsystem` is **not** something that gets added to a site by the Notify module. Instead that path is what gets added after you enable the Mail System module, at least for the 7.x-2.34 version of it, which is what the rest of my answer assumes you're using.
2. After you enable the Mail System module you can navigate to the `admin/config/system/mailsystem` path.

After you do so, within the settings for "**Site-wide default MailSystemInterface class**", you'll be able to select either *DefaultMailSystem* or *TestingMailSystem*. However you can not, repeat not, select *HtmlMailSystem* (as in your question).

In order to be able to select *HtmlMailSystem*, you first have to enable the HTML Mail module. Which is what I did, I enabled the 7.x-2.65 version of it, which is what the rest of my answer assumes you're using.

With the above crucial additions, I think that the actual answer to your question can be found within relative path `admin/config/system/htmlmail`, where you can configure the settings for the HTML Mail module. I'm not sure if it's the only solution to answer your question, but pretty sure that you should select some other text filter within **Post-filtering** (located near the bottom within **Step 3**): by default it uses `unfiltered`, so check the results you get if you use any of the other filters you have available (or define a new filter to make it work as you want).

---
Tags: 7, notifications
---


# Question
Title: Views XML Backend, Render URL as MP3 player
I have a podcast feed that currently i am manually maintaining. I am planning to automate the xml generation in the near future from one site then have it displaying on another.

I am trying to get the displaying part to work now. I am using Views XML Backend to pull the feed (I don't want to import the content as nodes as there is no need to) which is working for me on the text stuff.

I have an enclosure tag and a guid tag in the xml that has the URL to the MP3 file. I want the url to change from being a link (which I had to use the rewrite to link feature in views) to an Embedded MP3 player that displays in a page or block.

Anyone got any tips or suggestions on how to do that? I've tried a few things and am yet to find anything that works.

Running Drupal 7

# Answer
> 0 votes
Guess you should have every mp3 path wrapped by a player instance somehow. jPlayer has a nice field formatter which maybe works with your Views setup. Otherwise you'll maybe have to try to accomplish this on template level.

---
Tags: views
---


# Question
Title: Is there a way to override paths defined in *.libraries.yml
Guess I found a bug here and already filed it:

* Created custom profile,
* added https://www.drupal.org/project/mmenu dependency (which then is placed under `profiles/profile_name/modules/contrib/mmenu`).
* Added MMenu libraries (jquery.mmenu, hammer.js, jquery.hammer),
* activated everything but then Drupal looks for the wrong library paths under `libraries/mmenu` instead of `profiles/profile_name/libraries/mmenu`.

`libraries_get_path('mmenu')` returns correct path `(profiles/profile_name/libraries/mmenu)`.

`drupal_get_profile()` returns correct profile.

Drupal seems to only take the paths defined in `mmenu.libraries.yml` into account. Changing them makes everything work as desired. So, I'm asking myself now: Is there any possibility to override the paths defined in `mmenu.libraries.yml` from a custom module?

# Answer
Yes, this is possible. `hook_library_info_alter()` is used to alter basically anything in the library definition.
> 6 votes

---
Tags: theming, 8
---


# Question
Title: How to use the Menu Badges to show the number of recieved messages via Privatemsg?
I use Privatemsg on my site to allow users to communicate with one another. New messages appear in the "Inbox" tab.

I also have the Menu Badges module installed to have a count of unread messages displayed in a badge. The `Tab Menu Badges` edit page does not list the inbox path (it's `/messages/received`). It lists other paths like `/messages/list`, `/messages/blocked`, `/messages/sent`, etc. (all being Privatemsg paths). But there is no path for **Received messages**.

So, I cannot display a badge on the inbox tab.

Is this a common error? Is there a fix or a workaround for this?

# Answer
If you don't want to use that "scotch tape" anymore (as in your own answer), then have a look at some of the comments in issue # 1719112, which detail how you may get it to work "as it is supposed to work":

* (Comment # 6): The tab menu badges are meant for tabs specifically, not links in the menu. You need to edit the Messages menu item and select a badge there if you want the badge to appear up in your header.
* (Comment # 9) You have to create your own menu item. Disable the one created by Privatemsg.
> 1 votes

# Answer
After peeking into the database, it appears the path /messages/received does not exist. This is probably due to the fact that the inbox being the first tab (default tab,) the path defaults to /messages. This path is also the path of the main menu tab. The Menu Badge module does not have an uninstall file, therefore uninstalling it does not clear up the database.

The work around I used is by putting the badge on the All Messages tab *(/messages/list)* The count of unread messages is the same as with the Inbox tab. Then, I used a little css to move the badge 222px to the left (position: relative) so that it falls on the Inbox tab instead.

It's like using scotch tape, but it works. :)
> 1 votes

---
Tags: 7, notifications, privatemsg
---


# Question
Title: Custom submit handler is also called when deleting a node
So these are my functions:

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

I can also attach the custom submit handler in other ways to the form, but only this way I can still access the nid and the bundle of the node.

```
function b2share_form_submit($form, &$form_state, $entity_id, $entity_type) {
   $values = array(
   'url' => $form_state['values']['b2share_fieldset']['url'],
   'pid' => $form_state['values']['b2share_fieldset']['pid']
  );

  if ( (empty($values['url'] == false) || (empty($values['pid']) == false)) ) {

    $insert = db_insert('field_data_field_b2share')
      -> fields(array(
       'field_b2share_url' => $values['url'],
       'field_b2share_pid' => $values['pid'],
       'entity_id' => $form_state['node']->nid,
       'entity_type' => 'node',
       'bundle' => $form_state['node']->type,
       'delta' => 0,
       'language' => 'und',
    ))
   ->execute();
 }
}

```

I can add nodes and edit them perfectly, but whenever I try to delete one, the custom handler function is called and prevent drupal from doing anything. No error messages, nothing in the logs.

Can someone help?

# Answer
> 1 votes
You made the mistake of giving the form submit function a name that matches the patter `form-name_submit`. So it does not only trigger by your submit button. It is triggered by every submit button in the form.

Rename your function and you should be good.

---
Tags: 7, forms
---


title: How to translate Entityform type name

text:
# Question
Title: How to translate Entityform type name
I created a form using Entityform module. I'm not able to translate name of entity form type. How is it possible to translate name for each enabled language?

# Answer
I found the answer! I was using latest stable release 7.x-2.0-rc1. It does not support i18n but they add a sub module which its name is entityform translation in dev version (7.x-2.x-dev). Once this module is enabled, a translate link appears on the table list of entity form types.
> 0 votes

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


# Question
Title: How to drupal_add_js an external and defer script
I've spent quite some time on `drupal_add_js` and didn't manage to solve this. How can I load an external JavaScript script which will also have the `defer` attribute?

I want to use this type of syntax:

```
drupal_add_js('http://example.com/whatever.js', 'external');

```

But it only produces:

```
<script src="http://example.com/whatever.js"></script>

```

I want the end HTML to be:

```
<script defer="defer" src="http://example.com/whatever.js"></script>

```

# Answer
Try the following syntax:

```
drupal_add_js('http://example.com/whatever.js', array('type' => 'external', 'defer' => 'defer'));

```
> 4 votes

# Answer
Just add a value in `$options`

```
$options = array(
  'type' => 'external',
  'defer' => TRUE,
);
drupal_add_js('http://example.com/whatever.js', $options);

```

From the documentation:

> **Parameters**
>
> **$options**: (optional) A string defining the type of JavaScript that is being added in the $data parameter ('file'/'setting'/'inline'/'external'), or an associative array. JavaScript settings should always pass the string 'setting' only. Other types can have the following elements in the array:
>
> * **type**: The type of JavaScript that is to be added to the page. Allowed values are 'file', 'inline', 'external' or 'setting'. Defaults to 'file'.
> * ...
> * **defer**: If set to TRUE, the defer attribute is set on the tag. Defaults to FALSE.
> 8 votes

---
Tags: 7, javascript
---


title: POST: 403 error in REST

text:
# Question
Title: POST: 403 error in REST
I created a custom entity, next I enabled (via RESTui) the GET and POST methods. I gave anonymous users permissions to "Access GET", "Access POST" and "Create new content" of that entity.

When I navigate in my browser to "http://mywebsite/my\_entity/1?\_format=json", I get a proper JSON response. When I navigate to "http://mywebsite/my\_entity/add", I can add a new entity.

When I try to POST a new entity via "http://mywebsite/my\_entity?\_format=json", I get a 403 repsonse with following body:

> { "message": "" }

Does someone have an idea what I'm missing here?

EDIT: When i put a `die('give me something')` in the method `post()` of the class "EntityResource" (which is the base class for all entities), the message isn't displayed...

EDIT2: I added headers "Content-Type" and "X-CSRF-Token"

# Answer
> 1 votes
Do you provide a (Basic) authorization header, as well as a X-CSRF-Token header in your POST?

See also: https://www.drupal.org/documentation/modules/rest/start \- "2.2 Unsafe methods & CSRF protection: X-CSRF-Token request header"

Edit: So you should at least specify the following HTTP headers:

* Content-type: application/json
* X-CSRF-Token: \[TOKEN RETURNED FROM A REQUEST TO /rest/session/token\]

---
Tags: users, 8
---


# Question
Title: Render a template file from module's controller method
I wanted to create and render a custom twig template, like it is described at Drupal.org: https://www.drupal.org/node/2640110. I have a module which is called "game" and has this route in the **game.routing.yml** file:

```
game.index:
  path: '/gamecanvas'
  defaults:
    _controller: '\Drupal\game\Controller\MainController::gameShowCanvas'
    _title: 'Gamecanvas'
  requirements:
    _permission: 'access content'

```

The route works with the controller below - I have tested it with different output. The controller is located at **game/src/Controller/MainController.php** and looks like this:

```
namespace Drupal\game\Controller;

use Drupal\Core\Controller\ControllerBase;

class MainController extends ControllerBase {

  public function gameShowCanvas() {
    return [
      '#theme' => 'game',
      '#description' => 'foo',
      '#attributes' => [],
    ];
  }

}

```

The **game.module** file looks like this:

```
function game_theme($existing, $type, $theme, $path) {
  return array(
    'gamecanvas' => [
      'variables' => []
    ]
  );
}

```

The **game.html.twig** file in **game/templates folder** contains just the word "hello", to indicate that the template file content output works.

If I call http://my-website/gamecanvas, I do not see the desired output. What am I doing wrong?

# Answer
Thank you guys. I needed to change the value of "#theme" into "gamecanvas".

Drupal 8 is excepting NAME.**html**.twig. NAME.**tpl**.twig does not work. Mind the "html" in the file name.

The working code looks like the following.

MainController.php:

```
<?php
namespace Drupal\game\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Default controller for the permissions_by_term module.
 */
class MainController extends ControllerBase {

  public function gameShowCanvas() {
    return [
      '#theme' => 'gamecanvas',
      '#description' => 'foo',
      '#attributes' => [],
    ];
  }

}

```

game.module:

```
<?php

/**
 * Implements hook_theme().
 */
function game_theme($existing, $type, $theme, $path) {
  return array(
    'gamecanvas' => [
      'variables' => []
    ]
  );
}

```

gamecanvas.html.twig:

```
hello

```

game.routing.yml:

```
game.index:
  path: '/gamecanvas'
  defaults:
    _controller: '\Drupal\game\Controller\MainController::gameShowCanvas'
    _title: 'Gamecanvas'
  requirements:
    _permission: 'access content'

```
> 1 votes

# Answer
Rename your template to `gamecanvas.html.twig` and adjust your controller-code:

```
namespace Drupal\game\Controller;

use Drupal\Core\Controller\ControllerBase;

class MainController extends ControllerBase {

  public function gameShowCanvas() {
    return [
      '#theme' => 'gamecanvas',
      '#description' => 'foo',
      '#attributes' => [],
    ];
  }

}

```

Your theme-key is `gamecanvas` but you are referring in your controller to `game`. You should also add `description` and `attributes` to your theme-declaration, as they get stripped out by drupal otherwise.
> 0 votes

# Answer
The main error in the code you are showing is the incoherence between the theme hook you define, and the one the controller is using.

Either you edit `game_theme()`, or you edit `MainController::gameShowCanvas()`. In the first case, the code should be the following one.

```
function game_theme($existing, $type, $theme, $path) {
  return [
    'game' => ['variables' => []]
  ];
}

```

Also, since you are using `#description` and `#attributes`, it is probable you need to use the following code.

```
function game_theme($existing, $type, $theme, $path) {
  return [
    'game' => [
      'variables' => [
        'description' => 'default value for description',
        'attributes' => 'default value for attributes',
      ],
    ]
  ];
}

```

Differently, Drupal would not use `#description` nor `#attributes`.

Also, as general rule, a module with a machine name like game should not define a routing for /gamecanvas, since this could conflict with a module using gamecanvas as machine name. Take as example the Node module; it has a route for /node/{node} not /node\_menus/{node}.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How to add profile2 field data to a programatically created user
I create a user from a form (that part works fine) but no profile2 information seems to be created....

profile2\_load\_by\_user returns an empty array which results in the below error. Do I need to some other step to first associate an "ae\_sa" profile with the newly created user?

> Recoverable fatal error: Argument 1 passed to profile2\_save() must be an instance of Profile, instance of stdClass given, called in D:\FULLREPO\trunk\sites\all\modules\sps\_users\sps\_users.module on line 115 and defined in profile2\_save() (line 291 of D:\FULLREPO\trunk\sites\all\modules\profile2\profile2.module).

```
...
$account = user_save(null, $new_user);
$obj_user = user_load($account->uid) ;
$profile2 = profile2_load_by_user($obj_user) ;
$profile2["ae_sa"]->field_full_name[LANGUAGE_NONE][0]["value"] = $fullname;
$profile2["ae_sa"]->field_title_role[LANGUAGE_NONE][0]["value"] = $titlerole;
$profile2["ae_sa"]->field_company[LANGUAGE_NONE][0]["value"] = $ucompany;
$profile2["ae_sa"]->field_bio[LANGUAGE_NONE][0]["value"] = $bio;
profile2_save($profile2["ae_sa"]) ;

```

# Answer
> 5 votes
You need to create the new user's profile:

```
$profile = profile2_load_by_user($user->uid, 'ae_sa');
if(empty($profile)) {
  $profile = profile2_create(array(
    'type' => 'ae_sa',
    'uid' => $user->uid,
  ));
}

// Fill fields
$profile->field_full_name[LANGUAGE_NONE][0]["value"] = $fullname;
$profile->field_title_role[LANGUAGE_NONE][0]["value"] = $titlerole;
$profile->field_company[LANGUAGE_NONE][0]["value"] = $ucompany;
$profile->field_bio[LANGUAGE_NONE][0]["value"] = $bio;

// Save the newly created OR updated profile
profile2_save($profile);

```

# Answer
> 3 votes
You need a second variable for the `profile2_load_by_user($obj_user)` function. What you currently get back is an array of profiles, e.g

```
'candidate' => Profile object,
'person' => Profile object,
'student' => Profile object

```

You need to specify the profile in the call and then you just get a profile object back. Then you can save the profile as it is an Profile object.

e.g. `profile2_load_by_user($obj_user,'candidate');`

---
Tags: users
---


title: Alter schema on creating a new field

text:
# Question
Title: Alter schema on creating a new field
I want to create a module that on installing and creating a new field on a content type it should alter the schema of another module.

Im trying to use hook\_storage\_create\_field to react on creating an new field but its not running.

```
function mymodule_field_storage_create_field($field) {
  exit(var_dump($schema));
  $schema = _field_sql_storage_schema($field);
}

```

Im I misusing the hook? or there is something faulty in my module?

**Update**

What Im trying to do is to create a new module that extends the Link module to work like Facebook parser.

So when users add a new link a preview will show a preview like this Redsun parser The functionality is already made and adapted into Drupal, but still having problem extending link schema to have extra fields for images and body fields.

A new widget is added to link field called "link with parser", and it will fire our extra codes to save and validate the link.

# Answer
hook\_field\_storage\_create\_field and hook\_field\_create are called when the user creates a new field, i.e. from "Manage Fields", "Add new field". In my tests, hook\_field\_create was called as expected, but hook\_field\_storage\_create\_field was not called. I did not look into why this was, because (a) you could use hook\_field\_create here just as well as hook\_field\_storage\_create, and (b) this isn't really the approach you should be taking to implement the functionality you need. If you were going to modify the schema for the link field, you would do it once when your module was installed, in hook\_install. Your use case is much more complicated than the standard behavior of the link field, though; you would be better off creating your own field type, and do all of your field storage management in one place. You might want to look at the source for existing fields that have complex data storage needs, such as the date field.
> 1 votes

# Answer
To alter schema, you can use `hook_schema_alter`, if it's a new field, you need to create such field in `hook_install` or `hook_update_X` (if it's already installed). E.g.

```
/**
 * Adds new field to the existing user schema.
 *
 * Implements hook_schema_alter().
 */
function foo_user_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['users']['fields']['migrated'] = array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Timestamp for when user was migrated.',
  );
}

/**
 * Implements hook_install().
 */
function foo_user_install() {
  $schema = drupal_get_schema('users');
  db_add_field('users', 'migrated', $schema['fields']['migrated']);
}

/**
 * Implements hook_uninstall().
 */
function foo_user_uninstall() {
  db_drop_field('users', 'migrated');
}

/**
 * Adds migrated field for user schema.
 */
function foo_user_update_7101() {
  foo_user_install();
}

```
> 0 votes

---
Tags: 7, hooks, database
---


# Question
Title: How to remove a line of HTML in webform?
The company I work for uses Drupal Webform to collect information regarding it's customers. At the very end of the webform, we have a file component with a size maximum of 64 MB. I was tasked with removing the description under the upload.

Just to clarify, I don't want to remove the max size, just the text that says what the max size is.

# Answer
You need to add to your **css file** this style:

```
div.field-widget-file-generic p.help-block{
    display: none;
}

```
> 1 votes

# Answer
I am not sure which Drupal version are you using, as you have not provided. But if I use common sense, it should be D7, as webform module does not have stable D8 version.

Since you want the **`64MB`**, it has to be done programmatically as that number comes from the code, so if you change tomorrow to **`32MB`**, it needs to change accordingly, and display on that?

This we can do the by overriding the themeable output, You need to use function theme\_file\_upload\_help()

Copy and paste that following code in your theme's `template.php` file, change the `YourThemeName` with your theme name. save and clear cache.

```
function YourThemeName_file_upload_help($variables) {
  $description = $variables['description'];
  $upload_validators = $variables['upload_validators'];

  $descriptions = array();

  if (strlen($description)) {
    $descriptions[] = $description;
  }
  if (isset($upload_validators['file_validate_size'])) {
    $descriptions[] = t('!size.', array('!size' => '<strong>' . format_size($upload_validators['file_validate_size'][0]) . '</strong>'));
  }
  if (isset($upload_validators['file_validate_extensions'])) {
    $descriptions[] = t('Allowed file types: !extensions.', array('!extensions' => '<strong>' . check_plain($upload_validators['file_validate_extensions'][0]) . '</strong>'));
  }
  if (isset($upload_validators['file_validate_image_resolution'])) {
    $max = $upload_validators['file_validate_image_resolution'][0];
    $min = $upload_validators['file_validate_image_resolution'][1];
    if ($min && $max && $min == $max) {
      $descriptions[] = t('Images must be exactly !size pixels.', array('!size' => '<strong>' . $max . '</strong>'));
    }
    elseif ($min && $max) {
      $descriptions[] = t('Images must be between !min and !max pixels.', array('!min' => '<strong>' . $min . '</strong>', '!max' => '<strong>' . $max . '</strong>'));
    }
    elseif ($min) {
      $descriptions[] = t('Images must be larger than !min pixels.', array('!min' => '<strong>' . $min . '</strong>'));
    }
    elseif ($max) {
      $descriptions[] = t('Images must be smaller than !max pixels.', array('!max' => '<strong>' . $max . '</strong>'));
    }
  }

  return implode('<br />', $descriptions);
}

```

**Image out-put:**

>

---

Now this will remove **`Files must be less than`** part from entire web-site.

If you want to apply this change only to that particular webform you need to replace the following code in above code,

```
if (isset($upload_validators['file_validate_size'])) {
    $descriptions[] = t('!size.', array('!size' => '<strong>' . format_size($upload_validators['file_validate_size'][0]) . '</strong>'));
}

```

With,

```
if (isset($upload_validators['file_validate_size'])) {
      if('webform_ID'){
    $descriptions[] = t('!size.', array('!size' => '<strong>' . format_size($upload_validators['file_validate_size'][0]) . '</strong>'));
 }
}

```

Note:Change the 'webform\_ID' with your webform's ID.
> 1 votes

---
Tags: webforms
---


# Question
Title: How to create a read-only flag that can only be used by an admin to actually flag nodes?
Long story short, I installed Flag because Best Answer was not working properly. Is it possible to configure flags so that only the admin can flag something (aka an answer as being approved) but everyone can view the flag?

# Answer
> 1 votes
Try setup Flag as "global flag" and then in "Flag access" setup "Roles that may use this flag" check-boxes only for Admin.

If in this case flag will not be shown for other users - you need create script that get flag value for each node and display this info.

```
$flag = flag_get_flag(FLAG_NAME);
$node->flag_value = $flag->get_count($node->nid);

```

# Answer
> 1 votes
You can use the Rules module for this, especially by using the not commonly known/used Rules Action "***Trim a flag***", which looks like so:

Here is a rule (in Rules export format) that you could use to trim a flag, say with machine name `best_answer`:

```
{ "rules_limit_access_to_best_answer_flag" : {
    "LABEL" : "Limit access to best answer flag",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_best_answer" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "flagging-user" ], "roles" : { "value" : { "3" : "3" } } } }
    ],
    "DO" : [
      { "flag_trim" : {
          "flag" : "best_answer",
          "flagging_user" : [ "flagging_user" ],
          "cutoff_size" : "0",
          "trim_newest" : "1",
          "permission_check" : "1"
        }
      },
      { "drupal_message" : {
          "message" : "Be aware: since you do not have the administrator role, your flagging-attempt has been ignored.",
          "type" : "warning"
        }
      }
    ]
  }
}

```

After you adapt `best_answer` to the machine name of the flag you're using, simply use the Rules UI to import the above rule in your own site (and enable the rule afterwards).

Some more details to explain the magic in the above rule:

* Rules Event = A node has been flagged (using the `best_answer` flag).
* Rules Condition = The flagging user does **not** have role "administrator".
* Rules Actions =
    + Trim the `best_answer` flag, with `cut_off` value equal to zero (which is the same as saying "*Ignore any flags from the flagging user*").
    + Set an appropriate warning message.

So with this approach, any user who has permission for the flag, will actually see the flag. But if they try to use the flag, it will be ignored unless they are an administrator.

Happy flagging with Rules!

---
Tags: flags
---


# Question
Title: How do I show a message about the currently executed operation?
I have created a batch, and it's working, but I want to control the messaging a little better. I would like to give the user some feedback about the currently executing operation, other than just letting them know that it has completed.

Here is what I am attempting to do, but it is still executing `sleep(5)` before updating the message.

```
function batch_callback(&$context) {

  // set up message for batch operation
  if (empty($context['sandbox'])) {

    $context['message']  = t('Pre-execution message...');
    $context['finished'] = FALSE;

    // put something in sandbox (doesn't matter what)
    $context['sandbox']['step'] = 1;

    return;
  }

  sleep(5);

  $context['finished'] = TRUE;
}

```

So, how do I set a pre-execution batch message?

# Answer
> 0 votes
The message will be shown just when the batch callback returns. If your intent is pausing the batch operations to let users see the pre-execution message, I would rather use the following code.

```
function batch_callback(&$context) {
  if (empty($context['sandbox'])) {
    $context['message']  = t('Pre-execution message...');
    $context['finished'] = FALSE;
    $context['sandbox']['step'] = 1;

    return;
  }
  elseif ($context['sandbox']['step'] == 1) {
    sleep(5);
  }
  // Do your operations.
}

```

You could also set the progress message using `$batch_definition['progress_message']` (where `$batch_definition` is the value passed to `batch_set()`, but that just gets *@current*, *@remaining*, *@total*, *@percentage*, *@estimate* and *@elapsed* as placeholders. You could not use it to show, for example, the title of the node being processed, since it doesn't allow to use a custom placeholder. It is used more for messages like *Completed @current of @total.*

---
Tags: 7, batch-operations
---


title: How to attach js in services?

text:
# Question
Title: How to attach js in services?
Here is my code:

services file

```
  services:
  my_module.event_subscriber:
    class: Drupal\my_module\EventSubscriber\My_moduleSubscriber
    arguments:
      - '@authentication'
      - '@current_user'
    tags:
      - {name: event_subscriber}

```

My\_moduleSubscriber.php

```
 <?php

  public function xyz) {
  // I want to attach js here
  $attachement['#attachement'][js] = .....
//    drupal_add_js(libraries_get_path('audio-player').'/audio-player.js');

  }

  static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('xyz');
    return $events;
  }

```

Since there is no argument passed like $attachement, $page, in which variable should i attach js file in Drupal?

# Answer
> 0 votes
A response event is possibly too late, I think at that point, you already have a built response object, and the page is just a string that will be replaced.

You're better of using a hook for this, namely `hook_page_attachments()`, which exists just for the purpose of adding additional libraries to the page.

---
Tags: 8, javascript
---


# Question
Title: Passing Argument from URL in Panel to View Pane or Block
I have a page where I want to display all resources for a course grouped by taxonomy term. The courses are organic groups and the resources are materials belonging to those groups. I'm using panels to display the content and I'm overriding view\_node for this. I have already created a view pane which lists all the different resource categories, and I'm now trying to list all the resources for a category.

The panel is using the following URL structure:

course/course-name/resources/resource-taxonomy-term

So for instance I have a URL

/course/test-course/resources/transport

I then want to display all resources that belong to the taxonomy term "transport". So I guess the URL argument I want to pass is %4.

I've tried for over a day now trying different methods to pass the URL argument to the view without success. I've tried using a view pane to display the results and also a view block, and explored various methods of passing the argument across without success. It works fine in the view itself, but when I put it in the panel it doesn't work. Can anyone show me how I can do it?

I'm using D7.18, ctools 7.x-1.0-rc1, panels 7.x-3.0 and views 7.x-3.7.

# Answer
> 2 votes
I've managed to solve this problem. The solution is not exactly what I was hoping for but it works.

First of all I changed the URL argument to use the term id rather than the term name in the panel. Then in the view pane, instead of using "taxonomy term id from URL" in the "provide default argument" section of the context settings, I used "raw value from URL", and specified the path component. I also needed to set up basic validation to use the term id.

I'd still be interested to hear if there is a neater way of doing this where it would be possible to use the term name in the URL instead of the id.

# Answer
> 3 votes
Example scenario:

There is a panel containing View Content Pane.

Panel URL: /panel\_url

Example with argument: /panel\_url/term\_name

With BEF: /panel\_url?category=123

How to set up (having existing panel and added Content Pane):

1. Add Contextual filter to the View. E.g.: Views contextual filters taxonomy name
2. Change settings in 'View -\> Pane settings -\> Argument input' to load the argument 'From panel argument' (e.g. First).

Done.

---

In addition, if you're using Better Exposed Filters, you could do the following improvements.

To set the current active link based on the argument (if you're using select\_as\_links):

```
/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select_as_links(&$variables) {
  $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
  $selected = end((arg()));
  if (array_key_exists($selected, $options)) {
    $variables['element']['#value'] = $options[$selected];
  }
}

```

To set the current active link based on the argument (if you're using select):

```
/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select(&$variables) {
  switch (arg(0)) {
    case 'panel_url':
      if (@$variables['element']['#name'] == 'category') {
        $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
        $selected = end((arg()));
        if (array_key_exists($selected, $options)) {
          if ($variables['element']['#value'] <> $options[$selected]) {
            $variables['element']['#value'] = $options[$selected];
          } else {
            // drupal_goto('panel_url');
          }
        }
      }
    break;
  }
}

```

To make the links SEO friendly, you can try something like:

```
/**
 * Implements hook_url_inbound_alter().
 */
function foo_url_outbound_alter(&$path, &$options, $original_path){
  if (arg(0) == 'panel_url') {
    // Convert URL like: /panel_url?category=29 into /panel_url/term_name (SEO friendly)
    $path_info = parse_url($path);
    switch (@$path_info['path']) {
      case 'panel_url/term_name':
      case 'panel_url/term_name2':
        $path = 'panel_url/all'; // Convert loopy urls into base url
    }
    if (strpos($path, '?category=') !== FALSE) { // Convert term id into human name
      list(, $tid) = explode('=', current(explode('&', $path_info['query']))); // get tid from URL
      $term_name = strtolower(taxonomy_term_load((int)$tid)->name);
      $path = '/panel_url' . '/' . $term_name; // See also: $path_info['path']
    }
  }
}

```

# Answer
> 0 votes
In your view pane, create a relationship with the taxonomy term. Once you've done that create a contextual filter based on that relationship to pass the term name. Set the filter to accept raw URL argument, set the item number in the path and that does it.

# Answer
> 0 votes
My trouble with getting the argument to pass was due to not understanding panels/page enough. I **wrongly** created a node (from basic page content type) expecting that I could edit it in panels to send the argument. Adding an argument in the url path always resulted in page not found.

What I later realized was that I needed go to Structure \> Pages \> Add custom page and then add content pane view to effectively pass the argument. Also needed to make sure that content pane view had argument input set correctly before was able to find it from the custom page.

I found where I went wrong when reading this tutorial: http://www.metaltoad.com/blog/passing-page-arguments-view-panes

---
Tags: 7, views, panels, uri
---


# Question
Title: How can I create a relation between a number of related pages and a main event?
I need to create mini-site within existing website. I have new content type called Events.

Single event will be number of pages related to that event. Some of the pages that will be under single event are:

* Registration
* Scheadule
* Sessions
* Resources
* Travel

All of this pages needs to be on their unique url like mysite.com/event-name/registration. My first guess is to create all these as different content types and create some relation to single Event.

So my question is: How to create a relation between these pages and a main event? Since this mini-site needs to have its own navigation menu, can I automatise this menu creation somehow or should I create a separate menu for every event.

# Answer
> 2 votes
**Method 1.**

I would create a content type to act as a parent node for each event.

Then for each other content type, add an Entity Reference field, with only that parent content type available. (If you need to restrict the available parent nodes to certain users, you can use a view to get the results of the entity reference field and only allow the node author to select that node).

You can then start adding views to that parent content type for things like "Child nodes" with a reverse relationship to act as an automatically generated menu.

**Method 2.**

Everything goes into one content type, but use the Field Group menu to create horizontal tabs, and place those fields in those tabs. This will make editing the pages easier as they are all in one place, but depending on the amount of content in each of these mini sites, might have a slow load. There could be a good SEO argument for this method, as your content count would be good for each mini site all on one page.

I would probably choose method 1, unless the "mini site" is small enough to manage with field groups. **The benefit of Method 1, is that you can use Rules to automatically add the other pages, and fill in the Entity Reference fields once the initial "parent" node is created.**

---
Tags: nodes
---


title: Auto-create navigation link to a node

text:
# Question
Title: Auto-create navigation link to a node
I use RULES module to create a node (my custom content type) on user creation - so another words every user gets **ONE, UNIQUE** node when creating account.

Now I would like to have a navigation menu for users, where each user has a link to his own node. How can I achieve this?

**EDIT:**

Just as example, imagine we are talking about node as user profile. Each user gets one of those nodes on user creation and I want to have a navigation link to edit/view this node.

# Answer
> 0 votes
To achieve this I wrote a module, which creates a node on user create. The node has an alias, which is the username. Code below:

```
function mymodule_user_insert(&$edit, $account, $category) {
    $node = new stdClass();
    $node->type = 'article';
    node_object_prepare($node);

    $node->title = $edit['name'];
    $node->path = array(
        'alias' => $edit['name'],
    );
    $node->uid = $account->uid;
    $node->language = LANGUAGE_NONE;
    node_save($node);
}

```

Additionally I used MENU\_TOKEN module, which allows to input tokens into title and path of menu links. So my new navigation link path is **\[current-user:name\]**, which links user's article to his profile.

**EDIT:** Of course in the example I used 'article' as content type, but in practice I use a custom content type. So if you want to use this code, make sure this line:

```
$node->type = 'article';

```

is adjusted as per requirements.

---
Tags: 7, users, navigation
---


# Question
Title: Programmatically creating a new instance of a custom content entity that contains a field collection
I am trying to write a script that will create about a thousand instances of a custom content entity type I defined via a module from existing data that I have prepared. Right now I just need to figure out how to create an instance of my entity type programmatically.

This entity type contains multiple field collections. I don't understand how to structure the arguments of {entity\_type}::create() to accommodate field collections.

Following the accepted answers to Programmatically create nodes and How to programmatically insert and update Field Collection values?, here is my function code so far (i have it inside `hook_entity_view_alter()` just for easy testing):

```
$food = Food::create([
    'type'  => 'food',
    'title' => 'Allspice',
    'field_category' => 'Spices'
]);
$variation = FieldCollectionItem::create([
    'field_ingredients' => 'allspice',
    'field_safe_for' => [
        'field_nut_allergies' => 'Yes',
        'field_seafood_allergies' => 'Yes',
    ]
]);
$variation->setHostEntity($food);
$food->field_variations[] = ['field_collection_item' => $variation];
$food->save();

```

where `food` is my entity type, `field_variations` is the ID of the field collection in `food` which may have unlimited values per `food` instance, and `field_safe_for` is a nested field collection.

No matter what I do, I always get this:

```
The website encountered an unexpected error. Please try again later.

Drupal\Core\Entity\EntityStorageException: Missing bundle for entity type field_collection_item in Drupal\Core\Entity\ContentEntityStorageBase->doCreate() (line 83 of core\lib\Drupal\Core\Entity\ContentEntityStorageBase.php).
Drupal\Core\Entity\EntityStorageBase->create(Array) (Line: 509)
Drupal\Core\Entity\Entity::create(Array) (Line: 39)
food_food_view_alter(Array, Object, Object) (Line: 501)
Drupal\Core\Extension\ModuleHandler->alter(Array, Array, Object, Object) (Line: 268)
Drupal\Core\Entity\EntityViewBuilder->buildMultiple(Array) (Line: 203)
Drupal\Core\Entity\EntityViewBuilder->build(Array)
call_user_func(Array, Array) (Line: 381)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 144)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 62)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 98)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 77)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 628)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

which I do not understand in the slightest since my custom entity types don't make use of bundles.

How can I fix this?

# Answer
The bundle of the entity type "field\_collection\_item" is `field_name` and the error messages says this is missing:

```
$variation = FieldCollectionItem::create([
  'field_name' => 'my_field_name',
  ...

```
> 3 votes

---
Tags: 8, entities
---


# Question
Title: How to override menu link href to be something like javascript:jQuery....?
I need to override one menu link in footer to be href like this javascript:jQuery - after click the modal window will open.

Drupal not allowed me to insert it directly to the menu link form. Thanks a lot!

# Answer
> 0 votes
There is a way to make this happen with the assistance of a module called Special menu items. Essentially, the module allows you to fill in placeholder / separator menu items to work around the menu item system (the module overrides `theme_link()` when you give it a special path). Per the project page:

> If you use module than require to output a link, go in **/admin/config/system/special\_menu\_items** and use `<a>` as the HTML tag. You can even use `<a href="#">` if you need to.

In your instance, you could use `<a href="javascript:alert('Hello World!');">` in the configuration page, then add your menu item with the `<nolink>` path to have produce a menu item with the javascript embedded `href`.

---
Tags: 7, navigation
---


# Question
Title: How to access fields attached to taxonomy term in views-view-field.tpl.php?
A vocabulary has an additional field field\_information attached. In a view i just want to render this information field exclusively (without term name etc). In my views-view-field.tpl.php I did a `dpm($field)`, but I can't figure out how to get to the value of field\_information. Unfortunately due to my setup I can't use the module taxonomy\_field\_formatter, I'll have to do it manually.

# Answer
Puh, finally I found a way. This is my template file views-view-field.tpl.php (instead of a custom field I used the description field, but that doesn't matter in this case):

```
<?php
if (isset($row->_field_data['nid']['entity']->field_myfiled['und'][0]['tid'])) {
  $tid = $row->_field_data['nid']['entity']->field_myfield['und'][0]['tid'];
  $term = taxonomy_term_load($tid);
  $output = $term->description_field['und'][0]['value'];
} else {
  $output = $output;
};
?>

<?php print $output; ?>

```
> 0 votes

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


# Question
Title: Can I make add "display:none" to a HTML element via PHP?
In my theme on Drupal 7.50 there is a #banner element just beneath a #menu element. The *banner* CSS styles are `{border-bottom:5px solid blue}`. The problem is that sometimes the #banner element is empty and this causes problems with the layout.

Is there a way to add `display:none` to #banner when the banner is empty, using PHP?

# Answer
> 2 votes
If there is no banner there is no reason to output the banner div. Assuming the banner is in a region by itself you can fix this in the page template (page.tpl.php) where the region is printed.

Example:

```
<?php if ($page['banner_region']): ?>
<div id="banner">
  <?php print render($page['banner_region']); ?>
</div>
<?php endif; ?>

```

A workaround would be to apply the border to the actual banner, e.g. the image. In that way the border will only show up if there is an image.

Example:

```
#banner img {
  border-bottom: 5px solid blue;
}

```

# Answer
> 1 votes
One way would be to set a minimum height on #banner. That way when #banner is empty of content, there will still be a space between #menu and the border. This solution does not require you to involve PHP at all.

```
#banner {
  min-height: 10px;
}

```

---
Tags: theming
---


# Question
Title: Validate all instances of a field programmatically
What is the best way(hook) to validate all instances of a field programmatically? I have a lot of content types having the same fields like `field_phone`. I want to programmatically validate `field_phone` everywhere it is used.

# Answer
You could implement hook\_field\_validate and check if its the correct instance. Doesnt work if the field is not defined by the module.

One way to build that would use hook\_form\_alter and add element\_validator if the field exists on the form.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
   if (isset($form['field_phone'])) {
      $form['field_phone']['#element_validate'][] = 'mymodule_somevalidator';
    }
 }

function mymodule_somevalidator($element, &$form_state) {
  if (!empty($element['#value']) && !is_numeric(parse_size($element['#value'])) {
    form_error($element, t('The "!name" must be x', array('!name' => t($element['title']))));
  }
}

```
> 6 votes

# Answer
Try the Field Validation module.

You still have to add proper validation to each field you want to validate.
> 4 votes

# Answer
From field\_attach\_form\_validate:

> There are two levels of validation for fields in forms: widget validation, and field validation.

for widget validation you may follow the hook\_form\_alter path. This is hard to generalize since you need to know details about how the form is built. For example elements or values may be nested for some entities.

IMO, it's best to do field validation. It is performed by implementing hook\_field\_attach\_validate. Here's a simple example:

```
function hook_field_attach_validate($entity_type, $entity, &$errors) {
  if (isset($entity->field_phone)) {
    $errors['field_phone'][LANGUAGE_NONE][0][] = array(
      'error' => 'error_key',
      'message' => t('Error message'),
    );
  }
}

```

`error_key` is used by hook\_field\_widget\_error to flag a form element when a widget is compound of several elements. For example, in text field's implementation of this hook the error key `text_summary_max_length` is used to flag an element within the widget structure.

In the general term, the error key is not used for widgets with a single element. In the case of phone field type (that I assume you're using), they provide a compound widget but don't implement error distribution to elements, so just ignore it.
> 2 votes

# Answer
The best way to implement it by implementing **hook\_form\_alter**. The logic is such that you need add the custom validation function against all those Content Type forms which have the same field like `field_phone` (in your case) and it needs to be dynamic. Once, I had encountered such situation but I had to validate against the single form. The code below is almost the same implementation but I have made it much more dynamic for your case.

Create a module and implement **hook\_form\_alter** like this:

```
/**
 * Implementation of hook_form_alter
 */
function MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
  // $cck_type contains the array of all Drupal content type machine names
  $cck_type = array_keys(node_type_get_types());

  // Machine names of those content type whose instance you want to validate
  // Add your machine name for whom you want to validate. You can get the
  // machine names of content types from Admin > Structure > Content types. Fill
  // as many required bu you.
  $my_types = array('CCK_TYPE_1', 'CCK_TYPE_2', 'CCK_TYPE_3');

  // Since, a user fill one form at particular time. The variable $current_type
  // hold the Content Type machine name for current form.
  if (arg(0) == 'node' && arg(1) == 'add') {
    $current_type = arg(2);
  } elseif ((arg(0) == 'node') && is_numeric(arg(1)) && (arg(2) == 'edit')) {
    $node = node_load(arg(1));
    $current_type = $node->type;
  }

  // gets current form's ID
  $id_of_form = $form['form_id']['#value'];

  // checks if the current form is part of Drupal Content Type
  if (in_array($current_type, $my_types) && in_array($current_type, $cck_type)) {
    $id_of_form = $form['form_id']['#value'];
    if ($form_id == $id_of_form) {
      // Adding custom validation function to the form so that we can validate
      // the field of that form
      $form['#validate'][] = 'custom_validates';
    }
  }
}

```

Now, implement the custom validation function for validation.

```
/**
 * Implementation of custom validation for validating 'field_phone' in your case.
 * It can be any field, assuming that it is part of that form.
 */
function custom_validates(&$form, $form_state) {
  $values = $form_state['values'];

  // Language of the $form
  $lang = $form['language']['#value'];
  $field_phone = $values['field_phone'][$lang][0]['value'];

  // In my case, for testing purpose, I had set the strings in Phone field
  if (!is_integer($field_phone)) {
    form_set_error('field_phone', 'Invalid phone number');
  }
}

```

In the simple approach, you just need to check the `$form_id` of your content type form and add the custom validation function like this:

```
/**
 * Implementation of hook_form_alter
 */
function MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
  if (($form_id == 'content_type_form_id_1') ||
          ($form_id == 'content_type_form_id_2') ||
          ($form_id == 'content_type_form_id_3')) {
    // Adding custom validation function to the form so that we can validate
    // the field of that form
    $form['#validate'][] = 'custom_validates';
  }
}

```

But the problem with this simple approach is such that you will need to know form ID of every single content type form and then add it to the if statement with `||` operator as I have shown previously. This will take a lot of your time.

I have made respective comments to make your understand the logic and implementation.

I hope that my solution answers your problem.
> 1 votes

# Answer
The answer is **hook\_field\_widget\_WIDGET\_TYPE\_form\_alter()** in my opinion. Use the hook to add your validation callback to the *$element\[#element\_validate\]* array and you are good to go.

*hook\_form\_alter()* is very general and it will be invoked for every form whether it has field\_phone or not (increasing overhead). Besides, what if the field\_phone is deep inside various field sets or containers? You will have to look for it recursively (additional overhead).
> 0 votes

---
Tags: 7, entities
---


# Question
Title: D7: How can I list duplicate entities based on the entity title and bundle, without custom coding
There is a module for removing duplicate nodes, but how to delete duplicate entities (in my case ECK entities) based on title and bundle that are the same?

I was thinking that the search api module might be of help, which I installed. But listing duplicates requires something extra.

I also have Rules installed, but not sure how to create such rule.

What would be a recommended way to do this?

# Answer
Eventually I created an aggregated view with counted title field, and filters on the bundle.
> 0 votes

# Answer
I'd look at the Entity Bulk Delete module. This module provides a Drush command that can bulk delete arbitrarily specified entity types.

The caveat here is the module does not delete based on your specified logic of duplicate titles. For that, you can modify its `EntityFieldQuery` in the `_entity_bulk_delete_query()` function so it matches your criteria for deletion removal.
> 1 votes

---
Tags: entities
---


# Question
Title: A referenced node is missing--when did it disappear?
So, I inherited a long-standing and complicated drupal site with a lot of records that reference each other. The site started out in Drupal 6 and these references used to be CCK Nodereferences, but they ported to Drupal 7, and I think things are now mostly entity-references, though there might be a CCK Nodereference here or there. I'm mentioning this because it's an area that I don't know much about and I think it might be relevant for what follows.

The problem is this: There are some nodes that are referenced by ID by other nodes that seem to have disappeared. Let's say, for example, we have a content type "Chicken coop", which contains references to 100 "chicken" nodes. If I edit "Chicken coop", I'll see 100 fields, each with a name and value, for example, "Hen 1\[nid:1\]", "Rooster 50\[nid:62\]" but one of them will be a null reference. "\[nid:4\]", and when I build a view to list all the "Chickens", there will be no chicken with nid:4. It's like that chicken got removed from the database and removal didn't propagate to all the things that referenced it like it should have. Obviously, I'd like to know how this happened, and I've noticed that we have had backups turned on for several years. I'd like to find out when this happened and what other things happened around this time. Did these null references appear at the same time?

* I can download the backups and load them into a local mysql instance. How would I query to see if chicken nid:4 is still in them? This does not seem simple or intuitive from the drupal schema I've seen.
* Does this problem seem familiar to anyone and do you have any suggestions on whether this was a one-time thing that's not likely to happen again?
* Any other logs that you would recommend examining or troubleshooting steps I ought to take?

# Answer
> 2 votes
You can copy the database to your local version of MySQL. That is generic database exporting and importing that you can find instructions for elsewhere.

To query specific nodes you can use this SQL:

```
SELECT * FROM node WHERE nid = 4;

```

If you get a result the node exists, if not then it doesn't.

It might be possible that you have an entry in the node table but other related node data is missing, in which case your data is corrupted somehow. Hopefully that's not it.

There are so many options as to how it may have happened that we can't really give a definite answer, but the first 2 most likely possibilities that come to mind are:

1. The nodes are gone, for whatever reason
2. During the migration from Drupal 6 to Drupal 7, nodes somehow ended up with different node IDs and the referencing fields were not updated to match.

If it is the second one you can search on the node title, for example:

```
SELECT * FROM node WHERE title = 'Chicken';

```

If you get a result and the nid isn't what you expect based on the reference field then that is probably your problem. In that case you will need to somehow map the old node IDs to the new node IDs and then update the reference field values to match the new IDs.

Depending on how complex the problem ends up being you may have to further familiarise yourself with the Drupal schema.

I would assume that there probably aren't any logs that would help you out here. There may be logs stating when a node was updated but not the values that were updated. Or you might be able to see PHP errors at a similar time to things updating and maybe they are related but I probably wouldn't waste my time down that path.

After a few queries to determine whether the data is missing or if it is still there but has changed, I would probably start by comparing different database versions around points of interest in time (eg, before and after any serious development or migrations) to try to narrow down when the data disappeared/changed. Then work out what was happening at that time (was it a migration? etc.) then investigate based on that.

# Answer
> 2 votes
Drupal 7 does not delete references to deleted nodes by default. See the Field reference delete module. Some details about it, from its project page (check that page for even more details):

> This module removes references to a deleted entity from fields stored in an SQL database. It exists to prevent stale references to non-existent content from causing unexpected problems (for example, when the referencing content is being displayed).

I'm not sure if it will clean up existing "dead" references, but at least moving forward it does.

---
Tags: database, nodes, upgrading
---


title: Install issues via composer

text:
# Question
Title: Install issues via composer
I ran composer global require drush/drush:dev-master. I'm not sure how to resolvirthis issue as it seems that the package isn't found anymore. Do I have to update somehow?

```
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for drush/drush dev-master -> satisfiable by drush/drush[dev-master].
    - drush/drush dev-master requires codegyre/robo ~1.0.0-beta1 -> satisfiable by codegyre/robo[1.0.0-beta1] but these conflict with your requirements or minimum-stability.

Installation failed, deleting ./composer.json.

```

# Answer
> 1 votes
I did a work around without using composer to do the install by doing the following:

1. make a drush directory in your home folder (~)
2. git clone https://github.com/drush-ops/drush.git
3. cd into that directory
4. ./drush --version (it should complain about composer install)
5. run **composer install**
6. ./drush --version **WORKING!**

I'm using ubuntu so initially I did **apt-get install drush**, but that version is 5. Then I did the following to download the latest into ~/drush

From there I went to my global run folder: /usr/bin and renamed the old drush to drush\_old and then did a **ln -s ~/drush/drush drush** now its on the latest drush!

# Answer
> 0 votes
The `codegyre/robo` project has moved to `consolidation/Robo`, so Drush needs to be updated.

See also: drush/drush dev-master requires codegyre/robo ~1.0.0-beta1.

---

I've merged a PR into the Drush master branch that fixes the problems Drush was having with Robo. It is still complicated to install the master branch of Drush with Composer. This will get better after the stable release of Robo 1.0.0, or after I implement a fix for this issue. Until then, I recommend against installing Drush master via `composer require`. Either install Drush 8.x, or, if you need the master branch, use `git clone` followed by `composer install`.

---
Tags: drush, installation
---


# Question
Title: call from form alter - undefined function error
I try to use code for redirecting after submitting a form, but I am getting the below error:

> undefined function my\_search\_form\_submit\_funtion in form.inc.

Why do I get this error? Thank you. The module name is `utility`.

```
function utility_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['#submit'][] = 'my_search_form_submit_funtion';
  }
}
function my_search_form_submit_function(&$form, &$form_state) {
  $search_str = $form_state['values']['search_block_form'];
  $form_state['rebuild'] = TRUE;
  drupal_goto('search', array('query' => array('search_api_multi_fulltext' => $search_str)));
}

```

# Answer
You have a typo error in your code.

Change

```
$form['#submit'][] = 'my_search_form_submit_funtion';

```

To

```
$form['#submit'][] = 'my_search_form_submit_function';

```
> 1 votes

# Answer
You have spelling mistake in your function name, in the line $form\['#submit'\]\[\] = 'my\_search\_form\_submit\_funtion'; you can replace '**funtion**' with '**function**' to make your code run perfect.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Install new site from existing config plus data migration
I need to install a new site on drupal 8 from existing config plus data like content, users.

I used config installer to install a new site from existing config.

How to make it import content after complete configuration import.

New ideas and other solutions are welcomed.

# Answer
After doing some research I found multipurpose corporate profile a distribution which does the job and accelerates the development process.

It deserves discovering its key features.
> 1 votes

---
Tags: 8, installation-profiles
---


# Question
Title: How to add a link to slide elements in MD Slider?
I have used the MD Slider module (which is Mega Slider, a paid module) in my websites to create slideshows.

But there is no default option to create a link for each slide.

Is there any way to hyperlink a slide?

# Answer
I have created a patch with the changes to convert a slide into hyperlink. Since I cannot upload a file here, I am copy-pasting the contents of my .patch file:

```
From 3f72f263b3673ce27ca4114963b007752b566c2a Mon Sep 17 00:00:00 2001
From: Raj Pawan Gumdal <gumdal@gmail.com>
Date: Sat, 6 Aug 2016 11:02:04 +0530
Subject: [PATCH 1/2] Ported changes regarding MD_Slider done for an older
 version

---
 .../templates/front/front_layers_render.tpl.php    | 13 ++++----
 .../templates/front/front_slide_render.tpl.php     | 35 ++++++++++++++++++++--
 2 files changed, 41 insertions(+), 7 deletions(-)

diff --git a/sites/all/modules/md_slider/templates/front/front_layers_render.tpl.php b/sites/all/modules/md_slider/templates/front/front_layers_render.tpl.php
index a8dd7fc..16c30b4 100644
--- a/sites/all/modules/md_slider/templates/front/front_layers_render.tpl.php
+++ b/sites/all/modules/md_slider/templates/front/front_layers_render.tpl.php
@@ -11,11 +11,14 @@
 <?php endif;?>
   <div class="<?php print $class; ?>" <?php print $data; ?>>
     <?php if ($layer->type == 'text'): ?>
-        <?php if (isset($link)):?>
-            <a href="<?php print $link;?>"<?php if (isset($layer->link["target"]) && !empty($layer->link["target"])) print " target='{$layer->link["target"]}'";?>><?php print $layer->title;?></a>
-        <?php else:?>
-            <?php print $layer->title;?>
-        <?php endif; ?>
+    <?php /* Raj: Changes to make MD_Slider slide as hyperlink */?>
+       <?php if (strpos($layer->title,'URL:') === false):?>
+           <?php if (isset($link)):?>
+               <a href="<?php print $link;?>"<?php if (isset($layer->link["target"]) && !empty($layer->link["target"])) print " target='{$layer->link["target"]}'";?>><?php print $layer->title;?></a>
+           <?php else:?>
+               <?php print $layer->title;?>
+           <?php endif; ?>
+        <?php endif; ?>
     <?php elseif ($layer->type == 'image'): ?>
         <?php if (isset($link)):?>
             <a href="<?php print $link;?>"<?php if (isset($layer->link["target"]) && !empty($layer->link["target"])) print " target='{$layer->link["target"]}'";?>>
diff --git a/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php b/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
index 8df2c39..5dd71dd 100644
--- a/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
+++ b/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
@@ -18,10 +18,41 @@
       <div class="md-slider-overlay" style="background: <?php print $slide->settings['background_overlay']; ?>">
       </div>
     <?php endif; ?>
-    <div class="md-objects">
+
+    <?php
+    // Raj: Check if there is a string which starts from "URL:". If so, extract the URL and make this div a hyperlink
+    $hasURL = false;
+    $URLString = '';
+    foreach ($slide->layers as $index => $layer):
+    $layerTitle = $layer["title"];
+    drupal_set_message("Layer object: $layer");
+    drupal_set_message("Layer title: $layerTitle");
+    // http://stackoverflow.com/a/4366748/260665
+    if (strpos($layerTitle,'URL:') !== false) {
+       $hasURL = true;
+       $URLString = str_replace('URL:', '', $layerTitle);
+       break;
+    }
+    endforeach;
+
+    if ($hasURL)
+    {
+       print "<a href=$URLString>";
+    }
+    print "<div class=\"md-objects\">";
+    foreach ($slide->layers as $index => $layer):
+    print theme('front_layers_render', array('index' => $index, 'layer' => $layer));
+    endforeach;
+    print "</div>";
+    if ($hasURL)
+    {
+       print "</a>";
+    }
+    ?>
+<!--     <div class="md-objects"> -->
       <?php foreach ($slide->layers as $index => $layer):?>
         <?php print theme('front_layers_render', array('index' => $index, 'layer' => $layer));?>
       <?php endforeach;?>
-    </div>
+<!--     </div> -->
   </div>
 <?php endif;?>
--
2.7.4 (Apple Git-66)

From 74c3d0644fd505729163d4803c9a0f9cb014e679 Mon Sep 17 00:00:00 2001
From: Raj Pawan Gumdal <gumdal@gmail.com>
Date: Sat, 6 Aug 2016 14:04:39 +0530
Subject: [PATCH 2/2] Finalized the changes to support hyperlinking whole slide

---
 .../templates/front/front_slide_render.tpl.php     | 30 +++++++++++++---------
 sites/all/themes/IndianSnakes/css/custom.css       |  6 +++++
 2 files changed, 24 insertions(+), 12 deletions(-)

diff --git a/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php b/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
index 5dd71dd..764d46e 100644
--- a/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
+++ b/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
@@ -9,6 +9,7 @@

 <?php if (!isset($slide->settings["disabled"]) || !$slide->settings["disabled"]):?>
   <div class="md-slide-item slide-<?php print $index+1;?>" <?php print $data_properties;?>>
+
     <div class="md-mainimg" style="<?php print $background_style;?>">
       <?php if (!empty($background_url)):?>
         <img src="<?php print $background_url;?>" alt="<?php print htmlentities($slide->settings["background_image_alt"], ENT_QUOTES, 'UTF-8');?>"<?php print $background_style;?> />
@@ -25,34 +26,39 @@
     $URLString = '';
     foreach ($slide->layers as $index => $layer):
     $layerTitle = $layer["title"];
-    drupal_set_message("Layer object: $layer");
-    drupal_set_message("Layer title: $layerTitle");
+//     drupal_set_message("Layer object: $layer");
+//     drupal_set_message("Layer title: $layerTitle");
     // http://stackoverflow.com/a/4366748/260665
-    if (strpos($layerTitle,'URL:') !== false) {
+    if (strpos($layerTitle,'URL:') === false) {
+    }
+    else {
        $hasURL = true;
-       $URLString = str_replace('URL:', '', $layerTitle);
+       $URLString = str_replace('URL:','',$layerTitle);
        break;
     }
     endforeach;
-
+//     drupal_set_message("URL: $URLString");
+//     drupal_set_message("Has URL: $hasURL");
+    $outputString = "";
     if ($hasURL)
     {
-       print "<a href=$URLString>";
+       $outputString .= "<a href=$URLString >";
     }
-    print "<div class=\"md-objects\">";
+    $outputString .= "<div class=\"md-objects\">";
     foreach ($slide->layers as $index => $layer):
-    print theme('front_layers_render', array('index' => $index, 'layer' => $layer));
+    $outputString .= theme('front_layers_render', array('index' => $index, 'layer' => $layer));
     endforeach;
-    print "</div>";
+    $outputString .= "</div>";
     if ($hasURL)
     {
-       print "</a>";
+       $outputString .= "</a>";
     }
+    print $outputString;
     ?>
-<!--     <div class="md-objects"> -->
+<!--     <div class="md-objects">
       <?php foreach ($slide->layers as $index => $layer):?>
         <?php print theme('front_layers_render', array('index' => $index, 'layer' => $layer));?>
       <?php endforeach;?>
-<!--     </div> -->
+</div> -->
   </div>
 <?php endif;?>
diff --git a/sites/all/themes/IndianSnakes/css/custom.css b/sites/all/themes/IndianSnakes/css/custom.css
index 3d69b0d..3f0354e 100644
--- a/sites/all/themes/IndianSnakes/css/custom.css
+++ b/sites/all/themes/IndianSnakes/css/custom.css
@@ -27,3 +27,9 @@ display: inline-block;
 width: auto !important;
 height: 300px !important;
 }
+
+/* Reset the hyperlink style to normal inside slides */
+.md-slide-item a {
+    color: inherit;
+    text-decoration: inherit;
+}
\ No newline at end of file
--
2.7.4 (Apple Git-66)

```

I have defined a new "**URL:**" label protocol for each slide. If a slide has this label defined then the whole slide's div is converted into hyperlink with whatever link is provided after my **URL:** protocol. For example check this:

The code (patch) is configured such that label with text which begins with `URL:` is never rendered as text but it is used to convert the slide into a hyperlink.

For a live working example check: http://indiansnakes.org/homepage

Assumption: The only limitation of this method is, you should not hyperlink any text or images which are used within this hyperlinked slide coz the anchor tags cannot be nested, apparently.

**Edit**: I thought its best to update the patch details in the MD Slider community as well, here it is: http://megadrupal.com/comment/13066#comment-13066

Also a gist is created with the contents of same patch: https://gist.github.com/gumdal/e580cd80199c871fa52f677538771551
> 3 votes

---
Tags: 7, views, javascript
---


# Question
Title: Notification + Subscription: Can this combination recipe be used to create notification system similar to Facebook's?
I understand that this combination of Notification + Subscription modules can accomplish a lot of different notification setups. However, I am only looking to emulate the notification system similar to Facebook, as in this example:

Can anyone provide any tip or guidance as to how this combination may be configured to achieve this goal?

Any sugestions?

# Answer
> 1 votes
you can use my module for this Total Subscription.

> Total Subscription provides functionality which would allow the user to subscribe to node pages, taxonomy terms, etc. The main feature which distinguishes it from other subscription modules is that it allows subscription for Anonymous along with Authenticated users.

# Answer
> 0 votes
The Menu Badges module can be used to add such notifications to any **menu item** and/or **menu tab** of your choice. Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)
>
> ### Adding Badges to Menus
>
> Once enabled, go to `Administration > Structure > Menus`, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
>
> ### Adding Badges to Tabs
>
> For adding badges to menu tabs, there is a tab under `Administration > Structure > Menus` called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
>
> ### Badge Types
>
> The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like this:

* **Step 1**: Just create an appropriate view of it, create a menu item or menu tab for that view.
* **Step 2**: Do a 15 seconds Menu Badges configuration to tell it which menu item/tab you used for it in your view.

### Video tutorials:

---
Tags: 7, social-network, notifications
---


# Question
Title: How to add custom column in-between people/users admin page table?
I have created a custom column to display last user changed time, but I need this field to be inserted before OPERATIONS column. Below is my code which appends my custom field at the end.

```
function meme_user_update_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  $changed_column = array('changed' => array(
    'data'  => 'LAST CHANGED',
    'field' => 'u.changed'
  ));
  $form['accounts']['#header'] = $form['accounts']['#header'] + $changed_column;
  foreach ($form['accounts']['#options'] as $key => $row) {
    $user_object = user_load($key);
    $user_language = ($user_object->language) ? $user_object->language : LANGUAGE_NONE;
    $form['accounts']['#options'][$key]['changed'] = $user_object->field_user_changed[$user_language][0]['value'];
  }
}

```

# Answer
> 2 votes
You need to change the sequence of the array, like:

```
function meme_user_update_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  $changed_column = array(
    'data'  => 'LAST CHANGED',
    'field' => 'u.changed'
  );
  $operation_column = array_pop($form['accounts']['#header']);

  $form['accounts']['#header']['changed'] = $changed_column;
  $form['accounts']['#header']['operations'] = reset($operation_column);

  foreach ($form['accounts']['#options'] as $key => $row) {
    $user_object = user_load($key);
    $user_language = ($user_object->language) ? $user_object->language : LANGUAGE_NONE;

    $operation_column = array_pop($form['accounts']['#options'][$key]);

    $form['accounts']['#options'][$key]['changed'] = $user_object->field_user_changed[$user_language][0]['value'];
    $form['accounts']['#options'][$key]['operations']['data'] = reset($operation_column);
  }
}

```

# Answer
> 1 votes
You could switch to the Administration Views module and customize the entire view, including using the Views Bulk Operations module, if you wanted.

> Replaces administrative overview/listing pages with actual views for superior usability.

This is a very similar pattern to the way administrative pages work in Drupal 8, where views are core entities.

---
Tags: 7, hooks
---


# Question
Title: Custom ajax widget can't save generated value to database - $item always zero
I'm currently working on a custom module that communicates with a REST API. It is implemented as a new field type with a custom widget. The entire communication with the API works fine. The thing is that I'd like to save one part of the response in the database and I can't get it to work.

My code is here: https://github.com/stopopol/b2share/blob/master/b2share.module

Basically, I only need the information of one textfield ( $form\['b2share\_fieldset'\]\['pid\_button'\]) to be saved in the database, but the save function doesn't seem to be called.

I tried following this tutorial: http://getlevelten.com/blog/ian-whitcomb/defining-custom-field-types-drupal but I had no success yet. Maybe it's also important to mention that this field will be embedded in a content type together with plenty of other fields, therefore the communication with the rest api is done via ajax, but the values I get from the API should be stored together with the regular fields in the node form.

I only need someone to tell me what's missing from being able to save it. I've been stuck for days and can't figure it out.

Thanks.

**EDIT:** Ok. I narrowed it down and it seems like the problem is that

`foreach ($items as $delta => $item)`

never runs because the size of $items is always 0. I haven't found the reason yet. But will post my insights here.

**EDIT2:** Thanks for the helpful comments. I used hook\_submit and was able to save values in the database, but drupal is complaining about the entity\_Id and delta.

Example code I found suggests a function like this:

```
 function b2share_form_alter(&$form, &$form_state, $form_id) {
   $form['actions']['submit']['#submit'] = array('b2share_form_submit');
   return $form;
 }

 function b2share_form_submit($form, &$form_state) {
 drupal_set_message( 'submit handler is called' );

 $values = array(
   'url' => $form_state['values']['b2share_fieldset']['url'],
   'pid' => $form_state['values']['b2share_fieldset']['pid']
 );

 $insert = db_insert('field_data_field_b2share')
   -> fields(array(
    'field_b2share_url' => $values['url'],
    'field_b2share_pid' => $values['pid'],
    //'entity_id' => 1,
    //'delta' => 0,
    //'language' => 'und',
))
->execute();
}

```

But apparently the functions needs to give more info or I am missing something somewhere else.

**EDIT 3:** Calling b2share\_form\_submit breaks the node form. The error message says: "The requested page "/.../node//current-revision" could not be found."

Logs say :

"Warning: Missing argument 3 for b2share\_form\_submit(),"

"Warning: Missing argument 4 for b2share\_form\_submit()"

**EDIT 4:** As described here in a comment (Do something after submit the form at hook\_form\_alter) this is the correct way to write the form\_alter function: `function b2share_form_alter(&$form, &$form_state, $form_id) {
 $form['#submit'][]='b2share_form_submit';
 return $form;
}`

# Answer
I found multiple examples on how to write your a custom submit handler, but most of them had a flaw in it. They were either always or never called. Sometimes I couldn't access the node\_id, which was crucial for me.

I ended up using this:

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

function seal_the_deal($form, &$form_state, $entity_id, $entity_type, $form_id) {
 $values = array(
  'url' => $form_state['values']['b2share_fieldset']['url'],
  'pid' => $form_state['values']['b2share_fieldset']['pid']
 );

 if ( (empty($values['url'] == false) || (empty($values['pid']) == false)) ) {

    $insert = db_insert('field_data_field_b2share')
     -> fields(array(
        'field_b2share_url' => $values['url'],
        'field_b2share_pid' => $values['pid'],
        'entity_id' => $form_state['node']->nid,
        'entity_type' => 'node',
        'bundle' => $form_state['node']->type,
        'delta' => 0,
        'language' => 'und',
     ))
    ->execute();
     }
   }

```

Details can be found here:

Custom submit handler is also called when deleting a node

http://atendesigngroup.com/blog/form-altering-node-addedit-forms

Drupal 7 custom form submit handler is not being called
> 0 votes

---
Tags: database, ajax, 8
---