# Question
Title: How to add a file lock to all existing files in directory
I've just started using file lock to prevent images getting deleted, so we can build up a store of images for use at a later date. I think this module will solve a problem I've had, but only for images uploaded *from this point forward*.

How can I *also* apply this protection retrospectively to:

1. Images already in file fields
2. Images uploaded by FTP (well, you know, SFTP )

# Answer
## To add a file\_lock usage record for all existing files without one:

```
INSERT INTO file_usage (fid, module, `type`, id, `count`)
SELECT fid, 'file_lock' module, 'module' `type`, 0 id, 1 `count`
FROM file_managed
WHERE status AND NOT EXISTS (
  SELECT id FROM file_usage
  WHERE file_managed.fid = file_usage.fid
        AND `type`='module'
        AND id=0
        AND `module` = 'file_lock'
        AND `count`>0
);

```

## To add a file\_lock record for all files in a directory that are NOT registered in the file\_managed table

Here I loop through all likely image files in and write them as `public://` `file_managed` records if none exists.

* preg\_ls is not PHP/Drupal core - nicked it from PHP comment \- v useful!
* I exclude the `styles/` directory which stores the variants made by different image styles. I also exclude the `images/backup/` directory - this is particular to my needs, but I left the code in as you'll likely have something to exclude too.
* This assumes you have no `private://` files and that everything under sites/default/files is to be a `public://` file. **do not run this as it is if you use private files at all!**
* It also assumes that on `file_save`, `file_lock` will add its own lock (based on your config for `file_lock`).

And now the code:

```
$dir = DRUPAL_ROOT . "/sites/default/files/";
foreach (preg_ls($dir, true, '/\.(jpe?g|gif|png|bmp)$/i') as $_) {

  $_ = substr($_, strlen($dir));
  if (preg_match('@^(styles/|images/backup/)@', $_)) {
    continue;
  }

  $uri = "public://$_";
  if (!db_query("SELECT fid FROM {file_managed} WHERE uri = :uri",[':uri' => $uri])->rowCount()) {
    $file = new stdClass();
    $file->fid = NULL;
    $file->uri = $uri;
    $file->filename = drupal_basename($uri);
    $file->filemime = file_get_mimetype($file->uri);
    $file->uid = $user->uid;
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
  }
}

```
> 0 votes

---
Tags: 7, files
---


title: Webform default value of select list

text:
# Question
Title: Webform default value of select list
I have created a website for yacht charter http://cozmoyachts.com

I have created one booking form for yacht booking using webform module and used that form on all yachts pages. Like 45 feet yacht, 55 feet yacht and so on...

In that form there is a select list to select a yacht.

I want to change the default value of that select list according to the URL of page.

So if the visitor is on 33 feet yacht page the default value in select of booking form should be 33 Feet Yacht.

Hope I am able explain my question properly.

# Answer
> 0 votes
If you fx want to set the default value using, given it is passed as a parameter in the URL:

```
function hook_form_FORM_ID_alter(&$form, &$form_state) {
  $params = drupal_get_query_parameters();
  if (isset($params['my_param'])) {
    $form['FIELD_NAME']['und'][0]['#default_value'] = $params['my_param'];
  }
}

```

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_form\_FORM\_ID\_alter/7

---
Tags: webforms
---


# Question
Title: Drupal CKEditor module remove line breaks
I have legacy content that has line breaks as paragraph separator. When trying to deal with them using CKEditor module 7.x-1.16 and CKEditor 4.5.4 library, all line breaks are removed and the text turned into an ugly mass of text.

I tried disabling some filters from the *Full HTML* input format:

1. Limit allowed HTML tags
2. Convert line breaks into HTML
3. Correct faulty and chopped off HTML

I also tried to use custom formatting options and disabling \_Advanced content filter. In any case, I didn't achieve my purpose.

# Answer
> 1 votes
The solution is simply in two points:

1. Adding the following config to in the advanced option tab of the desired profile: `admin/config/content/ckeditor/edit/Full`

config.protectedSource = \[/\r|\n/g\];

This will keep the source of the content with new lines as it is and forget about its shape in the wysiwyg.

2. In for the container that holds your content, use the following css rule:

white-space: pre-line; This will keep lines separated as paragraphs.

checkout those screen shots:

Add the protected source config:

Don't worry about it in wysiwyg:

Just look at the source:

It will look like the following on the frontend:

> Don't forget to flush cache specially if you optimized and aggregate js and css, also remove your browser cache or enabling remove cache during using dev tools (chrome)

# Answer
> 1 votes
Wysiwyg Linebreaks

> You can choose between two different methods:
>
> * Force linebreaks: Your content will always preserve whitespace/linebreaks around blocks of text, rather than paragraph
> and break tags.
> * Convert linebreaks: Your legacy content will appear correctly in your WYSIWYG editor, then the content will be saved with the markup added by the editor).

---
Tags: 7, wysiwyg
---


# Question
Title: Is there a way and/or reason to unload a node after node_load?
I have a custom module that loads one specific node to get its field value, and then uses that field to make a bunch of calculations. I've seen several comments like this one that node\_load is a resource hog...

My question is if there is a significant benefit to unsetting the node object once I've retrieved my field value, and if yes what is the best way to unset it? I've googled for some time but only can find references to deleting nodes, not unsetting the object. Thanks!

# Answer
It's advised to use `node_load()` rather than building your own queries.

If you worry about memory impact, you can unload it by unsetting it:

```
unset($node);

```

It would destroy the specified variable/object, however you don't have to do it as PHP should handle garbage collection internally.

Secondly the node would be only loaded in your local scope, so once PHP exits your function, it should be automatically flushed from the memory at some point.

If you're worry about memory impact, you may:

* reduce number of modules which hook into the node objects,
* run PHP profiler (such as XDebug) to check the memory is used the most,
* enable Devel and its performance checking, it'll show you how much memory is used per individual page,
* implement memory caching (instead of using database layer), such as redis or memcached

See: How do you improve Drupal performance?
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Panels doesn't output views content pane title
I have a panel named **bar** in which I added a view-content-pane named **foo**.
For this view I created a *template-override named views-view--foo--panel-pane.tpl.php* in which I added, besides other things, a container for the $title like: `<div class="foo-heading"><div class="foo-title"><?php print $title; ?></div></div>`
The title of the view-content-pane is **Foo**.
To limit the moltiplication of *divs* I set to "No markup at all" the style of both the whole panel and the single pane.
Configured like that, the view shows with custom styles (which I setted in my custom theme-override) except for the title that doesn't display at all.
If I change the single pane style to "No style", the title is shown but using the panel default style (which breaks my layout).

It's there a way to output the view-content-pane title as configured in the template-override without this being rendered by the panel?

# Answer
> 2 votes
The `$title` variable for the `views_view` theme hook is added only for the administrative preview. Here is the section of code in `template_preprocess_views_view()` that adds the title: http://cgit.drupalcode.org/views/tree/theme/theme.inc?h=7.x-3.11#n85

If you want to add that variable to your template override, you can do so with an additional preprocess.

---
Tags: views, theming, panels
---


# Question
Title: Should I pass the $form parameter when building system_settings_form?
Usually I refer to core for best practices. When I was building a system settings form I copied and repurposed the following core implementation.

This define the path for the system setting form that gets invoked via `drupal_get_form()`

```
  $items['admin/structure/menu/settings'] = array(
    'title' => 'Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_configure'),
    'access arguments' => array('administer menu'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 5,
    'file' => 'menu.admin.inc',
    );

```

And this is the function that build the form:

```
       /**
        * Menu callback; Build the form presenting menu configuration options.
        */
        function menu_configure() {
          // The form definition is here ..
          //.....

        return system_settings_form($form);
       }

```

So my question is why isn't the `$form` param passed to the form function `menu_configure()`? There are other examples of system settings forms in core, called via the `drupal_get_from()` that do not have the `$form` parameter in the parameter list. So is it optional in this case?

# Answer
> 2 votes
The form parameter is passed from `drupal_get_form()`, but if you choose to start a new form array it doesn't really matter. The form works as expected.

However, it's good practice I think to include `$form` and `$form_state` in the parameter list because if you ever change your menu entry to pass an argument, then all you need to do in your form builder callback is to add it to the list at the end.

---
Tags: 7, forms
---


title: What do blocked IP addresses see?

text:
# Question
Title: What do blocked IP addresses see?
I have been getting a lot of failed attacks targeting my server in the last few months. I have been using the Drupal IP block to block IPs that where sniffing for vulnerabilities. I would like to know if this is only for drupal or is it adding it to the OS as well. Also once I block an IP address what do the attackers see? Do they get a 404? Do they get a banned message? or nothing at all? If this is not also adding to the server OS IP block is there a module that will?

# Answer
> 11 votes
They see a blank 403 page with this message specifying that their IP address has been banned:

The block is done at the application level. Drupal inserts a record into the `blocked_ips` table which is referenced upon bootstrapping; if a match is found the above page is shown.

I've not heard a module that does this at the OS level. Considering the variety of environments it would have to accommodate, and the potential harm of giving an application OS-level blocking (e.g. Drupal blocking you could lock you out of your own server), it's likely it doesn't exist.

---
Tags: security
---


# Question
Title: How to provide content type in module for Drupal 8?
How do I write a module that provides a content type in Drupal 8?

# Answer
> 8 votes
For a module name `my_module` and a content type called `awesome_page`, the directory structure would look like:

* my\_module/
    + my\_module.info.yml
    + config/install/
        - node.type.awesome\_page.yml

And the file contents would be:

`my_module.info.yml`:

```
name: Awesome page content
type: module
description: 'Add awesome content type.'
core: 8.x
dependencies:
  - node

```

`node.type.awesome_page.yml`:

```
type: awesome_page
name: 'Awesome page'
description: '<em>Awesome</em> pages are a little better than other pages.'
help: ''
new_revision: false
display_submitted: true
preview_mode: 1
status: true
langcode: en

```

For several other examples, find all modules in core that provide new content types: `find . -iname "node.type*"`

# Answer
> 2 votes
You can use Drupal Console, this will automatic ask you for couple question an generate the content type (entity type) for you on a module.

Here is the command that you need to `generate:entity:bundle [options]`

---
Tags: nodes
---


# Question
Title: Change input method of "Description field" in "File" type
I have added a "File" field in a Content type. Now I can mark the option " Enable Description field". This "Description field" only let use direct input. I need to change this to a select field. I'm not expert in hooks use. I'd like to set it as a dropdown or autocomplete. Which is the best option? create a taxonomy list or a hand made term list? I have to use only in one content type. Thanks

# Answer
> 1 votes
One way to do it without coding might be to create custom entities with Entity Construction Kit and insert them to your content type using Inline Entity Form. Using ECK, you can add the dropdown/autocomplete field and the file field.

You may then need to use something like Automatic Entity Label to prevent the user from needing to enter description/title themselves (The site won't allow me to insert a third URL here, but an internet search for "automatic entity label drupal module" will bring it up).

---
Tags: entities
---


# Question
Title: Database error when creating entities using hook_update_N
I'm trying to create an entity (using `entity->save()`) in a hook\_update\_N function. The errors appear at the mysql insert query in the entity's insert function; the insert strings are wrapped in `mysql_real_escape_string()`.

I get a series of warnings:

```
mysql_real_escape_string(): A link to the server could not be established mod_person.entity.inc:402

mysql_real_escape_string(): Access denied for user 'xxx'@'localhost' (using password: NO) mod_person.entity.inc:403

```

Followed by the error:

```
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'val' at row 1

```

When I remove the `mysql_real_escape_string()` from the mysql insert query code it works! However now I'm worried that leaves the server vulnerable.

My questions are:

\[1\] Why does using `mysql_real_escape_string()` work in normal site operation and not through hook\_update\_N?

\[2\] Do I need to use `mysql_real_escape_string()` with Drupal 7 database queries or is there another way?

I suppose I could remove the `mysql_real_escape_string()` for the update and then put them back but that feels like I'm missing the point somewhere.

Many thanks for any help.

# Answer
Similar to what Clive said, you will want to use the Database API (db\_update, db\_insert) or use an Entity Metadata wrapper.
> 0 votes

---
Tags: 7, entities, database, updating
---


# Question
Title: Create a block with information regarding the number of comments and contents created in a specific group
I am using Drupal commons 3.31. I would like to know how many contents and how many messages are written within a group and make a block out of it. Also be able to see how many comment,page a specific user has created.

Thank you

# Answer
It sounds like this can be accomplished using the views module. Create a view of content from the group you are wanting, and then turn on aggregation. For each field, you can set it to display a count() of the field results.

For the per user part, just set up a filter/contextual filter for the UID.
> 0 votes

---
Tags: 7
---


# Question
Title: Will importing a View that already exists merge with what isn't there in Drupal 7?
I have a dev and prod instance of my site. I cloned my Prod to my Dev server. Now I created a new display block inside an existing view on Dev. I tested it and it works. Now i want to export it to my Prod, but it has the same View name. I can manually create it on prod, but thats the slow way of doing it. If i export the view code and paste it to my prod, would it throw an error saying that view exist? Or would it just merge the changes and add in the new display i created?

# Answer
The views import form has this option:

> Replace an existing view if one exists with the same name.

It does what it says.
> 1 votes

# Answer
WHOA STOP. haha

Install the Features module and create a feature with this View in it and deploy (git/sftp) the Feature up to production. then revert feature and boom. latest view is there.

1. Download, enable Features on Dev
2. Create a new Feature
3. Add your View to this Feature
4. Save the exported feature into your file system for Drupal
5. Enable on Dev and verify that it is in the default state (it should be)
6. Download, enable Features on Prod (or use git to merge you dev branch into prod)
7. Place this new Feature onto prod (either using git or SFTP)
8. Enable this feature on prod. Since you have the View already, it will probably be Overridden. You can simply view differences (using Diff module) or revert it.

*Note: I highly recommend a staging environment between development and production so you can test these types of reverts and adjustments prior to making changes on a production site.*
> 1 votes

---
Tags: 7, views, importing-exporting
---


title: Which search method should I use?

text:
# Question
Title: Which search method should I use?
I want to add search option to my site but I can't decide what I should use.

I am building a news site. It has a simple structure but in time there will be lot of indexed page. When somebody use the search box, they can search inside news, the categories of the news, and the authors of the news.
The search result page should show all of them like 3 blocks as in this screenshot.

>

I tried the Search API, but it doesn't provide these.

What should I use? Can you please give me some links for tutorials/documentations. How can I do that?

To make it cleaar, when I type "Marvel" in the search box, the result should include all nodes containing *marvel* and all tags including *marvel* (e.g. *marvel's movies*, *marvel's show*). I try to show two different blocks per node and tags in the search result page.

# Answer
To restrict the search you can use the Custom Search module, this module adds options to select:

* which content type(s) to search,
* which specific module search to use (node, help, user or any module that implements search),
* which input type to use (with Elements),
* advanced criteria

And if you want modify the search result page you can modify the tpl file `search-result.tpl.php`
> 1 votes

---
Tags: 7, search
---


# Question
Title: How can I prepare a database statement and execute it many times with different input?
I have a situation where I need to update a Drupal module's query to run a `SELECT` query \[and based on the results\] an `INSERT` for a data set of ~a million items.

Outside of Drupal I would accomplish this by first preparing my `SELECT` and `INSERT` statements, then executing them once for each item:

```
$db = new PDO(...);
$check = $db->prepare('SELECT COUNT(*) FROM other_tablename WHERE colname = :value');
$insert = $db->prepare('INSERT INTO tablename (colname) VALUES (:value)');
foreach ($my_many_items as $item) {
  $check->execute(array(':value' => $item));
  if ($check->fetchColumn() < 1) {
    $insert->execute(array(':value' => $item));
  }
}

```

With the Drupal 7 DB-API however, there seems to be no way to get a prepared statement without executing it first using `db_query($query, array(':value' => $item), array('return' => Database::RETURN_STATEMENT))`.

The only option I've found is to run `db_query()` / `db_select()` / `db_insert()` in a loop for each item which ends up requiring the query string to be re-parsed for every single iteration.

How can I prepare a database statement (with Drupal doing its table-name rewriting) and then execute it many times with different input?

**Background:**

The existing implementation uses `db_select()` to build a query using a giant `SELECT ... IN` clause, filters the items in PHP, then uses `db_insert()` to save all of the values at once. While this implementation only runs two queries, it unfortunately blows up the memory usage when handling large numbers of items:

```
...
$result = db_select('other_tablename', 'o')
  ->fields('o', array('colname'))
  ->condition('colname', array($my_many_items),'IN')
  ->execute()
  ->fetchAll();
$existing = array();
foreach ($result as $r) {
  $existing[] = $r->colname;
}
$insert = db_insert('tablename')->fields(array('colname'));
foreach ($my_many_items as $item) {
  if (!in_array($item, $existing)) {
    $insert->values(array('colname' => $value));
  }
}
$insert->execute();

```

# Answer
> 4 votes
Prepared statements can be created after changing the statement class to `PDOStatement`. This technique is described in How to execute stored procedures in drupal?

```
// Get the Drupal database connection and change the statement class to PDOStatement.
// Save the current class for cleanup later.
$conn = Database::getConnection();
$saved_class = $conn->getAttribute(PDO::ATTR_STATEMENT_CLASS);
$conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement'));

// code from the question:
$check = $conn->prepare('SELECT COUNT(*) FROM other_tablename WHERE colname = :value');
$insert = $conn->prepare('INSERT INTO tablename (colname) VALUES (:value)');
foreach ($my_many_items as $item) {
  $check->execute(array(':value' => $item));
  if ($check->fetchColumn() < 1) {
    $insert->execute(array(':value' => $item));
  }
}

// Revert the connection to its previous statement class.
$conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, $saved_class);

```

---
Tags: 7, database
---


# Question
Title: How to alter node body content through Views pre render hook?
I have build the view to display node title and node body also I have applied combined fields filter which searches the keyword in title and body and returns the results.

While rendering the contents I have to render the title and body with the highlighted keywords that are been searched.

Currently I am using hook\_views\_pre\_render to alter the same.But unable to replace the body text with my generated results.

How can I alter the body contents?

# Answer
What variable are you modifying? When I modify Views results I usually use `hook_views_post_execute`. I then modify the appropriate element in `$view->result`. You may be able to do the same from `hook_views_pre_render` (I don't use that one often especially in this type of case).
> 0 votes

---
Tags: views
---


# Question
Title: How to add an attribute to CkEditor 4.x iframe tag
Does anyone know of a clean way to add an attribute to an iframe tag, or to add an equivalent parameter to the src attribute? Here is what I am trying to do:

I am using the iframe wysiwyg button in Ckeditor to allow users to paste in a video url from YouTube. The problem is, the mega menu dropdown shows up behind the video. To fix this, the iframe tag for the video either needs to have the attribute `wmode="transparent` added to it, or the actual src url needs to have the parameter `&wmode=transparent` appended.

Ideally, this would be enforced and not asked of the user. Has anyone dealt with this and implemented a solution? If so, please let me know what you did. Thanks!

# Answer
As a quick and dirty work-around, I used jquery to add a parameter to the url (which always has at least one parameter already, thus the ampersand).

`$('iframe').each(function() {
 $(this).attr("src", $(this).attr("src") + '&wmode=transparent')
 });`

But I want to later refine this to only target urls starting with https://www.youtube.com at the very least and use an attribute instead of a parameter. If anyone can suggest the code for that based on what's above, that would be appreciated. If not, I'll eventually update this post with that code when I have more time to figure it out. Thanks.
> 0 votes

---
Tags: wysiwyg
---


title: Serve drupal page to secondary domain

text:
# Question
Title: Serve drupal page to secondary domain
I have a drupal site running on a server with two domains pointed to it: domainA.com and domainB.com. I would like domainB.com to serve a specific landing page, `http://domainA.com/landing-page`. I know I can do a normal htaccess redirect like this:

```
RewriteCond %{HTTP_HOST} ^domainB\.com
RewriteRule ^$ http://domainB.com/landing-page [L]

```

Which will serve my users the correct content.

But I would rather the path wasn't added to the url. Is there a way to do a 'transparent' redirect for domainB.com so that `http://domainB.com/` serves up the content from `http://domainB.com/landing-page` without modifying the url? So that it seems more like the 'homepage'?

# Answer
At least two ways of doing this come to my mind:

**1. "Masking" your subdomain and proxying the content.** What you do in this case, is that besides your `mod_rewrite`'s redirection, you use `mod_proxy` to show your other domain's content without changing your URL. Have a look at Using mod\_rewrite for Proxying.

**2. Using the Domain Access module.** Another option, maybe overkill if you are going to use this only for one page, but useful if you have to repeat this with many domains/landing pages.

Since this module allows you to create individual homepages on a per domain basis, you just have to add a second domain (domainB.com) and set `/landing-page` as Drupal's default homepage in the domain settings. Now when you go to domainB.com, your url bar will just show `http://domainB.com` but will render `/landing-page`'s contents (since it's the homepage).
> 0 votes

---
Tags: redirection, .htaccess
---


# Question
Title: Create 3 Views blocks that display 1st, 2nd, and 3rd most recently created nodes
How can you create **three View blocks** such that (based on a particular **field value** or **taxonomy category** or just **content type**) the **first block** displays the most **recently CREATED** (not updated) node, the **second** displays the **second most recently created** node, and the **third** displays the **third most recently created** node?

# Answer
> 1 votes
Create the 3 views blocks with your filters and order by **created**. Then change the *Pager* to *Display a specified number of items*.

For 1st block update the *settings* (it should say displaying X items) then update the *Items to display* to 1 and the *offset* to 0.

For the 2nd block do the same but change the *offset* to 1 and then for the third block set the *offset* to 2.

Untested but on a quick check of the options, this should give you what you are after.

Paul

---
Tags: views, nodes, theming
---


# Question
Title: How to make links to private directory always use ssl?
I am trying to connect all links to files in a *private directory* to use *SSL*.

This is what I have done so far;

```
if (preg_match('!^system/files/webform/([^/]+)(/.*)?!', $path, $matches)) {

    if($_SERVER['SERVER_PORT'] != '443') {
       header('Location: https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
       exit();
    }

}

```

This forces *private directory* file links to use `https` but it has some issues for users who are not logged into the site.

# Answer
> 1 votes
Depending on where you've placed the above code (e.g. a `hook_init` invocation), it might not trigger for an anonymous user if caching is involved on your site.

An alternative to this approach is to do it at the web server level so that any request that matches a URL pattern will always switch over to HTTPS. For example, with Apache `RewriteRule` you could do the following:

```
  RewriteCond %{SERVER_PORT} !^443$
  RewriteRule ^system/files/webform/(.*)$ https://www.example.com/system/files/webform/$1 [R=301,L]

```

---
Tags: 7, webforms, files, ssl
---


# Question
Title: Printing field item attributes with Twig / Drupal 8
In Drupal 7, I can do this in a custom field template to print the alt tag of an image:

```
<?php print $item['#item']['alt']; ?>

```

And though "item" seems to be a variable in Twig / drupal 8 fields, I can't seem to do the same thing. I've tried these:

```
{{ item.alt }}
{{ item.item.alt }}

```

These don't work but I don't get any errors either. Looking at the API does not give me much insight. I saw this gist but again, no alt tag rendered separately. My image is rendering the alt tag as i can see it in the code though.

# Answer
> 10 votes
The syntax to print the alt tag in that case is this:

```
{{ item['#item'].alt }}

```

Twig in Drupal 8 doesn't deal with hash keys like `#item` in render arrays cleanly. Part of the problem is that `#` signifies a comment in Twig, so `{{ item.#item.alt }}` wouldn't work.

There is the possibility of working around this with a Twig extension to allow drilling down into hash attributes with the syntax `{{ item.item.alt }}` but I'm not sure if anyone is working on that. I should mention that Twig extensions can be added in contrib as well.

# Answer
> 3 votes
I achieved printing the alt attribute of my field using this line `{{ item.content['#item'].alt }}`

---
Tags: entities, 8, theming
---


# Question
Title: Weekly check of the admin/performance/status report pages
We run around 100 Drupal sites. I want to automate a weekly check that will scan all of the admin/performance/status report pages. I had a look at `drush status` but it doesn't give me the same information as the web interface does.

Has anyone done this and how did you go about it? Ideally I want to just email weekly to the developers team if there is an alert on any particular site

# Answer
If you want to use drush, `drush -n up` will show the available module updates.

Getting the status report (really "requirements" from the API's perspective) is a bit more convoluted, and can be output with

`drush php-eval 'include_once DRUPAL_ROOT . "/includes/install.inc"; drupal_load_updates(); print_r(module_invoke_all("requirements", "runtime"))'`

Other options are Nagios, Update Status Aggregator, Droptor, or the Acquia Network.
> 2 votes

# Answer
Drush now has the `core-requirements` command (whose aliases are `status-report` and `rq`). It's enough to run `drush core-requirements`.

For mass status checking, there is the Lumturio service which works through the System Status module.
> 2 votes

---
Tags: drush
---


# Question
Title: Is there any module for Restful API in drupal 7 with commerce
I am working in a ecommerce website in drupal 7 by using commerce module, also developing for mobile (android/ios) application for the same project.

So that I want to send data's for mobile application, for that I am searching API integration module.

Anybody found any module or have any relevant idea?

# Answer
Both Drupal and Drupal Commerce support API integrations with mobile apps.

Look into the following:

1. Start with Services for basic web service support in Drupal.
2. Throw Commerce Services on top of it to expose Drupal Commerce entities.

There are a couple of good articles by Tyler Frankenstein:

1. Drupal Services Example
2. Build a Mobile App to Sell Products with Drupal
3. Sell products with a custom mobile app a Presentation with Scott Hooker (then Commerce Guy) at DrupalCon Austin
> 2 votes

---
Tags: 7, commerce, database
---


title: How does importing a content type work?

text:
# Question
Title: How does importing a content type work?
I have used featured to create a yml file for views and other configurations. When I import my yml file all that is created is a content type that has a title. Is there a way to import the fields with the content type?

```
uuid: 1bd0f08e-cf80-4fc3-8707-7a9d19c404da
langcode: en
status: true
dependencies:
  module:
    - menu_ui
third_party_settings:
  menu_ui:
    available_menus:
      - main
    parent: 'main:'
name: Podcast
type: podcast
description: 'Allows Drupal to play an audio file.  The Embed Podcast field should contain the name of the Podcast exactly as it is uploaded to Drupal.'
help: ''
new_revision: false
preview_mode: 1
display_submitted: true

```

this is my file and there is nothing about the fields in a content type

# Answer
To add a field to custom content type you need

1. **field.field.node.content-type.field-name.yml**
2. **field.storage.node.field-name.yml**

The easiest way for you is create the content type and fields via UI and then just simply export it in `admin/config/development/configuration/single/export` (you have to install the config core module). Then remove **uuid** and you are done.

While exporting, export following configuration types..

* Content Type
* Entity form display
* Entity view display
* Field
* Field Storage

Hope this will help you.
> 9 votes

---
Tags: 8, importing-exporting
---


title: Multiple checkboxes in an AJAX calls

text:
# Question
Title: Multiple checkboxes in an AJAX calls
I've been developing this phonegap app and I'm stuck with a few things and one of them is multiple checkboxes - I hope you can help.

I've got the below code

*HTML*

```
<input type="date" id="date" />
<input type="hidden" id="hidden">
<fieldset id="oyuncuKategori">
    <legend>Kategori</legend>
    <div class="roundedOne">
        <input type="checkbox" id="oyuncu" name="kategori" value="oyuncu" class="squareTwo" />
        <label for="oyuncu">Oyuncu</label>
    </div>
    <div class="roundedOne">
        <input type="checkbox" id="yardimci_oyuncu" name="kategori" value="yardimci_oyuncu" class="squareTwo" />
        <label for="yardimci_oyuncu">Yardımcı oyuncu</label>
    </div>
    <div class="roundedOne">
        <input type="checkbox" id="cocuk_oyuncu" name="kategori" value="cocuk_oyuncu" class="squareTwo" />
        <label for="cocuk_oyuncu">Çocuk oyuncu</label>
    </div>
    <div class="roundedOne">
        <input type="checkbox" id="stand_hostesi" name="kategori" value="stand_hostesi" class="squareTwo" />
        <label for="stand_hostesi">Stand hostesi</label>
    </div>
</fieldset>

```

*JavaScript*

```
$("input[type='date']").on("change", function () {
    // var checkbox = $("#oyuncuKategori").serialize();
    var checkboxes = '';
    $('input[name=kategori]:checked').each(function(i, e) {
        checkboxes += '&node[field_kategorisi][und][value]='+$(this).val();
    });
    console.log(checkboxes);
    monthNames = [
        "Oca", "Şub", "Mar",
        "Nis", "May", "Haz", "Tem",
        "Ağu", "Eyl", "Eki",
        "Kas", "Ara"];
    date = new Date($("input").val());
    day = date.getDate();
    monthIndex = date.getMonth();
    year = date.getFullYear();
    finalDate = day + ' ' + monthNames[monthIndex] + ' ' + year;
    $.ajax({
        url: 'http://www.rejicast.com/services/node.json',
        type: 'post',
        dataType: 'json',
        data: 'node[type]=oyuncu&node[title]=testnomikos456&node[language]=und'+ checkboxes +'&node[field_dogum_tarihi][und][0][value][date]=' + finalDate +',
        success: function (data) {
            console.log(JSON.stringify(data));
        },
        error: function (xhr, status, message) {
            console.log(xhr);
            console.log(status);
            console.log(message);
        }
    });
});

```

The thing is, this code works for creating a node but and inserts values for field\_kategorisi overwriting other values, thus always the last checked box is there, while trying with `[und]['+i+'][value]` gives me `406: An illegal choice has been detected. Please contact the site administrator`. and something like `Illegal choice Array in field_kategorisi` (I don't remember the English wording) on the server side. I'm really stumped. Can you give me any ideas?

UPDATE: When I make an ajax call, my POST looks like this.

> http://www.rejicast.com/services/node.json?node\[type\]=oyuncu&node\[field\_kategorisi\]\[und\]\[0\]\[value\]=stand\_hostesi&node\[field\_kategorisi\]\[und\]\[1\]\[value\]=yesilcam

# Answer
> 0 votes
**Edit:** Just looked at the code more closely, and saw this was the Services module.

From https://www.drupal.org/node/1971484#comment-7318114:

> For those of you who will probably have the same problem, here is the correct way to handle LIST type fields (in ex. below field\_mosaic\_bu):

```
{
  "type":"TEST",
  "title":"TITLE",
  "uid":"1",
  "field_mosaic_bu":{ "und": ["bu name"] },
  "field_mosaic_var1":{ "und": [{ "value":"test1" }] },
  "field_mosaic_var2":{ "und": [{ "value":"test2" }] },
  "field_mosaic_var3":{ "und": [{ "value":"test3" }] },
  "field_mosaic_image":{ "und": [{ "fid":"4" }] }
}

```

> Hope this helps someone. Took me a lot of time to figure this out.

---

When you get that message from Drupal, it generally means that you have tried to set a form value to a non-allowed value from the perspective of the field configuration. So, for example, `field_kategorisi` might be a Term Reference field. If you try to set it to a `tid` that isn't allowed according to the Drupal field configuration, that happens.

If it's a simple checkbox field, then adding the value you want to set to the Allowed Values in the field configuration should solve the issue.

If this doesn't help, please provide more information about the Drupal-side field configuration and whether you are using the form Drupal generates or not. It embeds various things like the form ID, form build ID, and so on into its form markup, so if problems persist, it could be related to it not receiving something it's expecting.

---
Tags: ajax, services, javascript
---


# Question
Title: How to show user created node in user's profile page in drupal 7?
I need to show user created page content on own profile page.In my site user will create a node content then I need to show user created node content in user profile page. For this I am creating a views.. But I am not getting how to show particular user created node.. In my case all nodes are showing.

# Answer
Entity View Attachment will do the job for you. Here is a tutorial about that.

if you don't want to use a new module , views can handle it by its own , first of all create a page of that view and then use these settings :

then what you need is a contextual filter . these settings will work for you:

and then :

now save settings . go to a user profile page and you will see a new tab which shows users contents .
> 1 votes

---
Tags: views
---


# Question
Title: How to update disabled modules using Drush?
Is there a way to update disabled modules with `Drush`?

Currently, when I try to update a disabled module with Drush, I get this message:

> Project has no enabled extensions and can't be updated

Enabling the module is not an option as this is a live site, actually many sites. They all run off of the same Drupal code base. Some modules are used by some sites but not others (possibly not on the main site).

If Drush can't handle this, what's an easy alternative for updating modules?

# Answer
> 6 votes
You can use `drush` for it. First, you have to get the list of all modules that you've, for it you use `drush pm-list` like this `drush pm-list --no-core --pipe --type="module"` you'll get a list of all modules (enabled, disabled and uninstalled).

After, when you get all list of your modules, you can use `drush dl [modules - list]` with this command `drush` gonna download and replace the existent module. Like he does with `drush up`.

The last problem is to run the `update.php`, unfortunately this one you've to do it for each website or you can easily code a small script that do it.

# Answer
> 15 votes
I use: `drush pm-updatecode --check-disabled` followed by: `drush @sites updatedb`

The `--check-disabled` option was added 2014-11-04

# Answer
> 10 votes
```
drush vset update_check_disabled 1 -y

```

# Answer
> 6 votes
So, I just realized that updating disabled modules is possible through Drush provided that you've set the check box for `Check for updates of disabled modules and themes` in the settings of your **Update manager** manager module (at `admin/reports/updates/settings`).

Then it's a matter of issuing the command `drush up modulename` to update the module.

---
Tags: drush, multi-sites, updating
---


# Question
Title: How to print barcode labels on standard printer?
I am using **barcode creation module** to create barcode labels on standard printer.while giving print option it is not showing any barcode labels on print preview.

How can i able to see my labels?

It shows this error.

> The directory **/var/www/html/transgenic/sites/default/files/barcodes** is not writable or not exist or something else wrong. You can not print barcodes without correct settings.
> An error occurred while generating the barcode.
> The directory **/var/www/html/transgenic/sites/default/files/barcodes** is not writable or not exist or something else wrong. You can not print barcodes without correct settings.

# Answer
> 0 votes
You have to set the permissions right. try 'chmod 755 -R /var/www/html/transgenic/sites/default/files/barcodes' Do this with the same account as the webserver uses.

---
Tags: files
---


# Question
Title: How to add ShareThis link field into View
I have a view and I want to add ShareThis(module enabled) link to each result of the view. How this can be achieve so that any of the result row of the View will be shared on social networking sites.

# Answer
> 1 votes
Please check images for how to use sharethis filed within views

RESULT PAGE:

---
Tags: views, social-network
---


# Question
Title: How to use Views Page + Attachment to show parent and children nodes?
I have a site with a node type `Lesson`, which has a `Category` field that points to a taxonomy term.

There is another node type `Exercise` which is a child to a `Lesson` node.

I previously figured out how to make one view page for a term url that displays both a parent and child nodes. But I was thinking that maybe it is better to have a page view with an attachment, where the page would display a `Lesson` node's fields and an attachment would display the children `Exercise` node's fields.

The page view has relationship set to taxonomy term and contextual filter set to the category. Then it is set to display `Lesson` fields.

In the attachment view, parent is set to page, relationship is set to a `Lesson` reference field. But I have no idea what to choose as contextual filter because there is no filter for me to choose that will get me the lesson id. The attachment doesn't seem to have a way to get the parent node id (lesson id) from a contextual filter, since the url will only have the term id.

Any ideas on how to make the attachment display the children of the parent that is displayed in the page view?

Thanks!

# Answer
> 0 votes
It sounds like you're getting stuck messing with relationships in the view - this shouldn't be needed to do what you're trying to do. You can accomplish this with these basic settings:

**Lesson**: All your lesson fields + term reference to category

**Exercise**: All your exercise fields + term reference to category

Your view's page display just needs to be set up to display `content` of type `lesson`.

The part that I think you're missing is setting the contextual filter.

1. Add the contextual filter `Content: Has taxonomy term ID`
2. Provide default value -\> `Taxonomy Term ID from URL`

Your attachment should be set to show the `exercise` content type. Add the same contextual filter to this display and make sure you have `inherit contextual filters` checked.

This will give you a page that displays the lesson, followed by all exercises tagged with the matching category.

---
Tags: views
---


# Question
Title: Views Slideshow - Bullets or Numbered Pager not displaying
I have used Views Slideshow to generate a page slideshow. The rotation / cycle is working fine but I need to display a bulleted pager. Since I am not able to display any kind of pager, I started with trying to show a numbered pager first which is not working for me.

I have basically used this guide to setup numbered pagers.

However, I do not see the numbers after doing the same.

I have enabled the page controls and current page index for testing purpose. Below is what I get using Devel Themer module and the developer tools.

I just increased the height of the area which is supposed to display the pager so that I can click that area to show the themer information. I cannot see anything rendered in the div responsible for displaying the pager. Also, as I see in the template which is rendering the code for pager is simple.

From the file "views-slideshow-pager-fields.tpl.php" the code is the following.

```
<div id="<?php print $widget_id; ?>" class="<?php print $classes; ?>">
  <?php print $rendered_field_items; ?>
</div>

```

I do not understand why the pagers are not getting displayed. Where should I start looking for the fix?

# Answer
You can achieve **pager** using View Slideshow by following steps:

**Step 1:** In view, add **Global: View result counter** field and mark it as **Exclude from display**.

**Step 2:** Now click on Slideshow format settings, go to **Pager** part and select **Global: View result counter** field as a **Pager Type**.

**Step 3:** To give perfect bullets effect, you will have add some **CSS** as given below

```
.views-field-counter {
    float: left;
    margin-left: 5px;
}

.views-content-counter {
    text-align: center;
    width: 29px;
    background: url(../bullets.png) no-repeat scroll center center transparent;
    cursor: pointer;
}

```

**Step 4:** Please check out CSS Classes, ID's and HTML markups form below screenshot, which worked at my end.
> 5 votes

---
Tags: views, paging
---


# Question
Title: vbo action without selecting row (in other mean all rows)
Is there any option available to apply bulk operation on all rows of views result, which means no need of selecting any rows?

A good example is in GMail's ***Delete all spam messages now*** which deletes all rows (spam mails) without complaining about row selection.

# Answer
The closest thing to this is **Enable "Select all items on all pages"** in Bulk operations settings.

It presents itself as a button to select all items in the view which you select the "select all" checkbox on the current page.

It's not exactly what you describe, but you're not going to get that without custom code to modify VBO.
> 0 votes

---
Tags: views
---


# Question
Title: programmatically get default value from translated body field per language
I am trying to get a default value loaded programmatically into every **body** field when we add translate from english, but it doesn't seems to work using form overwrite fields

I tried using `$form[][] = 'value';` but not working

as I also unable to pull the default value that is already set via field\_translations.

I used **form\_alter** for the options

can anyone please point me some clue of which method I used for the custom module

thank you!

# Answer
eventually, I fixed it myself by using the hook form alter and custom db\_query to load the locales tables and then match the LID to get the source and target language and then manually overwrite the default language for every new translated language.

so my problem is solved, thank you guys for helping out.
> 1 votes

# Answer
If you are using **Internationalization** Module for translation, then using **Synchronize translations** Module you can do it.

From project page

> The Synchronize translations module, part of the Internationalization (i18n) package, allows you to synchronize fields and other node elements across translations of a given node. This is available for content types where multilingual support, with translation, is enabled.
> 0 votes

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


# Question
Title: How do I enable Backlinks View and What Links Here?
We used the backlinks view in D6, as well as the **What Links Here** tab for each node.

We're now using Commerce Kickstart 2. I don't see that View and it appears that the `search_node_links` table is empty.

Is this disabled because Commerce Kickstart uses the SOLR search in place of the default Search? If so, is there a way to have both the SOLR search -and- the backlinks as well?

# Answer
Were you using Reverse Node Reference? Now in Drupal 7, you have reverse references available to you in views:

So you can use those relationships to go and load other content from one base content type (e.g. list blog posts or other products that reference this node or product).

Ideally, though, you might use EVA or or Views Field View to attach a view to an entity via a field. That view would use a base of whatever type of content or entity you were wanting to display, and then you'd just a contextual filter to limit it based on the field that references it.

Secondly, Commerce Kickstart doesn't use Solr out of the box, but it does use Search API. You can use Search API with Solr but faceted search and regular search do not require Solr. You can have Solr index entityreference fields and Views can use them, but all that does is change which checkbox you select in your Views config and not how you actually create the View.
> 0 votes

---
Tags: 7, search, commerce
---


# Question
Title: Rule to complete checkout for all orders
How can I create a rule to process checkout for all orders. Te be more specific: I'm creating a shop in which the whole checkout is based on a cronjob. So customers add their products to the shopping cart and every week at friday a cronjob is processed to process all shopping carts and create a order for them. Payment is not necessary, and users can not manually complete orders.

I've tried to create this in rules, but their is only the option to "Complete checkout for **an** order" not **all** orders.

# Answer
There is no default Commerce rules action that selects all orders. You're going to have to build your own action, or find a contrib module that provides it for you, that selects such a list of commerce orders to act upon.
> 0 votes

# Answer
You can do a lot with rules, but that doesn't mean you should... but if you were going to try it, you might start here:

1. Create a new Rule **Component**. (This is important.)
2. Use rules to Fetch entity (Commerce Order) by property (status) to have it generate a list of commerce order entities. (Alternatively, you could use Views Rules to be a bit more granular.)
3. Use Rules to loop over the list that has been loaded.
4. Inside the loop, use the "Complete checkout for an order" action.

It may be advantageous for you to do some other stuff to (create a new transaction, send an email, etc). In that case, create a new rule component and use that inside your loop. Just make the action rule take an order as a parameter and then you can do a bit more. You could use that to check the conditions of an order (user, date, etc.) before processing it, too.

Finally, set up the Rules Scheduler module that ships with Rules and schedule the main rule to run when you'd like. Just make sure that the rule you schedule **reschedules itself**, otherwise it'll only run once.
> 0 votes

---
Tags: rules, commerce
---


title: How to activate "Add existing field"?

text:
# Question
Title: How to activate "Add existing field"?
In the section called **Manage fields** within a content type, there is an option called **Add an existing field**. How this field is activated?

Some time ago I installed Drupal 7.38 and I worked with such option. This option was there. I never knew how it appeared there.

Now, I have two new Drupal installations (7.38 and 7.40). None of them shows by default the option called "Add an existing field".

Does the option "Add an existing field" belong to *Drupal core* or to some *contributed module*?

# Answer
**Add an existing field** is belong to *Drupal core* only.

You are not getting the option to **Add an existing field** because you have not created any field as of now. You cannot add an existing field until you have created it as a new field first. After you have created the new field, you can attach that field to multiple content types using **Add an existing field**

The Drupal.org documentation does not recommend that you re-use fields:

> "It is recommended to create new fields, rather than reusing existing ones, unless you have a clear reason to do so".
> 1 votes

---
Tags: 7, entities
---


title: Theming Site off-line page

text:
# Question
Title: Theming Site off-line page
Is there any way to theme or override the Site off-line page?

The page with below massage:

> **The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.**

This page uses Garland by default and it has Drupal logo on the page. I would like to remove this Drupal logo and also change the texts.

# Answer
Yes, there are 2 templates files that handle this in your theme:

1. **maintenance-page.tpl.php:** The theming template used for when your site is in maintenance mode.
2. **maintenance-page--offline.tpl.php:** The theming template used for when your site doesn't have database connectivity.

Read Theming the Drupal maintenance page on d.o for more information.
> 1 votes

---
Tags: theming, 6, maintenance-mode
---


# Question
Title: How to create a URL to an unmanaged public file in Drupal 8
I'm running into a problem creating a URL to an unmanaged file in the "public" file directory (this is for the file\_example for Drupal 8).

The following code will throw an exception:

```
use Drupal\Core\Url;

$stuff = "content for an unmanaged file\n";
$dest = file_unmanaged_save_data($data, "public://unmanaged-mahem.txt");

print "URI: $dest\n";
$url = Url::fromUri($dest);
$our_uri = $url->getUri();
print "Our URL was created, and thinks it corresponds to the URI $our_uri\n";

//but this throws:
$external_link = \Drupal::l(t('External link'), $url);
print "External Link: $external_link\n";

```

When run, here's what you see (the stack trace is removed):

```
$ drush @d8 scr unmanaged-mahem.php
URI: public://unmanaged-mahem_1.txt
Our URL was created, and thinks it corresponds to the URI public://unmanaged-mahem.txt
exception 'InvalidArgumentException' with message 'The URI 'public://unmanaged-mahem_1.txt' is invalid. You must use a valid URI scheme. Use base: for a path, e.g., to a Drupal file that needs the base path. Do not use this for internal
paths controlled by Drupal.' in /var/www/drupal/core/lib/Drupal/Core/Utility/UnroutedUrlAssembler.php:69

```

I'm not sure if this is a bug or if this is by design, since in general, you'd want to use a managed file for anything in the public files directory that was for public consumption. But the change record doesn't say anything about this.

Is there a valid way to create a link to an unmanaged file in Drupal 8?

# Answer
> 7 votes
You need to run the file path through file\_create\_url() ~~and then use it together with `base:`~~

```
Url::fromUri(file_create_url($dest));

```

(file\_create\_url() should return absolute URL's, so you don't need base)

There's an issue to simplify that: https://www.drupal.org/node/2539622

---
Tags: uri, 8, files
---


title: How to send watchdog logs to email?

text:
# Question
Title: How to send watchdog logs to email?
I want Drupal send me watchdog logs by emails.
I found Logging and alerts 7.x.
But it sends every alert/warning etc. log in a seperate email.
But i want it to gather that entries and send emails.
For example 50-60 entry in an email.

Is it possible by using these settings in that module:
\- Maximum number of allowed consecutive similar email alerts
\- Email alerts should be considered "consecutive" if sent within

Or should i use something else?
Thank you

# Answer
Create a module that implements `hook_watchdog()`. You could have your own cache of log entries and send a digest of them once a day, or whatever policy you like.
> 3 votes

# Answer
There's a module called Watchdog Digest that seems (to aspire) to do exactly that.
> 0 votes

---
Tags: emails
---


# Question
Title: How to get the publishing and menu fields from the node edit form in the "Manage fields" tab?
I am wondering what is the cleanest way to customize the core node edit form fields like the publishing and menu options fields?

They do not appear in the ***Manage fields*** tab, otherwise I would be able to organize them using modules like Display Suite, Field Groups, and either Conditional Fields or Field Conditional States as I do with other fields.

Here are a few example of things I would like to do (I achieved such things in the past with Drupal 6 by altering the form array, but I want to avoid this now since this was more complex, less maintainable and with not enough separation between the presentation and application logic):

* *Adding supplementary fields to existing tabs:* My site has news articles which can be promoted on the front-page (using the standard Drupal checkbox) and/or appear on some other pages (using multiple Entity Reference fields). All these control should be grouped together since they all are publishing options from the end-user perspective.
* *Core fields availability dynamically depends on custom fields:* A user can choose to link the node title and the node's menu link title so changing one will alter the other automatically. In such case the field asking to enter the menu link title must be hidden. However, it must show-up if for some reason the user choose to unlink them and set different values for both titles.
* *Core fields availability dynamically depends on other core fields:* Some content can be created either with no menu item, in which case it can only be referenced by other nodes, or with a menu item, in which case the end-user can choose to publish or unpublish it. The ***Published*** option should therefore be available only when the user chose to create a menu item since it is not relevant otherwise for this content-type.

I tried with Display Suite extra's ***Extra fields*** feature, but it only adds the fields on the ***Manage display tab***, and not the ***Manage fields*** as I need.

My current solution is to add standard custom fields to the node, hide the default ones and code the logic in `hook_node_presave()` for instance, but I do not know if there any cleaner solution?

# Answer
> 0 votes
Issue solved mainly thank to the ***Renderable elements*** module.

It adds the core node edit form's vertical tabs and their content to the usual ***Manage fields*** tab, allowing any kind of customization (adding, removing, reordering tabs and fields, the tabs properties can even be turned into horizontal tabs if one needs this, etc.).

There is a very good short video introducing this module's main features.

The only limitation is that the way this module alter the forms may cause incompatibilities with other modules. On my side I just noticed minor issues with no impact to the end-user:

* The standard checkbox "Provide a menu link" does not hide automatically the other menu related options depending on its state, this is a non-issue for me since I precisely wanted to customize this behavior,
* Modules like ***Conditional Fields*** do not detect yet the supplementary fields added by the ***Renderable Elements*** module. The few States API effects directly involving these fields might need to be coded specifically (***Conditional Fields*** offers an option to manually define the jQuery selector to be used, I didn't tried yet if this could be a reliable workaround for this issue),
* Other modules which were already programmatically altering the default vertical tabs may be confused and become unable to alter the tabs anymore. For instance, ***Fast Permissions Administration*** does not add anymore its "*Manage Permissions*" link in the ***Publishing options*** vertical tab.

The good news is that this module is fully compatible with ***Display Suite*** and ***Field Group***. The vertical tabs and its components can be moved to any Display Suite's region, but more importantly the vertical tabs content can be organized in any kind of group you like (`<DIV>` markers, (collapsible) fieldsets, other tabs, etc.).

---
Tags: nodes, forms, display-suite
---


# Question
Title: Get all related sister (same content type) nodes through a view in Drupal 7
On my node detail page, I am hoping to show all the related nodes through a view which have the same taxonomy term(s) selected.

How can I make sure to get the related nodes on the node detail page (Note:- I don't have taxonomy term in the URL )

Thanks.

# Answer
To filter nodes with the same taxonomy term, when a node is displayed as main content (/node/???)

View , Display as block

2 contextual filters:

* Content: nid -\> provide default value: content id from url - more: exclude
* Content: Has taxonomy term ID -\> provide default value: taxonomy term id from url

It is important to put the contextual filters in this order, the first filter excludes the actual node from display, the exclude-checkbox is at the end under "More"

add additional filters, for example:

* Content: your content-type
* Content: Published (Yes)

Put the view block right below your Main page content in the Content-Region
> 1 votes

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


# Question
Title: How to alter the fields available for commerce backoffice Quick Edit?
I have added a "waiting time" field to the orders in Drupal Commerce, so that each order has a waiting time.

I would like for the field to be available using the Quick Edit options of Commerce Backoffice. How to do it?

# Answer
i am not sure if this might help, but recently i've written a custom hook to enable stock quantity field on commerce product quick edit form.

It should theoretically be possible yes to write a similar hook on commerce order. Here's my custom module copy pasted :

```
<?php
/**
 * Implements hook_form_FORM_ID_alter().
 */
function commerce_stock_quickedit_form_commerce_backoffice_product_quick_edit_form_alter(&$form, &$form_state, &$product){
  $product = $form_state['product'];
  $product_wrapper = entity_metadata_wrapper('commerce_product', $product);
  $form['stock'] = array(
    '#type' => 'textfield',
    '#title' => t('Stock'),
    '#title_display' => 'before',
    '#default_value' => !empty($product->commerce_stock) ? $product_wrapper->commerce_stock->value() : 0,
    '#size' => 5,
  );
  $form['price']['#title_display'] = 'before';
  $form['#validate'][] = 'commerce_stock_quickedit_commerce_backoffice_product_quick_edit_form_validate';
  $form['#submit'][] = 'commerce_stock_quickedit_commerce_backoffice_product_quick_edit_form_submit';
}
/**
 * Validation callback to make sure stock is numeric.
 */
function commerce_stock_quickedit_commerce_backoffice_product_quick_edit_form_validate($form, &$form_state) {
  if (!empty($form_state['values']['stock'])) {
    if (!is_numeric($form_state['values']['stock'])) {
      form_set_error('stock', t('Please enter a numeric stock value'));
    }
  }
}
/**
 * Submit callback to update the product stock.
 */
function commerce_stock_quickedit_commerce_backoffice_product_quick_edit_form_submit($form, $form_state) {
  $product = $form_state['product'];
  if (!empty($product) && !empty($form_state['values']['stock'])) {
    $product_wrapper = entity_metadata_wrapper('commerce_product', $product);
    $product_wrapper->commerce_stock->set($form_state['values']['stock']);
    commerce_product_save($product);
  }
}

```
> 1 votes

---
Tags: views, commerce
---


# Question
Title: A General Strategy for Images with Captions in Content
This is a 'general direction' topic. I'm looking for some strategy and philosophical guidance, before marching over to the module development forum at Drupal.org.

I'm new to Drupal, and am very impressed by the architecture - the flexibility and power of the framework as a whole.

However, like many 'newcomers', I've quickly discovered that there's some planning and investment required in creating a new Drupal site (which is apparently the subject of many debates that are shaping the future of Drupal itself - http://www.lullabot.com/articles/understanding-8-where-drupal-and-where-...).

At the moment, for me at least, there's only one piece missing, and that's a non-Javascript method for allowing content creators (site owners) to insert one or more images with captions into the content of a node (like a news article, or blog post).

I also understand that in terms of semantic purity, it would be nice if the content of a node was clean and tidy, without a lot of additional markup - and so I'm looking for an eloquent way to solve the image/caption problem.

I poured over several other solutions - although as a new poster here I can only share two links in this post :(

and...

http://purewebmedia.biz/articles/2013-01-10/how-insert-and-float-inline-... - which is a great write-up describing the difference between using an Image field (with custom locations/folders for image stores), vs. Media Manager - although it doesn't address the caption problem.

I've also read a little about the new Entity model in DR7 - and I'm beginning to wonder of File Entities, with some kind of token replacement might be the right approach? (although I confess I don't entirely understand yet if a token can be placed into the free text/content field of a node - like the main text of an article or news story).

What I'm looking for is a method that will allow a user to insert one or more images into the content area of any content type (article, basic page, whatever - assuming the field/function has been defined for the content type), and that when they upload and insert that image, they are allowed to enter additional information like a title, copyright, caption, date etc.

They should be able to 'see' the image in their WYSIWYG editor (although maybe not the metadata), and then when the node is published, the required metadata is retrieved and inserted via a hook, pre-processor - for example, by surrounding the image in a div, and placing the required metadata above or below the image (perhaps in additional divs or elements) - requiring only CSS to style the title, caption, etc. as required.

I also really like Image Styles feature of Drupal and so I'm wondering how this could all be brought together.

To be clear, this is not a gallery module. The requirement here is to be able to insert one or more images with captions (and possibly other metadata fields) into a the content/body or a story, news article, blog post etc.; needing only CSS to style the result (format caption, float left or right etc.)

Thoughts?

Any pointers on how to start with this?

# Answer
> 2 votes
Your desire for a "non-Javascript" solution is in conflict with your desire to allow users to "see" the image in their WYSIWYG editor, as you need to run Javascript for those to work. So, you'll have to either drop the "non-Javascript" requirement, or be satisfied with image fields that may appear above or below the main body. \[Note 1: Images "above" the node body can be set to float left or float right, and thereby appear to be inside the text. Note 2: If by "non-Javascript" you mean non-JS at render time, then no problem.\]

Whichever way you go -- be it images embedded in a WYSIWYG editor, or images as file fields, you'll probably want to use the media module, as it can support either method.

There is a lot of information available on the media module, which is becoming "the way" to do images in Drupal. Many additional contrib modules are compatible with media. You'll want to take a look at the following two configuration guides:

Media 2.0 Quickstart

Configuring embedded images with media and wysiwyg modules

Here is the point where I remember to take a step back and point out that my experience is with media 2.0-unstable7. Depending on how comfortable you are with making adjustments to php code, you might prefer to use the stable release, which is currently 7.x-1.2. I didn't have too much trouble with 2.0-unstable7, except for the fact that it does not support editing of arbitrary image metadata on WYSIWYG images, so I am using only image file fields at the moment. If the only metadata you wish to attach to your images is a caption, then I expect that 7.x-1.2 should work for you, although I have not tried it myself.

In any event, I would recommend using the provided "title" field, and render that as a caption. Doing that is as easy as visiting admin/structure/file-types and clicking on "manage display" for the image file type. This page works just like the "manage display" page in cck; you can just drag the "title" field up so that it is under the "file" field, and use css to style it as a caption. You'll probably also want to download and enable the entity\_view\_mode module, which will allow you to define additional view modes for your image files.

As I said, I'm not embedding images in WYSIWYG editors at the moment, but the article you quoted gives good advice on that. If you're using the media module, you should still be able to format the title field as a caption regardless of whether you're using file fields or WYSIWYG.

# Answer
> 1 votes
Solved - using the new File Entity module, the new Media module (2.x) and the new Entity view modes module (http://drupal.org/project/entity\_view\_mode) - along with the basic instructions here... http://drupal.org/node/1699054 \- it's possible to create custom Entity view modes for left, center, or right aligned images, along with matching CSS classes, and image styles.

Here's the result.

# Answer
> 0 votes
I too do not understand why most, if not all image caption modules require JavaScript. Scripting is fine for dynamic content. Here it just adds unnecessary complexity.

Drupal natively offer a filtering feature allowing to edit the HTML code content on-the-fly on server-side before it is delivered to the client. IMO this is the most natural place to turn image's title into caption, and it is even very easy to do!

1. Create a module in which you will define two functions as the ones shown below:

```
/**
 * Implements hook_filter_info().
 * Add a new text filter implementing images captions.
 */
function my_module_filter_info() {
  $filters = array();
  $filters['image_caption'] = array(
    'title' => t('Display image title as caption'),
    'process callback' => 'filter_image_caption_callback',
  );
  return $filters;
}

/**
 * Callback for my_module_filter_info().
 * Takes a content text as input, edit all <IMG> tags and reuse the  `title'
 * parameter as caption.
 */
function filter_image_caption_callback($text, $filter, $format, $langcode, $cache, $cache_id) {
  $text = preg_replace(
    '%<img ([^>]*(?:(style="[^"]+")[^>]*)?title="([^"]+)"[^>]*(?:(style="[^"]+")[^>]*)?)/?>(?:</img>)?%iU',
    '<div class="image" $2$4><img $1/><div class="caption">$3</div></div>',
    $text
  );
  return $text;
}

```

These functions will add a new text filter labeled "*Display image title as caption.*" which will take the content images' `title` attribute to generate the captions.

The image and caption become encapsulated in CSS-styleable `<DIV>` containers, the outer-most inheriting the original `<IMG>` tag style (`float` attribute, etc.).

You may want to personalize the produced `<DIV>` tag classes, or maybe replace them with the HTML5 `<FIGURE>` and `<FIGCAPTION>` tags.
2. Refresh your Drupal cache to take these new function into account,
3. Go in ***Configuration \> Texts formats*** to edit your text format,
4. Add the newly created text filter:
    * *After* any other filter which could generate `<IMG>` tags needing captions,
    * *Before* any security and file structure checking filter.

---
Tags: 7, media, nodes
---


# Question
Title: How do I make a carousel with an highlighted node and thumbnails to the left and right?
I'd like to make a carousel exactly like the picture below: six thumbnail nodes on the left, one highlighted node in the middle and six thumbnail nodes on the right; when users click on the controls, the next set of nodes shows up.

>

I guess it would be possible to achieve this with a view and using a module like the OwlCarousel module. So far I couldn't make it work.

How can I use a view and the *OwlCarousel* module to make a carousel?

# Answer
> 1 votes
If you are looking for an easy to implement approach try this:

* Make a Content-type called: "Slideshow"

Make three different `Entity Reference` field referencing your desired nodes (your another content-type that you want to show)

call your entity reference fields like: "Right", "Middle" & "Left".

* Create a node of content-type "Slideshow" Using display suite module and view format of `Rendered Entity` define your image sizes and extra fields you want for your "Middle" node.
* Create a views of Slideshow nodes using OwlCarousel or any other carousel module you want.
* Do a little bit of CSS magic and you must be good to go!

# Answer
> 2 votes
You could do this with the jCarousel module:

1. Build your view to show the required nodes in the order you wish them to show.
2. Enable jCarousel view format
3. Create a style output template using a file name from OTHER -\> Theme: Information -\> Style output
4. Copy the code from the style template offered by the jCarousel module
5. Change the template code to output 7 rows at a time with the necessary wrappers and classes to make it look like your design
6. Make sure the `.jcarousel` and `.jcarousel-clip` divs are outside each group of 7 rows. \[edit: it appears this happens outside of the template file, so not usually something you'll need to worry about\]

---

Here's something to get you started with the style template file:

```
<?php

/**
 * @file jcarousel-view.tpl.php
 * View template to display a list as a carousel.
 */
$count = 0;
$rowcount = count($rows);
?>
<ul class="<?php print $jcarousel_classes; ?>">
  <?php while ($count < $rowcount): ?>
    <li class="<?php print $row_classes[$id]; ?>" style="display: none;">
      <?php // Print your seven rows here ?>

      ...

    </li>
    <?php // Advance the counter ?>
    <?php $count += 7; ?>
    <?php // Depending on how you print your rows you may wish to slice 7 items off the $rows array ?>
    <?php $rows = arracy_slice($rows, 7); ?>
  <?php endwhile; ?>
</ul>

```

Note that if you're referencing each row like `$row[id]` you may need to do a check before printing each one unless you're certain there will be a multiple of 7 rows in your view.

# Answer
> 0 votes
Simply You could build the view to get content needed then from

> OTHER -\> Theme: Information -\> Style

make the tpl file with the name suggested

In that file you could take the source of the markup that you need to build in the image you provided and start make the content be dynamic using that piece of

```
foreach ($view->style_plugin->rendered_fields as $delta => $item):
 //Do stuff here, you could control items display and order to meet your case and add the html
endforeach

```

After building the same html markup needed for that layout, Start add your **js** and **css** files needed by that plugin

by that way you could have full control over the items being rendered and markup out of views display settings and without needing extra modules

---
Tags: views, theming
---


title: Move title display below other fields

text:
# Question
Title: Move title display below other fields
When viewing a node, I'd like the Title to display below one of the other fields in the Content Type, but it's not available to arrange in the Manage Display tab.

With all of the flexibility and power that Drupal gives me, do I really need to create a custom template for each of my content types? :(

Any help is appreciated!

# Answer
> 4 votes
You can do this in Panels.

First, remove the print title statement from page.tpl.php in your theme.

Usually it looks something like this:

> ```
>       <?php if ($title): ?>
>             <h1 id="page-title"><?php print $title; ?></h1>
>           <?php endif; ?>
>
> ```

This will prevent Drupal from printing the title automatically.

Then open up Panels and activate (if you haven't already) the node override template and the user override template as well as any other places where you need to display the title.

Then add the title where you want it to appear from within the Panels interface (*Add content* -\> *Page elements* -\> *Page title*).

# Answer
> 4 votes
I agree the **Title** module is a great solution for many use cases. The **Title** module converts node titles to the field API in order to make nodes fully translatable. This has the effect of adding the title field to the manage display UI and they can be managed like any other field. In many cases this is much better than using template overrides or installing a much heavier module such as **Display suite** or **Panels** just to manage node titles. The **Title** module can be configured to convert the title on all future bundles and existing title fields have a convert link next to them on their manage fields UI.

# Answer
> 2 votes
Page title is not displayed as one of the available elements on the `Manage Display` page.

To do that, you have to edit the `node.tpl.php` file. Here's a short overview of what you need to do:

* Copy the default `node.tpl.php` file from `modules/node/node.tpl.php` to your theme directory.
* Rename the file in your theme to `node--YOUR-CONTENT-TYPE.tpl.php`. This way changes you make in this file will be only reflected for this particular content type.
* Open the `node--YOUR-CONTENT-TYPE.tpl.php` file and reorder the way elements are printed for your node.

Here are some guidelines for `node--YOUR-CONTENT-TYPE.tpl.php`:

* To render a field use: `<?php print render($content['field_your_field']); ?>`
* Make sure you always have the `<?php print <?php print render($content); ?> ?>` in your `node.tpl.php` file, as well as the `<?php print render($title_prefix); ?>` and `<?php print render($title_suffix); ?>`. They render additional output by other modules, e.g. Contextual links, etc.

To read more about this check the docs page for node.tpl.php and theming nodes by content type.

# Answer
> 1 votes
Instead of using a module for this simple request, you can also just adapt your node.tpl template file, and print the field required before the title.

# Answer
> 0 votes
```
admin/structure/types/manage/article/display

```

Please follow image to restructure, from manage display you can set the order of filed according to your requirement: (Please drag and drop fields to reorder )

Thanks!

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


# Question
Title: Combining several attributes with string join
My XML is structured like this:

```
<Export>
  <ProductType Type="Book">
    <Products>
      <Product Title="The Pragmatic Programmer">
        <Chapters>
          <Chapter Title="1 A Pragmatic Philosophy">
          <Chapter Title="2 A Pragmatic Approach">
          <Chapter Title="3 The Basic Tools">
          ...
        </Chapters>
      </Product>
    </Products>
  </ProductType>
</Export>

```

I am trying to map an XPath Expression to a multivalue field that contains a list of all the chapters.

I think the context expression is causing the xpath function for the mapped field to return an empty value.

I've tried the following and both do not work:

Context: `/Export/ProductType[@Type='Book']/Products/Product`

Target Field: `fn:string-join(Chapters/Chapter/@Title, ', ')`

This just outputs a comma. Is there a way to combine all of the Chapter titles into one string like "1 A Pragmatic Philosophy, 2 A Pragmatic Approach, 3 The Basic Tools"?

**UPDATE**

I'm not sure that you can use expressions in string functions, but this stackoverflow post lead me to believe that it is possible.

# Answer
The Feeds Tamper module has an implode plugin that makes this work.

> Feeds Tamper provides a small plugin architecture for Feeds to modify data before it gets saved. Several plugins are available by default and are described in the examples section below. Additional plugins can be added in separate modules or through the issue queue.
>
> * Replace every instance of 'dog' with 'cat'
> * Filter items based on keywords or vocabularies
> * Make every letter uppercase, lowercase, or capitalise every first letter
> * Break a comma separated list of words into Taxonomy terms or a multivalued text field
> * Combine separate 'first name' and 'last name' fields into one 'name' field
> * Convert urls from relative to absolute
> 1 votes

# Answer
If you're using Feeds and FeedsXPathParserXML, `fn:string-join` is not supported.

However you can use other functions, for example this worked for me:

```
concat(field1, ".", field2)

```

when having the right context. If you're trying to implode and explode a string, use Tamper Plugins.

Alternatively use Feeds extensible parsers module instead.
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: Selling per-node access without creating two entities
I want to create a Pay-per-view site under Drupal.

I followed the instructions of Commerce guys, which combines the use of Drupal Commerce and Content access.

But this solution means creating two entities: a product display + the paying article. It raises several problems: two nodes with the same name, two nodes as we can comment...

I would thus want only one node, with a visible teaser before purchase, then all the text after purchase.

My question : how to selling per-node access without creating two entities ?

# Answer
It really depends on how you want to display the content to your customers. For example, you could show a teaser of the content page via Views. Access to the full content page could be contingent on node access implemented via the Content Access module. You then just have to figure out how to display to the customer which articles they have full access to - for example, a "Purchased articles" View that shows all fully accessible articles using a node access filter.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Create a view of nodes based on user record
In Drupal 7, I have a Content Type, let's call it **fruit**. I have added an entity reference field to fruit to the user record. I want to create a view that lists all the fruit, but puts a mark next to those that have been ticked on their user record.

I am unable to work out how to do this, principally because I can't see how to add a Relationship to the user record.

Any help would be appreciated.

# Answer
> 0 votes
For entity reference fields there are 2 types of relationships added to views: a *Referenced entity* and a *Referencing entity*.

* *Referenced entity* is used for a reference *from the base table* (e.g. A user view that references a fruit node).
* *Referencing entity* is used for a reference *to the base table* (e.g. a fruit node view that references a user)

In your case, it's *Referencing entity* that you want.

Create a node view and a *Entity Reference: Referencing entity* relationship (the description should read *A bridge to the User entity that is referencing Content via field\_FRUIT\_NODE\_REF*) that refers to your fruit node reference.

That should handle the data/reference part. What remains is aggregation/filtering (e.g. there will duplicates if fruit node references aren't distinct for each user) and display (e.g. how to display marking a fruit node referencing a current user).

Depending on your needs, you might need a custom field/template since there is a limit of what you can do with field basic rewriting and default user contextual filters.

---
Tags: views, entities, users
---


title: Downgrade Drush from 8-dev to 7

text:
# Question
Title: Downgrade Drush from 8-dev to 7
I installed Drush with `composer global require drush/drush:dev-master` but it has some problems. I am using Xampp and Windows 8.

How can I downgrade Drush from 8-dev to 7?

# Answer
You can first uninstall (remove) the version you don't want anymore (8-dev) and then try install the version you want.

So, first run `drush status`; then look for `drush script`. You can see the directory Drush was installed on your computer; try remove it manually or with `rmdir <path>`.

And according to Drush Documentation page, install the version you want (i.e. 7).

```
  composer global require drush/drush:7.*

```
> 5 votes

# Answer
```
# Remove the current version of drush.
composer global remove drush/drush
# Install drush version 7.
composer global require drush/drush:7.*

```
> 5 votes

# Answer
You can install drush as git clone, and either checkout master or a tag to accomplish this. Just remember to do a `composer install` if you checkout a version that uses composer (pretty sure all of the 7.x tags do, not sure about the 6.x tags), or add this as a post-checkout hook.
> 1 votes

---
Tags: drush
---


# Question
Title: Views: Suggest nodes based on user behaviour and history
I tried to search here and there to see if there's an easy solution for what I'm trying to do but to no avail!

I want to show a list of nodes using views based on user's behavior specifically based on previously viewed nodes and Likes on Rate module, so it will be something like "suggestions based on user".

# Answer
> 3 votes
What you're looking for is known as a Content Recommendation Engine (CRE). There are a few modules out there are provide elements of CRE functionality. See this g.d.o. post for a pretty comprehensive listing, but nothing is a popular, easy, & comprehensive CRE solution.

The most popular is Similar By Terms, but it's a pretty basic and doesn't take user viewing history into account. The most comprehensive are the various Recommender modules based on the Recommender API, one of which, Browsing History Recommender, is based off of viewing history, however this isn't an easy solution; it requires a few dependendencies.

Note that CRE's are complex; think of the man-hours and money NetFlix has spent for its proprietary CRE. You're probably not going to find an easy/comprehensive solution from a install-and-ready-to-go Drupal module. If none of the above can cover what you need, you're best going to a 3rd party that provides easy integration into any website (e.g. LinkWithin).

---
Tags: views, users, cookies
---


# Question
Title: Will upgrading PHP version affect my current site that running Drupal 6?
I am going to test Drupal 8 RC, unfortunately my PHP version is too old.

It's asking for upgrade the version higher than PHP 5.5.9.

If I upgrade it to PHP 5.5.9 or latest version PHP 5.6.14, ***will it affect my current site that running Drupal 6?***

```
Your PHP installation is too old. Drupal requires at least PHP 5.5.9. See the system requirements page for more information.

```

# Answer
> 4 votes
As reported in System requirements, Drupal 6 requires PHP 5.x, since support for PHP 4.x has been dropped by PHP maintainers; it is recommended PHP 5.2.5 or higher, but PHP 5.3.x and higher may produce errors or unexpected behavior.

So, yes, PHP 5.6.14 is going to affect your Drupal site, especially if you installed third-party modules or themes.

Bear in mind that Drupal 6 core code will not be changed, after Drupal 8 will get its first official and stable release. If they don't fix Drupal 6 code before, it will not get fixed. Once Drupal 6 code is not fixed, it is also probable third-party modules stop to get updates too.

# Answer
> 0 votes
Take a look to the specific version notes on PHP requirements to understand the compatibility:

https://www.drupal.org/requirements/php#all

Although PHP 5.3-5.5 are supported by Drupal 6, some contributed modules are not compatible with PHP 5.3 and higher many will throw E\_STRICT errors and have other errors. Your Drupal 6 in 5.5 core will work ok. However, some contrib modules and themes may have problems.

You can configure your environment to have multiple php versions if you are interested. This tutorial helped me a lot to configure my environment in my Mac http://getgrav.org/blog/mac-os-x-apache-setup-multiple-php-versions

---
Tags: 6
---


# Question
Title: How do I debug a the output errors on SimpleTest when I'm not sure where in the script the error occurred?
I'm trying to build a simple test. I'm having trouble submitting webforms. With help form a previous question I've cobbled together these functions within the larger class.

They completely work in the following test.php script run on the command line via `drush scr test.php`

```
$data = array(
  1 => array('1'),
  2 => array('2'),
  3 => array('3')
);

$T = new MyTest();
$T->insertMockData($data);

```

However, when I try to run as \`drush test-run MyTest things fail completely.

Source snippet:

```
  function setUp($modules = array()) {
        $modules[] = 'webform';
        parent::setUp($modules);

        $this->insertMockData($this->randomData());
    }
function insertMockData($data = array(), $submitted_datetime = REQUEST_TIME) {

        $node_web = node_load(1);
        $submission = (object) array(
        'nid' => $node_web->nid,
        //'uid' => $user->uid,
        'submitted' => $submitted_datetime,
        'remote_addr' => ip_address(),
        'is_draft' => FALSE,
        'data' => $data,
            'serial' => $this->serial_value++,
        );
        module_load_include('inc', 'webform', 'includes/webform.submissions');
        webform_submission_insert($node_web, $submission);
            //webform_submission_send_mail($node_web, $submission);
          }

    function randomData() {
    $random_line_of_text  = array(
      "Mary had a little lamb",
      "a little lamb",
      "With fleece as white as snow",
      "And everywhere that Mary went",
      "That lamb was sure to go");

    return array(
      1 => array($random_line_of_text[array_rand($random_line_of_text)]),
      2 => array($random_line_of_text[array_rand($random_line_of_text)]),
      3 => array($random_line_of_text[array_rand($random_line_of_text)]),
    );
}

```

Errors on console

```
Test MyTest->insertMockData() failed: Trying to get property of non-object                       [error] Test webform_webform_submission_presave() failed: Trying to get property of non-object             [error]
Test webform_webform_submission_presave() failed: Invalid argument supplied for foreach()          [error] Test webform_submission_insert() failed: Trying to get property of non-object                      [error]
Test webform_submission_insert() failed: Trying to get property of non-object                      [error] Test webform_submission_insert() failed: Trying to get property of non-object                      [error]
Test webform_submission_insert() failed: Trying to get property of non-object                      [error] Test webform_submission_send_mail() failed: Trying to get property of non-object                   [error]
Test webform_submission_send_mail() failed: Invalid argument supplied for foreach()                [error] Test MyTest->insertMockData() failed: Trying to get property of non-object                       [error]

```

**Question: How do I debug a the output of SimpleTest when I'm not sure where in the script the error occurred?**

# Answer
> 1 votes
Good for you for writing tests!

The best friend I've had while doing Drupal development work is a little gal called xdebug with an IDE like PHPStorm. Xdebug allows you to set breakpoints, much like you can for JS in Chrome dev tools, and stop the PHP script at that moment. You get access to all the variables and a stack trace among other things.

I'm no expert on xdebug or debugging, but getting PHPStorm and installing xdebug has saved me so much time and pain, I wouldn't go a day more without it.

Once you have xdebug handy, start setting breakpoints early on where you would think the issue is. For your example, I can tell `$this->insertMockData($this->randomData());` was called since it is in the error messages. Set a breakpoint before that and you can see what $this is and why that object method isn't available.

If you don't want to pay for PHPStorm (which is so worth it!), Netbeans is free.

A simple `var_dump($this); die();` should also print the $this variable to the screen for you to see what it is at that point, but you might as well upgrade to an IDE and xdebug. You're gonna need it for Drupal 8 anyway :)

# Answer
> 2 votes
Part of why your test is failing is pretty easy to see. Your code is relying on node 1 existing:

```
function insertMockData($data = array(), $submitted_datetime = REQUEST_TIME) {

        $node_web = node_load(1);
        $submission = (object) array(
        'nid' => $node_web->nid,
        //'uid' => $user->uid,
        'submitted' => $submitted_datetime,
        'remote_addr' => ip_address(),
        'is_draft' => FALSE,
        'data' => $data,
            'serial' => $this->serial_value++,
        );
  //lots of stuff omitted here...
}

```

The code assumes that there's a node in your DB for you to load. Sadly, no :-)

When SimpleTest runs, it creates a whole empty DB that's just installed. If you need a node, you have to create one, like this:

```
$settings = [
  'title' => 'My Test Content',
  'body'  => 'and what a body it is',
  'status' => 1,
  'type' => 'article',
];

$test_node = $this->drupalCreateNode($settings);
$this->assertNotNull($test_node, "Make sure our settings work");

```

See core/modules/simpletest/src/WebTestBase.php for some of the methods you can use to create nodes and users and other useful test data. But in general: your test or the test's superclasses need to create everything you need either in setUp() or in your test itself.

---
Tags: testing
---


# Question
Title: request new password link does not work if not logged in
When anonymous user comes to the site, the login block offers a link to "Request new password". This returns the user to the home page with no action happening. If a user is logged in, using the same link brings one to the reset password by email link.

What I want is a form taking username and returning email address with a link to the one time password change.

# Answer
Drupal 7's core handling of password reset can seem a bit cumbersome, since it uses a one-time link to a one-time login reset page which can be confusing to users. I recommend using the Simple Password Reset module which streamlines the process and makes it very easy for users. It works great right out of the box.
> 0 votes

---
Tags: users
---


# Question
Title: How to allow the setting of the Views Exposed Filters one at a time, instead of showing all available exposed filters at once
I have a view with a ton of exposed filters. Placing all in one page (even in a collapsible fieldset) is overwhelming for the users. Is there a module that allows a users to add a filter one-by-one?

Hopefully the screenshot of a third party application helps to explain

# Answer
I believe the views dependent filters module will do it for you.

I haven't used it but from what I can see it works just like dependent fields.
> 0 votes

---
Tags: views
---


# Question
Title: How to create a filter condition autocomplete for entity reference field or normal?
I am trying to create a filter condition for entity reference field in views, i tried by using rendered entity option it is showing dropdown for filter condition. **I need autocomplete or it should be without dropdown and autocomplete** (plain filter field).

It should apply after giving full value in filtercondition?

Any suggestions..

```
/* Filter criterion: Content: Cage ID_VBC (field_cage_id_vbc) */
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['id'] = 'field_cage_id_vbc_target_id';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['table'] = 'field_data_field_cage_id_vbc';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['field'] = 'field_cage_id_vbc_target_id';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['group'] = 1;
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['expose']['operator_id'] = 'field_cage_id_vbc_target_id_op';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['expose']['label'] = 'Cage ID';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['expose']['operator'] = 'field_cage_id_vbc_target_id_op';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['expose']['identifier'] = 'field_cage_id_vbc_target_id';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['expose']['remember_roles'] = array(

```

# Answer
you can change an exposed filter to **Select List** or **Text Box** using the following code..

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
        $options = array('your options');
        $form['your field name']['#type'] ='select'; //Use TEXTBOX for text field.
        $form['your field name']['#size'] = null;
        $form['your field name']['#default_value'] = '';
        $form['your field name']['#options'] = $options; //not needed for textbox
    }
  }
}

```

Another option is use **Autocomplete Deluxe for References** Module.

Hope this will help you..
> 1 votes

---
Tags: views
---