# Question
Title: Changing an exposed filter to use check_plain() or filter_xss()
I have a view with a search filter. I am using **Acunetix** scanner to scan for vulnerabilities, which reports me an issue about the search filter. How do I alter it to use `check_plain(filter_xss($string))` or `filter_xss(check_plain($string))` in view exposed forms (a block, in my case)?

# Answer
You can write a form alter in your custom module. ie :

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'views_exposed_form') {
        $view = $form_state['view'];
        if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
            // alter your exposed form here
            $form['yourdata_item'] = check_plain(filter_xss($string));
        }
    }
}

```
> 1 votes

---
Tags: views, forms
---


# Question
Title: How to vote for both answers and question using the Answers module?
I am using Answers module. In that only for nodes of type ***Question*** I can add vote up/down field.

But I wonder how I can add a voting feature for the nodes of type ***Answer***?

# Answer
> 2 votes
Instead use Question/Answer module, it have the vote system for both question and answer

> It adds a question/answer section for website. Different from other modules, it uses only one node type for question, and the core comment.module for answer. This allow reutilisation of CCK, Views..

or

You can try Vote Up/Down module

> Allows votes on some drupal entities and provides the base for implementing votes on other entities

or take a look at Rate module

> This module provides flexible voting widgets for nodes and comments. Multiple ratings on the same node (i.e. for "comfort", "location", "services" etc.)

# Answer
> 1 votes
If you're using the most recent 7.x.-4.x version of the Answers module, then all that should be needed is to enable the "Answers Voting" submodule (which of course requires its dependencies to be enabled also).

To see it at work, head over to an online example from its demo site (this site has read only access for anonymous users though). Be aware that this demo version is a further enhanced version of the most recent dev release (eg the views have been enhanced) which will be pushed to D.O shortly), though there are no differences for the Answers Voting submodule as compared to what's available on D.O.

Disclosure: I'lm a co-maintainer of this module.

---
Tags: rating, 7
---


# Question
Title: How to activate some flag field when create a content?
I have a many *flag* fields. When Authenticated users bookmark a content, they can enter value in flag fields.

I want to activate some fields of flag field when I create (add) a content.

For example, I have many flag fields of colors. When I create (add) a content, I want to activate some of the flag fields of colors. Because I want users to enter value of some colors, not all of color's field.

When I create first content I want to active 5 fields and when I create second content I want active 3 fiels and etc. I want to active some fields when I creating a content actually I want to have a control on flag fields.

How can I do it?

# Answer
Consider using the Conditional Fields module. Excerpt from its project page:

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
>
> When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
>
> You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.
> 1 votes

# Answer
Okey, this one was fairly easy.

You will need the Flag per node module. Once you install this, you can select which flags are active for each node. Below are some screenshots, demonstrating how different flags are available for different nodes. You can see each node's view and edit pages, on the bottom right corner of the node view pages you can see the active flag fields:

---

## Node A

---

## Node B
> 0 votes

# Answer
I want to manage First Screenshot, not second Screenshot. First Screenshot is flag field, and second screenshot is flag type.
> 0 votes

---
Tags: flags
---


# Question
Title: How to replace "Enter quantity" text for Production variation?
I'm working on Drupal commerce kickstart.

On Product variation, I need to change the text **Enter quantity** to **Enter your quantities** and change **Add to Cart** to **Buy Now**.

I tried with form alter it works to change **Add to Cart** to **Buy Now** but its not working for **Enter quantity** to **Enter your quantities**.

Can any one help on this?

# Answer
> 1 votes
I too had the same problem. Because this text is hardcoded and there is no configuration for updating the text.

**Ways to change the text**

* Use String Overrides module.
* Do a form\_alter and change the text from **Add to Cart** to **Buy Now**

**Form Alter for Enter quantity**

```
function module_name_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_cart_add_to_cart_form') {
    $form['quantity']['#title'] = t('Enter your Quantities');
  }
}

```

Hope this code helps.

# Answer
> 0 votes
This string is being set by a form\_alter in the commerce\_kickstart\_product\_ui.module. You can use the module string\_overrides: https://drupal.org/project/stringoverrides to change the string, or You can use your own form alter code in a custom module but you may have to use the weight module https://drupal.org/project/modules\_weight so that your module executes it's code after te commerce module.

---
Tags: 7, commerce
---


# Question
Title: How do I count the number of Facebook likes in articles?
I am working on a Drupal 8 site. I added fblikebutton to my articles to enable users to like content.

Is it possible to get the number of likes for each article as field? I am using the Views module to show the latest 3 articles, as in the following screenshot.

>

# Answer
> 0 votes
Probably setting the layout to **button\_count** will do all the magic ;) This should be available in settings, or can be changed in MYTHEME\_preprocess\_fblikebutton.

Or use modules which provide this functionality, like:

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


title: how to add checkbox value as json data

text:
# Question
Title: how to add checkbox value as json data
I have created a custom module for a form. And I have json data which I want to add as checkbox values.

```
$request = drupal_http_request($url);
$jsonarray =drupal_json_decode($request->data);
print_r($jsonarray);
 foreach($jsonarray as $info) {
$output1 =$info[0];
$output2 =$info[1];
$output3 =$info[2];
}

 echo $output1;

```

# Answer
> 0 votes
Set

`'#checked' => !empty($default_value)?1:0,`

in your form checkbox field.

---
Tags: 7, forms
---


title: Passing values to a view block

text:
# Question
Title: Passing values to a view block
I have a page that contains 4 separate blocks, from the same view,

Items block 1 - this contains a list of item titles Items block 2 - this contains a different list of item titles Content block 3 contains content unrelated to this functionality Results block 4 - this needs to display the details of the items that are highlighted in the above 2 sections after the user selects 'Next' in list 2.

I've found some information about passing variables to a view using contextual filters, but I'm not clear on exactly how this works still

* how do I set up a filter - does it go in the source or target block or both?
* how do I access the value in the target block?
* how do the values get passed, on the URL, or as session values?

also my situation involves passing variables from 2 view blocks to another view block.

And presumably AJAX would need to be used to load the third view?

I could split the third block into 2 and display results from block one and block two separately, if that's any easier.

But I'm really not sure how to set up a filter or how to use the passed values, or how exactly contextual filters work, any guidance appreciated.

Update: I have updated this question to try to make it clearer what I have and what I need to do.

Thanks to Remy I understand how the filter value is accessible, but I still don't understand the following:

* Is there something I have to do to enable a block to be able to receive parameters (does it need to be an attachment, an embedded view, or something else)?

# Answer
> 0 votes
Placing the contextual filter in the master view makes sense if every display has it, thus it still can be overridden. If there is only one block display out of X other displays, I would place the contextual filter in that display.

The contextual filter will be available as 'field' in your view and you can use it in the filter-criteria.

Contextual filters are passed via the url (in most cases), no matter if AJAX or not. Or when using views\_embed\_view as method-arguments.

***For your propose, conditional filters nor relationships will not work.***

You could then add the other view display as fields and make them conditional. But this is not really good practice nor performant. (Use also a caching module)

From views\_field\_view:

> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.

A ctools tools multi step form wizard is a better approach. here's an example https://github.com/jgottwig/ctools-wizard-example.

---
Tags: 7, views
---


# Question
Title: Check whether a field value exists in a custom table when a webform is submitted
I created a custom table named **"test\_customerid"** for the use of select queries from the drupal database. The fields are naid (for national id), name and surname.

My aim is to display an error message if the user attempts to insert an National ID which is already present in the table. Otherwise, all information are added to the table "test\_customerid". **This must occur when a webform is submitted**.

Here are my codes that I included in the webform.module of my drupal project (inside **function webform\_webform\_submission\_insert($node, $submission)**):

```
$accessnode=$node->nid;
if($accessnode==6)
{
    $dataSub=$submission->data[1]['value'];//submitted value of National ID

    $result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub));
    if(!(empty($result)))//I also tried "if($result)"
    {
        drupal_set_message(t('The NID already exists.'), 'error');
    }
    else
    {

        db_insert('test_customerid')
        ->fields(array(

        'naid' => $submission->data[1]['value'],
        'name' => $submission->data[2]['value'],
        'surname' => $submission->data[3]['value'],
        ))
        ->execute();
    }

```

The problem is: It displays the error message even if the user inputs a new National ID. I can't add new information in the table.

I even tried to convert the data into strings by using these before placing the variable into the insert query but it gives me the same error message:

* $dataconvert=implode(",",$dataSub);
* $dataconvert=serialize($dataSub);

I want that the query to take the National ID value from the webform and check out if it exists in the table. Can you someone help me with this please?

# Answer
> 1 votes
Just replace

```
$result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub));

```

with

```
$result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub))->fetchAll();

```

and try, hope it will work

# Answer
> 0 votes
It should be like

```
$accessnode=$node->nid;
if($accessnode==6) {
  $dataSub=$submission->data[1][0];//submitted value of National ID

  $result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub));
  if(!(empty($result))) {
    drupal_set_message(t('The NID already exists.'), 'error');
  }
  else {
    db_insert('test_customerid')
    ->fields(array(

    'naid' => $submission->data[1][0],
    'name' => $submission->data[2][0],
    'surname' => $submission->data[3][0],
    ))
    ->execute();
  }
}

```

$submission-\>data\[1\]\['value'\] does not exist in the $submission object. Change this to $submission-\>data\[1\]\[0\] and it will start working.

Also you have to change

```
db_insert('test_customerid')
  ->fields(array(
    'naid' => $submission->data[1]['value'],
    'name' => $submission->data[2]['value'],
    'surname' => $submission->data[3]['value'],
))
->execute();

```

query as well.It should be

```
db_insert('test_customerid')
  ->fields(array(
    'naid' => $submission->data[1][0],
    'name' => $submission->data[2][0],
    'surname' => $submission->data[3][0],
))
->execute();

```

Hoping that this would solve the problem of yours.

---
Tags: 7, database, webforms
---


# Question
Title: find Menu Settings of node, given URL alias (or node ID)
In the Drupal 8 screen for editing a node, we have these two sections:

> URL Path Settings \> URL alias
>
> Menu Settings (Menu link title, Description, Parent item, Weight)

How, given the URL alias of a node, can we get those Menu Settings, particularly the *Menu link title*?

This may break down into two separate problems:

1. finding the node ID from the URL alias
2. finding the Menu Settings from the node ID

and in fact I would be thrilled at a solution to either one, even as a high-level explanation.

I would go into detail about how I've attempted to answer this question already, and the services & classes that appear to be relevant, but I don't want to post a complicated-looking question. If data is that easy to put into those basic fields in the UI, it should at least be possible for some module code to get it back out.

# Answer
Comments in my question getting URL from Route: breaks in localhost subdirectory have clarified that the solution of @4k4 is absolutely the right way to get the alias from the current path. But the alias is not as useful as I thought in applying suggestion (@Ivan Jaros) to use `entityQuery` to take it the rest of the way, since the current path is able to match the `link.uri` field of `menu_link_content`, except for a leading slash in the pathname and the `entity:` protocol:

```
$current_path = \Drupal::service('path.current')->getPath();
$system_uri = 'entity:' . trim($current_path, '/');

$query = \Drupal::entityQuery('menu_link_content')
  ->condition('link.uri', $system_uri)
  ->condition('menu_name', 'main');

$result = $query->execute();
$menu_link_id = (!empty($result)) ? reset($result) : FALSE;

if ($menu_link_id) {
  $menu_link = MenuLinkContent::load($menu_link_id);
  $menu_link_title = $menu_link->getTitle();
} else {
  drupal_set_message(t('no Menu Link Content for ID that we found...'), 'error');
}

```
> 2 votes

# Answer
I only can answer the first part of the question.

The path to the node is not a basic field, as it appears to be because it is in the node form beside the basic fields.

The url aliases are stored in the table "url\_alias".

You can access the data directly or use the alias manager to access the alias by providing the node id or vice versa to get the path which then contains the node id:

```
$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid);
$path = \Drupal::service('path.alias_manager')->getPathByAlias($alias);

```
> 1 votes

---
Tags: nodes, 8, routes, path-aliases
---


# Question
Title: How do I render my date field using my custom date format?
I have a content type with two "date and time" fields, configured to display in "22 November 2012 5:19pm" format:

On the item itself, the start and end dates are both set to include times:

In my node.tpl.php, I output the two fields:

```
print drupal_render(field_view_field('node', $node, 'field_date'));
print drupal_render(field_view_field('node', $node, 'field_end_datetime'));

```

However, the two fields are displayed without the time:

> **Start Date and Time**: 02 December 2012
>
> **End Date and Time**: 02 December 2012

How do I output these two fields using my custom date format?

# Answer
In the node template you should be able to output your dates with your selected format by doing:

```
print render($content['field_date']);
print render($content['field_end_datetime']);

```
> 4 votes

# Answer
If you use field\_view\_field for formatting date, pass **$display** parameter as defined below:

```
$display = array('settings' => array('format_type' => 'medium'));
$output = field_view_field('node', $node, 'field_date_time', $display);

```

*format\_type* \- is any valid date-time format name, defined in admin/config/regional/date-time of your drupal site.
> 4 votes

# Answer
You may need to use `field_view_value()` to just show the formatted value.

Similar question which may be of use here:

How do I render a field value including its format?
> 1 votes

# Answer
I used this to create and render the date without a label.

```
$display = array('settings' => array('format_type' => 'medium'),'label'=>'hidden');
$output = field_view_field('node', $node, 'field_date', $display);
print render($output);

```

Then you can subsitute the machine name for your custom date format where it says 'medium'.
> 1 votes

---
Tags: 7, entities, datetime
---


# Question
Title: How to save custom commerce_profile_reference field widget data
**Description:**

My drupal commerce line-item's have extra "add-to-cart form" fields attached to the line-item type.

One of the fields is a field-collection that contains 2 fields:

1. A customer\_profile\_reference field with a custom widget (basically the same as an address field)
2. A custom field for time-window

When I loop through the line-items on "Checkout:Complete" with a rule action, I get the field value in the field collection as the field collection entity id, which I suppose is fine. When I now load the field\_collection\_item i get this:

**Problem:**

The field\_delivery\_profile, which is the customer\_profile\_reference field, does not show a value, and now I find out that the values aren't stored.

For the custom field + custom field widget I've created, everything works as intended.

The field widget for the custom customer\_profile\_reference field is basically a select list with profile\_id's as the value, and I'm not sure now do I have to somehow specifically write some sort of a save hook? Because for the custom field + field widget module, all I've done is a presave for the field. By default this field stores only an id (for the profile to reference) and shouldn't need anything extra.

Or is there a specific way I have to build the options list? Currently the options list gets built like this:

```
foreach (commerce_customer_profile_load_multiple($profiles) as $profile) {
        $options[$profile->profile_id] =
            $profile->commerce_customer_address["und"][0]["name_line"].", ".
            $profile->commerce_customer_address["und"][0]["thoroughfare"].", ".
            $profile->commerce_customer_address["und"][0]["postal_code"].", ".
            $profile->commerce_customer_address["und"][0]["country"];
    }

```

And implemented as the element like this:

```
$element['select_address'] = array(
            '#type' => 'select',
            '#options' => $options,
            '#default_value' => $default,
            '#title' => t('Address'),
            '#required' => TRUE,
            '#id' => $element_id,
        );

```

**Edit:**

I have found out, that at one point it used to work, and has values in the db, however I've no way of pinpointing what has changed. Comparing the older versions of the module file, I see that they're essentially same, and even when reverting back to the older one, it doesn't seem to store data. What else could be causing this?

**Edit 2:**

Added a custom validation function to the widget element, and the $element\['#value'\] exists and is proper. I am however clueless as to why it's not being stored to the database.

**Edit 3:**

I've been struggling with this issue now for 3 days without any clear idea what could be causing it. I've debugged everything I can think of, and yet the code from when it was working does not differ by much, and even using the old code doesn't seem to remedy the situation.

This is the $element array from a validation function:

```
function _validate_cosmobutler_address($element, &$form_state, $form) {
    dpm($element);
}

```

As can be seen, it has the value of a profile id, as it's supposed to. Also the database table commerce\_profile\_reference field created when first creating the field is the following:

```
Table: field_data_field_delivery_profile
Columns:
   entity_type varchar(128) PK
   bundle varchar(128)
   deleted tinyint(4) PK
   entity_id int(10) UN PK
   revision_id int(10) UN
   language varchar(32) PK
   delta int(10) UN PK
   field_delivery_profile_profile_id int(10) UN

```

I've also tried changing the element creation from:

```
$element['select_address']

```

to:

```
$element['value']

```

But that didn't seem to help either.

**Edit 4:**

I've deducted that the problem must come somewhere from the custom widget implementation, as the same field with a different widget stores data well.

The complete widget code can be found here:

http://kopy.io/5unZS

**TL;DR Summary:**

I'm unable to store data for customer\_profile\_reference field from a custom field widget. The storeable data should only require an id (of the profile), which are my select list options values anyway. The code for both options list and element implementation is above. The field seems to have stored values in the past but isn't any longer, so I'm hoping someone can give me more debuging insights or maybe can pinpoint the issue based on these descriptions.

Hope someone has a solution I may have overlooked.

Best,

Alari

# Answer
> 1 votes
So, finally overpowered the issue.

Apparently for the commerce customer\_profile\_reference field the widget for the field element has to be created with "profile\_id" as the array key (name).

I'm having difficalty understanding why exactly as the default core select options widget does not have this but in the end the following code for implementation worked:

```
$element['profile_id'] = array(
            '#type' => 'select',
            '#options' => $options,
            '#default_value' => $default,
            '#title' => t('Address'),
            '#required' => TRUE,
            '#id' => $element_id,
        );

```

Hopefully, if anyone is ever tackled by the same issue, this is of help.

---
Tags: 7, commerce, entities
---


title: Add class to section in tpl

text:
# Question
Title: Add class to section in tpl
In my template (Bootstrap), in the following line:

```
<section<?php print $content_column_class; ?>>

```

I need to add a custom class AND keep the dynamic column class. I tried `<section class="myclass <?php print $content_column_class; ?>">` but it give me:

```
<section class=" class=" myclass"="" col-sm-12"="">

```

Any idea what to do?

# Answer
Try

```
<?php print $content_column_class; ?>

```

and see what is exactly printed

I think you should try something like this instead

```
<section class="<?php print "myclass ".$content_column_class; ?>">

```

Hope This helps Cheers
> 1 votes

# Answer
there is two option to fix this :

1) Add the following code in your .tpl file to add your custom class

`$content_column_class = implode(" myclass", str_split($content_column_class, 16));`

2) In Bootstrap theme folder go to template \> system folder and then open page.vars.php file and and copy

`function bootstrap_preprocess_page(&$variables) {
 if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
 $variables['content_column_class'] = ' class="col-sm-6"';
 }
...//Rest of the code
}` and create a sub theme with template.php and override the above function in template.php :

`function mytheme_preprocess_page(&$variables) {
if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
 $variables['content_column_class'] = ' class="col-sm-6 myclass"';
 }
}`
> 0 votes

---
Tags: theming
---


# Question
Title: How to style answers from the Answers module to make them look as in the demo site?
The voting element of the Answers module does not look as in the following screenshot:

What should I do to make them appear as in the screenshot?

# Answer
> 1 votes
First you should enable vote\_up\_down Field module too, so you can add it to your preferred content-type (e.g answers), while adding it, in settings it asks which kind of widget to use; set it as default, then it will be like in your picture, without any need of altering the used CSS styles. If you still dont get your desired look, it must be the CSS styles that are overwritten. Inspect the element, and look for it.

# Answer
> 0 votes
The screenshot in the question here is from the prior release of the Answers module, and the demo site where that screenshot originated from does not exist anymore (now replaced by a new demo site).

The newest 7.x-4.0 version comes with the (new) `Answers Theme` sub-module, which, out-of-the-box, transforms the (rather boring) vanilla display of a Question (and its related Answers below it), into a way more attractive look-and-feel. Such as the orange bubble that is added around the question (to better highlight it). If you don't enable this sub-module, then you get a similar vanilla display (still).

To see this newest version at work, head over to this example question (from its new demo site). Here is a screenprint that is pretty close to what's included in the newest version:

Something that I think make sense as a future enhancement of this (new) sub-module, is to add a notion of "skins", consisting of a combination of CSS and/or JS, so that the purely theming (colors, buttons, etc) could be done as much as possible by tuning the delivered skins, or creating your own new skins.

Disclosure: I'm a co-maintainer of Answers.

---
Tags: theming, 7
---


# Question
Title: How to get the node ids of answers for a question in Drupal Services (REST)?
I have a Drupal setup that is currently having a question and answers module.

I am able to read the question and answers by accessing `http://mysite.tld/rest_endpoint/node/{nodeid}` . However when I access a question, I am not able to get the nodeIds of all the answers to that question.

So I am looking to get the Node Ids for all the answers for a specific question.

* What params/filters do I need to use in the Drupal Services GET call? I have services module.
* Can I achieve this by doing a database query? I am not able to find a link between questions and answers in the DB too!

Any suggestions?

# Answer
> 4 votes
I didn't know what are **question and answers modules** that you used. My assumption is your answer and your question has a content type and they linked together. So if my assumption is correct here is the way that you can use for solving your problems:

1. Create a views will list all the **answers** of specific **question**(your question nid).
2. using Views Services to get the views that you created before and use your question (question nid) for the views parameter.

In case my assumption is wrong. Your have to create custom resource by your own to get the list of answers. In this way you must create your SQL sentences too. The reference for creating custom resource here

# Answer
> 0 votes
Have a look at this (exported) **custom view** related to the Answers module, which lists all existing answers for any of the existing questions:

```
$view = new view();
$view->name = 'answers';
$view->description = '';
$view->tag = 'answers, answers_best_answer, answers_userpoints, answers_voting';
$view->base_table = 'node';
$view->human_name = 'Answers';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'All Answers';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['style_plugin'] = 'datatables';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'name' => 'name',
  'value' => 'value',
  'flagged' => 'flagged',
  'nid' => 'nid',
  'created' => 'created',
  'changed' => 'changed',
  'new_answers' => 'new_answers',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'name' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'value' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'flagged' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'nid' => array(
    'sortable' => 1,
    'default_sort_order' => 'desc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'created' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'changed' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'new_answers' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['style_options']['elements'] = array(
  'search_box' => 1,
  'table_info' => 1,
  'save_state' => 1,
  'table_tools' => 0,
);
$handler->display->display_options['style_options']['layout'] = array(
  'autowidth' => 0,
  'themeroller' => 0,
  'sdom' => '',
);
$handler->display->display_options['style_options']['pages'] = array(
  'pagination_style' => 'full_numbers',
  'length_change' => 1,
  'display_length' => '25',
);
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['area']['id'] = 'area';
$handler->display->display_options['empty']['area']['table'] = 'views';
$handler->display->display_options['empty']['area']['field'] = 'area';
$handler->display->display_options['empty']['area']['label'] = 'No Questions Blurb';
$handler->display->display_options['empty']['area']['empty'] = TRUE;
$handler->display->display_options['empty']['area']['content'] = 'No questions have been entered yet';
$handler->display->display_options['empty']['area']['format'] = 'filtered_html';
/* Relationship: Userpoints total: User */
$handler->display->display_options['relationships']['uid_1']['id'] = 'uid_1';
$handler->display->display_options['relationships']['uid_1']['table'] = 'userpoints_total';
$handler->display->display_options['relationships']['uid_1']['field'] = 'uid';
/* Relationship: Content: Vote results */
$handler->display->display_options['relationships']['votingapi_cache']['id'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['table'] = 'node';
$handler->display->display_options['relationships']['votingapi_cache']['field'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['votingapi'] = array(
  'value_type' => 'points',
  'tag' => '',
  'function' => 'sum',
);
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Relationship: Entity Reference: Referenced Entity */
$handler->display->display_options['relationships']['answers_related_question_target_id']['id'] = 'answers_related_question_target_id';
$handler->display->display_options['relationships']['answers_related_question_target_id']['table'] = 'field_data_answers_related_question';
$handler->display->display_options['relationships']['answers_related_question_target_id']['field'] = 'answers_related_question_target_id';
$handler->display->display_options['relationships']['answers_related_question_target_id']['required'] = TRUE;
/* Relationship: Flags: best_answer */
$handler->display->display_options['relationships']['flag_content_rel']['id'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['table'] = 'node';
$handler->display->display_options['relationships']['flag_content_rel']['field'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['required'] = 0;
$handler->display->display_options['relationships']['flag_content_rel']['flag'] = 'best_answer';
$handler->display->display_options['relationships']['flag_content_rel']['user_scope'] = 'any';
/* Relationship: Userpoints total: User */
$handler->display->display_options['relationships']['uid_2']['id'] = 'uid_2';
$handler->display->display_options['relationships']['uid_2']['table'] = 'userpoints_total';
$handler->display->display_options['relationships']['uid_2']['field'] = 'uid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'answers_related_question_target_id';
$handler->display->display_options['fields']['title']['label'] = 'Question';
/* Field: Userpoints total: Current total reputation */
$handler->display->display_options['fields']['points']['id'] = 'points';
$handler->display->display_options['fields']['points']['table'] = 'userpoints_total';
$handler->display->display_options['fields']['points']['field'] = 'points';
$handler->display->display_options['fields']['points']['exclude'] = TRUE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
$handler->display->display_options['fields']['name']['label'] = 'Answered by';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['name']['alter']['text'] = '[name]
([points])';
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
/* Field: Vote results: Value */
$handler->display->display_options['fields']['value']['id'] = 'value';
$handler->display->display_options['fields']['value']['table'] = 'votingapi_cache';
$handler->display->display_options['fields']['value']['field'] = 'value';
$handler->display->display_options['fields']['value']['relationship'] = 'votingapi_cache';
$handler->display->display_options['fields']['value']['label'] = 'V';
$handler->display->display_options['fields']['value']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['value']['precision'] = '0';
/* Field: COUNT(Flags: Flagged) */
$handler->display->display_options['fields']['flagged']['id'] = 'flagged';
$handler->display->display_options['fields']['flagged']['table'] = 'flagging';
$handler->display->display_options['fields']['flagged']['field'] = 'flagged';
$handler->display->display_options['fields']['flagged']['relationship'] = 'flag_content_rel';
$handler->display->display_options['fields']['flagged']['group_type'] = 'count';
$handler->display->display_options['fields']['flagged']['label'] = '';
$handler->display->display_options['fields']['flagged']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['flagged']['alter']['text'] = '';
$handler->display->display_options['fields']['flagged']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['flagged']['empty_zero'] = TRUE;
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['label'] = 'Answer';
$handler->display->display_options['fields']['nid']['link_to_node'] = TRUE;
/* Field: Content: Post date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = 'Created';
$handler->display->display_options['fields']['created']['date_format'] = 'short';
$handler->display->display_options['fields']['created']['second_date_format'] = 'long';
/* Field: Content: Updated date */
$handler->display->display_options['fields']['changed']['id'] = 'changed';
$handler->display->display_options['fields']['changed']['table'] = 'node';
$handler->display->display_options['fields']['changed']['field'] = 'changed';
$handler->display->display_options['fields']['changed']['label'] = 'Updated';
$handler->display->display_options['fields']['changed']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['changed']['date_format'] = 'short';
/* Field: Answers: Has new content */
$handler->display->display_options['fields']['new_answers']['id'] = 'new_answers';
$handler->display->display_options['fields']['new_answers']['table'] = 'answers';
$handler->display->display_options['fields']['new_answers']['field'] = 'new_answers';
$handler->display->display_options['fields']['new_answers']['label'] = 'New';
/* Sort criterion: Content: Nid */
$handler->display->display_options['sorts']['nid']['id'] = 'nid';
$handler->display->display_options['sorts']['nid']['table'] = 'node';
$handler->display->display_options['sorts']['nid']['field'] = 'nid';
$handler->display->display_options['sorts']['nid']['order'] = 'DESC';
/* Contextual filter: Content: Author uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'node';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'answers_answer' => 'answers_answer',
);
$handler->display->display_options['filters']['type']['group'] = 1;

/* Display: Answers */
$handler = $view->new_display('page', 'Answers', 'page');
$handler->display->display_options['display_description'] = 'List of all answers';
$handler->display->display_options['defaults']['arguments'] = FALSE;
$handler->display->display_options['path'] = 'answers';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'Answers';
$handler->display->display_options['menu']['description'] = 'All Answers';
$handler->display->display_options['menu']['weight'] = '1';
$handler->display->display_options['menu']['name'] = 'menu-answers-menu';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$handler->display->display_options['tab_options']['weight'] = '0';

/* Display: Answers by User */
$handler = $view->new_display('page', 'Answers by User', 'page_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Answers by author (uid = %1)';
$handler->display->display_options['display_description'] = 'List of all answers from a specific user';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'datatables';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'value' => 'value',
  'flagged' => 'flagged',
  'nid' => 'nid',
  'created' => 'created',
  'changed' => 'changed',
  'new_answers' => 'new_answers',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'value' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'flagged' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'nid' => array(
    'sortable' => 1,
    'default_sort_order' => 'desc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'created' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'changed' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'new_answers' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['style_options']['elements'] = array(
  'search_box' => 1,
  'table_info' => 1,
  'save_state' => 1,
  'table_tools' => 0,
);
$handler->display->display_options['style_options']['layout'] = array(
  'autowidth' => 0,
  'themeroller' => 0,
  'sdom' => '',
);
$handler->display->display_options['style_options']['pages'] = array(
  'pagination_style' => 'full_numbers',
  'length_change' => 1,
  'display_length' => '25',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'answers_related_question_target_id';
$handler->display->display_options['fields']['title']['label'] = 'Question';
/* Field: Vote results: Value */
$handler->display->display_options['fields']['value']['id'] = 'value';
$handler->display->display_options['fields']['value']['table'] = 'votingapi_cache';
$handler->display->display_options['fields']['value']['field'] = 'value';
$handler->display->display_options['fields']['value']['relationship'] = 'votingapi_cache';
$handler->display->display_options['fields']['value']['label'] = 'V';
$handler->display->display_options['fields']['value']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['value']['precision'] = '0';
/* Field: COUNT(Flags: Flagged) */
$handler->display->display_options['fields']['flagged']['id'] = 'flagged';
$handler->display->display_options['fields']['flagged']['table'] = 'flagging';
$handler->display->display_options['fields']['flagged']['field'] = 'flagged';
$handler->display->display_options['fields']['flagged']['relationship'] = 'flag_content_rel';
$handler->display->display_options['fields']['flagged']['group_type'] = 'count';
$handler->display->display_options['fields']['flagged']['label'] = '';
$handler->display->display_options['fields']['flagged']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['flagged']['alter']['text'] = '';
$handler->display->display_options['fields']['flagged']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['flagged']['empty_zero'] = TRUE;
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['label'] = 'Answer';
$handler->display->display_options['fields']['nid']['link_to_node'] = TRUE;
/* Field: Content: Post date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = 'Created';
$handler->display->display_options['fields']['created']['date_format'] = 'short';
$handler->display->display_options['fields']['created']['second_date_format'] = 'long';
/* Field: Content: Updated date */
$handler->display->display_options['fields']['changed']['id'] = 'changed';
$handler->display->display_options['fields']['changed']['table'] = 'node';
$handler->display->display_options['fields']['changed']['field'] = 'changed';
$handler->display->display_options['fields']['changed']['label'] = 'Updated';
$handler->display->display_options['fields']['changed']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['changed']['date_format'] = 'short';
/* Field: Answers: Has new content */
$handler->display->display_options['fields']['new_answers']['id'] = 'new_answers';
$handler->display->display_options['fields']['new_answers']['table'] = 'answers';
$handler->display->display_options['fields']['new_answers']['field'] = 'new_answers';
$handler->display->display_options['fields']['new_answers']['label'] = 'New';
$handler->display->display_options['path'] = 'user/%/answers';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'Answers';
$handler->display->display_options['menu']['description'] = 'Answers';
$handler->display->display_options['menu']['weight'] = '5';
$handler->display->display_options['menu']['name'] = 'user-menu';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$handler->display->display_options['tab_options']['weight'] = '0';

```

You can see it at work in the demo site of the Answers module. It uses the dataTables format, but you could easily replace that with any views display format you'd want.

By using this view, you should be able to:

* tune the fields, sorting, etc to fit your needs.
* addng a filter for the question for which you want to retrieve all answers.
* use the Services Views module to ***get the nodeIds of all the answers to that question***.

---
Tags: services, 7
---


# Question
Title: With current D8 status, what's the decision tree for creating a new content entity type versus creating a Content Type for the "Node" content entity?
We have seen four years and Drupal 8's first release since the accepted answer was written for the question "When is it appropriate to create an Entity versus just adding a new content type?" And, entities are more central to Drupal 8 than they were in Drupal 7.(RefB, RefC, RefD)

**In this new Drupal 8 world, what is the decision tree for creating a new content entity type versus a new Content Type for the content entity of type "Node"?**

As you consider a response, please consider the following:

* Is a new Content Type for the content entity type of "Node" still appropriate in 99% situations versus a new content entity type?
* Does the decision tree now include more, better, or clearer reasons to veer away from using the "Node" content entity type and instead create a new content entity type? And if yes, what are they? Do they include:
    + Performance?
    + Security/permissions?
    + The number of modules that work with Node-entity-type Content-Types and do not work with other content entity types?
* Perhaps -- based on the previous accepted answer that is referenced above -- the only general reason to do a custom content entity type is if you want to group Node data, e.g. with taxonomy terms, or otherwise annotate Node, e.g. with comments?

Module compatibility seems like a particularly interesting consideration for a decision tree. At present, few of the most-installed modules have a release for 8.x that is not merely alpha, beta, or rc (a release candidate). And it seems difficult to identify how many of them will work out-of-the-box with a new custom entity type versus a new Node-entity content type. There does not appear to be a project attribute to distinguish between those that are "written for entities" versus "written for node entity content types".

Take a look at pathauto, which is currently the fourth-most installed module of those that have any kind of 8.x release. Folks are working hard on a 8.x version that generally supports entities and not just Node-entity-type Content Types. But what about all the other modules? And will modules that support entities going to generally require custom content entity types to have module-specific "hooks" before the module will work with them? (Versus how the modules may just work straight out of the box with new Content Types?) That appears to be the kind of challenge the pathauto team is working with, and perhaps it is a reason to veer away from a custom content entity type?

It might also be worth mentioning that Drupal 8 core contains a UI for creating new Content Types for the content entity of type "Node", but it does not currently contain a UI for creating new content entity types. (RefX, RefY, RefZ)

# Answer
Decision tree for choosing between creating a new Node-entity-type Content Type versus a new content entity type:

1. Are you a programmer, or do you have easy access to a programmer?
    * If no, then you are presently pretty-much limited to creating new Node-entity Content Types. (There isn't a UI in core for creating new content entity types, and the Entity Construction Kit (ECK) contrib module currently only has an alpha release.)
    * If yes, then continue...
2. Do you know exactly which contrib modules you want to leverage for your data?
    * If no, then the safe bet is probably to just create a Node-entity Content Type.
    * If yes, do those modules already support the custom entity type(s) you're considering, or are you willing to help enhance them so they will or recreate the desired functionality in your module?
        + If no, then just creating a Node-entity-type Content Type may be best for you.
        + If yes, then continue...
3. Will the actual content data that is enabled by your module merely help group or annotate other content data? (So that it will seldom be viewed on its own.)
    * If yes, then consider whether your module is like the existing entity types for taxonomy terms and comments. If it is, then a new entity type may be a safe bet.
    * If no, then continue...
4. Can you clearly articulate why a new Node-entity-type Content Type will not work for you?
    * If no, then your safe bet is to probably just create a new Node-entity-type Content Type.
    * If yes, then continue...
5. Lastly, are you sure that you can't just extend the Node-entity-type and that you want to recreate all of its useful functionality like CRUD operations?
    * If yes, then go ahead and create a new custom entity type.
    * If no, or if you're not sure, then you probably want to engage some experts to help you decide.

Notes:

1. This decision tree does not consider performance or security. I'm not sure if or when a new custom content entity type would perform better and be more or less secure than a Node-entity-type.
2. Even if this tree is a good answer, it will probably not remain one over time due to updates in Drupal core and contrib module releases. StackExchange doesn't seem to accommodate how the "best" answer today may not be the best answer tomorrow.)
> 17 votes

# Answer
**A simple approach** about that issue is to take in consideration the project purpose, size and business requirements.

1. **How** default node-entity content type affect building the project in an easy, neat way closer to the architecture and data flows produced from the analytic thinking of project docs.

**An important notice** here the decision of creating new entity type usually took by developers or technical leads not site builders or project owners that manage the application and only focus on business.

2. **Drupal 8** depends on some symfony2 packages and is more close to frameworks, development that traditional cms talking about Drupal with that big architectural changes, I envision building a new entity is better than doing many customization and complex configurations over node-entity content types in order to leverage Drupal among other frameworks as many people don't love the way Drupal configuration and distributed settings, You may face some people comes from WordPress and used to config every thing from one form which makes them annoyed when dealing with the Drupal admin dashboard.
3. **Drupal 9** plans to totally remove hook system and replace with **event dispatcher** that leads to a big need for an admin interface to create a new entity as altering existing functionality from code will be much harder to people who are not developers and will be very essential to add that feature.

**At the end**, I see new entities tailored for the project needs gives high performance better than complex content types with big numbers of fields as we now each field adds 2 tables to the DB and needs to load its config on each request, especially with the heavy business logic required.
> 3 votes

# Answer
**Plain and simple: It's not all content.** The list of the content could go quite long and be confusing if you're just using content types. (*ContentEntityBase* could also be implemented by a custom entity thoe)

> *If you have an author and published state* you should go for a content type.

---

Otherwise (assuming your a programmer) custom entities should be preferred. A lot can be easily implemented with all the interfaces (like revision-able, field-able, access restriction etc.)

> In my view this is just clearer and **tail-ordered architecture** (and also more performant).

Thinking of reusability in several projects the effort to make the custom entities blow out .. there are also nifty helpers like drupal-code-generator. To keep custom coding (or complexity) at a low level you should consider using content types if you want:

* To translate the 'entity' (at least in D7), there would be also an interface.
* (open for suggestions) ..
> 3 votes

# Answer
It is a tough question that honestly I think is only understood once you have implemented it before. But as remy metioned, **not everything is raw, user facing content**.

In Drupal 7, the capability of creating custom entities existed, but could be a daunting task if you were rough around the edges with OOP. It was kind of half implemented (or half done, however you want to say it), which lead to ways of creating entities that were not all exactly uniform and agreed upon approaches, with mixed procedural and mixed OOP.

In Drupal 8, the idea is much more realized, and it is a lot easier to get up and running with a custom entity. Node itself is based on ContentEntityBase, as are Blocks, Users, File, and Taxonomy.

Nodes are *specifically* for published, visible (or authorized) content data that typically act as content (that is, in a menu, or in the sitemap, or xml sitemap, or RSS feeds, etc). Drupal was designed in a way where you could hook in to any step of the process of node operations and alter it which can have unintended consequences if you have the wrong mix of contributed modules. This is probably a controversial opinion, but it helps to divorce yourself from the idea of "everything is a node" in order to embrace the Entity concept more.

Ideal content that make great content types:

* Article
* Page
* Job posting
* Event
* Landing Page
* Homepage

The common thread to them is that they share a concept of a type of content. It is usually in any number of workflow states (published, promoted, sticky, archived, featured, etc - if you use custom publish options), and a large number of contributed modules interact with it directly, like Pathauto.

But lets assume you want to store data in Drupal that is internal, private, drives other data, or data that should not allow integration outside of its scope unless you allow it. What kind of data could this be? Here are some possible types:

* Product (Drupal Commerce)
* Line Item (Drupal Commerce)
* Search server (ApacheSolr / SearchAPI)
* Contact (like CRM lead)
* Ticket (like support ticket)

What makes these so different? Why would you want an entity for contact, instead of use the User model? You could make a few arguments there, but my example would be that if you are say, collecting email addresses and names and some other meta data from a contact form, store that data as an custom entity. You prevent the user list from being polluted with non-account items, you reduce potential security issues (what if a script or someone accidentally updated those accounts to be admins or sent a mass mail?), you make internal overhead management of the actual user accounts easier, and you segment what you are capturing out to what it is, a specialized bit of data.

From here, it is largely divorced from the more automatic parts of Drupal/Node system and you can tailor the actions and experience. You determine the routes, access, and CRUD workflow.

In that mindset, it makes it easier to view why the approach to that would be done that way. Take the support ticket example - it is incoming requests, but isn't published data, and likely has a very specific workflow that is easier to setup your way than to divorce it from parts of the node system you don't want it to adhere to.

Another example would be external, imported data. In most cases, this data usually is not enriched with local Drupal data (even if it is, as an entity, you can still do it). It could be anything. Maybe it's invoices, maybe they are books, maybe it is pulling brands of beer.

Data like this is usually specific and requires control beyond what node is meant for. That isn't to say that you can't augment it by using a reference field on a node to point to your custom entity (this is how Drupal Commerce worked, at some level) to enrich the data. At the same time, you are isolating and ensuring control over your data and UI from errant contrib code going beyond it's design and interfering with your model. This is likely less of a problem in D8 than it was in D7, though some hooks remain.

The proper architecture now exists to encourage separation. Not everything is a node.
> 3 votes

---
Tags: entities, 8
---


# Question
Title: How to better distinguish answers from questions when using the Answers module?
Bare with me, I am not a programmer, and I'm using the Answers module. I would like to make the background color of the ***answer*** content type a different color to distinguish it from the **question**.

So that when you browse both the question and the answer(s) (which the Answers module shows below the actual question on the same page), they don't look too similar.

I know I can add the field label (of the body of each answer), but I'd like to figure this out.

Any suggestions?

# Answer
> 2 votes
Depending on your configuration, there are probably already classes supplied by default with Drupal. Have you used Firebug to check the markup provided by Drupal by default? (video tutorial on how to use Firebug)

If you do need to add a class, one quick way to add a class to a field is the Field Group module. Navigate to the "Manage fields" page for the content type you wish to modify, create a new field group of type *div*, and then add the class and place the fields you wish to be "in" the class within it.

# Answer
> 0 votes
The newest 7.x-4.0 version of the Answers module comes with the (new) `Answers Theme` sub-module, which, out-of-the-box, transforms the (rather boring) vanilla display of a **Question** (and its related **Answers** below it), into a way more attractive look-and-feel. Such as the orange bubble that is added around the question (to better highlight it). Here is a screenprint that is pretty close to what's included in the newest version:

If you don't enable this sub-module, then you get a similar vanilla display (still). To see it at work, head over to this example question in its demo site).

With this submodule enabled, it might no longer be needed to makeg the background color of the *answer* content type a different color (to distinguish it from the question to view both the answers and the question on the same page), since they don't look the same anymore, already out-of-the-box. Though you could still adapt the CSS (eg the orange bubble) to fit your preferences.

Disclosure: I'm a co-maintainer of Answers.

---
Tags: 7
---


# Question
Title: field_group #states does not working with using hook_field_group_build_pre_render_alter()
I am trying to use `#states` on field\_group at node add form.

From the search results I can find a couple of links which shows that `hook_field_group_build_pre_render_alter()` can make the magic but there is no luck for me.

I try to clear cache and `dpm()` some message inside the function. It seems the hook function has not been implemented at all.

These are the links I found.

# Answer
> 1 votes
I have gotten hook\_field\_group\_build\_pre\_render\_alter(&$element) to work. Without seeing an example of your code, it's hard to give any really helpful advice.

Here's an example for a nested fieldgroup made visible when a checkbox field is checked (the checkbox boolean field is "field\_primary\_not\_caller"):

```
function MYMODULE_field_group_build_pre_render_alter(&$element) {
    //... Detect whether this is the right form...
    $element['group_contact']['group_primary_contact']['#states'] = array(
      'visible' => array(
        '#edit-field-primary-not-caller-und' => array('checked'=>TRUE),
      ),
    );
}

```

Finally, it's truly worthwhile to invest the time in getting xDebug up and running on your development machine - much better and easier to use than dpm()/var\_dump()/etc, can save you hours with stuff like this.

# Answer
> 2 votes
After debugging I found that `hook_field_group_build_pre_render_alter()` is indeed working, but `dpm()` cannot work inside it at all.

For debugging, you can only use `var_dump()` or `kpr()` inside this hook function.

---
Tags: javascript
---


title: External menu link within same domain

text:
# Question
Title: External menu link within same domain
Call me stupid, but I currently have a site that is using both Joomla and Drupal (long story). The site uses a number of sub-domains to represent different geographic locations.

For the main menu in Drupal, I have some items linking to pages within Joomla. However, Drupal doesn't allow to to specify a relative URL if the link is external to Drupal. This means I have to put the full URL including http scheme and hostname. Consequently, clicking these menu items results in a new window or tab being opened up, which is not what I want!

Does anybody know of a way I can have Drupal accept an external URL without needing to include the domain? For example: "/myJoomlaURL", instead of "http://www.mydomain.com/myJoomlaURL"?

Currently using Drupal 6.

# Answer
I think you have in drupal to make a hook\_menu to declare all your new page that you need and you can use drupal\_goto function in the call back function to redirect it to your page :)

about target blnk You can use http://drupal.org/project/menu\_attributes to add new attribute to menu like target
> 0 votes

# Answer
Links opening in new window have nothing to do with the URL, relative or not, but with the `target` attribute of the `<a>` tag.
> 0 votes

# Answer
If your worry is to open subdomain target in the same window (to avoid a new window) then the simple solution is to use a extrnal link module, https://www.drupal.org/project/extlink, It will allow you in its configuration to specify regular expression to treat as external link (to be opened in new window) or internal link (not to be opened in new window.) For example: you can include your subdomain in configuration option: "Exclude links matching the pattern" like "http://www.mydomain/myJoomlaURL". and the links will be opened in same window. But if your concern is "an external URL without needing to include the domain", then me too looking for an answer till now global variables in settings.php is the thing the closest i got.
> 0 votes

---
Tags: routes, navigation
---


title: Links in menu with domain name

text:
# Question
Title: Links in menu with domain name
When I create a link in a menu containing `localhost` it doesn't naturally work from outside. When I create a link with my public IP address it doesn't work from inside. Can I use some Drupal variables for this purpose containing the site name?

# Answer
If you are just trying to create links to pages within your Drupal site you can use relative paths and when Drupal renders the link it will show as a complete URL. You only need to have the domain name in the path when you are linking to an external site (not the same domain)

Example, to link to the Site Configuration admin page:

Use `admin/settings` instead of `http://localhost/admin/settings` and it will still show up in your menu as a full URL.
> 5 votes

# Answer
Enable clean URLs in apache configuration first (mod\_rewrite) , then you will able to omit /q?= and hence can use admin/setting like URLS without the need of specifying domain name
> 0 votes

---
Tags: 7, routes, navigation
---


title: Base URL for all external links

text:
# Question
Title: Base URL for all external links
I have site that has multiple external links. I need a way to edit them all at once. For example: I have a site www.example.com that has multiple external links like SOME-IP/getaccess, SOME-IP/getaccess/todolist etc. As the number of these external links is large, its extremely difficult to move a site to a new setup.

I am looking for a way to edit these external links at one place. like i want to change base url of external links. Something like to change SOME-IP/getaccess, SOME-IP/getaccess/todolist etc. TO SOME-OTHER-IP/getaccess, SOME-OTHER-IP/getaccess/todolist etc. so that all external links will work in a new setup.

I know this is something that many have experienced in websites with multiple external links.

I read read and read, only thing i come up with global variables in settingg.php but how to use these variables in existing modules. Or Is there a module that allow to edit all external links at once.

Thanks for all the support.

# Answer
This sounds like an unfortunate build decision coming back to hurt maintenance; that in itself is a common occurrence. One phrase I must repeat here is "if things dont go as you planned, you have had an experience." The issue that you have, at least in the school I went to, is called a Magic Number `Unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants`

Now, solutions. If you just want to plaster on more code to resolve this, then look at the External Links module. This module adds javascript that checks every link on your site to see if they use the site's base url, and if not it adds an image to indicate the link goes elsewhere. You could modify this code (the joys of open source) to change the IP from the old to the new. This is what I would consider a weak solution. It gets the desired result but it adds more code and processing to the site, and doesn't truly fix the root issue.

A better method would be to define a site variable ( code example ) to hold the ip address and then go and edit all of the references to it throughout the entire site to use that variable instead. This works if all of the links are generated in php somewhere, and not just hard-coded in the body field of various nodes. The advantage here is, if that ip address changes again you only have to update the variable value. That can even be done with a drush vset.

Now, assuming these links are in node bodies and do not have the ability to use a php variable, you can get a similar result with a hook. I would still recommend setting the new ip in a variable. Then using a hook\_node\_view you can preg\_replace the old ip address with the contents of the variable in the whole body field for any node. Or in other fields too, or only on nodes of `if( in_array( $node->type, $target_types_array))` etc. This has the advantage of similar flexibility to the variable solution, but it does add extra processing like the javascript solution. However, it is a hook that does not need loops so it will not be much of an increase.
> 1 votes

---
Tags: navigation
---


# Question
Title: drush pm-update "File drupal6-eol is corrupt (wrong md5 checksum)."
PHP version 5.3.3
Scientific Linux release 6.5 Carbon (like CentOS/Redhat)

Can't update a Drupal 6 site using Drush 6.x. Installed Drush 6.x using composer. "drush pm-update" produces the following, which makes me think something's wrong with the hash for the end of life announcement.

```
# drush pm-update --verbose --no-cache
Initialized Drupal 6.38 root directory at /var/www/html/<url-removed>                      [notice]
Initialized Drupal site default at sites/default                                              [notice]
Loading release_info engine.                                                                  [notice]
Loading version_control engine.                                                               [notice]
Loading package_handler engine.                                                               [notice]
Executing: wget --version
Loading update_info engine.                                                                   [notice]
/usr/bin/php  -d magic_quotes_gpc=Off -d magic_quotes_runtime=Off -d                          [notice]
magic_quotes_sybase=Off /home/<user>/.composer/vendor/drush/drush/drush.php
--php=/usr/bin/php --php-options=' -d magic_quotes_gpc=Off -d magic_quotes_runtime=Off -d
magic_quotes_sybase=Off'  --backend=2 --verbose --root=/var/www/html/<url-removed>
--uri=http://default  pm-updatestatus 2>&1
Update information last refreshed: Thu, 04/14/2016 - 12:32
 Name                                    Installed     Proposed       Message
                                     Version       version
 Backup and Migrate (backup_migrate)     6.x-2.8       6.x-2.8        Installed version not supported
 Drupal                                  6.38          Drupal 6 has   SECURITY UPDATE available
                                                   reached end
                                                   of life
 CCK Facets (cck_facets)                 6.x-1.x-dev   6.x-1.x-dev    Installed version not supported
 Field Indexer (field_indexer)           6.x-1.0       6.x-1.0        Installed version not supported
 Content (cck)                           6.x-2.9       6.x-2.9        Installed version not supported
 Content Access (content_access)         6.x-1.2       6.x-1.2        Installed version not supported
 Data export import                      6.x-1.1       6.x-1.1        Installed version not supported
 (data_export_import)
 Date (date)                             6.x-2.10      6.x-2.10       Installed version not supported
 External Links (extlink)                6.x-1.17      6.x-1.17       Installed version not supported
 Faceted Search (faceted_search)         6.x-1.0-beta  6.x-1.0-beta3  Installed version not supported
                                     3
 Google Analytics (google_analytics)     6.x-3.6       6.x-3.6        Installed version not supported
 Image (image)                           6.x-1.2       6.x-1.2        Installed version not supported
 ImageAPI (imageapi)                     6.x-1.10      6.x-1.10       Installed version not supported
 ImageCache (imagecache)                 6.x-2.0-rc1   6.x-2.0-rc1    Installed version not supported
 ImageField (imagefield)                 6.x-3.11      6.x-3.11       Installed version not supported
 IMCE (imce)                             6.x-2.7       6.x-2.7        Installed version not supported
 IMCE Wysiwyg API bridge (imce_wysiwyg)  6.x-1.1       6.x-1.1        Installed version not supported
 jQuery UI (jquery_ui)                   6.x-1.5       6.x-1.5        Installed version not supported
 Link (link)                             6.x-2.11      6.x-2.11       Installed version not supported
 Menu Block (menu_block)                 6.x-2.4       6.x-2.4        Installed version not supported
 Override node options                   6.x-1.14      6.x-1.14       Installed version not supported
 (override_node_options)
 Pathauto (pathauto)                     6.x-1.6       6.x-1.6        Installed version not supported
 Poormanscron (poormanscron)             6.x-2.2       6.x-2.2        Installed version not supported
 Site map (site_map)                     6.x-2.2       6.x-2.2        Installed version not supported
 Token (token)                           6.x-1.19      6.x-1.19       Installed version not supported
 Views Data Export (views_data_export)   6.x-2.0-beta  6.x-2.0-beta7  Installed version not supported
                                     7
 Views modify query                      6.x-1.x-dev   6.x-1.x-dev    Installed version not supported
 (views_modify_query)
 Webform (webform)                       6.x-3.21      6.x-3.21       Installed version not supported
 Weight (weight)                         6.x-1.3       6.x-1.3        Installed version not supported
 Wysiwyg (wysiwyg)                       6.x-2.4       6.x-2.4        Installed version not supported

Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Executing: svn info '/var/www/html/<url-removed>/drupal-Drupal 6 has reached end of life'
Executing: bzr root '/var/www/html/<url-removed>/drupal-Drupal 6 has reached end of life'
Executing: wget --version
Executing: wget -q --timeout=30 -O /tmp/download_fileBIUKo0 https://www.drupal.org/about/drupal6-eol
Downloading drupal6-eol was successful.                                                       [notice]
File drupal6-eol is corrupt (wrong md5 checksum).                                          [error]
Updating project drupal failed. Attempting to roll back to previously installed version.   [error]
Rolling back update of Drupal core code ...                                                   [notice]
Executing: svn info 'drupal-Drupal 6 has reached end of life'
Executing: bzr root 'drupal-Drupal 6 has reached end of life'
Backups were restored successfully.                                                        [ok]
Command dispatch complete                                                                     [notice]
Command dispatch complete                                                                     [notice]

```

# Answer
\[I presume you meant to say that you installed Drush 6.x by Composer, since it is not possible to install Drupal 6.38 via Composer.\]

If you are working with Drupal 6, you should be using Drush 8. Drupal.org changed some things in the metadata when Drupal 6 went EOL; Drush 6 and Drush 7 probably can't handle this.
> 1 votes

# Answer
Drush 6 is not supported by the drush developers anymore. Drush 7 is supported and is still compatible with PHP 5.3.x, though according to @greg\_1\_anderson you will be better off using Drush 8. ("Drupal.org changed some things in the metadata when Drupal 6 went EOL; Drush 6 and Drush 7 probably can't handle this.")

Unfortunately, there is a bug in PHP 5.3.3 that prevents Drupal 7 from running on it. You can verify that you are being affected by this bug by running **drush sql-cli**. If you get the following error, you are affected:

```
exception 'ReflectionException' with message 'Class Drush\Sql\Sql6 does not have a constructor, so you cannot pass any constructor arguments' in                                                  [error]
/home/user/.composer/vendor/drush/drush/includes/drush.inc:117
Stack trace:
#0 /home/user/.composer/vendor/drush/drush/includes/drush.inc(117): ReflectionClass->newInstanceArgs(Array)
#1 /home/user/.composer/vendor/drush/drush/commands/sql/sql.drush.inc(607): drush_get_class('Drush\Sql\Sql', Array, Array)
#2 /home/user/.composer/vendor/drush/drush/commands/sql/sql.drush.inc(590): drush_sql_get_version()
#3 /home/user/.composer/vendor/drush/drush/commands/sql/sql.drush.inc(428): drush_sql_get_class(NULL)
#4 [internal function]: drush_sql_query()
#5 /home/user/.composer/vendor/drush/drush/includes/command.inc(361): call_user_func_array('drush_sql_query', Array)
#6 /home/user/.composer/vendor/drush/drush/includes/command.inc(212): _drush_invoke_hooks(Array, Array)
#7 [internal function]: drush_command()
#8 /home/user/.composer/vendor/drush/drush/includes/command.inc(180): call_user_func_array('drush_command', Array)
#9 /home/user/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(64): drush_dispatch(Array)
#10 /home/user/.composer/vendor/drush/drush/drush.php(70): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#11 /home/user/.composer/vendor/drush/drush/drush.php(11): drush_main()
#12 {main}

```

Fortunately, the bug is easy to work around.

GitHub user diarmy suggests replacing a single line in your drush 7 install:

> In PHP 5.3.3, the line $reflectionClass-\>newInstanceArgs($constructor\_args) in drush\_get\_class throws an exception.
>
> A clue as to why this might be the case may be found in http://php.net/manual/en/reflectionclass.newinstanceargs.php where the documentation says that a ReflectionException will be thrown if the class does not have a constructor and the args parameter contains one or more parameters.
>
> The base class SqlVersion class does not have a constructor and yet an empty array is passed into its descendant (Sql6 or Sql7).
>
> To work round this, the line
>
> return $reflectionClass-\>newInstanceArgs($constructor\_args);
>
> should be replaced with:
>
> return !empty($constructor\_args) ? $reflectionClass-\>newInstanceArgs($constructor\_args) : $reflectionClass-\>newInstanceArgs();
>
> I had the same issue as above and this fix worked for me -7.0-dev is now working on PHP 5.3.3.

After applying this update, **drush sql-cli** and **drush pm-update** should work.
> 0 votes

---
Tags: drush
---


title: drush sql-dump skip extended inserts?

text:
# Question
Title: drush sql-dump skip extended inserts?
Does drush have an option in its `sql-dump` command to skip extended inserts?

I am looking for a particular value in the database, and having shorter lines would be a boon for my task.

# Answer
Yes, it has, just add `--ordered-dump` parameter to the `sql-dump` command, e.g.

```
drush sql-dump --ordered-dump

```

Tested under Drush 8.x.
> 2 votes

---
Tags: drush
---


# Question
Title: What code should I use where I used db_query()?
I want to execute `SHOW TABLES` in Drupal 8. In Drupal 7, I would use `db_query("SHOW TABLES")`, which is deprecated in Drupal 8.

What should I use for Drupal 8?

# Answer
> 5 votes
As quick replacement for queries on the database Drupal uses by default, you can use the following code.

```
use Drupal\Core\Database\Database;

$db = Drupal::database();
$result = $db->query("SHOW TABLES");

```

Keep in mind that:

* `db_query()` will not be removed before Drupal 9 goes off; you can still use it, even if it is preferable to refactor your code to be more object oriented
* The code I shown should be used in legacy procedural code; when possible, you should consider refactoring it to be object oriented and use Drupal 8 services and Dependency Injection Container

# Answer
> 4 votes
You can still run arbitrary queries against the database. `db_query` is deprecated because it does not go well with the dependency injection pattern found elsewhere in D8.

All you need to do is getting the database object.

**Default database**

This should fit almost everyone, unless you are trying to run the query on a different connection.

```
$db = \Drupal::service('database');
$result = $db->query('SHOW TABLES'); // You can run the good old fetchAll(), etc on the $result now.

```

**Other databases**

If you want to run the query on a different database connection, just get the service spawn, and you can run `query()` on it.

**Examples**

I could find several examples from the Backup and migrate module's `MySQLiSource` class.

---
Tags: database, 8
---


# Question
Title: Display file upload images in webform view
I have a webform where users can upload images. For easier administration, I created a view of these submissions.

The default behavior of the field is to display as a link. However, I would like to preview the images by displaying them in an image tag.

I looked at the field re-write behavior, but it only gives me the entire href.

How can I display image field values as images in a webform view?

# Answer
**This can not be done with webform module alone.** All you need to do is get help of 2 extra modules.

1. File Entity
2. Views Field View

Further you need to do following things.

1. Download and enable both of the modules and clear the cache.
2. Webform is storing file, not only image. I am assuming here you are only uploading image files, you can further get idea to show any type of file there. So go to Image File Type Display: `admin/structure/file-types/manage/image/file-display` and set the preview/image style. Or if you do not want to change settings for default view mode of the file, download another module Entity View Mode. Go to it's configuration and create specific display and set image style accordingly in file display settings.
3. Create a view of files, it should be a block. and there add contextual filter for the fid and add field "`File: Rendered`". You can set file view mode by this field. For your convenience I'm exporting the view below, you just need to import this.

```
    $view = new view();
    $view->name = 'file_view';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'file_managed';
    $view->human_name = 'File view';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['title'] = 'File view';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['access']['type'] = 'perm';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['pager']['type'] = 'some';
    $handler->display->display_options['pager']['options']['items_per_page'] = '5';
    $handler->display->display_options['style_plugin'] = 'default';
    $handler->display->display_options['row_plugin'] = 'fields';
    /* Field: File: Name */
    $handler->display->display_options['fields']['filename']['id'] = 'filename';
    $handler->display->display_options['fields']['filename']['table'] = 'file_managed';
    $handler->display->display_options['fields']['filename']['field'] = 'filename';
    $handler->display->display_options['fields']['filename']['label'] = '';
    $handler->display->display_options['fields']['filename']['alter']['word_boundary'] = FALSE;
    $handler->display->display_options['fields']['filename']['alter']['ellipsis'] = FALSE;
    /* Field: File: Rendered */
    $handler->display->display_options['fields']['rendered']['id'] = 'rendered';
    $handler->display->display_options['fields']['rendered']['table'] = 'file_managed';
    $handler->display->display_options['fields']['rendered']['field'] = 'rendered';
    $handler->display->display_options['fields']['rendered']['label'] = '';
    $handler->display->display_options['fields']['rendered']['element_label_colon'] = FALSE;
    /* Contextual filter: File: File ID */
    $handler->display->display_options['arguments']['fid']['id'] = 'fid';
    $handler->display->display_options['arguments']['fid']['table'] = 'file_managed';
    $handler->display->display_options['arguments']['fid']['field'] = 'fid';
    $handler->display->display_options['arguments']['fid']['default_action'] = 'default';
    $handler->display->display_options['arguments']['fid']['default_argument_type'] = 'node';
    $handler->display->display_options['arguments']['fid']['summary']['number_of_records'] = '0';
    $handler->display->display_options['arguments']['fid']['summary']['format'] = 'default_summary';
    $handler->display->display_options['arguments']['fid']['summary_options']['items_per_page'] = '25';

    /* Display: Single File View */
    $handler = $view->new_display('block', 'Single File View', 'block');
```
4. Now in your main view (where you are showing submissions). Add a new relationship for `Webform submissions: Data`. You'll need to set the nid for the webform here and select the image component.
5. Add new field to the view `submission data: Value (raw)`. This will give you the file\_id for the associated file. Exclude it from display.
6. Add another field `Global: View`. Select the view you imported and the block display. In contextual filter set \[!data\] from replacement patterns. It was the raw value of the field which you excluded from the display. And Here you go, save the view and rock :). Thanks for asking such good question. Still if you face any problem during this tutorial, ask me.
> 3 votes

---
Tags: views, webforms
---


# Question
Title: How can I filter a view according to another view's results
I have one view with two display: "latest news" and "populer news"

I want show two block side by side like mashable.com.

I can easily do that of course but one problem. There are same news both block. I want to hide news in the "latest news block" according to "populer news block".

How can I do that?

# Answer
> 3 votes
This module might help you Views exclude previous

> The Views exclude previous module provides a views filter that excludes nodes that have already been loaded/displayed on the current page.

It excludes node in previous views loaded in your views. Example: you have two views block loading in the same page and the two block shows same node in views; you can exclude the other one in display, you can find the additional field in filter criteria in views configuration of your block. See image attached

---
Tags: 7, views
---


title: Feeds vs. Aggregator for rss

text:
# Question
Title: Feeds vs. Aggregator for rss
Is it fair to say that aggregator is retained in d7 core for legacy support, and that Feeds is the likely successor? Feeds covers more scenarios than aggregator, and appears to be better situated for adaptions, although the generalization makes it more difficult to understand how to go about implementing. Are there projects that you can recommend that build on themes to implement particular use cases?

--- Looking through the Feeds documentation, we find the statement

> "Feed: aggregation importer. Aggregates RSS/Atom feeds to nodes. Provides a node type Feed and a node type Feed item. Create one or more "Feed" nodes to add RSS/Atom feeds to your site. On cron, these feeds will continuously produce "Feed item" nodes. Requires the Aggregator core module to be enabled.

So project/feeds depends on core aggregator, although it seems to overlap and extend functionality as well.

# Answer
> 10 votes
Even though the module's name is 'Feeds' , it can import CSV, XML and other types of data too. Also, you can attach them to a stand alone form or a node type form.

The basic difference between aggregator and Feeds module is, how it stores data.

Aggregator module stores categories, feed URLs and imported data in its own tables. You will have Views support but it cannot be extended like nodes or such entity.

Also, you will not be able to map data. It's almost a fixed structure, like title to title, body to body, etc.

But in case of Feeds, you can decide what you need. You can build a standard feed importer that maps feed item's title to node title and contents to a body field. But you can also be radical by mapping to other fields.

You also can use different entities as the target. It also has 'pubsubhubbub' support which Aggregator doesn't support.

Both modules uses cron to fetch data.

Use aggregator if you want to show contents from few RSS/atom feeds in a simple block. For all other cases, I'd recommend Feeds module.

# Answer
> 0 votes
I would suggest "Feed import" module. I have a great experience at creating node with images and files attached to their fields. Hope it helps.

# Answer
> 0 votes
For Drupal 8, Aggregator is stable as of April 2016 (part of core) and works with views out of the box.

Aggregator is bare-bones next to the Feeds module but useful nonetheless. Especially since the Feeds modules appears to be ways off from a D8 port.

---
Tags: feeds
---


# Question
Title: How to create a organic-group-alias/content-type subpage?
I've created a page via views that show a list of all the nodes of a specific content type in a specific group.

`/node/groupid/post` lists all the nodes of type post in groupid.

But what I really need, is to be able to use the groups path alias. So:

`/group-name-here/post` should work for `/node/groupid/post`.

How can I do that?

### site specs

Drupal 7.41

Views 3.11

OG 2.7

Pathauto 1.3

# Answer
Views treats aliases the same as `node/id`. So, in the view, just set the path to `node/id/post` or similar.
> 0 votes

---
Tags: views, organic-groups, path-aliases
---


title: Drupal 7 Views Change the Query String

text:
# Question
Title: Drupal 7 Views Change the Query String
I have a complex View that needs to utilize multiple contextual filters. Currently to access the filters I need to separate the values with a "/". I'm attempting to code a solution that passes arguments to a View (via URL) and it would be ideal to have the query string look like this:

http://www.example.com/query?nid=1450&tid=543

vs (the current way)

http://www.example.com/query/1450/543

so that I can better parse this. How can I get a View to accept parameters like this?

# Answer
What you're actually saying is that you don't want contextual filters, contextual means that you want an argument based on the context of the site which is usually separated out by the url.

The quickest way to do what you want is this.

* move your contextual filters into the filters section of views, making sure that you expose them to visitors.
* Under the more setting of each filter is where you set the filter identifier and change the advanced options to label the filter as you require such as "nid" then your url would be mywebsite.com/page?nid=xxx
* Then under the exposed form settings, change the setting to "expose form as block" to yes to make the exposed filters disappear.
> 3 votes

# Answer
You need the module Views Contextual Filter Query.

From the module page:

> Allows url query values to be used as contextual filter arguments. This module is an answer to the many stackoverflow topics where the solution is to fetch query parameters by using the default PHP argument filter in Views (yucks!).
> 0 votes

---
Tags: views
---


# Question
Title: modify date token in View to extract only year?
We have a content type using a date field, in which the date is entered in the format mm/yyyy. An example entry might be 04/2016. In one particular View, we want to use only the Year value. It appears the token for this field is

```
[field_delivery_date-value]

```

In the Rewrite area for this View field, is there an operation that can be performed on the token in order to extract and display only the year value? Or would this need to be done in another way, not using tokens and the rewrite option?

# Answer
**Steps to get the just the year for Delivery Date field**

* Navigate to /admin/config/regional/date-time/formats page.
* Click on Add Format button (/admin/config/regional/date-time/formats/add)
* In the Format string text field add Y and save it.
* Now add a date type by navigating to /admin/config/regional/date-time page.
* Add a new date type and use the the format that we have added in the previous steps.
* In the view select the type you want the date to be rendered.

So instead of **Rewriting the output**, you would directly get the year.

Hope that this will help you.
> 3 votes

# Answer
In your view, click on your **date field**.

**Note:** In your Content Type your field needs to be a date field, text field won't work!

For formatter, select Custom.

For Date/Time Format, put `Y`

> **Note:** In Drupal 8 there seems to be a bug, you will have to do this twice, as when you save the 1st time it does not change. In Drupal 7 it should work on the 1st try.
> 1 votes

---
Tags: views, datetime, tokens
---


# Question
Title: How to solve Bootstrap Theme settings override problem?
I'm using the Bootstrap base theme and a sub-theme (cdn) in one of my websites.

Normally everything was fine. Then I installed a fresh Drupal into **another** server and installed the themes I was using before. The problem appears there, I **couldn't change** any theme settings of Bootstrap themes via Drupal **interface**. For example I tick the Fluid container and save but it doesn't change, the box goes back to being unchecked.

The new server configurations may be different from old one.

### Does anybody know what Bootstrap need for theme settings?

# Answer
> 4 votes
I solved this problem by disabling the ModSecurity on cPanel.

> ModSecurity is an Apache module that applies a set of rules to the activities of software run on Apache. It is used by some hosting environments to assure security, but some rules can **interfere** with the normal operation of Drupal.

---
Tags: 7, theming
---