title: Add custom form to panels?

text:
# Question
Title: Add custom form to panels?
How can I add a custom form to a Panels page in Drupal 7?

```
return drupal_get_form('my_custom_form');

```

I would prefer not to use the PHP input filter if possible.

# Answer
> 5 votes
Create a custom module that defines a block with that form as the content. You can then place that block anywhere on your site using the standard Drupal interfaces (blocks configuration, Panels, Context, etc.).

There are many readily available resources on creating custom modules that define blocks. The Drupal.org Module Developer's guide is a great place to start, as well as the Examples module, which includes a sample module for defining blocks that can be easily copied and customized.

# Answer
> 1 votes
it can be done using hook\_block

```
function MODULENAME_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      $blocks[1] = array('info' => t("BLOCK TITLE"));
    return $blocks;
    case 'view':
      $block =array(
        'subject'=>t("BLOCK TITLE"),
        'content'=>drupal_get_form('my_custom_form'));
  return $block;
  }
}

```

Now you can include this block in your panel :)

# Answer
> 1 votes
It was trickier to pass context's to blocks that I thought, but that was the simplest solution here.

Though while searching for a solution I did run across an interesting module that others may find useful.

Check out Page Manager: Existing Pages

You can use any path registered with hook\_menu() and it works beautifully.

# Answer
> 0 votes
You can create ctools plugin that will show the form. Passing context to plugins is close to trivial:

```
$plugin = array(
  'category' => ...,
  'render callback' => 'example_pane_render',
  'edit form' => 'example_pane_render',
  'required context' => new ctools_context_required(t('Account'), 'user'),
  'title' => t('User profile form'),
);

```

...

```
/**
 * Render callback.
 */
function example_pane_render($subtype, array $conf = array(), $args, $context) {
  module_load_include('pages.inc', 'user');
  if (count($args) > 1) {
    $profile_type = $args[1];
  }
  else {
    $profile_type = $conf['profile_type'];
  }
  return (object) array(
    'content' => drupal_get_form('user_profile_form', $context->data, $profile_type),
  );
}

```

---
Tags: 7, forms, panels
---


# Question
Title: Watchdog messages and string replacement
Hello I would like to know which of the following ways (or some other) of logging messages is better and why. I am writing lots of .install files since I create content types and fields programmatically and I often write statements as following:

```
$t = get_t();
watchdog('mymodule',$t('Field !field_name created.', array('!field_name' => $file_field_name)));

```

OR

```
$t = get_t();
watchdog('mymodule',$t('Field !field_name created.'), array('!field_name' => $file_field_name));

```

Note: in the first example I am doing string replacement in the $t function in the second in the watchdog() function.

# Answer
> 1 votes
Just use this:

```
watchdog('mymodule', 'Field !field_name created.', array('!field_name' => $file_field_name));

```

`watchdog()` function will translate the string you pass as the second parameter. You shouldn't translate the message before passing it to the `watchdog()`.

Check out this answer for more information and references.

Or consult the following document from Drupal's documentation.

---
Tags: 7, i18n-l10n, log-messages
---


title: Custom file types

text:
# Question
Title: Custom file types
I created a custom file type (to add documents and images). And in my content type, under allowed file types, I only checked my custom file type. However, when I trying to upload a file, it is giving a choice to select "document" or "custom file type". I don't want to have that choice. How can I prevent that choice menu from showing up ?

I can't disable "document" because it's used in other content types.

Any suggestions ?

# Answer
> 0 votes
Currently there is a support request to make file type in file field configurable, see https://www.drupal.org/node/2538102

---
Tags: files
---


title: Get custom comments of node

text:
# Question
Title: Get custom comments of node
I'm currently working on a simple reviewing system. I've created a custom comments type ("Review") with an integer list ("Rating") that can be added to my nodes. Now, while displaying the note, I would like to get an average rating based on the reviews posted.

I am quite new to Drupal, and I thought that I might achieve this by creating a custom twig template for the product-type nodes and getting the required value in a preprocess function.

I succeeded in getting the field\_reviews object with

```
$variables['comment_field'] = $node->get('field_reviews');

```

and when I `kint()`ed it out, I got a really big file structure, but the required data was in there.

However, whenever I tried following the path down there through dozens of variables and arrays, when I reached the review itself, kinting yielded `NULL` or the page didn't load at all.

I'm getting the feeling that this approach is not ideal and that I must've overlooked something much easier, but I can't seem to figure out what.

# Answer
> 3 votes
The comment field doesn't contain the *comments*, it just contains settings and statistics (e.g. open or closed).

To get the comments, you need to do an entity query and get all comments that have point to your node of your type, load them and then calculate the average from them.

Also, see http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet on how to work with content entities and fields. kint() is highly misleading and confusing.

Update. Instead of having to load all comments and calculate the average yourself, you should be able to do an aggregate entity query and get the average value of your field directly: https://www.drupal.org/node/1918702

---
Tags: 8, comments, theming
---


# Question
Title: How to add where clause to custom Drupal view
I am fetching data from two table to my view using View API. How can I add where clause to my view?

My actual SQL query is like:

```
select field1,field2,field3,t2field4 from table1,table2 where t2field=field1

```

I come across hook\_view\_alter() but I dont know how to implement that. Can I use any filter handler in my views.inc file?

# Answer
> 1 votes
You can implement `hook_view_query_alter()` to add where condition.

```
function MODULE_NAME_views_query_alter(&$view, &$query) {
  if ($view->name == 'view_name') {
    $query->add_where(1,'node.nid',$value,'=');
  }
}

```

---
Tags: views
---


# Question
Title: Panels, panel node print header and footer
I use Panels module and I've created Panel page, where I inserted Panel nodes.

Problem: Panel nodes have their own header and footer html tags that are printed. How to remove them? Any way to make it without custom template in code?

# Answer
I should use min-panel. Panel page and panel node both have page structure.
> 0 votes

---
Tags: 7, panels
---


# Question
Title: Views listing of nodes and node title as exposed filter
When I started this view I thought it would be simple… But it's not.

I've an "Office" content type and a view (block) where are listed my "Office" nodes as teaser.

First of all it could be great if the result should be sorted with AJAX, but it's only an option. I would like an exposed dropdown list filter with all the nodes title of my "Office" content type. But it seems I could only expose an input search field.

I already looked at BEF and several posts here but I didn't find a clear solution.

# Answer
Finally found a solution with Views Selective Filters. :)

By added a "Regions" field in my content type I've been able to get only the regions with results exposed as a filter in my views.
> 0 votes

---
Tags: nodes, ajax, views
---


# Question
Title: Taxonomy menu with a large list of terms
I want to display a list of terms and child terms using Taxonomy menu,my list is very large ( more than 2000 terms), and Im getting this error:

```
Additional uncaught exception thrown while handling exception.
Original

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT * FROM {system} WHERE type = 'theme' OR (type = 'module' AND status = 1) ORDER BY weight ASC, name ASC; Array ( ) in system_list() (line 165 of C:\wamp\www\Books\includes\module.inc).
Additional

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( [:name] => theme_registry:runtime:adaptivetheme_admin:cache ) in lock_may_be_available() (line 167 of C:\wamp\www\Books\includes\lock.inc).
Uncaught exception thrown in session handler.

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in _drupal_session_write() (line 206 of C:\wamp\www\Books\includes\session.inc).
Uncaught exception thrown in shutdown function.

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 14337154844f4e188d884c54.86419408 ) in lock_release_all() (line 269 of C:\wamp\www\Books\includes\lock.inc).

```

Is this because Taxonomy menu can not handle a large amount of terms?

# Answer
> 0 votes
Yes, this error usually is related to a large size of data, so database can't handle such sizes due the given limits and it fails, because the server timed out and closed the connection.

To fix it, you need to increase value of `max_allowed_packet` in your `my.cnf` (e.g. `~/.my.cnf`) under `[mysqld]` section, e.g.

```
[mysqld]
max_allowed_packet=256M

```

See: B.5.2.9 MySQL server has gone away for more detailed information.

Another thing is that in this particular case it happens in shutdown function (which is after Drupal finished the processing of the site), therefore it could be related to some cron or debugging tasks.

---
Tags: routes, taxonomy-terms
---


# Question
Title: How to add class in li element (for page where I am) in menu for drupal 8
I would like to add class in li element in menu for drupal 8 for page where I am. For example if i am on page Start, that li have active class. Or If I am on Join page that li element for join have active class.

```
<ul class="">
<li class="active"><a href="#" >START</a></li>
<li class=""><a href="#" >About</a></li>
<li class=""><a href="#" >join</a></li>
</ul>

```

So, How to ask if li is active or no?

```
{% for item in items %}
  {% if item=SOMETHING %}
    <li class="active">
      <a  href="{{ item.url }}">{{ item.title }}</a>
    </li>
  {% else %}
    <li >
      <a  href="{{ item.url }}">{{ item.title }}</a>
    </li>
{% endfor %}

```

# Answer
To add active class to `<li>` need to add the following code in your `.theme` file and `menu.html.twig`

In **.theme** file add this

```
function themename_preprocess_menu(&$variables, $hook) {
  if ($hook == 'menu__main') { // If it is not working replace "main__menu" with "menu"

    // Get the current path.
    $current_path = \Drupal::request()->getRequestUri();
    $items = $variables['items'];
    foreach ($items as $key => $item) {
      // If path is current_path, set active to li.
      if ($item['url']->toString() == $current_path) {
      // Add active link.
      $variables['items'][$key]['attributes']['class'] = 'active';
      }
    }
  }
}

```

In menu.html.twig replace your `<li>` with below line.

replace this line

```
{{ link(item.title, item.url) }}

```

by

```
<li {{ item.attributes }} ><a  href="{{ item.url }}"  {{ item.attributes }} > {{ item.title }}</a></li>

```
> 12 votes

# Answer
It will be better if you programmatically detect the page and apply the class on that condition.You can follow the following steps.

* Detect the current page ( CODE : For Drupal 7) .

```
 <php
  $path = current_path();
  $path_alias = drupal_lookup_path('alias',$path);
 ?>

```
* Add the if condition matching your page name with that of current page

```
if($path_alias == "current-page") { print  "active"; }

```

This may solve your issue
> 2 votes

---
Tags: routes, 8
---


# Question
Title: Add a relationship to logged in user, not content author, on content view?
I want to filter my content view by a field on the logged in user (the content type has that same field). I could implement `hook_query_alter` and add add a where condition with the field from `$global user`, but is there a way to do this out of the box though the UI?

# Answer
There is no way to accomplish this via UI. At least not if the User field may contain multiple values.

In the example below `'field_test' is a List(text)` field w/ select widget (unlimited values allowed for user account). When the same field is added to Content type - I set it to allow for single values.

The code will take in consideration multiple values from User field and add **`WHERE`** clause to the View that shows all nodes of a Content type.

**`WHERE`** clause filters out all nodes that have `'field_test'` set to anything other than what currently logged in user has set in `'field_test'` on their own account.

```
/**
* Implements hook_views_query_alter().
*/
function MYMODULE_views_query_alter(&$view, &$query) {
  // 'test_related_field' -> view's machine_name
  if ($view->name == 'test_related_field') {
    global $user;
    $user = user_load($user->uid);

    // 'field_test' -> field that is shared between user accounts ans content type
    $user_field = field_get_items('user', $user, 'field_test');
    if($user_field) {
        $query->ensure_table("field_data_field_test");
        // create query that processes multiple values of User 'field_test'
        $db_or = db_or();
        foreach ($user_field as $item){
            $db_or->condition('field_data_field_test.field_test_value', $item, 'IN');
        }
        $query->add_where('test_field_group', $db_or);
    }
    // use dpm() to see added WHERE clause
    //dpm($query);
  }
}

```

**UPDATE:** If User field and Content Type field are allowed to have only single values then you can use UI for filtering view's results.

* add shared field as Contextual Filter
* Provide Default value for the field -\> select PHP Code
* enter the following code in the box

`global $user;
$user_fields = user_load($user->uid);
$test_field = $user_fields->field_test['und'][0]['value'];
return $test_field;`
> 3 votes

# Answer
Don't think there is a way. For the record, here's some starter code.

```
/**
* Implements hook_views_query_alter().
*/
function MYMODULE_views_query_alter(&$view, &$query) {
  if ($view->name == VIEWNAME) {
    global $user;
    $user = user_load($user->uid);
    $user_field = field_get_items('user', $user, 'field_NAMEOFFIELD');
    if ($user_field) {
      // only care about the first result for now
      $user_field = $user_field[0]['value'];
    }
    $query->ensure_table("TABLENAME");
    $query->add_where(0, "TABLENAME.NAMEOFFIELD_value", $user_field);
  }
}

```
> 2 votes

---
Tags: 7, views
---


# Question
Title: Interfacing Data back and forth: JSapp <--> Drupal
I want to create custom products for every single one of my customers, and to add a thumbnail and custom order data from a JSAPP.

Seen on #2 My JS application must get the unique id from the user. regardless if they are logged in or not (i dont know how which is the exact data or variable in the db i should send, and how do i send it?)

in #3 i must recieve custom information generated on the jsapp, i can send this as a Json , XML or URLstring from the jsapp to drupal commerce; im unsure how could i somehow, inject this information or update a variation of my product. or maybe there's a more easy way to do this.

Does anyone have some pointers on how to address this communication problem?

# Answer
1. Once your step one runs, you've actually created a unique order with a unique line item that references a product.
2. The ID in #2 should probably just be your line-item id.

I would consider creating a rule on the event "After adding a product to cart" and a custom action (this is an answer where I provided the code to make a custom action) that takes a line item id (something the rule will easily have access to) and sends that to the three.js app.

3. You really just want to add the custom data to the line item (which is unique to each line item on the order). In fact, using Customizable Products you can easily create a bundle specifically for adding as many fields as you would need to track your data (and display/hide it in views or display modes).

To do this, I would create a menu item that somehow recieves the full json object. Perhaps this blog article will help? Regardless, once you have your data, you will want to update the line item with your data and the best way to do this is with entity meta data wrappers if you are using fields to store the data.

```
<?php

$line_item_id = 1;
$line_item = commerce_line_item_load($line_item_id);
$line_item_wrapper = entity_metadata("commerce_line_item",$line_item);
dpm($line_item_wrapper->getPropertyInfo());

// ... mess with fields

$line_item_wrapper->save();

?>

```
4. If you are using the fields on a line item to store your data, the cart will already be up-to-date because it simply references all the line items.
> 0 votes

---
Tags: nodes, commerce, users
---


title: Implementing CKeditor's plugin

text:
# Question
Title: Implementing CKeditor's plugin
I need to add the **Templates** plugin into Drupal8 CKeditor. So far it is available on the editor configuration page, but not on a node edit page. The code:

```
namespace Drupal\module_name\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\ckeditor\CKEditorPluginButtonsInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\editor\Entity\Editor;

class ContentTemplates extends PluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface {

  public function getButtons() {
    return array(
      'ContentTemplates' => array(
        'label' => t('Content templates'),
        'image' => drupal_get_path('module', 'module_name') . '/js/CKeditor/Plugin/templates/icons/templates.png',
        'image_rtl' => drupal_get_path('module', 'module_name') . '/js/CKeditor/Plugin/templates/icons/templates-rtl.png',
      ),
    );
  }

  public function isInternal() {
    return FALSE;
  }

  public function getDependencies(Editor $editor) {
    return array('dialog', 'dialogui');
  }

  public function getLibraries(Editor $editor) {
    return array();
  }

  public function getFile() {
    return drupal_get_path('module', 'module_name') . '/js/CKeditor/Plugin/templates/plugin.js';
  }

  public function getConfig(Editor $editor) {
    return array();
  }

  // TODO: to be sure, should be removed and served by config
  function isEnabled(Editor $editor) {
    return TRUE;
  }
}

```

I also could see the methods injected by `templates/dialogs/templates.js` while inspecting the CKEditor object, but the file is not listed in the Chrome's resources inspector. I also don't see any code changes in this file takes effect (browser and drupal cache disabled, aggregation disabled).

# Answer
> 3 votes
I used this two classes in *modules/custom/my\_ckeditor/src/Plugin/CKEditorPlugin*:

```
<?php

namespace Drupal\my_ckeditor\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\ckeditor\Annotation\CKEditorPlugin;
use Drupal\Core\Annotation\Translation;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "templates" plugin.
 *
 * @CKEditorPlugin(
 *   id = "dialog",
 *   label = @Translation("CKEditor Dialog"),
 *   module = "ckeditor"
 * )
 */
class Dialog extends PluginBase implements CKEditorPluginInterface
{

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getDependencies().
   */
  function getDependencies(Editor $editor)
  {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getLibraries().
   */
  function getLibraries(Editor $editor)
  {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::isInternal().
   */
  function isInternal()
  {
    return false;
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getFile().
   */
  function getFile()
  {
    $plugin = drupal_get_path('module', 'my_ckeditor') . '/js/plugins/dialog/plugin.js';

    return $plugin;
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getConfig().
   */
  public function getConfig(Editor $editor)
  {
    return array();
  }
}

<?php

namespace Drupal\my_ckeditor\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\ckeditor\CKEditorPluginButtonsInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\ckeditor\Annotation\CKEditorPlugin;
use Drupal\Core\Annotation\Translation;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "templates" plugin.
 *
 * @CKEditorPlugin(
 *   id = "templates",
 *   label = @Translation("CKEditor Templates"),
 *   module = "ckeditor"
 * )
 */
class Templates extends PluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface
{

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getDependencies().
   */
  function getDependencies(Editor $editor)
  {
    return array('dialog');
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getLibraries().
   */
  function getLibraries(Editor $editor)
  {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::isInternal().
   */
  function isInternal()
  {
    return false;
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getFile().
   */
  function getFile()
  {
    $plugin = drupal_get_path('module', 'my_ckeditor') . '/js/plugins/templates/plugin.js';

    return $plugin;
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getConfig().
   */
  public function getConfig(Editor $editor)
  {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getConfig().
   */
  public function getButtons()
  {
    return array(
      'Templates' => array(
        'label' => t('Templates'),
        'image' => drupal_get_path('module', 'my_ckeditor') . '/js/plugins/templates/icons/templates.png',
      ),
    );
  }
}

```

The CKEditor plugins (Dialog & Templates) are placed in *modules/custom/my\_ckeditor/js/plugins*

You also need a custom JS-file for your templates:

```
(function ($, Drupal, CKEDITOR) {
  "use strict";

  Drupal.behaviors.myCkeditor = {
    attach: function (context, settings) {
      var templates_path = '/modules/custom/my_ckeditor/templates/ckeditor/';

      var templates = [
        {
          title:       Drupal.t('Title'),
          description: Drupal.t('Description'),
          image:       'preview.gif',
          html:        'My Template'
        }
      ];

      // Remove default templates
      CKEDITOR.on("instanceLoaded", function () {
        CKEDITOR.config.templates_files = [];
      });

      // Load tempaltes
      CKEDITOR.on("instanceReady", function () {
        if (CKEDITOR.plugins.get('templates')) {
          CKEDITOR.config.templates_replaceContent = false;
          CKEDITOR.addTemplates('default', {
            imagesPath: templates_path,
            templates:  templates
          });
        }
      });
    }
  };

})(jQuery, Drupal, CKEDITOR);

```

This talk can help you: https://www.youtube.com/watch?feature=player\_detailpage&v=h9KV\_VRvIG8#t=1965

# Answer
> 0 votes
The concept sunk in when I saw this: https://github.com/wwalc/moonocolor

Its the drupal8 implementation for moonocolor plugin of ckeditor

The only additions i could find are the .module file .info.yml file

I did not find any reference to an extra js file. Also in the above solution its not mentioned where the extra js file should be.

My efforts, not working yet https://github.com/baverhey/d8\_ckeditor\_templates

# Answer
> 0 votes
See the documentation at https://www.drupal.org/developing/api/8/ckeditor.

You can find examples in Drupal 8 core, at:

* `\Drupal\ckeditor_test\Plugin\CKEditorPlugin\Llama`
* `\Drupal\ckeditor_test\Plugin\CKEditorPlugin\LlamaButton`
* `\Drupal\ckeditor_test\Plugin\CKEditorPlugin\LlamaContextual`
* `\Drupal\ckeditor_test\Plugin\CKEditorPlugin\LlamaContextualAndButton`

---
Tags: 8, wysiwyg
---


title: Multiple products per display

text:
# Question
Title: Multiple products per display
I'm working on a clothing store and I need to create a page type in which a model wears different pieces of clothes and users can see all the different products and add them separately to cart.

In other words, how could I have multiple products (of different kinds) on the same display, so that users can see the product of each product, choose sizes, etc., and add them to cart separately? (It's not a product bundle that you buy as a whole.) I've tried to create more than one product reference field, and I get multiple product-add-to-cart forms, but I can't have each product's price displayd separately. Is that possible? I can only display the price of the first product with the flag "Render fields from the referenced products when viewing this entity" checked.

# Answer
You have at least 3 options:

1. If you're requiring all of the products to be bought together, you could use Commerce Bundle to create a Bundle Group product, and then add all of the individual bundle groups (e.g. a top, a bottom, and a pair of shoes) to it. This would then give you the ability to have all three products on a single page, but it'd require you to buy all 3 as a bundle.
2. You could create a node or a taxonomy page that simply references the node or products using entity or product reference fields. This would then give you multiple separate add to cart forms on a single page, (basically taking the three pages and combining them together).
3. Use Commerce Add to Cart Extras (or Commmerce's built-in views plugin) and build views which you could display on a node, panel, etc. Add to Cart Extras would allow you to build a form which would allow for bulk purchasing as well.
> 1 votes

---
Tags: commerce
---


title: Hook within an exisiting hook?

text:
# Question
Title: Hook within an exisiting hook?
I have one hook, "hook\_form\_commerce\_checkout\_form\_alter" and that is modifying something on my checkout process. Within that though I have a switch statement that if true I want to use "hook\_commerce\_checkout\_router" to skip the page. Is this allowed? I can't get any signs of life via DPM. I ran through a bunch of other modules and can't find anything helpful

# Answer
> 1 votes
Since you're already loading the form, your switch statement won't do anything. If you want to skip the page, you'll need to implement `hook_commerce_checkout_router()` in your module so that you can control if it shows up or not.

---
Tags: commerce, hooks
---


# Question
Title: How do I programmatically update an existing submitted webform submission in Drupal?
I am attempting to use PHP in Drupal rules to update the values in submitted webform submissions. I can access and view the data correctly. When I assign a new value to a field it will even show up correctly if I use print $submission-\>data\[61\]\[0\]; But when I navigate to the submission results page the field hasn't been updated.

I have tried using the webform\_submission\_update() function to push my change but still no luck.

**Question:** How do I programmatically update an existing submitted webform submission in Drupal?

**Code:**

```
$submission = webform_menu_submission_load($nid, $sid);

// Two ways I've tried to update the data
$submission->data[61][0] = "testwork";
$submission->data[61]['value'][0] = 'Declined';

// If I do print $submission->data[61][0]; it will show the new value.

webform_submission_update($nid, $submission);

```

# Answer
> 5 votes
Here's how to do that:

```
// Load the webform submissions file. The webform_get_submission() and
// webform_submission_update() functions are located here.
module_load_include('inc', 'webform', 'includes/webform.submissions');

// Load the node and submission.
$node = node_load(YOUR_NODE_ID);
$submission = webform_get_submission($node->nid, YOUR_SUBMISSION_ID);

// Change submission data.
//
// To see what's available, install Devel and run dpm($submission);
$submission->data[YOUR_FORM_ELEMENT_ID][0] = 'Update';

// Finally, update the submission.
webform_submission_update($node, $submission);

```

Documentation:

---
Tags: 7, rules, webforms
---


# Question
Title: Separate page for payment methods selection in drupal commerce
is there a way to have a separate page for payment method selection, to allow clients to select the payment method they want to use instead of the current way drupal commerce use (integrating payment selection in the review order page)?

Thanks in advance for your support.

# Answer
> 3 votes
Sure! You can use a module like Commerce Checkout Pages to create a new page via the UI or you could implement `hook_commerce_checkout_page_info()` in your module and create a new page. Then just move your Payment pane onto your new page and you'll be all set:

```
/**
 * Implements hook_commerce_checkout_page_info().
 */
function MYMODULE_commerce_checkout_page_info() {
  $checkout_pages = array();

  $checkout_pages['payment'] = array(
    'name' => t('Payment'),
    'title' => t('Payment'),
    'weight' => 3,
  );

  return $checkout_pages;
}

```

Then, implement `hook_commerce_checkout_pane_info_alter()` to add your payment pane to your new page:

```
/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  // Payment selection on the new 'payment' page.
  $checkout_panes['commerce_payment']['page'] = 'payment';
}

```

---
Tags: commerce
---


title: H1 tag not showing on front page

text:
# Question
Title: H1 tag not showing on front page
Im using Drupal 7.41 and Omega3 sub theme and Ckeditor. I have added a sentence in the style of heading (h1) at the top of my Home Page content, it shows in Ckeditor using the source button (showing markups) with H1 tags around the heading, and shows in the style of H1 normally in Ckeditor. When I save and close off the edit, it just appears as normal text, and as P tags when I view via Firefox (View Source) , the H1 markup is not showing, when I go back into Ckeditor, I can see its in the style of H1 and when I click Source button, i can see it has the H1 tags around it. When I View Source on Firefox, it shows as P tags. I have flushed Cache, and checked but it still shows as P tags.

Basically, its showing correctly in Ckeditor (with/without clicking Source button), the markup is not getting wiped, but its just not showing when I view the webs page when I come out of Ckeditor (either logged in or not). Can anyone help?

# Answer
go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.

**If the above does not do it**, depending on which one you are using (filter or custom) You need to go to

/admin/config/content/formats/filtered\_html

### **add the `<h1>` to the limit allowed html list**
> 3 votes

---
Tags: theming, wysiwyg
---


# Question
Title: How can I rewrite an "edit" operations link in Views?
On Drupal 8, I'm trying to modify `/admin/people` to have the **edit** button read **edit username** instead of **edit**.

What's the easiest way to do this?

# Answer
1. Under fields, add the **User ID**. Select *Exclude from display* and choose *Unformatted* for the **Formatter**.
2. Under fields, add **User Name** again. Uncheck *display as link*. Under **Administrative Title**, you can add something descriptive like `user name (no link)` so that you can remember what this is for.
3. Rearrange the fields so that **User ID** and the second **User Name** fields are at the top.
4. Click **User: Operation Links** under **Fields**. Under **Rewrite results**, input the following for the text: `<a href="/user/{{ uid }}/edit">edit {{ name_1 }}</a>`

This makes a plain link instead of a button. I imagine there is a more efficient way to do this, but this is the best I could come up with for now.
> 3 votes

---
Tags: views, 8
---


title: Append Nodes To Top of View Result

text:
# Question
Title: Append Nodes To Top of View Result
I have a view with multiple taxonomy filters. I need to have it set up so that when a certain term is chosen I need certain nodes to show up on top. Because of this I can't just simply use Sticky!

I'm thinking I will need to write something custom or perhaps use in addition to EntityQueue.

# Answer
> 1 votes
I ended up creating a Flag and sorting by flag and using hook\_views\_query\_alter() to remove the sort condidtion if the filters were not set in the views.

# Answer
> 0 votes
I'm pretty sure that a views attachment will inherit the exposed filters. You can add it from the same list where you find page, block etc.

---
Tags: 7, views
---


# Question
Title: Handle formatting of longtext value for entity wrapper
So I have a working setup where some code pulls in the latest Wikipedia extract of a page. I then use Entities to handle a node creation, adding the contents of the extract to the longtext value of the generic body field:

```
$body = array();
$url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles='.urlencode($item['name']);
$result = @file_get_contents($url);
if ($result){
  // Oh yes!
  $decoded = json_decode($result, true);
  foreach ($decoded['query']['pages'] as $page){
    if (array_key_exists('extract', $page)){
      $body[] = t($page['extract']);
    }
  }
} else {
  // Boo, nothing found.
}

// Doesn't exist, we have to make it first. (Using Entities)
$node = entity_create('node', array('type' => 'article', 'uid' => 1));
$entity = entity_metadata_wrapper('node', $node); // $node->nid is probably better here
$entity->title->set($item['name']);
if ($body){
  $entity->body->set(array('value' => $body[0]));
}
$entity->save();
// Woo got our nid!
$nid = $entity->getIdentifier();

```

The problem is, I can't seem to control the output of the body at all. It renders surrounded with paragraph tags, using html line breaks for each paragraph. I want to surround each paragraph with paragraph tags. I've tried using preg\_match to catch newlines (\r\n) but anything I replace it with just gets rendered exactly - making paragraph tags show up in the extract text when viewing the node.

What's the best method of doing some formatting to the extract?

# Answer
You just need to specify a format for your text value:

```
$entity->body->set(array('value' => $body[0], 'format' => 'full_html'));

```
> 4 votes

---
Tags: 7, entities
---


# Question
Title: Adding priced options to products in Drupal Commerce
For something that's pretty basic this seems overly complicated! I'm working on updating a computer store from Ubercart to Drupal Commerce. Computers can be custom built so there are multiple options to choose. If I have to create a SKU for each variation I will go absolutely crazy!

So I've tried:

* bundling modules - but they doesn't allow you to choose options
* commerce pricing attributes - but it doesn't seem to work anymore "The "hunziker" approach to Drupal Commerce is not supported nor recommended by the creators of Drupal Commerce. Thus, any problems you might have with the modules is "by design" unfortunately." - Commerce Attribute price is not updating in cart
* Commerce Customizable Products - seems the most promising but after following the "pizza store" video multiple times even with a clean install - everything works A-OK till the rules. When I get to the part where I am adding in the rules, I can add in the "Entity has field" part properly, but when I add the loop, I don't have the option for just "commerce-line-item:field-foo". It ends the commerce-line-item:field-foo with a colon and wants you to pick more. no matter what combination I try I end up with a rule error about lists: "Error: The data type of the configured argument does not match the parameter's list requirement".

I'm absolutely going nuts with this!! It shouldn't be this hard... should it?

The process I'm following for Customizable products is as follows (adding an Antivirus choice to a custom computer content type):

1. Install Customizable Products
2. Add a custom line item Store \> Configuration \> Create New Line Item Type called “Custom Computers”
3. Create a Taxonomy, called "Computer Antivirus"
4. Add price field to taxonomy (with currency) called "Price" – Field Type “Price” \> Currency CDN
5. Add a few taxonomy terms with prices
6. Add a Taxonomy term reference field "Computer Antivirus" to custom line item type, Store \> Configuration \> Line Item Types \> Custom Computers

• Manage Fields

• Add new field “Antivirus” – Term Reference – Checkboxes

• Choose “Computer Antivirus” Taxonomy Vocabulary

• Include this field on Add to Cart Forms…

7. Set up products to use new line type. Configure the display of the add to cart form on the custom product type to use the custom line item type

• Structure \> Content Types

• Choose Manage Display on the Content type you need to change

• Edit the Product – Add to Cart form \> Choose the Line item type “Custom Computer”

• SAVE!!!

8. The custom options will now appear below the product
9. Change the price

• Create a Pricing rule

• Store \> Configuration \> Product Pricing Rules

• Add new Rule named “Antivirus Rule”

• Add a condition: Entity has field - Data Selector: commerce-line-item - Value: field\_antivirus

**HERES WHERE THE PROBLEM IS - Add a Loop:- Data Selector: commerce-line-item:field-antivirus - Current List Item: change name**

• Add an action to the loop: - Commerce line item: Add an amount to the unit price - Amount Value: switch to data selection: pizza-topping: field-price:amount \- Price Component Type: Fee - Value: Round the half up

I've been working with this about 4 weeks now with no solution. Can anyone shed some light on whats wrong?

# Answer
> 3 votes
> Oh and no - I didn't set the term reference field to unlimited values because I only want them to pick one value from the list

I believe that is the problem... either you make it unlimited; even though, you will use it once

OR leave it at 1, but don't use a loop, just add action (for Amount Value data selection use commerce-line-item:field-price:amount)

---
Tags: commerce, rules
---


# Question
Title: Getting field labels from the $node variable
How can I get the labels of specific fields within a node, in Drupal 7?

The field for which I am interested has the following structure:

```
    [field_text_question1] => Array(
      [und] => Array(
        [0] => Array(
          [value] => Sales Intern
          [format] =>
          [safe_value] => Sales Intern
        )
      )
    )

```

# Answer
> 13 votes
The best way is to use field\_info\_instance($entity\_type, $field\_name, $bundle\_name) to get information about specific instace of a field. The label of the field is contained in the array returned from that function.

```
 $info = field_info_instance('node','field_name','content_type_name');
 print $info['label'];

```

# Answer
> 1 votes
I believe you are looking inside the `$node`variable. It is not available there. Only the field values are store inside the `$node` variable not the field settings (such as the label). If you want the label look in the `$content` variable.

`$content` variable is available in the `MYTHEME_preprocess_node(&$variable)` theme template function, `node.tpl.php`, as well as, a few others.

If it is not available, you can call `field_info_field($field_name)`

# Answer
> 0 votes
The easiest way to print the field label of a node is:

```
<?php print $content['field_your_field_name']['#title']; ?>

```

(I've discovered it after a lot of print\_r arrays and objects of Drupal! If it's so easy, why isn't explained anywhere, or why is so hidden that I've not found the trick? And passed a long time from the question to this answer...)

---
Tags: 7, entities
---


# Question
Title: How do I get a field label by the field name?
How do I get a field label by the field name in Drupal 7?

# Answer
> 14 votes
The label is set per instance (not per field) so you would use the `field_info_instance()` function with some appropriate arguments:

```
$entity_type = 'node';
$bundle_name = 'article';
$field_name = 'field_some_field';

$info = field_info_instance($entity_type, $field_name, $bundle_name);

$label = $info['label'];

```

There's a bunch of other useful functions in the Field Info API documentation that might be helpful in case you haven't seen it already.

# Answer
> 2 votes
The easiest way to **print the field label** of a node is:

```
<?php print $content['field_your_field_name']['#title']; ?>

```

(I've discovered it after a lot of *print\_r* arrays and objects of Drupal! If it's so easy, why isn't explained anywhere, or why is so hidden that I've not found the trick? And passed a long time from the question to this answer...)

---
Tags: 7, entities
---


# Question
Title: How to exclude a node from being indexed based on a field value?
I would like to exclude some nodes from being indexed based on one field value (not content-type) on a drupal 7 installation, I can't find a hook letting me doing it, please help ! thank you

# Answer
The hook to use is the following one:

```
/**
 * Implements hook_search_api_index_items_alter().
 */
function CUSTOM_MODULE_search_api_index_items_alter(array &$items, SearchApiIndex $index) {
    foreach($items as $id => $item){
        if(isset($item->YOUR_FIELD) && $item->YOUR_FIELD[key($item->YOUR_FIELD)][0]['value'] == 'FORBIDDEN_VALUE') unset($items[$id]);
    }
}

```
> 1 votes

# Answer
As said in the API, using hook\_search\_api\_index\_items\_alter is not the best choice. You should use hook\_search\_api\_alter\_callback\_info

Example :

```
function mymodule_search_api_alter_callback_info() {
  $callbacks['exclude_some_nodes'] = array(
    'name' => t('Exclude some nodes'),
    'description' => t('Exclude some nodes from being indexed based on one field value'),
    'class' => 'SearchApiExcludeSomeNodes',
  );
  return $callbacks;
}

class SearchApiExcludeSomeNodes extends SearchApiAbstractAlterCallback {

  public function supportsIndex(SearchApiIndex $index) {
    return $index->getEntityType() === 'node';
  }

  public function alterItems(array &$items) {
    foreach ($items as $k => $item) {
      if($item->field_your_field['und'][0]['value'] == 'do_not_index') {
        unset($items[$k]);
      }
    }
  }

}

```

This will appear as an option in the UI of Search API, in the Data alterations section (admin/config/search/search\_api/index/your\_index/workflow)
> 3 votes

# Answer
Try to use the Finder module.

> Finder allows Drupal site administrators to create flexible faceted search forms to find entities such as nodes or users based on the values of fields and database attributes.

NOTE: Finder module is an Unsupported Project due to security issue as of October 14, 2008
> 1 votes

# Answer
Use `hook_apachesolr_node_exclude()`. An example implementation is given in the API doc:

```
/**
 * This is invoked by apachesolr.module for each node to be added to the index.
 * If any module returns TRUE, the node is skipped for indexing. Note that nodes
 * which are already present in the index and subsequently qualify to be
 * excluded will not be removed from the index automatically. This hook can be
 * used to remove them prior to returning TRUE.
 *
 * @param object $node
 *   The node object which is being indexed.
 * @param string $namespace
 *   Usually the calling module (eg. 'apachesolr_search').
 *
 * @return bool
 *   Return TRUE to skip the indexing of the node.
 */
function hook_apachesolr_node_exclude($node, $namespace) {
  // Exclude nodes from uid 1.
  if ($node->uid == 1) {
    apachesolr_delete_node_from_index($node);
    return TRUE;
  }
}

```
> 1 votes

---
Tags: 7, search
---


title: How do I get the field label?

text:
# Question
Title: How do I get the field label?
I added some fields to the "Article" content type. I want to output them in a page--front.tpl.php. How do I get the field label value?

When I use the following code in page--front.tpl.php, it doesn't show the name of the field label. Why? What code should I use to print the field label?

```
$node = node_load(1);
print_r($node);

```

The output is similar to the following:

```
    [field_sq] => Array(
      [zh-hans] => Array(
        [0] => Array(
          [value] => 250
        )
      )
    )

```

# Answer
In node-article.tpl.php add this code at the beginning

```
// loop through node properties
foreach ($node as $k => $v) {
  // ensure this property is a field
  if (substr($k,0,6) == 'field_') {
    // use the CCK function to get the field data for this field
    $fieldData = content_fields($k, $node->type);

    // add the label to the array
    $fieldLabels[$k] = $fieldData['widget']['label'];
  }
}

```

Than you can print labels like this:

```
<?php if ($node->field_YourField[0]['view']){ ?>

    <?php print $fieldLabels['field_YourField']; ?> // prints label (add div/span wrapper if you need it)

    <?php print $node->field_YourField[0]['view'] ?> // prints field value (add div/span wrpaer if you need it)

<?php } ?>

```

This is tested in Drupal 6. Hope it helps.
> 3 votes

# Answer
Fields are available in the node.tpl.php template (see the $content array), but not the page.tpl.php template unless you write some code to do that.

If you want to display node fields outside of the node template, Panels is another option but may be overkill depending on your needs.
> 2 votes

# Answer
Try to use in your tpl.php the following code to print the fields:

```
<?php print_r(array_keys($content)); ?>

```

Then you see the values and you can go modify creating for example a field--yournamefield.tpl.php.
> 2 votes

# Answer
You can use as follows to get field label

```
$entity_type = 'node';
$bundle_name = 'article';
$field_name = 'field_some_field';
$info = field_info_instance($entity_type, $field_name, $bundle_name);
$label = $info['label'];

```
> 1 votes

# Answer
The easiest way to **print the field label** of a node is:

```
<?php print $content['field_your_field_name']['#title']; ?>

```

(I've discovered it after a lot of print\_r arrays and objects of Drupal! If it's so easy, why isn't explained anywhere, or why is so hidden that I've not found the trick?)
> 0 votes

---
Tags: theming, entities
---


# Question
Title: How can I auto-increment available options for an integer field?
I have a set of available options for an integer field:

```
2011|2011
2012|2012
2013|2013
...etc

```

The thing is I want years all the way to 2050. Is there a way to set a step increment in this field? I could create the list in a text editor and paste it, but I'd love to find a more elegant solution using code or some way of incrementing the options.

# Answer
> 1 votes
> I could create the list in a text editor and paste it

You can use Microsoft Excel. on A(1) put 2015 on A(2) put 2016.

Highlight both cells, click on the bottom right corner (you will get a + cursor) and drag down.

---
Tags: 7, entities
---


# Question
Title: View displaying field collection items based on taxonomy term
I have a set of nodes that include a field collection item GeoImages. (Each node can contain multiple Geoimages, if that's relevant).

Geoimages includes (among other fields) an Image and and Image tags field (which relates to an Image Tags taxonomy).

When viewing a node including the GeoImages field collection, I want to click on a tag associated with an image and see the GeoImages field collection items with the same tag.

When I click on a tag within a GeoImage (say Image Tag1), I navigate to the path:\[site\]/image-tags/image-tag1 -- which shows a page title of "Image tag1" but no content.

I have created a view to view field-collection-items as below. When I preview the Page with with the contextual filter sat to "Image tag1" it shows a path of image-tags/Image tag1 and shows the desired content... Ditto if I set the contextual filter to image-tag1.

What blindingly obvious thing have I missed?

\[I will kick myself when I get an answer but I'm banging my head against a brick wall right now, so kicking myself will be less deleterious.\]

```
$view = new view();
$view->name = 'image_tags';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'field_collection_item';
$view->human_name = 'Image tags';
$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'] = 'Image tags';
$handler->display->display_options['use_more_always'] = FALSE;
$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['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'entity';
/* Relationship: Field collection item: Entity with the GeoImages (field_geoimages) */
$handler->display->display_options['relationships']['field_geoimages_node']['id'] = 'field_geoimages_node';
$handler->display->display_options['relationships']['field_geoimages_node']['table'] = 'field_collection_item';
$handler->display->display_options['relationships']['field_geoimages_node']['field'] = 'field_geoimages_node';
$handler->display->display_options['relationships']['field_geoimages_node']['required'] = TRUE;
/* Relationship: Field collection item: Image tags (field_image_tags) */
$handler->display->display_options['relationships']['field_image_tags_tid']['id'] = 'field_image_tags_tid';
$handler->display->display_options['relationships']['field_image_tags_tid']['table'] = 'field_data_field_image_tags';
$handler->display->display_options['relationships']['field_image_tags_tid']['field'] = 'field_image_tags_tid';
$handler->display->display_options['relationships']['field_image_tags_tid']['required'] = TRUE;
/* Field: Field collection item: Field collection item ID */
$handler->display->display_options['fields']['item_id']['id'] = 'item_id';
$handler->display->display_options['fields']['item_id']['table'] = 'field_collection_item';
$handler->display->display_options['fields']['item_id']['field'] = 'item_id';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: Taxonomy term: Name */
$handler->display->display_options['arguments']['name']['id'] = 'name';
$handler->display->display_options['arguments']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['arguments']['name']['field'] = 'name';
$handler->display->display_options['arguments']['name']['relationship'] = 'field_image_tags_tid';
$handler->display->display_options['arguments']['name']['default_action'] = 'empty';
$handler->display->display_options['arguments']['name']['title_enable'] = TRUE;
$handler->display->display_options['arguments']['name']['title'] = '%1';
$handler->display->display_options['arguments']['name']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['name']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['name']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['name']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['name']['limit'] = '0';
$handler->display->display_options['arguments']['name']['case'] = 'ucfirst';
$handler->display->display_options['arguments']['name']['transform_dash'] = TRUE;
$handler->display->display_options['path'] = 'image-tags/%';

```

The generated query is:

```
SELECT field_collection_item.item_id AS item_id
FROM
{field_collection_item} field_collection_item
INNER JOIN {field_data_field_geoimages} field_data_field_geoimages ON field_collection_item.item_id = field_data_field_geoimages.field_geoimages_value
INNER JOIN {node} field_geoimages_field_collection_item ON field_data_field_geoimages.entity_id = field_geoimages_field_collection_item.nid
LEFT JOIN {field_data_field_image_tags} field_data_field_image_tags ON field_collection_item.item_id = field_data_field_image_tags.entity_id AND (field_data_field_image_tags.entity_type = 'field_collection_item' AND field_data_field_image_tags.deleted = '0')
INNER JOIN {taxonomy_term_data} taxonomy_term_data_field_data_field_image_tags ON field_data_field_image_tags.field_image_tags_tid = taxonomy_term_data_field_data_field_image_tags.tid
WHERE (( (taxonomy_term_data_field_data_field_image_tags.name = 'image tag1') ))
LIMIT 10 OFFSET 0

```

# Answer
> 1 votes
The Drupal module Taxonomy Display allows you to modify the behaviour when you click on a tag, to display a view of your choice rather than see the default Drupal term page (which doesn't work for field collection items).

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


title: Display alias instead of node

text:
# Question
Title: Display alias instead of node
I am trying to create a link in page.html.twig that points to an alias. The code `{{ url('node/1') }}` shows an unexpected error, whereas {{ 'node/1' }} works fine but goes to url website/node/1.

In D7, one can use `<?php echo url('node/1'); ?>` and be directed to the page with proper alias.

What code can be used in D8 to display correct alias url?

# Answer
> 2 votes
You can use `getAliasByPath` function to get the url alias for a path.

Put the below code in `THEME_NAME.theme` file.

```
function THEME_NAME_preprocess_page(&$variables) {
  $variables['url_alias'] = \Drupal::service('path.alias_manager')->getAliasByPath('/node/1');
}

```

Finally print the `url_alias` in your `page.html.twig` file.

```
{{ url_alias }}

```

# Answer
> 1 votes
The twig functions `url` and `path` operate on *routes* and not *paths*, so you must specify the route name and the necessary parameters.

```
{{ path('entity.node.canonical', {'node': 1}) }}

```

---
Tags: theming, 8
---


# Question
Title: How to use Rules to disable access to selected fields while editing an existing node?
Based on couple of features I require to restrict/disable access to certain field based on other fields while editing the node.

The problem is that in Rules module, there's no "While editing an existing node" event.

What I want is to set an action for the user while editing the node.

# Answer
You're right, there is no such event like "While editing an existing node". Probably because an event is something that takes like a fraction of a second, while editing may take minutes (hopefully not hours!).

However, you might get it to work by implementing an "**edit-in-progress**" (= EIP) feature using the Flag module, combined with using the Rules module. Similar to what I described in my answer to "Can the Flag module be used to lock content while editing to prevent concurrent edits?" (BTW, that question is a variation of yours, I don't think it's a duplicate though ...).

After you'd have such EIP-flag available, it should be straight forward to use it in appropriate Rules to "*restrict/disable access to certain fields*" (eg based on a data comparison to validate selected field values (using their before and after save values).
> 2 votes

---
Tags: 7, entities, rules, users
---


title: Change the link title of a custom view

text:
# Question
Title: Change the link title of a custom view
I created a view via the administration interface. This view lists content (style teaser; title and image). The default link of titles is /node/'nid'; I want to replace the link with /custompate/'nid'.

I suppose I must "find" the template of my custom view and overwrite it in a custom module.

How can I find the name of the template for this specific view?

Edit : the "advanced" block in my view (theme information is missing :/)

# Answer
One way to accomplish this would be to change the view from showing content to showing fields. You can then add the fields that you want to show, title and image.

To change the link of the title, you can add the nid as a field, hide it, and then rewrite the output of the title field to include the custom path and nid in the link.

To find the template files of the view, you need to click on the "Advanced" tab and look for "Theme: Information". You'd need a sub-theme to register the template file being overwritten. Drupal Sub-theming

To overwrite it in a module, you could use a pre render hook and modify the rows on the result fields.
> 2 votes

# Answer
There are 2 aspects to the problem: 1) having the desired URL in the view for each content item; and 2) having those URLs go to the right Drupal page

The first part can be solved in the Views dialog by specify the fields you want in the view (Format\>Show\>Fields) and then for the Title field choose to "Rewrite results" into being a link. It's fiddly, and I imagine you'll have to use tokens, but it's a standard task and the Views docs should able to guide you through it.

The second part can be solved by modules like pathauto or redirect.
> 0 votes

# Answer
Use this format:

`views-view--[viewsMachineName]--[viewsDisplay].html.twig`

for example;

`views-view--articles--block.html.twig` for a view named `articles` which display type is block.

This worked for me, hope it helps you too.
> 0 votes

---
Tags: views, theming, 8
---


title: Why nodes are stdClass?

text:
# Question
Title: Why nodes are stdClass?
My question is a little bit vague. Why do we use stdClass(es) to represent objects in Drupal 7? is there a practical use to it ? Why not just using arrays ?

# Answer
Generally speaking, objects are used for storing structured data and arrays for lists or collections.
It even logically makes more sense. Node is an object with properties; it's not an array of properties.

See this answer posted on SO as an example.
> 3 votes

---
Tags: nodes
---


title: Translating contact forms

text:
# Question
Title: Translating contact forms
Is there a way to fully translate the contact message forms in Drupal 8? In the content language screen, the contact message bundle is marked as ***translation is not supported***.

**Edit**: To clarify, I would like to translate the fields of the form. As some answers note, the fields can be translated via the regular field translation, but I am running into an issue whereby translations are replaced by the English version when the cache is cleared. By going to /admin/config/regional/content-language and saving the form, the translations are back.

(Note that the default language on the site is not English.)

# Answer
I think, content in contact messages is the user input. Then you cannot translate this, because it is not saved to the database. The form itself is config translation, similar to the field definitions in content types.
> 2 votes

# Answer
Leaving a full answer here for post-release Drupal searchers.

The message "translation is not supported" refers to the content of the fields. The content in this case is not stored, ergo, cannot be translated - unlike, for example any node title or image description.

To translate content like field contents, the required modules are `languages` & `content translation`. In your case, you want to actually translate the field titles. This is classed as `configuration translation` which requires the module of the same name, and that in turn depends on `interface translation`. So basically, you'll have all of the core modules enabled to perform this task (as obviously you will be translating content as well, right?)

When you have enabled the required modules, you will need to download the .po translation file from .drupal.org and import them in the area `User interface translation > Import`. Also you can check for updates to your module interface translations under `Reports > Available translation updates`.

Translating a contact form's fields then is done automatically (if the language file provided for that). Translating the contact form's configurable items is a matter of visiting `Structure > Contact forms` and selecting `translate` on the edit/context menu of the form required, whereby you can translate the auto-reply etc.
> 2 votes

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


# Question
Title: How to check field value against same field on existing nodes of same content type
I wonder if it possible to check the value of a filed against same field in already existing nodes of same content type.

My case: I have a content type property where people advertise their properties, inside property content type I have a field Phone number. I would like to have a rule to check the value of phone number filed against all the existing properties when user click save on creating new property page and send email to administrator with value of the phone number field.

For my experience the Rules module should be able to do that, but I can't figure how.

How dose Unique field module work?

Knowing about the way Unique field module functionality i can customise the module/create my own to send email if there was a any other content with same phone number

# Answer
I don't know how to achieve that with rules, but you could use EntityFieldQuery, in a custom submit callback of property\_node\_form. Something like that :

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_property_node_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'mymodule_property_node_form_submit';
}

function mymodule_property_node_form_submit(&$form, &$form_state) {
  $phone_number = $form_state['values']['field_phone_number'];

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'property')
    ->propertyCondition('nid', $form_state['node']->nid, '<>')
    ->fieldCondition('field_phone_number', 'value', $phone_number)
    ->range(0, 1);

  $same_phone_count = $query->count()->execute();

  if($same_phone_count > 0) {
    // send mail
  }
}

```
> 2 votes

---
Tags: 7, nodes, rules, forms
---


# Question
Title: Creating view content link that links to data based on taxonomy terms
how can I create view content link that links to data based on taxonomy terms?

I have stores in stores page...stores are in views..each store should have a link that links to its products.

# Answer
> 1 votes
Here's how to achieve this:

* Add relationship that references the taxonomy field you use in the content type.
* Add a `Taxonomy term: Term ID` field in Views. Exclude it from output.
* Add a `Custom Text` field in Views.
* Under `Rewrite Results` check the `Output this field as a link` checkbox. In the link path use the token for taxonomy term id - `[tid]`. If you want to use the core page, just enter `taxonomy/term/[tid]`.

Hope it helps.

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


# Question
Title: Why doesn't drush check for updates of dev versions of my modules installed by composer?
I am using Drush (8.0.3) on my Drupal 8 site (8.0.3) to check for updates, but **Drush is not checking for updates of any modules that I checked out the dev branch for.**

```
$ drush @mysite ups --check-disabled
Checking available update data for Drupal.                                  [ok]
Checking available update data for Address (address).                       [ok]
Checking available update data for CloudFlare (cloudflare).                 [ok]
Checking available update data for Commerce (commerce).                     [ok]
Checking available update data for Composer Manager                         [ok]
(composer_manager).
Checking available update data for Chaos tools (ctools).                    [ok]
Checking available update data for Domain Registration                      [ok]
(domain_registration).
Checking available update data for Entity (entity).                         [ok]
Checking available update data for Google Analytics                         [ok]
(google_analytics).

```

I have dev branches of the following modules:

* Inmail
* SMTP
* Rules
* Several others not in the list above

Now I have some idea about what may be wrong: I am using Pantheon for my site, and I added these modules to `composer.json`, then ran `composer update` to install them. For dev modules, this adds `.git` repositories for each dev module.

I then committed all this to Pantheon, which gave me a message about not supporting submodules. I ignored this message because I could still install the modules on Pantheon, but I now suspect that either this or installing via composer has somehow busted Drush for me.

How can I get Drush to also check for updates to the dev branches of modules installed by composer?

# Answer
> 3 votes
Drush relies on information written by the Drupal.org package manager to determine whether or not updates are needed to modules or core.

If you use `git` to install Drupal modules, then you may also use the git-deploy module, and it will add the information needed for Drush to do the update. Git deploy also works for modules installed via Composer using git; Composer uses git to install when using the --prefer-source directive, or when the module version installed is a development version.

If you use the Composer option --prefer-dist, then Composer will install the tarball packaged by drupal.org, which is why git-deploy is not needed in most cases for stable modules.

Note that there is a bug in git-deploy that prevents it from working when the path to the Drupal root contains spaces. There is a patch to fix this problem available in the git-deploy issue queue; see #2672166.

# Answer
> 2 votes
If you are using Composer, why do you even need to use Drush to check for updates? You can just run `composer update` and it will automatically pull updates in.

(This is not the definitive answer, but it occurs to me I could take this approach since I only update modules from my local dev machine anyway.)

---
Tags: drush, composer
---


# Question
Title: remove theme tab on blocks for certain roles
I'd like to hide/remove theme block tabs for certain roles in drupal. For example Administrator can edit both theme blocks, but other roles can edit only blocks that are available in their current theme.

Picture:

As you can see on picture, I'd like to hide **SEVEN** from other roles that are not **Administrator** ? Any ideas.

Thanks!

# Answer
Your answer led me to the correct solution.

Correct answer is this :

```
function remove_tab_for_non_admins_menu_alter(&$items) {
  if(isset($items['admin/structure/block/list/seven'])) {
    $items['admin/structure/block/list/seven']['access callback'] = 'remove_tab_for_non_admin_check_access';
  }
}

function remove_tab_for_non_admin_check_access() {
  global $user;
  return in_array('administrator', $user->roles);
}

```
> 1 votes

# Answer
```
function HOOK_menu_alter(&$items) {
  global $user;
  if(in_array('administrator', $user->roles) == FALSE && in_array('admin/structure/block/list/seven', array_keys($items)) == TRUE) {
    // This allows the path to still be registered but not displayed
    $items['admin/structure/block/list/seven']['type'] = MENU_CALLBACK;
  }
}

```
> 2 votes

---
Tags: 7, blocks, theming
---


title: How easy is Drupal for E-Commerce?

text:
# Question
Title: How easy is Drupal for E-Commerce?
I'm looking for the right tool to develop a peer to peer trading website that would include E-Commerce. The site would need to allow registered sellers to enter details about their products this information would then need to be stored in a database that would allow buyers to search based on a set of parameters.

Would all this be achievable with current Drupal modules and how much additional coding would be required to knit it all together?

# Answer
> 3 votes
You don't need any coding to achieve this functionality, you can just go with Commerce and using Drupal's built-in roles, manage who has the permission to create content (items to sell) and who has the permission to buy it.

for the search aspect of it, I suggest trying Search API, which gives you facet like filtering feature (Like ebay), also you might wanna check Apache Solr for faster indexing

# Answer
> 1 votes
> Would all this be achievable with current Drupal modules

Yes your requirements/specs seem to be perfectly doable with "current" Drupal, if you're talking about Drupal version 7 and starting from Drupal Commerce with specific add-on modules.

For Drupal version 8, things will get even better ... provided you can be a bit patient. Refer to Commerce 2.x for Drupal 8 for lots of details about what's coming up in D8 ...

> How much additional coding would be required to knit it all together?

Since Drupal Commerce is pretty much entity based, you'll get a lot of things done without additional coding, only using modules such as Rules, Group, etc.

---
Tags: users, database
---


# Question
Title: How to set default form values based on query string, if the form uses AJAX file upload
I have a `Book` content type with a file upload field.
I'm using Filefield Sources module with Plupload integration for getting the file upload widget.

I need to set a default value based on the query string passed on `node/add/book` page.

However, the files are uploaded via AJAX, calling the `file/ajax` page, and losing all default values I set. Obviously, custom query string is not present in that call, and when the form is re-generated, I get an error.

Any ideas on how can I make sure that default values stay in the form?

Thanks!

# Answer
> 1 votes
I forgot to post the answer.

To keep the data persistent between AJAX calls, you should store it in the `$form_state` variable. This is how it worked in my case:

1. Check if I already have the data in `$form_state`.
2. If not and if there is query string, get the data, sanitize/validate it and store in `$form_state`.

This way it works even for AJAX calls where query string parameters are not available.

---
Tags: 7, forms, files
---


# Question
Title: After doing a file_save_upload() how do you resize the images?
I created a custom form in Drupal 7 with the ability to upload an image by using `file_save_upload()`. The image file has been uploaded and a fid has been assigned to it. How do I render this image into the different image styles I have setup?

# Answer
```
print theme('image_style', array(
  'style_name' => 'your_style_name',
  'path' => $your_file->uri,
));

```

theme\_image\_style
> 3 votes

# Answer
I went and used image magick to generate the images vs using drupal core functions. Since I didn't have the image styles setup. I needed a way to generate these resized images and then place them in the proper folder with the proper name. First I create a form field for file uploading. And in the \_submit function for the custom form. I have the following below. "file\_thumb" is the name of my form file field.

**thfile** is grabbing the existing thumbnail filename so it can be overwritten with imagemagick.

**-\>writeImage** function will write the file to its new location.

```
//Generate new images for CUSTOM image file uploaded
$file_thumb = file_save_upload('file_thumb', array(), 'public://');

if ($file_thumb) {
  $thfile = $node->field_thumbnail[$node->language][0]['value'];

  $grid_thumb = new Imagick(get_absolute_file_root() . $file_thumb->filename);
  $grid_thumb->thumbnailImage(200, 200, true);
  $grid_thumb->writeImage(get_absolute_file_root() . 'grid-thumbnail/' . $thfile);

```
> 0 votes

---
Tags: 7, media
---


# Question
Title: How do I load a third party PHP library?
I have a third party php library which I would like to use in a module. How do I do that in Drupal 8? In drupal 7, I have done things like the following code, but `libraries_get_path()` doesn't exist in Drupal 8, and I'm not exactly sure how things change, not that we use namespaces (of which I am a beginner).

```
require(libraries_get_path('twitter-api-php') . '/TwitterAPIExchange.php');

```

And, where should I place my library? Should I create a new libraries directory and put it in the root, just like modules and themes are now in the root?

# Answer
> 4 votes
The 8.x-3.x branch of the Libraries module still provides the `libraries_get_path()` function. And (as of now) it looks pretty much unchanged. So you should be able to use it in the same way.

As far as where to put your library, the `libraries_get_libraries()` function has been updated with the following addition to the `$searchdir` array:

```
// Always search the root 'libraries' directory.
$searchdir[] = 'libraries';

```

Which indicates that you can place your libraries in a directory named "libraries" at your site root.

# Answer
> 3 votes
Composer:

> Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you.

plus the Composer Manager module:

> Composer Manager provides a gateway to the larger PHP community by enabling Drupal modules to more easily use best-in-breed libraries that are managed by Composer.

can handle this.

# Answer
> 1 votes
If you use the libraries module and you put your library files in /libraries/library (which is where mine end up using drush make) you can simply call library\_load('library') and that will do the require\_once for you.

# Answer
> 0 votes
Using Composer Manager is good solution but it need access to command line to init Also you can use module\_load\_include like we use it in Drupal7. Put your Php file in you module directory and use

```
  module_load_include('php', 'modulename','filename');

```

---
Tags: 8, theming
---


# Question
Title: How to fix field collection ajax #edit-submit clash with node #edit-submit?
I have Drupal 7.41, field\_collection 7.x-1.0-beta10+1-dev, and field\_collection\_ajax 7.x-1.x-dev

I am the admin of a site where we have a disease content type, and a part of each disease node is its lab tests. (Some diseases have upwards of 400+ lab tests) I use Field Collection to format the lab tests, and I use Field Collection Ajax to display them in an way that makes them easier to work with when there are many lab tests.

Field Collection Ajax uses ajax to display, edit, and save the individual field collection items. The "Save Item to List" button for Field Collection Ajax appears to be getting mixed up with the node save button. They both have the same id #edit-submit. I don't know for certain, but it appears that on the disease nodes that have 400+ lab tests after you edit a lab test, the next time you try to save another field collection item to the list it acts like you are trying to save the node, and the next time you try to save the node it acts like you are trying to save a field collection item.

Does anyone have any experience with this happening with field\_collection\_ajax and know how to solve it?

# Answer
The problem was that that large node was hitting the max\_input\_vars cealing. So I just had to increase that and it worked.
> 0 votes

---
Tags: ajax, entities
---


# Question
Title: Anyway to disable minification (make line breaks) in the source view of CKEditor WYSIWYG
My question is different from one I've seen answered quite a bit here and elsewhere. My line breaks are showing up in WYSIWYG and the rendered content just fine. However, I was wondering if there is a way to make CKEditor/WYSIWYG preserve line breaks when I view the code as well. I sometimes need to edit code in the HTML, and it's a mild inconvenience to have to sift through minified code to find stuff.

Any help is appreciated. Thanks.

# Answer
> 2 votes
Edit WYSIWYG profile that uses CKEditor and in `"Cleanup and output"` settings check `"Apply simple source formatting".` (screenshots below for visuals)

---

---

---
Tags: 7, wysiwyg
---


# Question
Title: How can I compare data comparison with values submitted in a webform?
I am trying to use webforms with the Rules module.

How can I compare data with the values submitted in a webform ?

For example, if the webform has a yes/no radio button, how can check the submitted value is *yes*?

When adding a new condition, I choose:

* Data Comparison
* Data selector *
* Data (the submitted webform value)

I'm not sure how to access a particular form\_key to check its value. I feel like Data should have more options to choose from.

# Answer
At a minimum, make sure you have the Webform Rules module enabled. Some details about it (from its project page):

> This module adds rules integration on webforms.
>
> Did you ever want to react on webform submission using rules but couldn't find the proper event?
>
> Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

You may also want to have a look at feature request "Expose submission data to rules". Here is a summary of it:

> Right now, submission data is not exposed to rules except by way of token replacement or custom php actions. This patch exposes submission data in a "first-class" way.

Issue status is "Needs work" ... not an "easy" issue.

# Time for a work around ...

The very same issue contains a comment with a workaround (it's genious I think, because it's so simple), here is a relevant quote from it:

> You can initialize a rules string variable with the tokens. If you need integers or booleans you can subsequently convert it to whatever and then use it to load nodes or whatever.

A picture is worth more then 1000 words, checkout the screenprint included in that comment.

# ... and a demo

Consider this rule (in Rules export format):

```
{ "rules_validate_a_component_of_a_submitted_webform" : {
    "LABEL" : "Validate a component of a submitted webform",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "user" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform component submitted by [data:contact_us_first_name-value] (= [data:contact_us_first_name-title]) [data:contact_us_last_name-value] (= [data:contact_us_last_name-title]) contains a field labeled \u0022[data:contact_us_subject-title]\u0022 which has value \u0022[data:contact_us_subject-value]\u0022 and another field \u0022[data:contact_us_message-title]\u0022 which has value \u0022[data:contact_us_message-value-raw]\u0022." } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:contact_us_message-value-raw]" },
          "PROVIDE" : { "variable_added" : { "submitted_form_component_value" : "Submitted form component value" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "text_matches" : { "text" : [ "submitted-form-component-value" ], "match" : "mail.ru" } },
            "DO" : [
              { "drupal_message" : {
                  "message" : "Stop and listen! ... One of the form components of the form you just submitted (= \u0022[submitted-form-component-value:value]\u0022), contains some value that is not allowed around here ...",
                  "type" : "error"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

```

Some details about the above rule:

* Rules Event: After a webform has been submitted
* Rules Conditions: User does NOT have role "authenticated" (i.e: an anonymous user submitted the form).
* Rules Actions:

+ Show an informal message on the site (this is just for QA-purposes, omit this action after you're convinced it works).
    + Add a variable (this is the clue of it all ...), named `submitted_form_component_value` and with label "Submitted form component value", and with value `[data:contact_us_message-value-raw]` (the form component we want to validate in subsequent Rules Actions).
    + Use the Conditional Rules module to perform some text comparison. In this case it checks if it contains `mail.ru`. If so, then perform another Rules Action like "Show an error message on the site". Obviously, at this point you could make any Rules magic happen ("block IP address" seems appropriate).

Be aware: as per the Rules Event we used here, the Webform *has been* submitted (and so far I've not found a more appropriate event like "Before submitting a Webform").

# Showtime

With the above rule enabled, I submitted a webform. This is the message I got (as per the first Rules Action):

> The webform component submitted by Pierre (= First name:) Vriens (= Last name:) contains a field labeled "Subject:" which has value " This is a demo of a validation of a webform component using Rules ... " and another field "Message:" which has value "Bonjour! Guess what happens AFTER I submit a webform with a form component containing a string like mail.ru ? The bets are open ...".

And sure enough, this is the error message that follows it right away (as per the last Rules Action):

> Stop and listen! ... One of the form components of the form you just submitted (= "Bonjour! Guess what happens AFTER I submit a webform with a form component containing a string like mail.ru ? The bets are open ..."), contains some value that is not allowed around here ...

PS: In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".
> 2 votes

---
Tags: rules, webforms
---


# Question
Title: Create a view in D7 that displays and links the taxanomy term and displays and links nodes associated with the term
I'm trying to build out a HTML list menu of taxonomy term followed by nodes associated to that term as a sub HTML list. All items should be linked as well. Can this be done?

Example below:

* Taxonomy Term 1
    + Associated Node 1
    + Associated Node 2
    + Associated Node 3
* Taxonomy Term 2
    + Associated Node 4
    + Associated Node 5
    + Associated Node 6
    + Associated Node 7
    + Associated Node 8
    + Associated Node 9
* Taxonomy Term 3
    + Associated Node 10
    + Associated Node 11
* Taxonomy Term 4

# Answer
> 2 votes
## Views tree

> This module provides a tree-based style plugin for Views. It is equivalent to the tree-based style template from Views 1.
>
> It is based off of the list style. Although it generates a nested view, there is still only a single query run for the view making it quite performant.
>
> ### Compatibility
>
> This module has been tested and used with the following relationship-oriented modules:
>
> * Taxonomy (in core) - parent/child relationships References - node and user references Relation
> * references between any entities (D7 only)
> * Entity reference - references between any entities (D7 only)
> * Organic Groups (D7 only)
>
> Example:

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


# Question
Title: Should I use the Workbench Access module to implement the workflow we have in mind?
I am new to Drupal altogether and have a question about a site i was asked to work on. We think that Workbench Access will solve our problem but we have not yet figured out how to make it work the way we want.

I have a large site and I have the users setup, and Roles setup, etc. But what I want to do is let users edit submit edits (for approval) on only one portion of the site (the staff portion to edit/update their own info). I also want an email to be sent (to me) for letting me know they submitted a "needs review" request if possible.

I know this might be a lot to go over but I would really love any help or a good walk through for this.

# Answer
The Workbench Access module seems to only partially cover your needs. If it was up to me to implement a solution for the challenge you're trying to solve, I'd go for another approach, as further detailed below.

Have a look at my answers to either of these questions:

These answers explain how you can implement a workflow that is pretty (though not exactly) similar to what you are looking for.

To do so, it "only" requires you to use these modules (and regular content types):

And by using such approach, it does not require modules like "Webform" or "Workbench" (modules that are typically involved for these kinds of workfows).
> 0 votes

---
Tags: 7, workflows, workbench
---


# Question
Title: How to select nodes without taxonomy terms from a vocabulary in views?
Is it possible to select all nodes that have no taxonomy terms from a vocabulary in views?

I tried the "is empty" option in the filter section, but it does not work.

I need to do that in views because I have to use VBO on the results of the query.

# Answer
yes i think so.. for me it works when i select 'has taxonomy term' and next option 'is empty'
> 0 votes

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


# Question
Title: Protected $view values inside template_views_pre_render function?
I'm trying to alter the view page title by using the *template*\_views\_pre\_render function inside *mytemplate*.theme file. It works fine, I'm able to modify its title this way:

```
$view->build_info['title'] = ...

```

My issue now is that I need to restrict this action to only one specific view, so I simply need to check the view id. I tried with `if ($view->id == 'my_view_id') {...}` but I realized I can't access the $view values because they are protected. How can I implement this control here?

# Answer
To access the value of the view object you can use the method `get()`:

```
$view->get('id')

```

Or if the object provides a special method for the id, which is the case with the view object:

```
$view->id()

```
> 2 votes

---
Tags: views, hooks, 8
---


title: How to create static breadcrumb

text:
# Question
Title: How to create static breadcrumb
I've created a breadcumb using this and I've created one. But I would like to create breadcrumb for each page. I've 3 forms, above the form I need to set the progress of the form in the form of breadcrumb,

Drupal 7

```
$breadcrumb[] = l('hi', '/hi');
drupal_set_breadcrumb($breadcrumb);

```

In drupal 8 I've tried to use

```
$b = new Breadcrumb();
$breadcrumb[] = Link::createFromRoute(t('Home'), '<front>');
return $b->setLinks($new_breadcrumbs);

```

But this is not working... how we can show that and where am I doing wrong?

# Answer
> 0 votes
There is a block in drupal 8 for displaying breadcrumb on your pages. First set visibility of that block on the pages you want to show breadcrumbs.

Then in template\_preprocess\_breadcrumb in your theme's .theme file you can change the breadcrumbs variables.

For additional functionality you can create breadcrumb.html.twig file in templates folder of your theme.

---
Tags: 8, breadcrumbs
---


# Question
Title: hook_menu to change menu button item by checking group membership
I am using Organic Groups and I have used this postto override the roles and permissions of OG Groups.

I need a hook to alter a button on my main menu that changes depending on whether the user is a member of a group (has any role in that group) or isn't a member of a group (and therefore hasn't got a role associated with his username)

The default button that always shows is 'add' when a user is associated with a group that button needs to be changed to 'remove' - with the according URL

I have created the following using this Drupalpage:

```
function my_module_menu() {

    $items['link'] = array(
        'title callback' => 'change_link',
        'title arguments' => array(1),
        'page callback' => 'go_to’,
        'page arguments' => array(1),
        'access callback' => 'user_is_logged_in',
        'menu_name' => 'main-menu',
        );

    return $items;
}
function change_link($gid) {
  if(og_is_member('node', $gid)) {
    return 'Remove';
  }
  else {
    return 'Add';
  }
}
function go_to($gid) {
  if(og_is_member('node', $gid)) {
    drupal_goto('www.mydomainurl.com/remove');
  }
  else {
    drupal_goto('www.mydomainurl.com/add');
  }
}

```

As well as fixing the above code - what does the array(1) do in page and title call back? --\> I just copied them as is from the Drupal API page... (Does it look for the 'gid' in the last 2 functions?

**UPDATE: (if any user of the site are part of any group - regardless of role - they will see only the 'remove' button if they aren't part of any group they will see the 'add' button.)**

# Answer
Here is a sample code close enough to your question. It may need some modifications to its parts in order to meet your needs, but more or less you got the idea.

```
/**
 * Implements hook_menu_alter().
 */
function foo_menu_alter(&$items) {
  $items['alter/%gid/path']['access callback'] = 'og_user_role_callback';
  $items['alter/%gid/path']['access arguments'] = array(1);
}

/**
 * Determine if logged-in user has access to menu or not.
 */
function og_user_role_callback($gid) {

  // Get OG role of the user. Could be 'member', 'non-member' or 'Group administrator'.
  global $user;
  $group_type = 'node';
  $uid = $user->uid;
  $member = og_get_user_roles($group_type, $gid, $uid, $include = TRUE);

  switch ($member) {
    case 'member':
      return TRUE;
    case 'non-member':
      return FALSE;
    case 'Group administrator':
      return TRUE;
  }
}

```
> 0 votes

---
Tags: 7, routes
---


# Question
Title: What is causing Unknown field error in EntityFieldQuery API?
I am attempting to use the entity-field-query API to see if any node of referee content type has custom field that equals x. I've looked at dozens of code examples and references. (Included below)

If it is relevant I am executing this code as a custom PHP action in Drupal rules.

My problem is when the code is executed I get the below error:

```
EntityFieldQueryException: Unknown field: field_referee_id in EntityFieldQuery->addFieldCon
dition() (line 817 of /home/scienceorg/public_html/includes/entity.inc).

```

(The field does exist on the referee content type.)

**My code:**

```
<?php
error_reporting(E_ALL);

$query = new EntityFieldQuery();
    $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'referee')
    ->fieldCondition('field_referee_id', 'value', '1', '=');
    $result = $query->execute();
?>

```

**Further information:** If I remove the field condition line from the above code it works perfectly. So the problems seems to be around finding the field\_referee\_id.

Code references and examples

EntityFieldQuery condition

https://www.drupal.org/node/1343708

**Alternative answer:** If you don't know what is causing the above problem I will accept alternative methods of achieving the same outcome as the correct answer.

# Answer
The code above seems right only problem here might be the machine name of the field is not same as the one given in -\>fieldCondition('field\_referee\_id', 'value', '1', '='); or the field might be multivalued field, for multivalued field in place of '=' 'IN' should be used.
> 0 votes

---
Tags: database
---


title: Hierarchical Taxonomy Term View

text:
# Question
Title: Hierarchical Taxonomy Term View
I have a Taxonomy which looks like this:

```
Parent1
-Child1
--SubChild2
--SubChild3
-Child4
--SubChild5
--SubChild6
-Child7
Parent2
-Child8
-Child9
--SubChild10
-Child11

```

I have created a view to display all terms under a specified Parent by setting a context tid . Here you can find the exported view: http://pastebin.com/us7KnKsD

The Problem is that the view only shows the terms which have sub-children.

How can I also display the terms which doesn't have sub-children? Is it possible with views? In php I would just create some recursive function...

# Answer
> 2 votes
Start your query from the Taxonomy table. Meaning select Taxonomy as your base table when creating your view. Then establish a relationship to your content from there. This will ensure your results contain all taxonomy names and then their subsequent children.

# Answer
> 1 votes
You can use the module Views tree

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


title: Node with many product prices

text:
# Question
Title: Node with many product prices
I have a node which needs to contain a list of product prices in the following format:

```
Node Title
Node Body

Product 1 URL - Product 1 Price
Product 2 URL - Product 2 Price
Product 3 URL - Product 3 Price
Product 4 URL - Product 4 Price

```

I'm not sure how that list of URL's and prices should be stored in Drupal so that it can be given a relationship with a specific node and displayed within the node.

Do i use taxonomy or make each url/price pair its own node?

# Answer
> 1 votes
Try using Field Collection module. Create a group of fields and assign that field collection in content type.

# Answer
> 2 votes
You should use entity references for this. The end result will be that when you view a parent node, the products show up in a block (or panel pane).

1. Set up a parent node content type and add an entity reference field to the products content type.
2. When you create products, reference the parent node.
3. Create a block view and add a contextual filter for content: referenced (or maybe referencing). your entity reference field. ?
4. In that contextual filter's settings, click provide default: content id from url ?
5. Add fields for the products content type and maybe additional filters as needed.

When you place the block in a region, the products will show up if they reference that node.

---
Tags: nodes
---


# Question
Title: How to capture bank payment info to store for payment processing using Drupal Commerce?
I'm using Drupal Commerce. Is there any way to capture bank payment info to store for payment processing? So that a customer doesn't need to enter details on each transaction.

# Answer
### Commerce Card on File

> Commerce Card on File provides an API and user interface for storing and reusing credit card data on subsequent orders within Drupal Commerce. **The module does not retain full card numbers locally but instead stores the remote ID of the full card data from the payment gateway used to validate and process your credit card transactions.** This means card on file data will only be good for a single payment gateway; if you change payment gateways or accounts, your stored card data may no longer be usable.

### How this module is PCI compliant

This module is safe as it does not retain the full card number. Only the last 3 numbers and expire date are stored in your DB. So if your DB gets hacked, you'll be fine.

Furthermore, when this module connects your payment processor, it uses a token to represent the persons card. Only you can use that token to deposit funds to your account. So even if somehow they intercept the token value, they can't do anything with it.

source: David Kitchen

---

You should also get Commerce Dunning to deal with expired card numbers.

### Commerce Dunning

> Dunning management (Delinquent User Notification) is the automated process that's kicked off when a charge attempt of a recurring order fails. This process involves periodic customer communication and payment retries.

Dunning Video Tutorial
> 2 votes

# Answer
The modules already suggested in the prior answer are indeed the modules I'd also recommend.

However, for way more details (background info) about **capturing** and **storing** these sensitive data, I suggest you also checkout (= listen or watch) what's mentioned in these links:

* Commerce Subscriptions, which provides some insights about best practises for processing credit cards, and some more interesting Drupal Commerce related modules.

**Topics included**:

+ What is a subscription?
    + Credit Cards
    + Controlling Access to content / Feature
    + Drupal Commerce Components
* PCI Compliance, which provides a ton of details about pitfalls to avoid when processing these kinds of data (also mentioned in the previous link).

**Topics included**:

+ What is PCI Compliance
    + Who is at risk?
    + Validation Types
    + Payment Methods
    + Best approach for Drupal developers
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Display author profile fields in nodes created by that user
I have a user profile with extra fields like company address and company name etc.

I also have a content type *job* where i'd like to use the author's profile info (company name, address) in the content created by that author.

How do I use fields from the author profile in my nodes created via the *job* content type?

Is there something like a *token field* that I can use in my content type to display profile fields?

I know in views there's an option to use relationships, but I'd like to not use views for this if possible.

# Answer
> 0 votes
1)Go to **admin/config/accountsetting** then manage field **add fields (company name, address and company name)** into it.

2)Go to your content type **job** add fields **(company name, address and company name)** as a existing field not as a new field.find your existing field from the list of available dropdown and select it and save.

---
Tags: entities, users
---


# Question
Title: Using webform-form-[nid].tpl.php to change default template
On drupal 7, using webform 7.x-4.11, I am trying to modify the template of a specific webform.

So, in /web/themes/bartik/templates (I am using bartik theme) I created a file named webform-form-23.tpl.php

As "23" is the nid of my webform. But the template is not applying at all...

If a create a file webform-form.tpl.php it is well applying to all my webforms...

This is not a matter of caches as it is well applying when using a file named "webform-form.tpl.php" (with no ID) and despite of that the cache has been cleared at every changes.

Can someone help me on this one?

# Answer
> 0 votes
Have you made a clear cache in `admin/config/development/performance`?

Or have you looked if in the template there is a error in the code? To verify this you can try to copy all code of "webform-form.tpl.php" in your "webform-form-23.tpl.php" and at the top of the code, before the first TEST!!! , refresh the cache and look if TEST!!! is displayed. If you display TEST!!! in your previous code there is an error.

---
Tags: theming, webforms
---