# Question
Title: Send to 403 page if all Selection Rules aren't met for all Variants
I have a couple Variants set up for my node type with Selection Rules via Page Manager. If for some reason none of the rules are met for all the variants, it renders the node using the default node system instead of sending to a 404. How can I send the user to a 403 page instead?

# Answer
> 0 votes
I took care of this using hook\_node\_view(). This will only run if it is using the node system.

```
/**
 * Implements hook_node_view().
 */
function mymodule_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'collection' && $view_mode == 'full') {
    drupal_access_denied();
    drupal_exit();
  }
}

```

---
Tags: panels, chaos-tool-suite
---


# Question
Title: Is this the correct way to add a page with hook_menu()?
I'm trying to create a page through `hook_menu()` so I can add my custom block with context instead.

```
function my_module_menu() {
    $items['my_page'] = array(
        'title' => 'my_page',
        'description' => 'my_page',
        'page callback' => 'my_function',
        'access callback' => true,
    );
    $items['my_page2'] = array(
        'title' => 'my_page2',
        'description' => 'my_page2',
        'page callback' => 'my_function',
        'access callback' => true,
    );
    return $items;
}

function my_function() {
    return '';
}

```

Is it the right way to do it? I have some bug from time to time, like the block goes missing on those pages. Could it be related to that?

# Answer
> 0 votes
No, the menu items are fine. The problem seems with your block display configuration settings.

There is no permission with these menu items; give some loosely coupled permission (such as *access content*) to these callbacks. Function names should be prefixed with the module name to avoid clashes with other modules.

```
function my_module_menu() {
  $items['my_page'] = array(
    'title' => 'my_page',
    'description' => 'my_page',
    'page callback' => 'my_module_my_function',
    'access arguments' => 'access content',
  );

  $items['my_page2'] = array(
    'title' => 'my_page2',
    'description' => 'my_page2',
    'page callback' => 'my_module_my_function',
    'access arguments' => 'access content',
  );

  return $items;
}

function my_module_my_function() {
  return '';
}

```

# Answer
> 0 votes
If you want create `menu item` with `hook_menu` add

```
    'menu_name' => 'yourmenu-machinename', // This is the changed line.
    'type' => MENU_NORMAL_ITEM,

```

And as example

```
 $items['my_page'] = array(
    'title' => 'my_page',
    'description' => 'my_page',
    'page callback' => 'my_module_my_function',
    'access arguments' => 'access content',
     'menu_name' => 'yourmenu-machinename', // This is the changed line.
    'type' => MENU_NORMAL_ITEM,

);

```

---
Tags: 7, routes
---


# Question
Title: What is the difference between an entity in Drupal 7 and a content entity in Drupal 8?
The Drupal Examples "entity" project was really helpful for me when I was learning the entity API in Drupal 7. I have seen no explanation though for why this doesn't exist in Drupal 8 or why it was renamed, etc.

# Answer
I'm not sure what you are asking.

Example modules are named after what they're an example of, it's not for them to pick a name, really.

Drupal 8 has Content Entities, which evolved from the field structure of Drupal 7's entities and Config Entities, which are based on concepts from ctools exportables, entity.module's exportable entities and various other things.

Both share the same base class and a few comments and concepts but beyond that, they're quite different. Both are typed classes, Content entities have a strict although somewhat complex structure but are very extensible within that structure (That is, Entity -\> Field Item List \> Field Item \> Property). They can have revisions and translations which are conceptually similar to field translations in 7.x but have a different API.

While there isn't *that* much documentation yet, https://www.drupal.org/developing/api/entity has some, there are also plenty of presentions from DrupalCons and other events about the concepts, API's and so on, including a recent one that I co-presented: https://2015.drupalcamp.at/session/entities-drupal-8.
> 3 votes

# Answer
Entities were a key new feature and concept in Drupal 7, abstracting the ability to add fields to other types of content than just nodes, such as users and taxonomy terms. However, the Drupal 7 core API was severely limited, and required use of modules like the Entity API module to further flesh out basic functionality, such as saving and deleting.

In Drupal 8, the Entity API has been completely re-hauled to not only fill the gaps in functionality from Drupal 7, but also to greatly improve developer experience. All entities are now classed objects that implement a standard EntityInterface (no more guessing which of the 100 entity hooks you're required to implement!), with baked-in knowledge about the active language. Compare and contrast:

```
<?php
# Drupal 7 code.
$node->title $node->body[$langcode][0]['value']

# Drupal 8 code.
$node->get('title')->value
$node->get('body')->value
 ?>

```

Nearly anything you can create more than one of has been converted to an entity, bringing much greater consistency to Drupal development overall. There are two kinds: Config entities and Content entities. What's the difference?

**Content Entities**

* Can customize fields
* Stored in database tables (by default)
* Mostly created on front-end

*Examples*

* Nodes
* Custom Blocks
* Users Comments
* Taxonomy Terms
* Menu Links Aggregator
* Feeds/Items

**Config Entities**

* Can deploy to different environments
* Stored in configuration system
* Mostly created on back-end

*Examples*

* Content Types
* Custom Block
* Types User Roles
* Views Taxonomy
* Vocabularies
* Menus Image Styles
> 3 votes

---
Tags: entities, 8
---


# Question
Title: Use dropdown in views exposed filter on text fields with node->title?
I followed this link to transform my exposed filter from textbox to dropdown list.

Use dropdown in views exposed filter on text fields with entity not node?

I make it work with a custom textfield.

I have problem to use the module with node title.

My code till now is:

```
<?php

function views_dropdown_form_views_exposed_form_alter(&$form, &$form_state) {
global $user;

// Only alter forms with the necessary field
if (isset($form['title'])) {

// Build a query to get all node ids having the specified field
$query = new EntityFieldQuery();

$results = $query->entityCondition('entity_type', 'node')
                  ->entityCondition('bundle', 'rapporto_di_lavoro')
                  ->propertyCondition('uid', $user->uid)
                  ->propertyCondition('title', 'NULL', '!=')
                  ->execute();

// Attach the field values to the nodes
$ids = array_keys($results['node']);
print_r($ids);
print('<br>');
// Add a default so the filter is optional
$options = array('' => '<select>');

// Buld the options array based on the query results, overwriting duplicate entries
$query = db_select('node', 'n')
            ->fields('n', array('title'))
            ->condition('n.nid', $ids, 'IN');
$options = $query->execute()->fetchAll();

$op = json_decode(json_encode($options), true);
print_r($op);
print('<br>');

// Attach the field values to the nodes
//$nodes = $results['node'];
//field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));
// Buld the options array based on the query results, overwriting duplicate entries
//foreach($nodes as $nid => $node) {
  //$value = $node->field_cognome_l['und'][0]['value'];
  //$options2[$value] = $value; }

//Alter the field
$form['title']['#type'] = 'select';
$form['title']['#options'] = $op;
$form['title']['#size'] = 1;
}
}

```

I feel close to solution but I miss something.

On the picture I print four arrays.

Only the 4th was working when I tested the module with a custom field,

so probably I need to transform the 3rd array into the 4th.

# Answer
I solved the problem, here the code:

```
<?php

function views_dropdown_form_views_exposed_form_alter(&$form, &$form_state) {
global $user;

// Only alter forms with the necessary field
if (isset($form['title'])) {

// Build a query to get all node ids having the specified field
$query = new EntityFieldQuery();

$results = $query->entityCondition('entity_type', 'node')
                  ->entityCondition('bundle', 'rapporto_di_lavoro')
                  ->propertyCondition('uid', $user->uid)
                  ->propertyCondition('title', 'NULL', '!=')
                  ->execute();

// Attach the field values to the nodes
$ids = array_keys($results['node']);
// Add a default so the filter is optional
$options = array('' => '<select>');

// // Buld the options array based on the query results, overwriting duplicate entries
$query = db_select('node', 'n')
            ->fields('n', array('title'))
            ->condition('n.nid', $ids, 'IN');

$results = $query->execute()->fetchAll();

foreach($results as $id => $node) {
  $value = $node->title;
  $options[$value] = $value;
}

// // Alter the field
$form['title']['#type'] = 'select';
$form['title']['#options'] = $options;
$form['title']['#size'] = 1;
}}

```

I hope could help someone :)
> 3 votes

---
Tags: views
---


# Question
Title: How to add multiple suffixes for an integer field type?
Is there a way to add multiple suffixes for an integer field type? For example, I want to input a value, and I want to be able to specify whether this is in inches or centimeters with a drop down box.

Is there a way to do this using only the field module?

# Answer
> 1 votes
There are 3 options:

1. Install the Measured Value Field module.
2. In your custom module implement `hook_form_alter` and add your dropdown there with markups.
3. Create actual dropdown and work with just markup.

# Answer
> 0 votes
Create an additional field (apart from the integer field you already have), and make it a select list with possible values "*inches*" or "*centimeters*". With that, you don't have to install any other module (only the field module will do).

Optionally, you may want to group them together using the Field collection module (but that requires an extra module of course).

---
Tags: views, entities
---


# Question
Title: Adjust viewability of content based on the value of a field for a specific user
For my website, I have a view (created using the Views module), let's call it View1, that displays content types that have field of user entity references (as in, it's a select list with all the users for the website on there).

I have a separate view (Views module), let's call it View2, that is used by non-admin users. I would like that view to be populated by content types that have been assigned to them by the admin. The admin uses the select list mentioned above to assign users to a certain user.

Is there a way to filter content types in View2 so that it only displays content that has been assigned to you from View1?

# Answer
You can just create non-admin view which display all given content types, then users can see specific content types based on their role permissions. This can be achieved by adding Nodeaccess.

For example:

* user1 has role ct1
* user2 has role ct2
* assign view permission Nodeaccess:

+ ct1 role can view ct1 type, but not ct2
    + ct2 role can view ct2 type, but not ct1
    + to extend the access using field references, try: Node access node reference,
* create a view which lists ct1 & ct2 and users will see the right content based on their roles.

You other few options to investigate:

* in your non-admin view configure relationships, so field can point to the right content type (also check: Bundle Name Reference \+ EVA)
* in your users's View, create sub-views where you can override the fields (if your Style is set to Fields),
* create multiple views for each content type and implement Viewfield, so admin can assign the view based on the its value,
* create a non-admin view with rendered entity Style, create a template, write a logic in preprocess function and assign to the template variable.
> 1 votes

---
Tags: 7, views, users
---


title: Load and Save nodes with script?

text:
# Question
Title: Load and Save nodes with script?
I have about 30,000 nodes I need to load and resave so things like autotags and url aliases get generated. Is there a quick script I can write to do this?

# Answer
> 4 votes
I recommend to resaving for smaller count of nodes, and run next script few times. Of course using batch will better UI, add itself:

```
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$from_nid = variable_get('tmp_from_nid', 0);

$sql = "SELECT n.nid
        FROM {node} n
        WHERE n.nid > :nid
        ORDER BY n.nid";
$result = db_query_range($sql, $from, 1000, $from_nid);

foreach($result as $row) {
  set_time_limit(30);

  $node = node_load($row->nid);
  node_save($node);
  $from_nid = $row->nid;
}

variable_set('tmp_from_nid', $from_nid);
drupal_set_message(t('Last processed nid - !nid', array('!nid' => $from_nid)));
?>

```

Also VBO for mass resaving nodes.

# Answer
> 3 votes
Try something like:

```
#!/user/bin/env drush
<?php
ini_set('max_execution_time', 0);
$nodes = node_load_multiple(NULL, array('type' => "my_type"));
foreach ($nodes as $nid => $node) {
  // Do some stuff here.
  node_save($node);
  drupal_is_cli() && drush_print("Re-saved node $node->nid");
}

```

It can work also as a drush script (`drush scr`).

---
Tags: 7
---


# Question
Title: Rule to redirect to registration page after adding new product to cart
Rule to redirect to registration page after adding new product to cart. I am using ubercart module for this and working with drupal 7

# Answer
Yes, the options is given by default in ubercart. Go to admin-\>store-\>configuration-\>cart Please check the attached image for more clarification.
> 0 votes

---
Tags: rules, ubercart
---


title: Using views with a custom table/schema

text:
# Question
Title: Using views with a custom table/schema
I need to set up some views that will pull some data from a custom table I created. Some views will need to pull content the regular way and from my custom table (where I may query for a particular *nid*, etc.).

How do I do this, or where is a good place to research?

# Answer
> 27 votes
Your module needs to implement hook\_views\_data().

The example given in the hook documentation is for a table defined from the following SQL.

```
CREATE TABLE example_table (
  nid INT(11) NOT NULL,
  plain_text_field VARCHAR(32,
  numeric_field INT(11),
  boolean_field INT(1),
  timestamp_field INT(8),
  PRIMARY KEY(nid)
);

```

```
function mymodule_views_data() {
  $data['example_table']['table']['group'] = t('Example table');

  $data['example_table']['table']['base'] = array(
    'field' => 'nid',
    'title' => t('Example table'),
    'help' => t('Example table contains example content and can be related to nodes.'),
    'weight' => -10,
  );

  $data['example_table']['table']['join'] = array(
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    ),
  );

  $data['example_table']['nid'] = array(
    'title' => t('Example content'),
    'help' => t('Some example content that references a node.'),
    'relationship' => array(
      'base' => 'node',
      'base field' => 'nid', // The name of the field on the joined table.
      // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
      'handler' => 'views_handler_relationship',
      'label' => t('Example node'),
    ),
  );

  $data['example_table']['plain_text_field'] = array(
    'title' => t('Plain text field'),
    'help' => t('Just a plain text field.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  $data['example_table']['numeric_field'] = array(
    'title' => t('Numeric field'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  $data['example_table']['boolean_field'] = array(
    'title' => t('Boolean field'),
    'help' => t('Just an on/off field.'),
    'field' => array(
      'handler' => 'views_handler_field_boolean',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_boolean_operator',
      'label' => t('Published'),
      'type' => 'yes-no',
      'use equal' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  $data['example_table']['timestamp_field'] = array(
    'title' => t('Timestamp field'),
    'help' => t('Just a timestamp field.'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );

  return $data;
}

```

# Answer
> 3 votes
I think it would probably be worth investigating the Data module. This is very powerful, since it allows you to declare a non-Drupal table to Drupal such that it becomes visible in Views as a data source (like "Content", "Taxonomy", etc). You can also declare joins between the non-Drupal table and Drupal entities (so for example if you can stock a nid in your non-Drupal table, then you can declare a join on the nid with any node).

There is also a submodule which allows you to declare your non-Drupal table as an entity, but so far I've not tried that.

---
Tags: 7, views
---


# Question
Title: How can I import and export Drupal Commerce Products?
I have a Drupal 7 site and installed the Drupal Commerce module. In which I have added Commerce Product with Category like:

* Software Products
* Hardware Products
* Electronics
* Others

> I would like to Export those Commerce Products from My Development Server to Production Server.

So, for that we have any modules available in `Drupal.org` so, I can export the `Commerce Products` and Import to my server.

I found the Node\_Export module, but it only applies to exporting the `nodes`. It does not apply to `Commerce Products`.

Anyone has an idea how I can Import/Export the Commerce Module Products? I think it is general problem who are using the Commerce Module of Product (but not sure).

# Answer
> 2 votes
You can look at the Commerce Feeds module in Drupal

You can use this Views Data Export module to Export in CSV or Excel Format. Further read more details on that module for installation and configuration.

You can also watch View Tutorial

# Answer
> 2 votes
Commerce Feeds multitype

> Commerce Feeds multitype provides an additional Feeds processor that can create different types of products in one import. It provides mapping targets for the product type and any fields attached to any product type. If you're updating an existing product, any product type data in the source will be ignored.

# Answer
> 1 votes
There is a great explanation here about exporting from Views both the Products and the Product Displays and then importing using Feeds and associated modules.

So to export those products, we first create a view containing the products and then export this view via Views data export into CSV file.

1. Install views\_data\_export and dependent modules

```
 drush en views_data_export image_url_formatter

```
2. Create a view with products you like to export.
3. Configure View for export (Data export).
4. Generate the file via drush command, e.g.

```
 drush views-data-export --format=csv VIEW-NAME VIEW-DISPLAY-NAME exports/product-exports/theme_export_Jan11_2014.csv --quote-values --strict=0 --header-row

```

To import:

1. Install commerce\_feeds module and its dependent modules, e.g.

```
 drush en feeds feeds_ui commerce_feeds

```
2. Create New Feed Importer.
3. Run import.

> Go to `/import` URL, use the Product Importer and import your products.

Similar goes for Product Displays.

See also:

# Answer
> 1 votes
Another option that might work to **export any data from any Drupal database table** is to use the export capabilities of the Forena module (it comes with quite some community documentation).

*About Forena*: it is built of the idea of using SQL to get data out of a database (which can be the Drupal database or an external one such as My SQL, Oracle, MS SQL, ...) and use XHTML and CSS to format it into web reports. Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.

# Exporting data

Any report can be exported (saved) in various file formats, such as CSV, XLS, PDF, DOC, ... To do so, just add an extention to the report (output) URL that corresponds to the format you want (like `.csv` for CSV format). That contains the equivalent of that report (in the requested format). As a sample, consider the sample report located at `/reports/sample.states` (in your own site, one of the samples shipped with Forena). Change the URL to `/reports/sample.states.csv` (= just add `.csv` to it) to get the same report in `.csv` format. If you'd add such `.csv` to the URL of the Simple Table of States in the demo site, the result is like so ...

Same technique applies for other supported extensions (export formats), such as adding `.html`, `.xls` (MS Excell), `.pdf` or `.doc` (MS Word).

By the way, all *data blocks* are accessible directly via their url also, provided you have permission to access that block. Here are a few samples of that, for the sample report located at `/reports/sample.states`:

For short, to answer this specific answer I'd write the various (custom) SQLs I need, format it as reports that fit my needs, and then just save it as a CSV (Or XML? Or JSON?).

# Importing data

Using the Forena integration with the Feeds module it is possible to import data blocks.

For a tutorial about the available features check out the video about How to import data and reports based on data as Drupal nodes.

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

# Answer
> 0 votes
The best way to export/import products is features. You will need to use uuid, uuid\_features and commerce\_uuid modules to archive this.

# Answer
> 0 votes
Try the latest UUID Features and Commerce UUID modules which allows you to export the Commerce products (see: `uuid_commerce_product.features.inc`).

Image source: #1982738 at DO

---
Tags: 7, commerce, importing-exporting
---


# Question
Title: How to redirect to referenced entity form with Rules
I use drupal commerce. I have several entityform type. Each product has entity reference to one of these forms. How to page redirect to referenced form url when a product added to cart.

Thanks

# Answer
> 1 votes
You want to use Rules for this. It should already be installed since Drupal Commerce requires it.

Create a new rule by going to Admin \> Config \> Workflow \> Rules, and click Add rule.

A rule consists of 3 parts.

## The event, the action that triggers the rule.

The event that initiates the rule would be `After adding a product to the cart`.

## The conditions, the checks to make sure the rule applies.

Use this to find your reference field;

Add a rule `entity had field` and check if the `commerce_line_item` (I suppose you get that by default) has a field `commerce_product`. Then add a second check to see if `commerce_line_item:commerce_product` has a field `entity_reference`.

Depending on where you created the field you might require several layers.

## The actions, what to do if the rule is valid.

You want to use the `Page redirect` action in the `system` group. Make sure to click the `data selector` button, then you can search the redirect path. It suppose should look something like `commerce_line_item:commerce_product:field_reference:url`.

---
Tags: commerce, rules, entities
---


# Question
Title: After "?" redirect, the url is cut, why?
I am using the Anonymous Redirect module to redirect `example.com` to `example.com/login`.

But when I refer a link like `example.com/525?some=node/227` and log in, the url will be cut to `example.com/525`

I don't know why the url is cut after "`?`" or "`&`".

Any solutions for this one?

# Answer
Even though I haven't ever used the Anonymous Redirect module, I wouldn't be surprised if your "issue" is caused by the fact that this module does not support what you're trying to do.

However, as a possible alternative (as per your "*Any solutions for this one?*"), you may want to use the Rules module to perform the redirect you want to do. For an example of how to do so, refer to my answer to "How to redirect an anonymous user to the login form after a 403 error?" (the "option 2" part of it. Not sure what exact "Rules event" would fit in your case, but it'll be probably something related to a specific "path" in your site.

Not sure if it would fit your needs here also, but maybe you want to add the "Rules URL argument" module also to this. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

Refer to my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?" for way more details about this module also.
> 3 votes

---
Tags: 7, uri, redirection
---


# Question
Title: How to access rules condition values in the rule event?
I have created a rule (using Rules) in which I added 3 conditons. Now I want to access the conditions values in the action that on which condition the action is performed.

I am attaching the screenshot :

As shown in the screenshot, I want to access

```
[commerce-license:type], Data value: Diamond Subscription

```

How can I achieve this ?

# Answer
I'm not sure if it'll be the only thing you need to do to get this to work, but I think you may get closer (= simplify your challenge) by ALSO using the Conditional Rules module. Some more details about this module (from its project page):

> ... provides Rules plugins for conditionally altering execution flow directly inside a group of **actions**.

Here is a screenprint of a rule with an action that uses Conditional Rules (though only with an "if"-part here, no "else"):
> 1 votes

---
Tags: 7, commerce, rules
---


# Question
Title: Output the file name of images using the views_data_export module?
I'm using the https://drupal.org/project/views\_data\_export module to export a Views list of content as a CSV file.

The content has an image field (multiple values in it) then the CSV data show nothing for the images. I need to output the name of the image file.

I tried adding a Relationship field: **File Usage: File** but I get duplicated row (one for each image in each node)

I need to output a CSV file, something like:

```
TITLE, IMAGES
"my dog title" , "dog-picture-1.jpg, dog-picture-2.jpg"
"my cat title" , "cat-picture-1.jpg, cat-picture-2.jpg"

```

How can I sort this out?

# Answer
> 0 votes
Use **Rewrite the output of this field** option and add your fields like title, image1, image2.

1). In image1 field, use the rewrite option and use the taken of your image like

\[field\_gallery\_fid\]

and set the Group multiple values like below image

>

2.) In image2 field, use the rewrite option and use the taken of your image like

"\[title\]" ,"\[field\_gallery\_fid\],\[field\_gallery\_fid\_1\]"

and set the Group multiple values like below image

>

Note: Suppose if you have 10 images, you can repeat the above steps, but if you have **"n"** number of images, then it will not work out for you.

# Answer
> 0 votes
You have to install Image URL Formatter

> This module add a url formatter for image field. Then you can output image url directly.
>
> Most of the code, maybe more than 90%, is just copy from the drupal core. I think it is stable enough.
>
> I have created a content type, and add an image field instance to it, later I use views to export the data of this content type.And I want to output the data,then I could import it into another drupal 7 site with feeds module. What I need is the URL of the image field, but I could not export the image URL directly. That is why I create this small module.

---
Tags: importing-exporting
---


title: Custom input in edit profile page

text:
# Question
Title: Custom input in edit profile page
I create a template called `page--user--edit.tpl.php`

Into that file, I want to display **some inputs** for editing like `username` and `password` only, not the **default edit form**.

I don't know the code to put into this file for displaying only these input.

Thanks for your help !

# Answer
Use Hook form alter and find the id of user edit form. Unset all extra fields but username and password. In templates it is not recommended to add php. If you want to disable or hide something its better to disable it from the render array. here is an example:

```
<themnam>_form_<FORM_ID>_alter($form, &$form_state) {
 dpm($form);
 unset($form['your-field']);
}

```

I hope it helps
> 0 votes

---
Tags: users
---


# Question
Title: A PDF field open in a new window of Drupal
I add a field which type is PDF. When I click the PDF file, I want the PDF file to open in a new window (using `target="_blank"`).

How do I add such `target="_blank"` to the a label?

# Answer
If you're looking for a quick fix for ALL pdf links on your site you could use a little bit of javascript to accomplish this as well. This snippet finds all URLs ending in .pdf and sets the target attribute to be \_blank (new window).

```
(function ($) {
    $(document).ready(function() {
        // Open PDF In New Window
        $('a[href$=".pdf"]').attr('target', '_blank');
    });

}(jQuery));

```

Since you're looking for just files of your field type you could certainly use a less generic selector, such as `.field-name-field_pdf a[href$=".pdf"]`. Best of luck!
> 2 votes

# Answer
Add this to your theme template.php file:

```
<?php

function yourthemename_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
      'target' => '_blank',
    ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span>';
}

```
> 1 votes

# Answer
The FileField Target module takes care of it from now on…
> 1 votes

---
Tags: files
---


# Question
Title: In content type show same field twice with different widget
I want to show one field (file type) twice in the same content type (without display suite as it breaks my other modules). After a user uploads a pdf and saves this content. I want one link to lead to pdf file for download(which it does) and the other link to show generic file (open a pdf in browser) and i dont know how to do that part (To change widget type). I have searched Drupal Answers and found some clues on how to do this in `template.php`

```
function bsthemel_preprocess_field(&$vars) {
 $node = $vars['node'];
     if($vars['element']['#field_name'] == 'field_document_pdf') {

        //code to copy and render this field with different widget (havent figured out how yet)
}

```

Now i am still new to drupal and can't seem to figure this out. Also what i have found is `function hook_field_widget_form_alter` but i think this has to be done after the new field is made. Or i might look at this completely wrong. Any help is appriciated

# Answer
The "right" way to add additional elements to a view mode (without using a module like Display Suite or Panelizer to take over view modes) is to use hook\_field\_extra\_fields(): This hook will make your added element visible on the core view mode configuration screen.

If you're new to Drupal it might be easier to go with the preprocess route. But instead of working at the level of template\_preprocess\_field() you should be working at the level of template\_preprocess\_node(). The node hook contains the field you want to duplicate. The field hook deals with only one field at a time.
> 2 votes

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


title: Wysiwyg in views module

text:
# Question
Title: Wysiwyg in views module
Can I add a wysiwyg field in Views so that users can write and post text on my page?

Would I need to enable this as a block?

I have installed ckeditor and views already.

# Answer
> 0 votes
The only way WYSIWYG works with Views is with either an embedded comment or using the Editable Views module:

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

---
Tags: views, entities, blocks, wysiwyg
---


# Question
Title: Move uploaded content automatically from one node to another
Is it possible post `images/text` on a different page other than the one being uploaded?

I have an `insert` page where users can add `images/text` but I want whatever they post to go on another page automatically ('things' page) sorted by the most recent first. I only want to keep the 'insert' page as an 'insert' and without content!

# Answer
> 1 votes
Content in Drupal is organized in "nodes":

> A node is any piece of individual content, such as a page, poll, article, forum topic, or a blog entry. Comments are not stored as nodes but are always connected to one.

So you'll always have a "page" or whatever your content type is named, to store and edit the content. But you don't need to show these pages necessarily to the visitors or users of that site.

You should take a look into Views module, which will enable you to create (another sort of) "pages" that automatically collect content from "nodes" according to the rules and filters that you have definded for it.

---
Tags: 7, nodes, redirection, files
---


# Question
Title: Welcome email after user reset password in first time?
When a new user signs up with the website the user receives an email with link to reset the password and when they reset the password first time, they get a welcome email but when in future they reset their password , they will not get that welcome email.How to resolve this.

# Answer
You can do by using Login one time module

> Rules:
>
> * `[user:login-one-time]` token on user events.
> * `[comment:login-one-time]` token for node author on comment event.
>
> User profile - "Send login one time link" button.
>
> VBO - Create a view and send login links to the view. Checkout View Reference for ideas on how to embed views.
>
> Block - Select a user and send the link. You can use this block in nodes as a CCK field using Block Reference.
>
> PHP - Print a button in a template or directly send the emails using the functions described in the README.
> 0 votes

# Answer
you can try Recovery Password module.

> Drupal by default sends Password Reset URL by mail to user's email id in password recovery mail, but Recovery Password module makes it possible for Drupal to send any random generated password(new password) by email instead of URL to the user.
> 0 votes

# Answer
Another approach to answer this question is to use the Rules module, similar to what is described in either of these comments in the issue with title "Rule to redirect on login, except on one-time login and password reset":

> * **Event**: User logged in.
> * **Conditions**:
>     + *Elements*: Text comparison.
>     + *Parameter*: Tekst: \[site:current-page:path\], Matching text: user, Comparison operation: ends with

> * **Event**: User logged in.
> * **Conditions**:
>     + *Elements*: NOT Text comparison.
>     + *Parameter*: Text: \[site:current-page:path\], Matching text: ^user/reset/, Comparison operation: regular expression

Obviously, for either approach mentioned in these 2 comments, you'd have to add a **Rules Action** to actually send an appropriate eMail message also.

**Note**: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.
> 0 votes

---
Tags: users, emails
---


# Question
Title: How to add a checkbox in checkout form to optionally add 5$ to the product price as a donation?
I have a Drupal site using the Drupal Commerce module.

I want to add a checkbox to the checkout form, some thing like this

> > = Donate by 5$

If it is checked, then "5$" will added to the selected product price.

Any suggestions?

# Answer
Have a look at the Commerce Donate module. From its project page:

> This module provides a donation line item type along with a donation product and product display. This is partially based on Randy Fay's excellent screencast at http://commerceguys.com/blog/using-custom-line-items-provide-donation-fe...
>
> It uses the Select or Other module to provide the donation amount form field. If you need to modify the default donation option values, the install the Commerce Customizable Products module in order to modify the line item type form settings.
>
> In addition to being able to create a donation product, this module also provides a donation checkout pane, allowing customers to add a donation to their order as part of the checkout process.

Especially the last paragraph seems pretty close to what you're looking for.
> 1 votes

---
Tags: 7, commerce, payment-gateways
---


# Question
Title: PayPal Payflow Pro not allowing user to buy product
when I enable (and try to use) PayPal Payments Advanced and Payflow Link sub-module of Paypal module and submit the product form I get this error:

```
messageEntityMetadataWrapperException: Unknown data property
commerce_customer_address. in EntityStructureWrapper-
>getPropertyInfo() (line 335 of
/site/sites/all/modules/entity/includes/entity.wrapper.inc).

```

When I remove Payflow Link module I do not get this error.

**The problem occurs when I remove the default 'address' field from the Customer Profiles \> Billing Information and instead just use my own fields**...but I don't want to use that default address field because it contains items I don't want.

Anyone know how I can fix this so i can use Payflow?

It appears to be a problem in the Entity module but only gives me an error when trying to use Payflow Pro to purchase a product.

This is what that line of the entity module file has:

```
  public function getPropertyInfo($name = NULL) {
    $this->spotInfo();
    if (!isset($name)) {
      return $this->propertyInfo['properties'];
    }
    if (!isset($this->propertyInfo['properties'][$name])) {
      throw new EntityMetadataWrapperException('Unknown data property

```

' . check\_plain($name) . '.'); } return $this-\>propertyInfo\['properties'\]\[$name\] + $this-

> info\['property defaults'\] + $this-\>propertyInfoDefaults; }

# Answer
> 0 votes
No one but me seems to have encountered this problem. But in the oft-chance someone ever does encounter it, here's why.

This error is occurring because I had removed the default address field from the customer profile \> billing information in my drupal commerce store in favor of custom fields. But you apparently HAVE to use the default dynamic address field, or at least I don't know a way around it.

Since most of those fields are valuable anyway, and I just wanted them really in a different order, I found it valuable to KEEP that field, add some custom fields as well, and then just re-order them using hook\_form\_alter() and the '#weight' property of each form element. Additionally using this function you may also hide any of the fields in the default address field (it contains multiple fields) that you don't want.

---
Tags: commerce, entities, payment-gateways
---


# Question
Title: How to make state/provinces list dynamic on user profiles/registrations? with international addresses?
I have a site with international users, and I'm using location, user locations, and Google geocoding to show their locations on a map.

I'm using the US as the default for addresses, as most of my users are US based. The issue that I have is that the state/provinces drop down doesn't update the list for a different country until after the form is saved. The effect of this is that the newly registered users has to go back into their account an update their address if it isn't in the US.

Is there anyway to make the state/provinces list dynamic? that is to have the list match the country selected while the user is registering?

One solution to this is to email the user and remind them to update their address, but this seems like back UI and laziness.

Is there some way to refresh just the location fields before the form is submitted if it cannot be dynamic?

So, I'm not sure how to approach this and any advice would be appreciated.

# Answer
So, there's a patch for this. The last patch used against the 3.x dev module provided the desired results. Dynamic States list patch
> 1 votes

---
Tags: entities, location, google-maps
---


title: Find/Replace in File Field

text:
# Question
Title: Find/Replace in File Field
I'm working with a site that has many files that have been uploaded to it. Data has been pulled from these files to populate fields such as title, description, etc. Some of these fields contained ampersands which now appear as &.

Is there a way I can batch correct these—such as a find/replace? I tried the Find/Replace Scanner module but it doesn't seem to be able to work with file nodes.

# Answer
If you can find the file field in question in your database.

1. Export it as csv.
2. Use find and replace with excel, save.
3. Import it back in.
4. Clear the cache.
> 1 votes

---
Tags: database, files
---


# Question
Title: How to add weight to the total weight of the order witn Commerce Shipping with rules?
I want to add a constant weight to the total weight of the orders in my shopping cart to account for packing materials in the weight calculation.

I'm also using Commerce Shipping Postal Code Code Weight. The Postal code weights work brilliantly.Shipping Postal Code Weights

What I want to do is add a 6oz to the total weight of my order.

# Answer
> 0 votes
You should implement this hook in a custom module:

```
/**
 * Allows modules to alter the weight that has been determined for an order.
 *
 * @param &$weight
 *   The weight field value array representing the weight of the order or NULL
 *   if no weight has yet been determined.
 * @param $order
 *   The order object whose weight is being determined.
 * @param $unit
 *   The unit of measurement to use for the returned weight of the order.
 *
 * @see commerce_physical_order_weight()
 */
function hook_commerce_physical_order_weight_alter(&$weight, $order, $unit) {
  // No example.
}

```

---
Tags: rules, commerce
---


title: Add/attach saved pdf to node with rules

text:
# Question
Title: Add/attach saved pdf to node with rules
I have a setup with views PDF which send email after creating a node. (This works)
For logging purpose I would like the PDF added to my node in a filefield. Is there a rule action/php code available to add the saved PDF to the filefield.

# Answer
> 1 votes
For adding/attaching a file to a node using code you need a file object. If you know the **path of the created PDF file**, just try the following code in the **hook** you need. I used this code in **hook\_node\_insert** for attaching a programmatically created PDF file, while creating that node.

```
$source_node = node_load($nid); //load your required node here.
$file_path = 'your file path';
$file = new stdClass;
$file->uid = $source_node->uid;
$file->filename = $filename; //your file name;
$file->uri = $file_path;
$file->filemime = file_get_mimetype($file_path);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;
// Save file object to make it a 'managed file'.
$file_obj = file_copy($file, 'new path for your file', FILE_EXISTS_REPLACE);

$source_node->your_file_field_name['und'][0] = array(
 'fid'  => $file_obj->fid,
 'uid'  => $file_obj->uid,
 'filename'  => $file_obj->filename,
 'uri'  => $file_obj->uri,
 'filemime'  => $file_obj->filemime,
 'filesize'  => $file_obj->filesize,
 'status'  => 1,
 'display'  => 1,
 'description'  => '',
 );

node_save($source_node);

```

Hope this will help you.

# Answer
> 0 votes
```
$nid = $node->nid;
$source_node = node_load($nid);
$filename = 'filename.pdf'; //your specific filename
$dir = 'public://'.$filename; //path to specific file with name
$file_size = filesize($dir);
$source_node->type = 'my_nodetype'; // error if not used

//New file object
$file = new stdClass;
$file->uid = $source_node->uid;
$file->filename = $filename; //your file name;
$file->uri = $dir;
$file->filemime = file_get_mimetype($dir);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;
// Save file object to make it a 'managed file'.
$file_obj = file_copy($file, 'public://', FILE_EXISTS_REPLACE);
$file->type = 'document';

$source_node->field_custom_name['und'][0] = array(
 'fid'  => $file_obj->fid,
 'uid'  => $file_obj->uid,
 'filename'  => $file_obj->filename,
 'uri'  => $file_obj->uri,
 'filemime'  => $file_obj->filemime,
 'filesize'  => $file_obj->filesize,
 'status'  => 1,
 'display'  => 1,
 'description'  => '',
 );

node_save($source_node);
file_usage_add($file_obj, 'file', 'node', $source_node->nid);

```

PDF is attached to current node. thanks for help. Is anypone has the code to do the same with entitywrapper. please share.

---
Tags: views, rules, files
---


# Question
Title: Override entire user login / register page
I am trying to figure out a way to override the entire `/user` page in **D7**. There is a lot of articles out there that goes about altering the form, but I want to be able to rework the entire page (forms included) to get them into a nice bootstrap layout.

A lot of the information on the web is talking about `page--user--login.tpl.php`, but this does not work at all.

When using `page--user.tpl.php`, it seems to render my template file, but I cannot re-render the form.

When using

```
<?php
  $form = drupal_get_form('user_login');
  print drupal_render($form);
?>
My HTML goes here
<?php
  // Render any remaining elements, such as hidden inputs (token, form_id, etc).
  print drupal_render_children($form);
?>

```

I keep getting an infinite redirect loop. My best guess is because of a problem with the form\_id that does not match.

Ps: I am using a bootstrap subtheme.

All information about this would be greatly appreciated.

# Answer
> 0 votes
You should copy your theme's `page.tpl.php` to `page--user.tpl.php` as you already have to create the template that will be used for the page.

Following that, in your `template.php` create implement `hook_form_FORM_ID_alter()` using either `user_login` or `user_register` as the form ID depending on which part of the page you're wishing to alter. If you either add a `dpm()` or an xdebug breakpoint in here and refresh the page, you should see the form structure and the available fields. in this field, you can then alter the form elements' `#attributes`, `#prefix`, and `#suffix` fields to add the required Bootstrap classes.

I.e. (not a user register field, just an example)

```
$form['my_element'] = [
  '#type' => 'textfield',
  '#title' => t('My textfield'),
  '#prefix' => '<div class="form-group">,
  '#suffix' => '</div>',
  '#attributes' => [
    'class' => [
      'form-control',
    ]
  ],
]

```

One last thing that might be helpful; there was a change in Drupal 7.33 (I think) that added a `theme_debug` value to the global `$conf`. If you add `$conf['theme_debug'] = TRUE;` to your `settings.php`, then any template the is used will be shown in the dev tools as a comment just before it is loaded - this makes is super easy to work out which template is being called, as well as listing any possible alternatives.

# Answer
> 1 votes
In template.php, you could add an alter form to add classes, a wrapper, and I think also be able to add/edit fields in the form. Would that be of any help?

Example:

```
function THEME_NAME_form_user_login_alter(&$form, &$form_state) {
    $form['#attributes']['class'][] = 'custom-class';
}

```

in template.php would add the class `custom-class` around the login form, which you can then use to style the form.

As for using templates, I think they might have to be added in the correct location as well, e.g. I have recently built a site using custom templates with the user pages templates in `/sites/all/theme-name/templates/user/`. This also allows you to use custom markup. For example:

```
<div class="custom-class--wrapper">
    <?php print drupal_render_children($form) ?>
</div>

```

which is used in the file `user-register-form.tpl.php`.

Also, have you considered using panelizer to customise pages, that would be a lot easier than using template.php or custom templates. And if a change doesn't seem to take effect, you should try and clear the drupal cache.

---
Tags: users, theming
---


# Question
Title: How to make my new administration page use my administration theme?
I’ve created a user role of *accountant* and for this role have created a single page using Views. This page started out as a clone of another admin views page.

Unfortunately this page is using the website’s main theme CSS instead of the admin CSS and is causing some real problems.

I’ve been looking how to have this page NOT load the theme CSS, and use the admin CSS instead.

The *accountant* role has very limited permissions.

How can I correct this??

# Answer
> 4 votes
There's a permission named *View the administration theme*. This should be given to the accountant role to allow users with that role to view the admin theme instead of the site theme.

If that permission is granted, then check the URL for the page you've created. A last resort would be to check out the documentation for `hook_admin_paths()`. This hook allows you to specify paths that should use the admin theme and/or use the Overlay (if you've got it enabled). Something like the following would work:

```
/**
 * Implements hook_admin_paths().
 */
function MY_MODULE_admin_paths() {

  $admin_paths = [
    'my/new/admin/view' => TRUE,
  ];

  return $admin_paths;

}

```

# Answer
> 1 votes
You can use hook\_custom\_theme to change the theme to be used for the current page.

```
  /**
  * Implements hook_custom_theme().
  */
  function module_name_custom_theme() {
    $path = current_path();
    if ($path == 'your_view_path') {
      return 'admin_theme_name';
    }
  }

```

'admin\_theme\_name' would be applied to the path you check in the **hook\_custom\_theme**

---
Tags: views, theming
---


# Question
Title: how to render a node field of a referenced node on the node form
I'm using Display Suite to show a referenced node inside another node in the default display. But when I edit this node that has the entity reference field on it, it shows me the reference field and I'd like that to show the rendered content of a field of the referenced node. Is there a way in Display Suite or do I have to write some code in a tpl file somewhere?

# Answer
> 0 votes
You can create using Views a view with "Entity Reference" where you can make the rendered content you wish to add to the node. Than add a new field of type "Entity Reference" to the node edit form of this node type and set up in section "Entity selection":

* Mode -\> 'Views: Filter by an entity reference view"
* View used to select the entities -\> *choose the view machine name you have created for this purpose*

Additionally, you can provide a comma separated list of arguments to pass to the view.

To avoid some status messages like 'Do something on load', you should uncheck "Test behavior" in "Additional behaviors" section.

Hope it helps

# Answer
> 0 votes
You can use Inline Entity Display module,

> Overview
>
> Make available the fields and text properties from referenced entities into the parent entity template and the manage fields display overview. Drupal standard entity display:
>
> Node \- title \- field body \- field reference -\> default formatters With IED enabled:
>
> Node \- title \- field body \- field reference -\> default formatters \- field from field reference: field\_name1 \- field from field reference: field\_name2 \- properties of type text from field reference: propertyname1 -etc

**and Also** you can render it programmatically in `tpl` file with something like

```
 // $node = node_load($nid); if you in node $node exists by default
 $values = field_get_items('node', $node, 'yourfieldmachinename');
 $output = field_view_value('node', $node, 'yourfieldmachinename',    $values[0]);
 print render($output);

```

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


title: Installation fails due to clean URLs

text:
# Question
Title: Installation fails due to clean URLs
I have a Drupal 8.0.1 installation running under Apache 3.4 from /var/www. During installation, I cannot seem to pass the requirements for clean URLs. I've read through answers I've found on Drupal.org, but to no avail.

Does anyone have any suggestions?

# Answer
rewrite engine is required to use clean url and you need to intall on terminal by execute the below command.

```
sudo a2enmod rewrite

```
> 1 votes

---
Tags: 8, installation, uri
---


title: Duplicated content using Feeds Importer

text:
# Question
Title: Duplicated content using Feeds Importer
I'm trying to import a CSV file using Feeds Importer and I've got the content created correctly, but then I need to add more data into the CSV and re-import the content and I'm getting the old content created again...

All the fields can change and are not unique, so I've created a specific integer field that was mapped twice, once to the field itself and then again to the GUID. I've done this, in order to have one field that will be unique to each row and that I can fill with info from the CSV and ironically, that will allow me to stop the content to be duplicated...

This is the importer I'm using:

```
$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'csv_a_bienes';
$feeds_importer->config = array(
  'name' => 'CSV a Bienes',
  'description' => '',
  'fetcher' => array(
    'plugin_key' => 'FeedsFileFetcher',
    'config' => array(
      'allowed_extensions' => 'csv',
      'direct' => 0,
      'directory' => 'private://CSV',
      'allowed_schemes' => array(
        'public' => 'public',
      ),
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsCSVParser',
    'config' => array(
      'delimiter' => ',',
      'no_headers' => 0,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => '1',
      'authorize' => 0,
      'mappings' => array(
        0 => array(
          'source' => 'guid',
          'target' => 'guid',
          'unique' => 1,
        ),
        1 => array(
          'source' => 'guid',
          'target' => 'field_guid',
          'unique' => FALSE,
        ),
        2 => array(
          'source' => 'Postulados',
          'target' => 'field_postulados',
          'unique' => FALSE,
        ),
        3 => array(
          'source' => 'Bloque',
          'target' => 'field_bloque',
          'unique' => FALSE,
        ),
        4 => array(
          'source' => 'Departamento',
          'target' => 'field_departamento',
          'unique' => FALSE,
        ),
        5 => array(
          'source' => 'Municipio',
          'target' => 'field_municipio_lugar',
          'unique' => FALSE,
        ),
        6 => array(
          'source' => 'Tipo de bien',
          'target' => 'field_tipo_bienfrv',
          'unique' => FALSE,
        ),
        7 => array(
          'source' => 'Clase del bien',
          'target' => 'field_clase_del_bien',
          'unique' => FALSE,
        ),
        8 => array(
          'source' => 'Subclase del bien',
          'target' => 'field_subclase_del_bien',
          'unique' => FALSE,
        ),
        9 => array(
          'source' => 'Nombre del Bien',
          'target' => 'title',
          'unique' => FALSE,
        ),
        10 => array(
          'source' => 'Consecutivo',
          'target' => 'field_consecutivo',
          'unique' => FALSE,
        ),
        11 => array(
          'source' => 'Numero de acta',
          'target' => 'field_n_mero_de_acta',
          'unique' => FALSE,
        ),
        12 => array(
          'source' => 'Documentos',
          'target' => 'field_archivo:uri',
          'unique' => FALSE,
        ),
        13 => array(
          'source' => 'Forma en que se recibio el bien',
          'target' => 'field_tipo_de_bien',
          'unique' => FALSE,
        ),
      ),
      'update_existing' => '2',
      'update_non_existent' => 'skip',
      'input_format' => 'plain_text',
      'skip_hash_check' => 0,
      'bundle' => 'bienes',
    ),
  ),
  'content_type' => 'bienes',
  'update' => 0,
  'import_period' => '-1',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
);

```

Can anyone please help me to identify what did I wrong?

# Answer
Add a node title as unique field in feeds and set your processor settings as "Update existing nodes". This will update your nodes when you change the fields value in csv.
> 1 votes

# Answer
You can use unique field module in Drupal 7,

https://www.drupal.org/project/unique\_field

Also please refer to this link for unique target.

https://www.drupal.org/node/661606
> 0 votes

---
Tags: 7, feeds, importing-exporting
---


# Question
Title: How to track users site use in a webform / contact form?
I was wondering if anyone knows a way of adding some data to the end of the emails I receive from a contact / web form, such that I can see what pages users (authenticated and unauthenticated) have visited prior to submitting the form?

Something like:

---

```
Here is the main body of the web form.

Before submitting this form the user visited:
/node/1,
/node/12,
/contact-us,
/node/45,
etc etc...

```

---

# Answer
> 1 votes
This is more or less the feature of the Google Analytics Contact Form, Webform, Rules Email module.

> This module will instantly append Google Analytics information to the bottom of the Contact Form, WebForm, and Rules emails.

The mail would look something like:

# Answer
> 0 votes
If your mail-sending-module supports tokens, you could provide tokens with the data you need and then simply use them. But this will not give you full trail, only (at best) referrer, one page back. To track him more thoroughly, you need to use make module track him and record last N visited pages in a FIFO. Again, tokens to put it in content seems easiest way to integrate it with mail sending solution.

Google Analytics is good, if all you need is to identify what pages makes people contact you. It's licence forbids using it to track individual users, so if you need it for error reporting and alike, it's no-go.

And don't forget to respect Do Not Track, it may be required in your jurisdiction and it's only fair everywhere.

# Answer
> 0 votes
You can use recently\_read module in drupal 7,

https://www.drupal.org/project/recently\_read

After that u can create token, check if it is provided by module, if not then create custom token and access that token in Email.

# Answer
> -1 votes
You could definitely do this by creating your own Module, but I Google Analytics is free and is built for tracking this sort of thing. Check out "Event Tracking" and "Goal Flow" in particular.

---
Tags: webforms, emails
---


# Question
Title: Filling the field with certain criteria before save
I had a case like this.

A **Document** content type with Taxonomy Term like this

**Title**

**Category :**

* CAT A
* CAT B
* CAT C

**Doc Number**

When user selects CAT A, then do some query to find last number of node with CAT A. If there is no data found then it will give a starting number, if there is data found it will increment last number of node CAT A.

Every category will have its own number format and reset yearly. This number will be stored in the **Doc Number** Field.

Whether there is a good idea for this case? I know PHP a little, but what makes me confused is how to know which category is selected before I save this node.

**Update** Obstacles that I faced was to make automatic numbering based on the selected category.

Each category has its own number and reset every year. After some reading on Drupal I made my custom module like this.

```
function custom_node_presave($node) {
//    dsm($node);
//    $test = $node->changed;
//    $term = taxonomy_term_load($tid); // find term
//    $name = $term->name; // get term name
  if ($node->type == 'dokumen') { // if type = dokumen
    if (empty($node->nid)) { // if no nid then this is new
      $tid = $node->field_jenis_peraturan['und'][0]['tid']; // taxonomy id
      // do query to find last number
      $result = db_query_range(
        'select
           n.nid,
           n.type,
           n.title,
           nomor.field_nomor_dokumen_value,
           tahun.field_tahun_value,
           tin.tid,
           term.name
         from node n
         left join field_data_field_nomor_dokumen nomor
           on n.nid = nomor.entity_id
         left join taxonomy_index tin
           on n.nid = tin.nid
         left join taxonomy_term_data term
           on tin.tid = term.tid
         left join field_data_field_tahun tahun
           on n.nid = tahun.entity_id
         where tin.tid = :tid',
       array(':tid' => $tid));

      if (!$result) { // if empty no data found
        $node->field_nomor_dokumen['und'][0]['value'] = 1; // set starting number
        $node->field_tahun['und'][0]['value'] = date("Y"); // set this year
      }
      else {
      // if data found then set data to var $no & $tahun
        foreach ($result as $item) {
          $no = $item->nomor.field_nomor_dokumen_value;
          $tahun = $item->tahun.field_tahun_value;
        }

        $ynow = date("Y"); // get current year

        if ($tahun < $ynow) { // if year in last data < current year
          $node->field_nomor_dokumen['und'][0]['value'] = '1'; // set starting number
          $node->field_tahun['und'][0]['value'] = date("Y"); // set year = current year
        }
        else {
          ++$no; // last number increment by 1
          $node->field_nomor_dokumen['und'][0]['value'] = $no;
          $node->field_tahun['und'][0]['value'] = date("Y"); // set year = current year
        }
      }
    }
  }

```

I hope I've explained well.

# Answer
To do this thing, you have to implement `hook_form_alter`, and `#ajax` for the drop down, after that create callback function for the same. In that AJAX callback you can query the database, and produce desired results.

Format is given below:

```
'#ajax' => array(
  'callback' => 'ajax_example_autocheckboxes_callback',
  'wrapper' => 'checkboxes-div',
  'method' => 'replace',
  'effect' => 'fade',
),

```
> 1 votes

---
Tags: 7, nodes, entities, taxonomy-terms
---


title: How can I connect to a database?

text:
# Question
Title: How can I connect to a database?
So I'm new to Drupal and am creating my first module. I can get the page to display html, but I'm not quite sure how to connect to the MySQL database. Here is my code:

```
<?php
// $Id$

/**
 * @News
 * First module
 *
 * Just a simple news module
 */

function news_main() {
    db_set_active('default');
    $query = mysql_query("SELECT * FROM news");
    while ($news = mysql_fetch_object($query)) {
        $output .= '<h1>'.$news->title.'</h1><p>'.$news->body.'</p><p>'.$news->date.'</p>';
    }
    return $output;
}

/**
 * Implements hook_menu().
 */
function news_menu() {
    $items = array();

    $items['news'] = array(
        'page callback' => 'news_main',
        'title' => 'News',
        'access arguments' => array('access content'),
        'type' => MENU_NORMAL_ITEM,
     );

    return $items;
}
?>

```

I just get a blank page whenever I try to view it. I'm sure it's something simple, but I'm completely new to Drupal and it's API. I've looked through documentation for hours and couldn't figure it out.

# Answer
> 3 votes
So what's happening is you're querying a database that you're not connected to.

```
db_set_active('default');

```

...that makes the active database the Drupal default (the one it was installed on, usually).

```
$query = mysql_query("SELECT * FROM news");

```

...that doesn't actually do anything. That is a MySQL Library function (i.e. not part of the Drupal API), so Drupal doesn't actually interact with it.

Now, depending on what you're trying to do here, it's not clear if you're trying to query a table that's part of the Drupal installation or if it's a secondary, external table in a database you're trying to connect to... however, based on the logic you're using I'm going to assume the table is in the Drupal database.

If news is a table in the default Drupal database, then what you want to use is `db_query`, and the API information for it is located here https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db\_query/7. You can read about interacting with the Drupal database through the Drupal API there.

Here's an example I pulled from the Migrate module:

```
$query = db_select('migrate_example_beer_topic', 'met')
         ->fields('met', array('style', 'details', 'style_parent', 'region','hoppiness'))
         // This sort assures that parents are saved before children.
         ->orderBy('style_parent', 'ASC');

```

Notice you don't actually have to specify the database you're connecting to, it just assumed 'default'.

In fact, for that matter, you should install the Migrate module and go through the examples that it has. They come with the module, and will be accessible under sites/all/modules/migrate/migrate\_example.

# Answer
> 0 votes
As said in the accepted answer, you don't use directly plain PHP functions to access the database, in Drupal. They don't have access to the database information Drupal uses; as such, your call to `db_set_active()` doesn't influence them.

Since by default Drupal uses the database defined in settings.php as `$databases['default']['default']`, your call to `db_set_active()` is perfectly useless: Just use the database function Drupal has, and you are all set.

If we are talking about accessing a database Drupal doesn't have set as default, then you need to use code similar to the following. I don't use `db_set_active()` simply for the fact it changes the database used from other modules, which could cause them to fail.

```
// db_select()
$query = Database::getConnection($target)->select($table, $alias, $options);

// db_insert()
$query = Database::getConnection($target)->insert($table, $options);

// db_delete()
$query = Database::getConnection($target)->delete($table, $options);

```

If the settings.php file doesn't contain the definition for the database you want to access, you can add it to the definition Drupal knows.

```
Database::addConnectionInfo($key, $target, $info);

```

`$info` is an array as described in default.settings.php. For example, to access a SQLite database, it is similar to the following.

```
$info = array(
  'driver' => 'sqlite',
  'database' => '/path/to/databasefilename',
);

```

There is no need to first check the information is already know to Drupal, since Drupal doesn't add the same information twice. If your module is using a specific connection, be sure to use for `$key` a value that doesn't conflict with any value used from Drupal or third-party modules. (It is enough to prefix its value with the short name of the module.)

---
Tags: 7, database
---


# Question
Title: How to create charts based on content types items?
I want to create a chart according to each content type created per month or week.

How can I do it? Is there any suggestion to use some module?

# Answer
> 2 votes
# Using the Charts module

### Step 1: Getting started

To create charts in Drupal, just use the Charts module. It comes with a sample view which will give you a chart for each of your content types.

Just clone and refine that view, and check how close you are to make it fit your needs. Refer to Create charts using Views (and its subpages) for more details.

For a sample of such chart (derived from the delivered sample view), have a look at this demo sample.

### Step 2: Create the tabular format of the view

A common mistake when creating charts, is that the data to be charted is (not yet) correct. So you really need to first work on getting the tabular format of the view created correctly. That's also what's recommended in the ***Bonus tip*** within Steps to create charts using the views UI, i.e.:

> You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. **It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.** ...

### Step 3: Add the chart to your view

Do not try to start this step if you didn't first complete the prior step.

There is an issue which might help to answer this question, or at least to understand the challenge here. I.e. Graph node input over time (support date formatting on a continuous axis).

In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'.

# Using the Quant module

If using the Charts module you can't get it to work (or don't want to consider the suggestions above), then you may want to look at the Quant module as an alternative. Here are some excerpts from its project page:

> ... provides an engine for producing quantitative, time-based analytics for virtually any Drupal component. Quant takes raw data about normal Drupal actions, such as node creation, and plots the activity over time, with the selected time being configurable. See the screenshot provided for a better understanding.
>
> Provided charts:
>
> * Content creation
> * Comment creation
> * Content creation by type
> * Aggregate content creation
> * User creation
> * Page views (requires Statistics)
> * User shouts (requires Shoutbox)
> * User point transactions (requires User Points)
> * Group creation (requires Organic groups)
> * Group joins (requires Organic groups)
> * Invites sent (requires Invite)
> * Invites accepted (requires Invite)
> * Statuses shared (requires Facebook-style statuses)
> * Private messages (requires Private message)

Especially the "Page views\* chart that is provided might be close to what you're looking for.

# Evaluating other charting modules

If none of the above modules would work in your case, then you might want to look at the "Comparison of Charting modules" documentation.

Disclosure: I'm a (co-)maintainer of all modules mentioned above (and original author of the comparison).

# Answer
> 2 votes
Please check the following module:

* Statistics Pro

> This statistics module provides statistical results of nodes, comments and users. Charts and Graphs module or the Views Charts module it enables specific features dependent on each one of these modules like page visualization reports and graphs.
>
> The Statistics Advanced (7.x) module should be used with Statistics Pro which provides a few advanced options to the core Statistics module.

---
Tags: 7, views, charts
---


# Question
Title: How does the events dispatcher map to map_save to a callback function?
MigrateEvents.php contains an event definition like this:

```
/**
 * Name of the event fired when saving to a migration's map.
 *
 * This event allows modules to perform an action whenever the disposition of
 * an item being migrated is saved to the map table. The event listener method
 * receives a \Drupal\migrate\Event\MigrateMapSaveEvent instance.
 *
 * @Event
 *
 * @see \Drupal\migrate\Event\MigrateMapSaveEvent
 *
 * @var string
 */
const MAP_SAVE = 'migrate.map_save';

```

If I grep the codebase for `map_save`, there is no other reference to it. What mechanism does Drupal/Symfony use to know the callback to call?

# Answer
> 1 votes
@larowlan indicates the correct way to implement a subscriber; however, the original question asks about how map\_save is called, and the two examples in core and contrib both call the addListener method directly.

From Core MigrateEventsTest:

```
\Drupal::service('event_dispatcher')->addListener(MigrateEvents::MAP_SAVE, array($this, 'mapSaveEventRecorder'));

```

From migrate\_tools:

```
$this->listeners[MigrateEvents::MAP_SAVE] = [$this, 'onMapSave'];
...
foreach ($this->listeners as $event => $listener) {
    \Drupal::service('event_dispatcher')->addListener($event, $listener);
}

```

According to the Drupal 8 services documentation this is not the recommended approach. Use the services container to ensure decoupled and testable code.

# Answer
> 3 votes
This event is fired by `\Drupal\migrate\Plugin\migrate\id_map\Sql::saveIdMapping()`.

```
$this->eventDispatcher->dispatch(MigrateEvents::MAP_SAVE, new MigrateMapSaveEvent($this, $keys + $fields));

```

To listen and react to this event you need to add a new service that implements `\Symfony\Component\EventDispatcher\EventSubscriberInterface` and tag it with 'event\_subscriber'.

This is what you find in content\_translation.services.yml.

```
content_translation.updates_manager:
  class: Drupal\content_translation\ContentTranslationUpdatesManager
    arguments: ['@entity.manager', '@entity.definition_update_manager']
    tags:
      - { name: event_subscriber }

```

This tells the event dispatcher the `ContentTranslationUpdatesManager` class subscribes to events.

When you look at `\Drupal\content_translation\ContentTranslationUpdatesManager::getSubscribedEvents()` you can see that it subscribes to the `\Drupal\Core\Config\ConfigEvents::IMPORT` event and when this event fires, the `\Drupal\content_translation\ContentTranslationUpdatesManager::onConfigImporterImport()` method should fire, with a priority of 60. Note that priority works in reverse to the typical Drupal weight: This listener goes before those with a lower priority and after those with a higher priority.

You can read about the generic event dispatcher in the symfony documentation.

The Drupal relevant bit here is the event\_subscriber tag, which is processed in a compiler pass by `\Drupal\Core\DependencyInjection\Compiler\RegisterEventSubscribersPass::process()`, taking care of the registering of listeners automatically, based on the presence of that tag.

---
Tags: 8
---


# Question
Title: Add html5 input types using drupal form api
I want to add HTML5 number type textfield in the form programmatically. I am building the form using hook\_form(). I tried adding the code:-

```
$form['field_price']['#attributes']['type'] = 'number';

```

But it isnt working.

Is there any other work around for the same?

# Answer
An alternative to using Element, and since `theme_textfield()` has a hardcoded value of type 'text', you may want to override `theme_textfield()` in your template.php. You can copy `theme_textfield()`, paste it in your theme's template.php and rename it, then make necessary changes. For example

(NB: I **HAVEN'T** tested this, so there may be some bugs):

```
function MYTHEME_textfield($variables) {
  $element = $variables['element'];
  if (isset($element['#attributes']['type'][0]) && $element['#attributes']['type'][0] == 'number'){
    $element['#attributes']['type'] = 'number';
  } else {
    $element['#attributes']['type'] = 'text';
  };
  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  _form_set_class($element, array('form-text'));

  $extra = '';
  if ($element['#autocomplete_path'] && !empty($element['#autocomplete_input'])) {
    drupal_add_library('system', 'drupal.autocomplete');
    $element['#attributes']['class'][] = 'form-autocomplete';

    $attributes = array();
    $attributes['type'] = 'hidden';
    $attributes['id'] = $element['#autocomplete_input']['#id'];
    $attributes['value'] = $element['#autocomplete_input']['#url_value'];
    $attributes['disabled'] = 'disabled';
    $attributes['class'][] = 'autocomplete';
    $extra = '<input' . drupal_attributes($attributes) . ' />';
  }

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

  return $output . $extra;
}

```

This will hardcode as type `text` any element that does not specifically have a key `$form['field_name']['#attributes']['type'] = array('number');`
> 0 votes

# Answer
Try Element module. it adds advance html5 elements to your form.

Similar question is asked here
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to create a content type based on users with entities?
I want to create a content type that I can add to a map view based on nodes. I am using the GMap and Location modules. There doesn't seem to be an obvious way to add users to view based on nodes. So, I want to make a content type, which is a subset of the users and the fields in my user profiles. I know that I can separately have a map view based on my users, but I need to show them all together users, and 3 spatial content types.

My initial thought was just to copy the raw user data from the database and create a content type and populate it from feeds, but this would lead to a lot of duplicate data in the database.

I've created a content type with an entity reference to users. This lets me manually add content with the user name but I don't know how to share fields between the content types and I don't know how to autopopulate the content from the existing user fields.

How do I proceed?

# Answer
So the thing is that u want to populate user fields with content from node, what you can do is enable module, hook\_post\_action, and after that use its hook "hook\_node\_update", and you will get user id (uid) from the user reference fields, u can load a user from that uid, using user\_load, after that set required value of field, and use user\_save function to save that user, If u are using profile2 for the user, then u can use profile2\_load\_by\_user, profile2\_save.
> 0 votes

---
Tags: users, entities, google-maps
---


title: Imagepicker doesn't appear as block

text:
# Question
Title: Imagepicker doesn't appear as block
I would like the Image Picker to be available on a node (page) as a block so that users can upload images without clicking on 'edit' where they can edit the actual page itself.

I have definitely enabled the setting in the configuration:

Do I need to do it via the Views module (which I do have installed also)?

# Answer
U want a block for image picker, I have checked it and found that it creates iframe for the same. so what we can do, is create a block either programmatically or manually and alter its content, by using hook\_block\_view\_alter, and load image picker in it, and hide rest of element in drupal 7.
> 0 votes

---
Tags: 7, views, media
---


title: Custom edit user page

text:
# Question
Title: Custom edit user page
I'm trying to build an edit form for specific users. **For one type of user I want to hide password field for example**

What I did is to create a module called `profilechange`.

Into `profilechange.module` I wrote this code :

```
function profilechange_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == 'user-profile-form') {
       hide($form['account']['pass']);
       hide($form['account']['current_pass_required_values']);
       hide($form['account']['current_pass']);
    }
}

```

So I enable the module and into my `page--user--edit.tpl.php` I've this code :

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

```

It displays the default edit form. But password fields are not hidden.

That's why I need your help, I don't know why it does not work even if I clear the cache

# Answer
> 2 votes
You also might try the user readonly module. It allows to disable or hide certain form fields for certain users.

# Answer
> 1 votes
You want to do this...

```
$form['account']['pass']['#access'] = FALSE;

```
* If you're altering a form HOOK\_form\_alter() you set #access to FALSE.
* If you're on the theme layer (theme function or file), you can use hide().

The '#access' property means the element is not rendered and the user submitted value is not taken into consideration See https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#access

The hide() function hides an element from rendering later in the process. See https://api.drupal.org/api/drupal/includes%21common.inc/function/hide/7

---
Tags: hooks, users, forms
---


# Question
Title: Attached view ajax call (lazy load) with exposed filters
I'm using views with a main view and an attachment to put 2 views on a single page. Each view is in it's own Bootstrap togglable tab. Because I don't know how many people will actually switch to the non-default tab, I'd like to wait to load that view until it's needed, then load it via ajax.

Is there any way to do this within the Views UI, or is it time for custom coding? This post is kind of old, but is that the best method for executing an ajax call to render a view?

**Edit:** A complicating factor is that I need to include exposed filters, which also need to fetch the data via Ajax. Right now, the filters work with the second tab, but not the first. I believe this is because Quicktabs creates multiple sections with `.view-dom-id-<settings.view_dom_id>`, which is the selector used in Views `js/ajax_view.js`.

Any solutions that work with exposed filters and Ajax?

# Answer
> 1 votes
U can use quicktab module for the same. Create Tab with it, and select your view which u want to use. After that there is an option to check how to load content of the tab, u can either choose to load at once, or on click of tab using ajax.

# Answer
> 0 votes
You could make the other view a page view so that they all have urls

then using the Ajax .load() function

```
(function ($) {
   $("#Tab1").click(function(){
     $("#Area").load("/view1URLgoesHERE");
   });
   $("#Tab2").click(function(){
     $("#Area").load("/view2URLgoesHERE");
   });
})(jQuery);

```

if you want an animated loading image add:

```
.html('<center><img src="/loading.gif"></center>').load("/view1URLgoesHERE");

```

before the `.load`

---
Tags: 7, ajax, views
---


# Question
Title: How to add custom theme for Add a Product page
I'm new to Drupal Commerce.

I have created new product type and added custom fields everything and it's working fine.

I want to theme the Add a Product (form page). Please suggest me how to do that.

Thanks, Selva

# Answer
> 2 votes
It depends what part of the page you want to theme, simple CSS, change the layout, or adjust the form.

To add CSS, you could attach your CSS file in `hook_page_build` for that path.

To change the page template, you could override the `page.tpl.php` file as `page--node--add--product.tpl.php`

You could also set a custom template in `hook_preprocess_page` by checking for the relevant path and setting `theme_hook_suggestions` to your template (e.g node/add/product and node/\[nid\]/edit)

Another option is using `hook_custom_theme` to specify a whole new theme for that specific path.

Lastly, you can theme the form itself using `hook_form_alter` and using either a template for the form, or adjusting the form elements there.

# Answer
> 1 votes
If you are afraid of codes, download the module "themekey" and install . then download the theme you want to use for the path. After that, go to the themekey admin link to set the theme for the specific path.

---
Tags: commerce, theming
---


# Question
Title: How to get list of sites with module enabled using drush?
How can I find out, using drush, which sites from my Drupal multisite installation have a particular module/theme enabled?

# Answer
> 2 votes
The drush command for this is:

```
drush @sites pml --type=theme --status=enabled --yes | grep bootstrap

```

That's for the bootstrap theme, for a module it would be something like this

```
drush @sites pml --status=enabled --yes | grep pathauto

```

---
Tags: drush
---


title: How to Reorder menus (not menu items)

text:
# Question
Title: How to Reorder menus (not menu items)
I have the standard Main Menu, Management Menu, User Menu, etc., plus a bunch of custom menus. They are consistently shown in the same strange order (not in the order created, not alpha, not alpha by machine name) when shown in /admin/structure/menu/manage/. I can't determine a logic for the order.

I use Footer sitemap to place links in the footer and the various menus show up in this same order. I can find no way to change the weight of entire menus or reorder them. The database table I found was sorted alphabetically by machine name and not in the order I see at /admin/structure/menu/manage/. Any way to control this order?

# Answer
You could probably try the alternative module Sitemap. They fixed the ordering issue in their latest version (7.x-1.3).
> 1 votes

---
Tags: navigation
---


title: Let Parent View child's result

text:
# Question
Title: Let Parent View child's result
I need to setup a view for a parent which shows the result of his child. The result is a content type which has a user reference field to each student who owns the result.

Each students' profile has a user reference field to his /her parent username. I.m using profile 2 to setup parent and children account differently.

By using contextual filter and relationships, I can easily show the fields of the result to each student who owns the result but since parents' account are different, I really don't know how to show contents linked to individual student to show in their parent account.

# Answer
> 0 votes
* Download and install the Entity Reference module
* In parent user fields, add a field with **Entity Reference** and a widget of **Auto complete (tag style)**

For example: I named mine lalala (click picture below to enlarge)

* For Target Type, select **User**
* Number of Values: **Unlimited** (as parent could have more than 1 child)

* Then go to the parents account and start typing child's account user name, you will see the name in the drop down, select it and save.

Use a comma `,` to add other child account. (parent has more than 1 child)

## In your view

* contextual filter of User id (uid) (which uses the parent's id)
* add a **relationship** of lalala Referenc**ed** Entity

+ If not, try Referenc**ing** entity, but if my memory is correct it's Referenc**ed**

---
Tags: 7, views
---


title: Multi-media files not showing

text:
# Question
Title: Multi-media files not showing
Uploaded `multi-media` files to:

```
public_html/sites/default/files

```
* no error messages
* permissions: 0775
* files do not appear (in Content, as do files uploaded through the media editor)

Switching from **Wordpress** to **Drupal**. New to Drupal. Not a programmer. It would take a long time to upload 1,000+ files through a media editor. How do I get Drupal to see these files without uploading them one-by-one?

# Answer
> 2 votes
You need to tell Drupal about your files *somehow*.

You could write a script yourself.

Another approach would be to use the archive upload of File entity, but you won't be able to upload hundreds of them in a single archive either, the file will simply get too big.

Maybe there is also a module for this, but it's likely not available yet for Drupal 8.

# Answer
> 0 votes
What works for now:

1. created a new content type named 'Media' and set upload to unlimited
2. added file field (could not change body because data has already been added elsewhere)
3. created a page
4. selected multiple files using the new 'Media' content type (not the CK Editor media uploader which only handles a single file per upload)
5. edited URL to reflect name of media page

Note 1: Did not see a place to include all displays, but that seems to be the default.

Note 2: 128MB is the default limit for uploads in my Drupal 8 install. Not optimal since there are 1,000+ files to upload, and not happy given Drupal's grand claims about media handling. But it is working though.

Note 3: Update. Host was kind enough to increase the max file upload in PHP to 256 so I am able to upload more files with each upload. Did need to reorganize folders and certain files offline first with naming conventions that will present a respectable order on the site. During the past several hours I was able to upload nearly half the files. Fair enough for half a day's work and a better than expected outcome.

# Answer
> 0 votes
Consider using Flysystem and Filefield\_sources\_flysystem.

With this approach, you can just place your files on Dropbox, Amazon S3, some FTP folder, etc. and the magic of Flysystem will enable you to attach them to file fields in Drupal and serve them to your site's visitors.

Filefield\_sources\_flysystem helps by enabling you to "pick" an individual file from your files folder (even if that's e.g. Dropbox) when editing a content item's file field in Drupal.

Batch processing 1000 files is still a little tricky, as the UI for associating files with Drupal content is always set up to do 1 (or at least a few) at a time. Migration is the best way of handling this that I know of. You can define a spreadsheet listing all the Drupal entities you wish to exist on a separate row each, specify the filenames or paths for each row, create a YAML file to that tells the Migrate module how to understand that spreadsheet, upload that migration file and trigger it. Not easy, but not hard core coding either.

---
Tags: 8, files, media
---


title: How to change $license->product_id?

text:
# Question
Title: How to change $license->product_id?
I've setup a Drupal Commerce site selling licensed roles per instructions on https://www.drupal.org/node/2039687 The same pages says:

> The customer receives the role referenced by the purchased license product. Changing $license-\>product\_id (from "Basic Membership" to "Premium Membership", for instance) changes the owner's role.

However, it is unclear how to change the $license-\>product\_id. Can anyone clarify can this be done in some kind of UI or rule, or if it should be done in custom module then which hook to use?

# Answer
I'm not sure there is an easy answer to this right now. Product IDs are updated on licenses when a line item is created or updated. This happens in `commerce_license_commerce_line_item_presave()`.

This gets complicated if you're using Commerce License Billing because your order renews according to your billing arrangement. If you are using that, then you'll need to review the code in there and figure out a way to save a new order that will be the one that gets renewed.

Otherwise, you could just create a new order, set the correct product, revoke the old license, and then complete the new order and then a user will have a new license and the old one will be gone.

If you have more questions, the issue queue is probably the best place to get help and provide feedback.
> 0 votes

---
Tags: commerce
---


# Question
Title: Change default Scald legend or caption output
I am sure the setting must be somewhere, but I only want to have the title as a default caption, the author field is irrelevant and the people updating content have to delete it each time.

**Update:**

I have found that going to Administration \> Structure \> Scald \> Image (/admin/structure/scald/image/player/full/image\_figure) I am able to alter the caption for that player, but not for the default player.

I have also found a hook in scald.api.php hook\_scald\_player(), but this is used like an info hook and using hook\_scald\_player\_alter() does not alter the value:

```
function mymodule_scald_player_alter(&$players) { // tried referencing
  $players['default']['settings']['caption'] = '[atom:title]';
  return $players; // tried returning
}

```

# Answer
It seems that you can alter the settings of players as much as you like, but it won't change the caption text because the pattern is hardcoded in the function `theme_sdl_editor_legend()` of the Scald module.

So we need to overwrite the output by something of our choice.

The previously mentioned theme function can be overwritten in your themes functions.php. Probably you use a Drupal Core or contributed theme as administrative theme, those template.php files you should not change. Thus the preferred method is below (a custom module).

Below you find a simple example of how to get rid of the "by" part in a custom module. Effectively we just completely overwrite the output of `theme_sdl_editor_legend()` using an implementation of the `hook_scald_dnd_library_item_alter()` hook. You can change `$item['meta']['legend']` to any string you like using data from `$atom`.

```
/**
 * Alter a scald library item.
 *
 * Implements hook_scald_dnd_library_item_alter()
 *
 * @param $atom
 *   The atom object.
 * @param $item
 *   The scald library item.
 */
function MODULE_scald_dnd_library_item_alter($atom, &$item) {
  $item['meta']['legend'] = "
   <div class='meta'>
    <!--copyright={$atom->sid}-->{$atom->rendered->title}<!--END copyright={$atom->sid}-->
  </div>
 ";
}

```
> 3 votes

# Answer
When the site is personal, or images are simple, you don't need neither want a caption or elaborate caption below the image as it breaks the esthetics of content. One may even prefer to have them a

If you are using CKEditor, the Drag and Drop Library configuration page (`admin/config/content/dnd`) allows doing away with Captions (all of them) but not part of them:

```
[ ] Enable captions by default

```

One would expect that changing the display at `admin/structure/scald/image/display` would take care of it (dragging fields not desired to hidden) or on a similar fashion. But it does not work.

Bottom line is there are plenty of situations where captions are not desired for images.

There seems to be no easy way of having them not added by default other than hard code edit or hiding them via css.
> 2 votes

---
Tags: 7, scald
---


title: Views Aggregation Problems

text:
# Question
Title: Views Aggregation Problems
I'm trying to work with aggregation in Views and I just can not seem to understand how to get it to do what it is supposed to be doing. First off, a simple example. I create a view with "Show" set to a parent table. (a list of accounts in this case). Next I add a relationship to a child table (a list of account entries). I add one field, the account name.

Finally I turn on aggregation and set the account name to "group by". The SQL statement it provides has no group by clause! The View says it is:

```
SELECT ledger_account.name AS ledger_account_name
FROM
{ledger_account} ledger_account
INNER JOIN {ledger_account_entry} ledger_account_entry_ledger_account
    ON ledger_account.aid = ledger_account_entry_ledger_account.aid

```

Where I would have expected

```
SELECT ledger_account.name AS ledger_account_name
FROM
{ledger_account} ledger_account
INNER JOIN {ledger_account_entry} ledger_account_entry_ledger_account
    ON ledger_account.aid = ledger_account_entry_ledger_account.aid
GROUP BY ledger_account_name

```

I know this is a simple example, but it's a piece to a larger summation with a few joins. However, if views isn't smart enough to do this correctly, or if I just fail to understand how to do this properly, my query will never work.

# Answer
For a short tutorial about the "aggregation" features of the Views module, refer to Using aggregation in Views. As an alternative, have a look at the (free) set of 30 video tutorials about the Views module. Specific to "Aggregation", you may want to look at these episodes (quotes are from the linked pages):

* The aggregation setting.

> ... makes Views return not one row per item in the database, but one row per aggregation group. Perhaps more importantly, it also makes it possible to count the number of items baked into each row, or sum them up, or calculate their average, or count the number of unique items, or…
* Aggregation and relationships.

> ... shows how to use the aggregation setting in Views in combination with relationships.
* Aggregation edge cases.

> ... shows some of the more rare use cases of aggregations in Views:
>
> + Using aggregation on filtering
>     + Using aggregation on sorting
>     + Using aggregation on contextual filters (which is currently broken)
>     + NOT aggregation on relationships (since aggregation doesn't apply to this handler)
>     + Using aggregation on multiple-value fields
> 2 votes

---
Tags: 7, views
---


# Question
Title: Intercept data of a field of a node Drupal 8
How can I intercept the data of a field when the user add's a node?

Below is the use case:

The user can input a address in a field, when the user submits the node. Drupal should make a rest request to the google maps distance matrix api. Then the returning value should be posted in that node. I can find enough example modules to export data from drupal through rest but not the other way around.

# Answer
That sounds like a job for `hook_node_presave(NodeInterface $node)` to me.

That is always called before a node is saved. To optimize it, you probably want to limit your call to only do it for new nodes or when the value changed (compare your field value with the value of $node-\>original, note that that only exits when updating, so you want to check something like this:

```
if (!empty($node->field_yourfield->value) && ($node->isNew() || $node->field_yourfield->value != $node->original->field_yourfield->value)) {
  // do your call here, change $node in any way you want and it will be saved with those updated values
}

```

The same works for any entity type. You could also limit it to running on form submissions, but this has the advantage that it also works in case nodes are updated or created through other ways.
> 1 votes

---
Tags: entities, 8, google-maps
---