# Question
Title: Allowed column type names and element type names for creating custom Field Types
I'm creating new Field Types in Drupal 8. I recently asked which are the type names allowed for the `DataDefinition::create()` method, receiving a good answer.

Now I figured out that I need at least other two type names:

* A **column** type name to use inside the method `schema(...)` from the `FieldItemBase` class.
* Another type name to create **elements** inside the method `formElement(...)` from the class `WidgetBase`.

For example this is a snippet of code used to create a new Field Type, defining the `schema()` method:

```
public static function schema(FieldStorageDefinitionInterface $fd) {

  $columns = array(

    //

    // Here the column type name is 'varchar'
    'password' => array(
      'description' => 'A plain text password.',
      'type' => 'varchar',
    ),

    //

  );

  $schema = array(
    'columns' => $columns,
    'indexes' => array(),
    'foreign keys' => array(),
  );

  return $schema;
}

```

In the above code the **column type name** is `'varchar'`.

And this is another snippet, defining the `formElement` method (always used defining the Field Type):

```
public function formElement(
  FieldItemListInterface $items,
  $delta,
  array $element,
  array &$form,
  FormStateInterface $form_state
) {

  //

  // Here the element type name is 'password'
  $element['passwordlist'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#description' => t('Select a password for the user'),
  );

  //

  return $element;
}

```

In the above code the **element type name** is `'password'`.

What can I use for `'type'` in the first case and `'#type'` in the second case?

# Answer
All available schema types are listed in the following table: https://www.drupal.org/node/159605

Here is a list of available types of render elements (first column of the table corresponds to the #type property of the element) https://api.drupal.org/api/drupal/elements
> 1 votes

---
Tags: entities, 8
---


# Question
Title: How can I save form data on a node in Drupal?
I want submit form data and save on specific node but I don't know that how to do?

```
function test1_menu() {
  $items['mytest'] = array(
    'title' => 'My Tes',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test1_form'),
    'access callback' => TRUE,
    'weight'=> 1,
    'type'=> MENU_NORMAL_ITEM,
  );
  return items;
}

function test1_form($form, &$form_submit) {
  $form['firstname'] = array(
    '#title' => t('First Name'),
    '#type' => 'textfield',
    //'#required' => TRUE,
  );
  $form['lastname'] = array(
    '#title' => t('Client Name'),
    '#type' => 'textfield',
    //'#required' => TRUE,
  );
  $form['submit'] = array(
    '#value' => 'Test',
    '#type' => 'submit',
  );
  return $form;
}

function test1_form_form_submit($form_id, &$form_state) {

}

```

# Answer
In your submit function, you just need to create a node, e.g.

```
$values = array(
  'type' => $node_type, // Drop in your desired node type.
  'uid' => $user->uid, // Want to set an author?
  'status' => 0,
  'comment' => 0,
  'promote' => 0,
);
$entity = entity_create('node', $values);

```

To make your life easier, I recommend to use entity\_metadata\_wrapper:

```
$ewrapper = entity_metadata_wrapper('node', $entity);

```

Now, you can just cycle through your form data and add the values to the correct fields of your node:

```
$key = '<MACHINE_NAME OF YOUR FIELD>'; // e.g. "field_firstname"
$val = '<VALUE TO BE SET FOR THAT FIELD>'; // e.g. $form_state['values']['firstname']
$ewrapper->$key->set($val);

```

This of course depends on the field type, the above works for example for simple textfields. Finally, if all is set, just save the freshly created node:

```
$ewrapper->save();

```
> 2 votes

---
Tags: nodes, forms
---


# Question
Title: Quick edit many SKU fields in Drupal Commerce
Is there a way to quickly edit many SKU fields in Drupal Commerce? I have the Back Office quick edit and its great for price or stock control, I have also tried editable views but it seems that the SKU field can only be edited by accessing a full edit of the individual product. With 500+ products this could take quite a while. We have a seperate database external to Drupal where the product ids don't correspond to the SKU but would like to make that happen so in the future we could use feeds to import price changes, product title changes etc.

# Answer
An alternative way of doing this is as follows:

1. Create a view for the products including SKU & Product Id (assigned by drupal commerce)
2. Export the view into a csv using the views\_data\_export module.
3. Amend your SKUs in the csv file using any text editor. This should make it easier to amend.
4. Create a feeds importer, with settings "Update existing commerce products", and using the "Product Id" as unique key (instead of SKU).
5. Load the amended csv to update the SKUs in the database.
> 1 votes

---
Tags: commerce
---


# Question
Title: How to Create a wall of activities (like Facebook wall) in my site, for each user?
I am building a social network site. My plan is that every user would be able to write articles, tips, upload pictures, comment to others, like other posts etc.

My question is how can I aggregate all the user different activities in to one page (e.g. wall), so the user and all the other users can see all the activities in one page (similar to facebook wall)?

Thanks in advance.

# Answer
> 1 votes
You need to give the ability to users to create a relationships. https://drupal.org/project/user\_relationships. You can set up what kind of content is shareable.

Then using https://drupal.org/project/heartbeat you can get activity streams.

Really do yourself a favor and get https://drupal.org/node/1849900. It can save up huge amounts of time, allowing you to set up a facebook-like network in a few hours!

# Answer
> 1 votes
The Drupal Wall module is what you're looking for. This matches your requirement.

> **Objective**
>
> To enable the users to get the status posting functionality **just like facebook** status posts and wall posts. Users can upload their status with an image and video.
>
> **Description**
>
> This module allows you to post the status on a user’s profile in the form of text, image or video status. Logged user can post comments on any user’s status. Visitors can only view the status and comments of any user (by default). While the permission of View/ Delete/ Edit can also be set by the administrator. The user can delete only that post or comment which he/ she has submitted to other profile. Posts on user’s own profile can also be easily deleted or edited instantly via AJAX.
>
> Also, it allows the user to like his own status or comments as well as other user’s status with help of a well known FLAG module. The theming of wall status will give you the experience just like the facebook wall.

The Statuses also does the same

> Provides status updates / microblogs like Facebook's Wall / News Feed, Twitter's Timeline, and Yammer's Feed. Users can update their own status or write messages to other users, nodes, Organic Groups, taxonomy terms, or other entity types. @mentions and #hashtags are supported, as well as comments on status updates, viewing conversations between users, the ability to "like"/"reply" to/RT a message, automatic updates without page refreshing, and integration with over 20 modules.

# Answer
> 0 votes
You can check Heartbeat module.

> Heartbeat displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.

Example image looks like this -

I used this module in D6 for a project in a block & it worked fine for my particular need.

---
Tags: users, social-network
---


# Question
Title: How to make view source code in single line
Is there any way to show rendered HTML in single line when you view source it in Drupal?

You may see in some websites like facebook.com. So, when you view source the entire HTML will be in single line, so that people can not read easily (though they can use firebug to investigate).

# Answer
A couple modules you might find interesting.

https://www.drupal.org/project/minify

https://www.drupal.org/project/minihtml
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: Conditional statement doesn't work in node.html.twig
I want to use `{% if %}` in a node.html.twig, but it doesn't work.

I am using this code.

```
{% if content.field_number == 0 %}
  zero
{% else %}
  one
{% endif %}

```

It always print *one*.

The following code always print *zero*.

```
{% if content.field_number %}
  zero
{% else %}
  one
{% endif %}

```

What code should I use to *zero* when the field contains zero?

# Answer
`content.field_number` is the rendered output and the value of the field is somewhere inside the render array, for example in a `#markup`. But this will change whenever someone reconfigures the view mode.

It is better to use the node object in this case, because the field value will be available for all view mode configurations:

```
{% if node.field_number.value %}
  not zero
{% else %}
  zero
{% endif %}

```
> 4 votes

---
Tags: theming, 8
---


# Question
Title: what is the use of universal unique identifier ,why its so much important in deployment?
What is the use of universal unique identifier in drupal7, why its play important role in deploy and service

# Answer
> 3 votes
UUID is used to identify the same objects (like nodes, taxonomy\_terms and users) across environments.

All of these has an ID, for nodes it's the `nid` (node id), but that is not reliable to use across environments, since it's serial (1, 2, 3 ...). Fx the about page on content staging environment might have id 5 while it on the production environment might have id 1.

Deploy is all about pushing content between environments, so if you make a change on your content staging site, you want to be able to push those changes to the correct node. Since nids can't be used, as they aren't *universially unique*, but only unique for the specific environment, we need something that is. That is exactly what uuids and the uuid module provide.

---
Tags: services, deployment, features
---


# Question
Title: How to add organisation to the Drupal.org user profile?
When posting on the drupal.org, I'd like to attribute the contribution, however when I'm selecting it, the label says:

> X at organization `not applicable` for customer `not applicable`

When clicked on *not applicable* link, I've got tooltip that I should add organization on my user profile. However I already did that (in *Edit/Account/Work*) and it's set as *Current organization*. What I'm doing wrong?

# Answer
As an example, have a look at my profile on D.O., which contains this link.

So make sure you have a similar Organization created there, which you can do via Create Organization, which is the link you can also find on Organizations.

If you're not the current owner (or something like that) of such organization, then you need to think of a way to get that Organization created around there. I don't remember any validation (when I registered the one I refer to), but what I would do:

1. Check with the organization you want to refer to if they are OK with getting such registration.
2. Have them complete such registration, or ask permission that you do it for them (and have them QA review it afterwards if needed).

If it's a huge organization, it may be a challenge to get approval from such organization, eg to find the right person to ask, and then get the actual approval. In that case, as an alternative, maybe you create something anyway about that organization, but without mentioning their actual name, and only using information that is considered as not confidential? But keep in mind that some companies may not want the world to know that they use Drupal ... eg for competitive reasons ...

Extra hint (for future occasions): try to make it part of contract negociations, something that they confirm that they are aware (and will not object) that you will register them as a company (if they are not yet registered). Possibly adding an appropriate annex to your contract with the details of that registration. It'll slow down contract negotiations, but that's probably the best moment to get approval. If needed offer them some kind of reduction on your rate to make them accept it. And of course, also explain the added value to them for being listed there (like free advertising?) ...

**Note**: there is also a Marketplace FAQ which may give you more ideas to get an organization registered correctly.
> 2 votes

---
Tags: community-official-site
---


# Question
Title: How to get the data of field collections
I have one field collection with 4 fields. How to get the data of field collection in views tpl file

I am trying to load data as

```
field_collection = entity_load('field_collection_item', array($node->field_suppliers_value['und'][0]['value']));
print_r($field_collection);

```

The fields in field collection are one is text field and another one is entity reference and one more is term reference and last one is date type.

I am able to retrieve the data only for text data type and for other data types it was showing as \[target\_id\]=some number.

How can i retrieve the data for other data types except text.

# Answer
These are the field data types and their column names:

* Text - *value*
* Entity Reference - *target\_id*
* Term Reference - *tid*

Combine that with `field_get_items()`, e.g.:

```
$items = field_get_items('node', $node, 'field_suppliers_value');

if ($items) {
  // Or $items[0]['target_id'], etc
  $fc = field_collection_item_load($items[0]['value']);
}

```

Hopefully that'll give you enough to go on.
> 2 votes

---
Tags: entities
---


# Question
Title: How to create suggestions conditionally (by block type/bundle) override system templates in Drupal 8
For example, I want to override image template (image.html.twig) to change how it outputs images from

```
<img{{ attributes }} />

```

to

```
<div class="image" style="background-image: url('{{ attributes.src }}');"></div>

```

But I require to override only those images, that are rendered inside specific block type (called "bundle" in Drupal terms) `b_partner_images`.

There is a hook\_theme\_suggestions\_alter(array &$suggestions, array $variables, $hook) hook, that allows to create suggestions based on some conditions, but the problem is that `$variables` does not contain anything more than image tag attributes - no objects or identifiers, so I see no way to create condition based on some identifiers or block (bundle) name.

How to create file name suggestion for system templates (such as image) to override image output based on block type or any other identifier?

# Answer
Currently, I have only found a workaround using `image-formatter` override

Create a file name suggestion hook for theme in `themename.theme`:

```
function themename_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
    switch ($hook) {
        case 'image_formatter':

            /**
             * @var Drupal\url_image\Plugin\Field\FieldType\UrlImageItem $item
             */
            $item = $variables['item'];
            $config = $item->getFieldDefinition();
            switch ($config->getTargetBundle()) {
                case 'b_partner_images':
                    $suggestions[] = 'image_formatter__b_partner_images';
                    break;
            }
            break;
    }
}

```

Create a template file `image-formatter--b-partner-images.html.twig`:

```
<a href="{{ url }}" title="{{ image['#alt'] }}" target="_blank">
     <div class="image" style="background-image: url('{{ file_url(image['#uri']) }}');"></div>
</a>

```

It works, but not as beautifully, as I would like.

PS: I used that specific `hook_theme_suggestions_alter` format, because I have more than one suggestions hook, and I put them inside this single function, so I can add more conditions with ease.
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: How to add dependency to a custom module with drupal-composer?
I have a problem with dependencies in my custom module.

I'm using drupal-composer and I'm able to install my own module with the composer.json. My module comes from custom Git repository.

At this moment, though, I'm unaware of any working way to get my custom modules dependencies installed at all. I can add them one by one to the `composer.json`, though they do not appear into right namespaces after that, but let's just disregard that because I would really like to be able to specify them into my custom module and get them installed automatically. This is because I will be having multiple modules with multiple dependencies. Also, some of these dependencies will be from my own repositories, but that should not make any difference. And to be specific, at this point I'm trying to add a custom git repository containing some PHP source files that I need for the services exposed from my modules.

I have also tried installing modules from Drupal packagist and their dependencies are all nicely downloaded.

So is there any way to specify these dependencies into my own module and how to get them working? I have added them to my modules `composer.json`, but that does not seem to have any effect. They also need to be there when I run my PHPUnit tests.

Also I'm aware of the composer-manager plugin for Drush, but at this point, (due to other requirements) it is not an option.

# Answer
Ok, seems to me that I almost got it.

This was due to my repository list in the Drupal root composer.json. I had this kind of thing there:

```
{
  "type": "package",
  "package" : {
    "name": "blaah",
    "version" : "xxx",
    "type":"drupal-module",
    "source": {
      "url": "gitblaag",
      "type": "git"
    }
}

```

That some how seems to override what ever is in the modules composer.json. I do not really know why but something along the lines that the entry defines the whole package and no more info will be read from the composer.json in the module.

So I adding "require" there does the magic. Also probably removing some of those lines and making it just a repository, not a package, would result into composer reading the individual modules composer.json.

But now everything seems to be right and module is installed and it will install my other files under vendor but PHP still goes to "class not found" in my service when I try to use my class from the other library.
> 1 votes

---
Tags: 8, composer
---


# Question
Title: Can I configure Send by Email to use CC instead of BCC?
So I have a node that is using the Print Module (www.drupal.org/project/print) and it's associated send by email functionality.

The issue is that if I include multiple emails on the send by email page, it sends them so that the email addressees cannot see the other people it was emailed to.

For instance, if my send to looks like: example1@example.com, example2@example.com

Both example1 and example2 will receive the email, but with only their name in the To: line. Is there a way to get the rest of them to show up there as well, or in the CC: line?

Thanks.

Here's the portion of the code I was able to find where it splits it into multiple emails:

```
  $addresses = explode(', ', $form_state['values']['txt_to_addrs']);
  foreach ($addresses as $to) {
    if ($use_job_queue) {
      // Use job queue to send mails during cron runs
      $queue->createItem(array('module' => 'print_mail', 'key' => $print_mail_send_option_default, 'to' => $to, 'language' => language_default(), 'params' => $params, 'from' => $from));
    }
    else {
      // Send mail immediately using Drupal's mail handler
      $ret = drupal_mail('print_mail', $print_mail_send_option_default, $to, language_default(), $params, $from);
    }
    if ($use_job_queue || $ret['result']) {
      flood_register_event('print_mail');
      $ok = TRUE;
    }
  }

```

Anyone know how I can make that so it just sends one email to all of the addresses?

# Answer
You could try the `hook_mail_alter()` which lets you intercept emails used by `drupal_mail()`, but that's problematic since, as you mentioned, each email gets sent out individually.

There's a `hook_print_mail_alter()` invocation before the email is sent, but this is problematic too since `$params` doesn't have the email recipients.

The route I would take is to alter the email form submission handler with your own custom submission based off the print module's implementation:

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'print_mail_form') {
    $form['#submit'] = array(
      'MYMODULE_print_mail_form_submit'
    );
  }
}

/**
 * Submission Handler.
 */
function MYMODULE_print_mail_form_submit($form, &$form_state) {
  //@TODO: Implement your own email code.

  //print_mail_form_submit($form, $form_state);
}

```
> 1 votes

# Answer
One possible way would be use that a form\_alter to make sure that there are no commas in the "to" list (i.e. replace all commas with semi-colons), and then use hook\_mail\_alter to revert the replacement.

That being said, I do find the use case here funny.. I specifically designed this code to prevent what you want to do in order to protect the privacy of each email recipient.
> 0 votes

---
Tags: 7, emails
---


# Question
Title: What should I enter as "Database file" for a SQLite database?
So I've practiced making Drupal 7 before using XAMPP and I want to try to make a Drupal 8 page but I have no clue about what to put in the field you can see in the picture below. I made a database in PHPmyadmin.

What should I enter in the *Database file* field?

# Answer
This configuration dialog is for SQLite-type databases only, it might be that your installation only has activated the PHP modules for this type of databases (for MySQL databases, you need pdo-sql, see here: https://www.drupal.org/node/2219779).

If you wish to use a SQLite database (which should work fine for testing purposes), you can either indicate a location for your SQLite database file, or leave the default, which should work fine. The Drupal installer will create the SQLite database for you in that location; you don't need to create it separately.
> 4 votes

# Answer
So I got this fixed a while ago by just reinstalling XAMPP. thanks for the help everyone.
> 0 votes

---
Tags: database, 8, installation
---


# Question
Title: How do I display self-hosted video content
What I am trying to do is embed a self-hosted video on a webpage. I have the video uploaded onto the web hosting in mp4, ogv and webm formats; converted where necessary using Miro Video Converter (if that helps?).

The code I have in place on the webpage is:

```
<center><video width="90%" controls>
<source src="/system/files/HBA_ONLINE.mp4.mp4" type="video/mp4">
<source src="/system/files/HBA_ONLINE.webm" type="video/webm">
<source src="/system/files/HBA_ONLINE.ogv" type="video/ogg">
Your browser does not support this video tag - Try viewing directly <a href="/system/files/HBA_ONLINE.mp4.mp4"> here </a></video></center>

```

The only format that seems to work is mp4 on Google Chrome; other browsers simply won't play the video in any format.

The silly question is; do I need to use a dedicated Drupal 7 module???

# Answer
> 0 votes
A learning process for anyone who makes the same mistake.

I found that the files had be uploaded with role based content access as part of our file repository. That meant anonymous users would get a 403 error.

# Answer
> 0 votes
There's the video module you could optionally join with the media system. this bridge module (Media Video) still is sandobx.

> This will provide you a field display of the video in HTML5 with flash fallback for the large majority of da browser's.

---
Tags: 7, files
---


# Question
Title: exposed filter result : how to check the results is lesser than 20 or greater than 20...?
i have created the content type named candidate\_profile, included fields like Current\_Salary\_Range and i have created a view named display\_candidate and also i am using better exposed filter for current\_salary\_range field the filtered the result print in view throw the Header-\>Global:Result summary.hence how should i proceed to check the results is lesser than 20 or greater than 20...?

# Answer
using the below code to check the result is greater than or lesser than 20

global $pager\_total\_items; print $pager\_total\_items\[0\] ;

if($pager\_total\_items\[0\]\>20) { print 'Result is greater than 20'; } else { print 'Result is lesser than 20'; }

In this code put into your theme folder like mytheme/templates/page.tpl.php file.

but this is working only that particular theme because of i write that code into mytheme page.tpl.php file thats why...
> 0 votes

---
Tags: views
---


# Question
Title: In which database table does the number views of a node get stored?
I'm using Drupal 7. After enabling the Statistics module (part of Drupal core), I see, under each node, how many times it has been read (e.g. "4 reads").

I wonder where this number of views of a node (e.g. "4 reads") gets stored in some table in the Drupal database.

# Answer
As well as statistics there is the aptly titled Node View Count module

https://www.drupal.org/project/nodeviewcount

It has a few advantages over the native stats module in the way it counts and also has views integration so you can get some nice tables up and going quickly.
> 1 votes

# Answer
Statistics does store some information in accesslog as Shai said, but the view counts themselves are in the table node\_counter.

Here's a query I wrote to get the top 100 nodes with titles by views.

```
select node_counter.totalcount, node.title, node.nid from node_counter, node where node.nid=node_counter.nid order by totalcount desc limit 100;

```
> 1 votes

# Answer
The Statistics module stores data in the accesslog table.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to add custom input type button in forms?
I want to add custom input type button in form. I tried following code, but it is converting it to submit type button. How can i add input type button ?

```
$form[custom_button] = array('#type' => 'button','#value' => t('Test Button'),);

```

# Answer
It's not converting it to a submit button type, they are different

Form items of type "button" will trigger the form submission but won't trigger the hook\_form\_submits like a form item of type "submit" does. It's eseentially a blank button apart from hook\_validate is called but in there you can do whatever special functionality your button is supposed to do
> 0 votes

---
Tags: forms
---


title: Can I OR views filter criteria

text:
# Question
Title: Can I OR views filter criteria
I'm sure this should be simple and I'm missing something because I'm tired on a Friday afternoon.

I have a Content Type (which I didn't design!) with fields "Start Date" and "Start Month". I want to show items in the View if EITHER "Start Date" OR "Start Month" are non-empty. However it seems that multiple Filter Criteria in the View are AND-ed ?

Any help much appreciated.

Thanks,

MB

# Answer
> 3 votes
You can simply create new filter group and `OR` them. Just use `And/Or, Rearrange` from drop-down Filter criteria. Use filter groups as per your needs. Hope this helps.

---
Tags: views
---


title: How to add percentage column in views

text:
# Question
Title: How to add percentage column in views
I use Views Aggregator Plus to calculate sum of a column.

----------------------
Item Data
----------------------
A 20
B 30
C 50
----------------------
100
----------------------

Then I want to add additional column for percentage.

-----------------------------------------
Item Data Percentage
-----------------------------------------
A 20
B 30
C 50
-----------------------------------------
100
----------------------

I know Global:Math expression. But I don't know how to get the sum, the sum field is not available. Only \[value\], \[value\_1\] and \[value\_2\] available for A, B and C respectively.

Is there a way to add a percentage column?

# Answer
> 2 votes
Now this problem has been solved, after VAP add percentage function
http://cgit.drupalcode.org/views\_aggregator/commit/?id=2539ac5
Now I can add additional column calculating the percentage (as an example below):

# Answer
> 1 votes
You could use preprocess functions and templates for that. Just add an extra field in your view and preprocess the value inside `template_preprocess_views()`.

Add your logic, for example:

```
function template_preprocess_views(&$variables) {
    $variables['percentage'] = $some_value % 100 . '%';
}

```

Then you can use the `$percentage` in your template which will contain your preprocessed value.
I'm just going through this very quick. If something is not clear, please ask and I'll go in further detail on how to tackle this with preprocessors and templates.

# Answer
> 0 votes
You can install views\_php module, This module adds a *PHP* field to the view and There are some tokens available. You can use the current row values to calculate percentage.

---
Tags: views
---


# Question
Title: How to override logic of specific drush command?
I'm aware of `validate`/`pre`/`post` COMMAND hooks and I would like to replace the logic of the existing drush command on specific condition using *policy commandfile* with something else, e.g.

```
/**
 * Implementation of drush_hook_COMMAND_validate().
 *
 * Validate feature revert of specific module.
 */
function drush_policy_features_revert_validate() {
  if (strpos($args[1], 'rules') !== FALSE) {
    drush_invoke_process('@self', 'rules-revert-all');
    drush_print('Rules reverted in custom way!');
    return drush_set_error('POLICY_DENY', dt('Rules features already reverted.'));
  }
}

```

However the problem is when I return `TRUE` \- the command which I want to override is called after than, on the other hand when I'm returning `FALSE`, the `drush` will fail with non-zero exit code which could cause some other issues (like breaking the deployment).

Is there any better way of overriding the logic of existing drush command without described side-effects? Secondly *validation* hook doesn't sound right to implement that kind of logic.

# Answer
Actually returning just FALSE without `drush_set_error` should work fine without error and the original command isn't executed, e.g.

```
/**
 * Validate feature revert of specific module.
 *
 * Implementation of drush_hook_COMMAND_validate().
 *
 */
function drush_policy_features_revert_validate() {
  $args = drush_get_arguments();
  if (strpos($args[1], 'rules') !== FALSE) {
    drush_log(dt('Reverting rules...'), 'ok');
    drush_invoke_process('@self', 'rules-revert-all');
    drush_log(dt('Reverting of rules finished.'), 'ok');
    // drush_postflight(); // Set context as completed, but this is not needed.
    return FALSE;
  }
}

```
> 0 votes

---
Tags: hooks, drush
---


# Question
Title: Programmatically add items to the menu - not hook_menu
We're redesigning our site and getting rid of the sidebar. The main reason for the sidebar to exist was to hold Organic Menus (og\_menu), which we have hundreds of groups, each with 2 or 3 menus. I want to move OG menus to the main menu.

What I would like to do is when a user visits a particular OG

* load the menus for that OG (trivial)
* programmatically make the menu's name the top level links linked to # (Trivial - we use bootstrap)
* add the menu's links below those top level links (this is where it gets tricky)
* and append them to the main menu as the last to links (no clue)

So the top level would look like this only when the user hit the group

Home Communities Forum Group-Menu-1 Group-Menu-2

Home, communities and forum are always there the group menus are appended when they're in that group. I don't need code I just need direction on which parts of the API will facilitate this.

# Answer
> 1 votes
I solved this by just appending my links to the menu tree with hook\_preprocess\_menu\_tree

```
<?php

function my_module_preprocess_menu_tree(&$vars) {

  if($vars['theme_hook_original'] != 'menu_tree__primary') {
    return;
  }

  $node = menu_get_object();

  //Check to see if this is a group node or group content and return the group_node
  $group_node = my_module_check_for_group_node($node);

  if($group_node) {

    global $user;

    $vars['tree'] = str_replace('last leaf', 'leaf', $vars['tree']);

    $result = db_query('SELECT menu_name FROM og_menu WHERE gid = :nid ORDER By weight', array(':nid' => $group_node->nid));

    $menus = $result->fetchAll();

    foreach($menus as $menu) {
      $tree = menu_tree($menu->menu_name);

      if(!empty($tree)) {
        // render the organic group menu as HTML
        $tree = drupal_render($tree);

        $tree = str_replace('menu nav', 'dropdown-menu', $tree);

        $menu_array = menu_load($menu->menu_name);

        //format <li> and top-level <a> for bootstrap
        $li = '<li class="expanded dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">'.$menu_array['title'].'<span class="caret"></span></a>'.$tree.'</li>';

        $vars['tree'] .= $li;
      }
    }

    $vars['tree'] .= $li;
 }
 ?>

```

---
Tags: organic-groups, navigation
---


# Question
Title: How to hide/show menu items using based on group membership?
I want to hide and/or enable certain menu links that are present on my main navigation bar depending whether users are/aren't part of any group.

I am currently using the Rules module with these settings but these delete and recreate the links completely! I just want to hide them from the view.

I have used the "update menu item" as action.

# Answer
A better way of doing this might be to use Drupal's built user permissions. You can use a 3rd party module such as https://www.drupal.org/project/content\_access so set specific access

E.g. so that only certain roles have access to those certain pages. Then drupal will automatically handle the showing/hiding of the menu links if they depending if the user does/doesn't have access to that page
> 0 votes

# Answer
I’ve done what you’re asking by using “roles”. In my case, I wanted to hide menu items from users who did not have a particular “role”.

That allowed me to specify the menu access for each menu.
> 0 votes

# Answer
Simplest solution is the Menu Item Visibility module. That is what is being used in rrirower's solution above.
> 0 votes

# Answer
Since you are already using the Rules module, it should be straight forward to get this to work with the approach detailed below ...

# Part 1: Rules block visibility

Have a look at the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules implement the logic to "***check whether users are/ aren't part of any group.***" (as in your question).

# Part 2: Create an appropriate Rules Component

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

> Configuration is done on a per-block basis. To control a block visibility using a rule component, go to the block settings page, scroll down to the "Rules" tab, and select the Rules component that you want to use.
>
> Notice that to be able to be used by this module, a Rules component *must* be constructed in a very specific way. See the next section for more information.

This module comes with 2 sample Rules Components, that should help to understand the concept behind it.

Here is a sample Rules Component you could use to start from (which just contains a Rules Condition to verify if the user has a role with role id "4"):

```
{ "rules_block_visibility_show_menu_block_for_role_4" : {
    "LABEL" : "Show menu block for role 4",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

You should be able to import this rule in your own environment.

What this sample Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the user YES or NO has the role with role ID equal to `4`.

Replace that Rules Condition to implement your "***check whether users are/ aren't part of any group.***" (as in your question). If you're already using Rules with OG, that's a straight forward replacement.

With that, we're coming close to an actual answer to your question, as explained in Part 3 below.

# Part 3:

Transform your menu for your main navigational bar in multiple similar navigation bar menus. And create 1 for each variation of groups for which you want that bar to be different. E.g.:

* `navbar1` for group A (only).
* `navbar2` for groups B and C (assume they have the same navigation bar).
* `navbar3` for all other cases.

Assume you customized the Rules Component (from Part 2) in something that would fit for group A, say you named it `RuleNavbar1`. Clone this Rule Component in 2 more similar rules:

* A rule named `RuleNavbar2` (for groups B and C).
* A rule named `RuleNavbar3` (for all others).

Head over to the "Block" settings for each of your menu blocks (1 for each of your menu bars). At the bottom of its settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

So if you created those Rules Components `RuleNavbar1`, `RuleNavbar3` and `RuleNavbar3` as described above, you just pick the one that fits for each `navbarX` (X = 1, 2 or 3). Done!
> 0 votes

---
Tags: 7, rules, organic-groups
---


# Question
Title: Where does Drupal set the uploaded file name syntax?
I have a file with a filename which has a double underscore in it. When Drupal saves the file, it shortens it to be only one. ie:

> Snapshot\__john\_doe\_2\_opt.jpg

When Drupal saves the file, it removes one of the underscores and names it this:

> Snapshot\_john\_doe\_2\_opt.jpg

Where does Drupal do this? I need to account for any changes which Drupal makes to the filename and I need to know what other characters it may remove etc.

# Answer
> 2 votes
You can use transliteration module.

and in code use code like

```
function hook_transliteration_clean_filename_prepare_alter(&$filename, $source_langcode) {
  $filename = drupal_strtolower($filename);
  $filename = str_replace('__','_', $filename);
}

```

Above code is not tested, Hope it will help you.

---
Tags: files
---


# Question
Title: Filtering comment by date range in Views
I have created a view to filter comments by date range. For date range i am using between operator.

* View type : Comment
* Date : comment created (default field)

**Issue :** When i am trying to filter comment from 2015-11-01 to 2015-11-15

i am getting result from 2015-11-01 to 2015-11-14 only.

what i am missing ? may be some help me ?

# Answer
> 1 votes
Views uses in between operator i.e. BETWEEN min AND max expression.

This is equivalent to the expression (min \<= expr AND expr \<= max). Now the query that views create for date is:

`(comment.created BETWEEN 1446336000 AND 1447545600)`

Search for unix time value of 1447545600

The problem is with the date **2015-11-15**, this is treated as 2015-11-15 00:00:00. So 2015-11-15 11:12:13 won't be included. Hope you get my point.

---
Tags: views, datetime
---


# Question
Title: Why does the Wysiwyg module and Ckeditor library not show the CKEditor when editing a node?
I installed latest version of the WYSIWYG module (`dev` version) and also the latest CKEditor library. This module can find the library, I selected the ckeditor for text format "Full html" only.

But when I try to edit the content it does not show up. All modules are update to date. I have other Drupal sites and this module works with no problem.

What to do?

**Notes**:

1. The text is there when you start an edit session of the node. But it is just full html text, with all the HTML code being shown, as in this example:
2. I also tried by enable of an additional editor, as shown here:

But still nothing happens.
3. The link to enable/disable the editor is missing (and it should be there). I spotted that problem at first. I wanted it to be disabled by default and then by clicking on it it should be enabled. but the link is not there. Here are the scripts errors:

I cannot see something.

# Answer
In the CKEditor page you have to select Enable in `CKEditor -> EDITOR APPEARANCE -> "Default editor state"`.

This you can find in `admin/config/content/ckeditor/edit/<yourtextformat>`

Or if you dont want to enable that by default, then you can click manually "Switch to to rich text editor" in `/node/<nid>/edit`
> 1 votes

# Answer
To use CKEditor version 4.x with the WYSIWYG module, you do in fact need to use the dev version of the WYSIWYG module: https://www.drupal.org/node/588512

I would advise deleting the WYSIWYG folder and dropping in this dev version, and running any applicable updates on update.php (but I do not suspect there will be any).

On Drupal 7 this is **required** for CKEditor 4 to load.

Regarding the very first script error "Cannot read property 'msie' of undefined" that is certainly a jQuery related error. What version are you running? You should get the jQuery Update module (my rule of thumb with that is 1.10+ on the front end, and 1.7 for all admin pages). The module will let you add that configuration in the admin UI.

I used to get stuck here quite a bit but it is usually one of the above two things.

Are you trying to use any custom plugins for CKEditor? If a plugin is missing common properties (in its plugin.js) it can throw JS errors which will certainly prevent the editor from loading.

As a final note, the reason you do not see the 'enable/disable rich editor' link is that the code that determines this lives in the WYSIWYG module. If the editor isn't loading, it will not show:

```
// Add basic Wysiwyg settings if any editor has been added.
  if (!isset($settings_added) && $loaded[$name]) {
    drupal_add_js(array('wysiwyg' => array(
      'configs' => array(),
      'plugins' => array(),
      'disable' => t('Disable rich-text'),
      'enable' => t('Enable rich-text'),
    )), 'setting');

```

So that is why you don't see it. Please check on your version of jQuery and WYSIWYG module and report back. I am fairly confident this is your issue. Also, if you could change your admin theme to Seven (looks custom / Bootstrap from youc pics) that could help narrow down what is using unsupported JS.
> 1 votes

# Answer
Here are some hints to help you debugging (= taking away all possible causes, 1 at a time):

* A possible explanation for what you're experiencing, is that it is a memory problem (not enough memory available. So try to (temporary) increase your memory limit (say with like 25% or so). To do so, check my answer at Why can I not find the og table after installing Organic Groups? (the `settings.php` part of it). You're looking for a line like `ini_set('memory_limit', '128M');`, if it is not there yet, just insert such line at the very end. And (temporary) try with `256M` instead of `128M`.
* As an alternative to increasing memory: try to (temporary) disable some other module(s) which might free up just enough memory without having to edit `settings.php`).
* Verify if you get the same issue with `user/1`. If so then you eliminate it is a permission issue (since with user/1 you skip/ignore any type of permission).
* Try to recreate the same issue using another browser (if that works it might be like a cookie problem).
* If none of the above helps, try to change the CKEditor library version, to see if that would help. Like if you now have 4.x, (temporary) replace it by some 3.6.x version and try again.

More attempts to try to figure out the real problem:

* You are using the DEV version of Wysiwyg, try with the latest official release. Know that that official release does not recognize the 4.x lib yet, but it does recognize that 3.6 lib.
* Why are you using the Wysiwyg module at all, and why not just the CKEditor module (with the same CKEditor library)? If you can't figure out the real cause of your issue, then just not using Wysiwyg might be a possible alternative (instead of trying to solve the problem, try to avoid the problem).
* Adding that other editor (for filtered html) is only going to complicate things (possibly create side effects). So I would remove that again. From what I read in your comments (or question), nowhere I see an indication that you tried with that 3.6.x version of the CKEditor library (instead of the 4.x I see in your last screenprint). Try that also. FYI: I always use official releases of Wysiwyg (and still with the old 3.6.x CKEditor library). I never ran into issues like yours here.

**Updates**:

* Your screenprint with the Script error: THAT seems to be an interesting NEW path for debugging, though I don't know how to further debug that (at least not for now). Could it be a jQuery problem? Could be related to (caused by) JQuery Update, similar to what is described in "Cannot edit my views.. I get a JSON string?".
* Replace the Wysiwyg module by the CKEditor module as I suggested before, at least temporary to see if that helps.
> 0 votes

# Answer
Just so everybody can get the solution, a friend of mine solved it. It was in fact jquery, so I had to go into jquery admin/config/development/jquery\_update and click third option jquery update and enable jquery migrate plugin....after i checked the box, no mor problem
> 0 votes

---
Tags: 7, wysiwyg
---


title: menu item required to edit content

text:
# Question
Title: menu item required to edit content
I need to add a menu item in my User menu which provides the facility for users to amend the content of a Content Type ( Sectors) i.e. so they can amend a sector. The User Menu only appears of course for logged in users.

I have tried setting up a menu option in the User menu which links to a View which displays all the Sectors so the logged in user can select one and amend it, this works fine, but the menu option is still displayed for anonymous users as well.

I have 'node/add' for other menu options to create content for content types, they behave properly in the User menu i.e. only appear when a user is logged in, how do I have an edit option for Sectors which only appears for logged-in user in the User Menu?

# Answer
> 0 votes
This is achieved by setting the Permission of the View to Role and selecting the role required.

---
Tags: nodes
---


# Question
Title: managed file problem with anonymous users and two managed file fields
I have a form with two `'#type' => 'managed_file'` fields.

1. Anonymous user selects a file on field 1, clicks the Upload. Ajax upload occurs and the browse widget is replaced by the filename uploaded and the Remove button, as expected.
2. user does same on field 2, which works same way. Form now displays with two uploaded files, as expected.
3. user clicks main (non ajax) submit button. **Form complains that file field 1 is missing**

## Other observations

1. If I disable ajax, I notice that on clicking Upload on one managed file field, the other one loses its file!
2. If I don't use the managed file upload button at all, and supply one file then press submit, the file shows as if uploaded, shows validation error about file 2 (as expected). However, if I immediately press submit again I would expect the same state to be preserved, but instead I see now that both file fields are again blank.

Is this bug/limitation in Drupal (7) or am I doing something stupid?

Here's my code:

```
function mymod_formtest($form, &$form_state) {
  $form['f1'] = [
    '#type' => 'managed_file',
    '#required' => TRUE,
    '#upload_validators' => [
      'file_validate_extensions' => ['doc docx odt pdf'],
    ],
    '#upload_location' => 'private://test/',
    '#title' => t('Upload 1'),
    '#default_value' => isset($form_state['values']['f1']) ? $form_state['values']['f1'] : '',
  ];

  $form['f2'] = [
    '#type' => 'managed_file',
    '#required' => TRUE,
    '#upload_validators' => [
      'file_validate_extensions' => ['doc docx odt pdf'],
    ],
    '#upload_location' => 'private://test/',
    '#default_value' => isset($form_state['values']['f2']) ? $form_state['values']['f2'] : '',
    '#title' => t('Upload 2'),
  ];
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => 'go',
    ];
  return $form;
}

```

# Answer
The `#value_callback` for a `managed_file` FAPI element is set to `file_managed_file_value()`.

This function is responsible for setting up the element's value in one of two possible ways.

1. If a file has been sent, then store this file in the `file_managed` table as a **temporary** file. Put this `fid` into the form element's value.
2. If instead a `fid` value has been sent then determine whether that is valid, and if so put that in the form element's value.

* The fid is invalid if it belongs to a **temporary file**.
    * The fid is invalid if it belongs to a `private://` file that the current user does not have access to, according to hook\_file\_download

What's happening above in the OP's question is:

1. 1sts File is sent. Gets stored. Form returns (because the 2nd file has not been provided) but for file 1 it shows the file uploaded and the file's new `fid` is added as the element's value.
2. The user now submits the 2nd file. Processing starts with the fist file field. No file has been sent for this, but instead we have the `fid` value. This file object is loaded and inspected. But this file is **temporary** so it's assumed that the POST-ed `fid` is invalid. Hence it shows that there is no input for the first file.

## Solution

So first of all you need the file to be made permanent. And then you need Drupal to realise that this particular anonymous user should be allowed to access this particular file (but not all files uploaded this way).

I did this by using an `#element_validate` property on the managed file fields which points to a function like this:

```
function anon_private_upload_remember($element, &$form_state, $form) {

  if (isset($element['#value']['fid'])) {
    $fid = (int) $element['#value']['fid'];
    if ($file = file_load($fid)) {
      if ($file->status != FILE_STATUS_PERMANENT) {
        // Looks like this file has just been uploaded.
        // Change status to permanent.
        $file->status = FILE_STATUS_PERMANENT;
        // Save.
        file_save($file);
        // Record that the module (in this example, user module) is using the file.
        file_usage_add($file, 'user', 'user', 0);

        // Now remember that this user is allowed this file.
        if (!isset($_SESSION['anon_user_owns_fids'])) {
          $_SESSION['anon_user_owns_fids'] = [];
        }
        $_SESSION['anon_user_owns_fids'][$file->uri] = $file->fid;
      }
      // Fine, the file is valid, so the field is valid.
      return;
    }
  }
}

```

**WARNING: as well as the above `#element_validation` you also NEED to add `file_managed_file_validate` *after* the above one.** So your form element's validation definition might look like:

```
$form['some_element'] =
  // ...
  '#element_validate' => ['anon_private_upload_remember', 'file_managed_file_validate'],
  // ...

```

That function (which is normally added via the file module's element info function) is responsible for simplifying the element's value into a simple `fid` instead of a nested array.

This will make files uploaded permanent, and stores their uris in a `$_SESSION` variable. Then implement `hook_file_download` like:

```
/**
 * Implements hook_file_download.
 *
 * This is the hook used to control access to private:// files.
 * Annoyingly it's supposed to return headers.
 */
function myrmod_file_download($uri) {
  if (isset($_SESSION['anon_user_owns_fids'][$uri])) {
    // We are supposed to return headers, but for our purposes this is fine.
    // @todo - this won't work if you try to download the file, but
    // is fine for just checking access.
    return ['foo' => 'bar'];
  }
  // Don't know - pass on to other modules.
  return NULL;
}

```

For my purposes I then need to do some extra cleanup - e.g. set the file back to temporary and remove the usage record on final form submission, since I don't need the file after that.

Phew. That was difficult.
> 1 votes

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


# Question
Title: "Home" not changing in Breadcrumbs when switching languages (Locale)
I am using Locale to translate content and menus.

Despite that, even when viewing a page in Spanish, the "Home" link in the breadcrumbs does not change to "Inicio".

What can I do to fix that?

I have attempted to create a node called "Home", translate it to be called "Inicio" and then changed the url to the homepage in the Configuration \> Site Information but have still not had any success.

Is there a possibility to fix this without an additional module and a ton of re-configuring?

Thank you.

# Answer
Navigate to **"Translate strings"** interface in **"Regional and language"** admin section (`/admin/config/regional/translate/translate`).

Search for "Home" and translate all untranslated instances of that string. This should fix the issue with translation of default breadcrumbs.

**Useful tip:** strings search is case sensitive, so make sure you enter your strings as they appear in html source (this condition gets easily overlooked).
> 1 votes

---
Tags: 7, breadcrumbs, i18n-l10n
---


# Question
Title: Can fields validation errors be displayed below the fields?
Can field validation errors be displayed below the fields instead of as a list at the top of the form?

# Answer
I think you are looking for something like the Inline Form Errors Module. Here is a quote about it (from the module's project page):

> ... allows you to place form submission error inline with the form elements. Three options are provided for setting your inline error behaviour. You can configure the default behaviour or override the behaviour on a per form basis. You can add as many forms as you like.
>
> IFE provides three behaviors for the configured forms
>
> * Leave the messages in place, this option will copy the error messages and place them inline. The original error messages set by Drupal will remain in place
> * Show an alternative message, this option will replace the original messages with a generic error message such as 'Please correct all errors.'. This message can be set in the IFE configuration page. The original error messages are placed inline with the form elements
> * Remove all messages, this option will remove all error messages and place them inline with the form element
>
> In all cases only the messages related to the form will be touched. All other messages will remain in tact.
> 2 votes

# Answer
The module of the last answer is only available in alpha for Drupal 7 (but anyway, it's working for me).

But I found this one for Drupal 7, it's just a little bit less good but it does the job if you don't want an alpha version: Inline Messages. Hope it can help someone on my case.

Here is a quote about it (from the module's project page):

> ... allows you to move form messages (error/status/warning) from the top of the page to just above where your form appears.
>
> You can enable Inline Messages for your site, content editing or administration pages. Additionally you can also specify forms to include or exclude by id. It will also work for pages with multiple forms.
>
> An example usage is with the comment form, which is typically placed at the bottom of the page. Should an error be generated when someone submits, they jump back to the top of the page. So to get back to the comment form, you have to scroll back to the bottom of the page.
>
> Using jQuery and the jQuery ScrollTo plugin, Inline Messages will capture the $messages, place them just above your form and move the page to the top of the form.
> 0 votes

# Answer
The Drupal Clientside Validation module transforms any form to support JavaScript clientside validation and allows the following error message placements:

* jQuery selector
* Top of form
* Before label
* After label
* Before input
* After input
* Top of first form
* Custom function

For example, here's a screenshot of a Webform in Drupal 7.x with inline error messages shown below the fields, instead of as a list at the top of the form (which is the default behavior).

---
> 0 votes

---
Tags: webforms
---


# Question
Title: Is there way to create regions for view modes programmatically?
So I have programmatically created a view mode and I need to theme it. The view mode will be rendered via views modules for different content types and The structure requires that I separate fields into to separate regions. A image region and content region. The different content types will be able to choose the fields they want for each region. So event may use featured image, while news article can use hero image field.

I really don't wan't to use display suite if there is some programmatic way of doing this.

# Answer
> 0 votes
You should be able to theme the fields behaving like a css-grid-system, maybe provided by your theme. Name view field templates like this:

```
views-view-field--foobar--page--field_name.tpl.php

```

And

* Make sure they have the correct order in the view.
* Empty fields wont be displayed.

If they have different names for the different content types, just include all field-names in your selectors ..

Maybe also have a look in the docs, and views have name suggestions under `Advanced` -\> `Theme`: Click on `Information`

---
Tags: theming, entities
---


# Question
Title: Internal server error when programmatically updating about 100 nodes
I'm writing a function that unpublishes a bunch of event-type nodes within a date range. My query pulls about 100 nodes, but I'm apparently maxing out the available memory. Here is the code in question:

```
$sql = "SELECT node.nid AS nid FROM node node  LEFT JOIN content_type_event node_data_field_event_date ON node.vid = node_data_field_event_date.vid WHERE (DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') >= '2014-09-10' AND DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') <= '2015-09-10') AND (node.type in ('event'))";

$nids = mysql_query($sql);
$report = "";

while ($nid = mysql_fetch_array($nids)) {
    $node_id = $nid['nid'];

    $node = node_load($node_id);

    $node->status = 0;

    node_save($node);
    $report = $node->title . " unpublished.";
}
drupal_set_message($report);

```

Any suggestions greatly appreciated.

# Answer
Give your server more memory ;)

* Better to use EntityFieldQuery (but this will not speed up your script ..)
* You could replace the while loop with `foreach (array_keys($result['node']) as $node_id)`
* In the worst case you'll need to limit the $result or $nids array to 10 or something .. and run the script several times, maybe in cron ?

Or run an update query (also possible without php)

```
$sql = "UPDATE node node LEFT JOIN content_type_event node_data_field_event_date ON node.vid = node_data_field_event_date.vid SET node.status = 0 FROM WHERE (DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') >= '2014-09-10' AND DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') <= '2015-09-10') AND (node.type in ('event'))";

mysql_query($sql);

```
> 0 votes

---
Tags: 7, nodes, caching
---


# Question
Title: How to write paragraph template to add tags and css classes?
I have a paragraph bundle (pr\_bnd1), which has several fields as below:

1. field\_txt
2. field\_bg\_clr (list field whose key values are mapped to a css class)
3. field\_font\_clr (list field whose key values are mapped to a css class)

The an example output

```
<div> field_txt value</div>

```

Desired output

```
<div class="field_font_clr_value">.
   <span class="field_bg_clr_value"> field_txt value</span>
</div>

```

How would i achieve the desired results? I am having trouble getting the template file to work. Any thought?

My paragraph bundle name is "pr\_bg\_font\_clr".

So i imagine i would have to write a template file with the name of "paragraph-items--pr-bg-font-clr", but i am not sure what the structure should be and which fields i can utilize.

# Answer
Have a look here for the naming

> The default paragraphs template is in paragraphs-item.tpl.php. It uses theme suggestions for other templates, the following suggestions are available:
>
> * paragraphs\__\[view\_mode\] (e.g. paragraphs--default.tpl.php)
> * paragraphs\__\[type\] (e.g. paragraphs--image.tpl.php)
> * paragraphs\__\[type\]\__\[view\_mode\] (e.g. paragraphs--image--default.tpl.php)

As this seems to be wrong .. Try the suggestion:

```
paragraphs-items--pr_bg_font_clr.tpl.php
paragraphs-item--pr_bg_font_clr.tpl.php

```
> 1 votes

---
Tags: 7, hooks, theming
---


# Question
Title: How do I wrap a div around specific fields in a view?
I have to make a small website using drupal 8 for a school project but I keep getting stuck with the twig templating. I'm trying to wrap a div around certain fields in drupal 8 with twig. The layout at the moment is as follows(this is an example);

```
<div>
Content type image
</div>
<div>
Content type Title
Content type Category
</div>

```

Is there any way to accomplish this using a twig template for the certain view?

The bottom two items have to go in a div.

# Answer
> 1 votes
To add CSS classes you don't need to use Twig, you can do it using the Views UI

Click on your field. Then under style settings, checkmark customize field HTMl and select DIV as your element. Checkmark create css class and type your class name.

# Answer
> 1 votes
In node.html.twig Twig you would do it like this:

```
<div class="cool">
  {{ content.title }}
</div>
<div class="kewl">
  {{ content.field_name }}
</div>

```

---
Tags: theming, 8
---


# Question
Title: In Drupal 8 how do I get the image path from a twig node template?
I'm working with Drupal 8 and twig

I created a Drupal content type called hero. It contains a title, body copy and an image. I'm overwriting node.html.twig for this content type but am having trouble accessing the image source to generate html I need to.

```
<div {{ attributes.addClass(classes) }} style="background-image: url(/img/site/about/about_hero_banner.jpg);">
      <div class="row">
        <div class="col-sm-7">
          <div class="copy">
            <h1>
              Headline
            </h1>
            <p>
              Subhead Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex, sed voluptatum fugit ipsa animi quos nobis?
            </p>
          </div>
        </div>
      </div>
    </div>

```

I can access the Headline and title with the code below but I don't want to load the image file I want only want the image path (source).

```
{{ content.body }}
{{ content.field_headline }}
{{ content.field_hero_image }}

```

How do I get the image file path from in my node template from {{ content.field\_hero\_image }}? How do I access the attributes of content.field\_hero\_image?

I've looked at image.html.twig and see

```
<img{{ attributes }} />

```

So I know it's in the attributes, but don't know how to access the attributes from the node template.

# Answer
> 3 votes
Ok, after writing this question a similar one showed up and I think I found the solution:

```
{{ file_url(node.field_hero_image.entity.fileuri) }}

```

---
Tags: theming, 8
---


# Question
Title: How do I add a validation handler to a specific exposed filter form?
I want to add a custom validation handler to the exposed filter form that is part of a view.
I am not able to target that specific exposed filter form: The validation handler is added to other forms too.

Is there a way to add a validation handler only to a specific exposed filter form and avoid the validation handler is added to other forms too, including other forms for exposed filters?

# Answer
To form alter a specific view exposed filter form, you need 2 conditions to check: the form id & the form's `'#id'` element.

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {

  // @NOTE: $form['#id'] will vary based on your your view & display machine names.
  // Here the view machine name is 'view' & display machine name is 'display'.
  // Use Devel's dpm() to inspect or the Views administration UI
  // to find your own form's values.

  if ($form_id == 'views_exposed_form') {
    if ($form['#id'] == 'views-exposed-form-view-display') {
      // @TODO: Add form alter code.

    }
  }
}

```
> 6 votes

---
Tags: views, 8, forms
---


title: Use module to change custom type theme

text:
# Question
Title: Use module to change custom type theme
I have built a module that adds a new custom type. I want to control the theme of that node type, and use a custom theme page for that node type. I can't find any documentation about this. How can customize the theme/page of that node type?

EDIT: I need to completely rewrite the entire page that shows the node content, discarding the default theme and handling with a custom code what must be shown and how.

EDIT: Based on the suggestion of cyclone, I've added this code:

module name: my\_module

node type name: mynode

I have a file called mynode.tpl.php in my module folder with an echo "hello world" to test it

I have added this code to my\_module.module:

```
function my_module_preprocess_node(&$variables) {
  // check so the node is your custom type
  if ($variables['node']->type == 'mynode') {
    // add a template suggestion, the example file here will be
    // called your-custom-template.tpl.php
    $variables['theme_hook_suggestions'][] = 'mynode';
  }
}

```

but when I load a node, it is still used the default theme.

# Answer
I was able to customize my node theme with this code. So far is the best result I got. I hope I will be able to reach a full page theme customization somehow.

```
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  $theme = array();
  $path = drupal_get_path('module', 'my_module');
  debug($path,'path',TRUE);
  drupal_set_message('path: '.$path);
  dvm($path,'path');
  $theme['node__mynode'] = array(
    'render element' => 'content',
    'base hook' => 'node',
    'template' => 'node--mynode',
    'path' => $path  . '/templates',
   );
  return $theme;
}

```
> 0 votes

# Answer
I'm not sure I understand the question. You can use `template_preprocess_node()` to add your own template:

```
function <module>_preprocess_node(&$variables) {
  // check so the node is your custom type
  if ($variables['node']->type == 'your-custom-type') {
    // add a template suggestion, the example file here will be
    // called your-custom-template.tpl.php
    $variables['theme_hook_suggestions'][] = 'you-custom-template';
  }
}

```

The above code should be placed in your `.module` file and of course you will need to change `<module>` in the above example to the actual name of your own module.

You can also follow the above link to see some examples on how to implement this in your custom module.

Notice that you also need to flush the cache whenever you add something new into your module file in order for the changes to take effect.
> 2 votes

# Answer
If you need to change site theme, you can try to use some contrib modules, like:
\- ThemeKey
\- Switchtheme

Or change theme programmatically in custom code with `hook_custom_theme()`:

```
/**
* Implements hook_custom_theme().
*/
function mymodule_custom_theme() {
  if ($some_condition_is_true) {
    return 'my_theme';
  }
}

```
> 2 votes

# Answer
If you need to theme only node page, would recommend you to use Panels module, with Panels you could override default node content page of particular type, you can chose layout there and add custom code. But Panels pretty complex module and you have to read Panels documentation to work well with it.
Shortly what should you do:
\- Enable Panels and Page manager modules.
\- Go to Pages: `/admin/structure/pages`.
\- Enable `Node template` page and edit it/.
\- Add new variant of type Panels.
\- Chose layout.
\- Click Continue then Create variant.
\- Go to Selections rules tab, add node type as criteria and chose your content type - so your page will work only on your content type.
\- Go back to Content tab and add content panes to regions.
I would recommend to read/watch some tutorials before working with Panels.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How to implement moderation of data entered through user profile pages?
I am in need of a means of moderating data entered through a user's profile page, or at least for certain specified fields, both upon initial submission and after any revision. These are fields that have been added to the basic user profile (example.com/user/#), editable through the "my account" link -- fields that can be added through Home » Administration » Configuration » People » Account settings.

The most important fields to moderate involve text entry fields and selected taxonomy terms. By moderation, I mean administrative approval of the changes before they go live on the site. My preference would be for the old data to remain visible pending approval of the new data.

I hired a web development company to create a site that includes a directory, with the explicit instruction that moderation of directory data was necessary. They nonetheless set the site up such that the information is provided through fields on users' profile pages and did not incorporate any means of moderation.

I have seen a potential work-around that involves the installation of the Profile2 and Profile2 Moderation modules, but simply implementing those modules does not fix the problem and creating new profile pages would unfortunately risk breaking the site.

If you have any ideas, I would be very grateful to hear them.

# Answer
> 0 votes
What I've done in a similar situation was this:

1. Turn on moderation of users /admin/config/people/accounts ie:

```
Who can register accounts?
--> Visitors, but administrator approval is required
```
2. Install Views Bulk Operations https://www.drupal.org/project/views\_bulk\_operations
3. Create a view that shows the moderated users by default (but you can use an exposed filter to change this). Include the fields that you want the administrator to be able to see (your text entry and taxonomy referred to above). Set your view to the VBO options and enable the operations for approving (or blocking) users.

Hope this helps!

# Answer
> 0 votes
I suggest you try to use a combination of 2 approaches, as further detailed below.

# Approach 1 - Prior approval required

The Profile 2 Moderation module, which depends on the Profile 2 module, enables moderation on user profiles. Here is a (self explaining?) screenprint from its project page.

Be aware however that, as mentioned on the project page, it requires a Profile revisions patch.

Disclaimer: I've never used this approach myself (yet ...), but worth invetigating!

# Approach 2 - After the facts

Use the Rules module to be informed about all sorts of updates that you're interested in, similar to what's detailed in my answer to "How to send an eMail notification when a specific field of a node or user has been changed?".

With this approach, and as per all the great things you can do with this module, your options are virtually unlimited. This approach also allows you to implement this type of moderation using a granular approach: start small, maybe only using a few custom rules, and keep refining them and continue adding new ones.

Not to forget all the available integrations with tons of other modules, of which the Flag module is probably your very first priority to also add that module for what you're trying to implement. Just a basic usecase about this:

* Use Rules to *flag* any user for which some profile update happened.
* Use Views to build a list of such flagged users.

If you'd only implement these 2 bullets of this approach (a matter of minutes, say an hour at max), you'd already have a Version 1.0 of your **User Profile Moderation Dashboard** (call it your *MVP* if you prefer ...).

# Approach 3 - Build your own spam filter

You could also use an approach/strategy similar to what I described in my answer to "How to use the Rules module to perform a simple anti-spam validation using specific keywords?", at least for anything that is text-field like. For those situations it would be an ongoing process to keep refining the various text strings you want to stop from being entered.

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework. And/or the similar set of 8 video tutorials about the Flag module.

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


# Question
Title: How can I create a view page that takes taxonomy machine name and has depth?
This question is a followup to How to load nodes that are associated with the child of a taxonomy term and refers to this answer in particular, but is standalone, so you need only visit those if you want more background.

I want to create a view that functions like the Taxonomy term view that comes with views with depth turned on in the contextual filter, **but taking the term's machine name** instead of tid as the contextual argument.

I have pathauto set up to alias /taxonomy/term/tid to /vocabulary/term, and I would like to override the page there with views to make it show nodes associated with the children of the term as well as the parent.

So if I had the following Taxonomy:

**Vocabulary 1 (vocab\_1)**

* Term 1 (term\_1)
    + Term 2 (term\_2)
    + Term 3 (term\_3)
* Term 4 (term\_4)
    + Term 5 (term\_5)

and nodes as follows:

Node 1 - Term 2, Term 5 Node 2 - Term 5 Node 3 - Term 3

A visitor to /vocab\_1/term\_1 should get a list that contains nodes 1 and 3 because they are associate with children of Term 1.

I haven't been able to figure out how to do that with the term machine\_name as the contextual filter instead of the tid.

# Answer
You can use the contextual filter **Content: Has taxonomy term ID (with depth)** without adding a *Relationship*. Use this settings for the contextual filter:

**When the filter value is *NOT* available**: Provide default value
**Type**: Taxonomy Term ID from URL
Make sure *Load default filter from term page* is **checked**.

**Please note:** When you visit a pathauto destination path, in this case with a source of `/taxonomy/term/%` pointing at `/vocabulary_name/term_name`, drupal passes the source path as a query variable, and your view still uses the source path to gather information. This means your path in the view should not change, it should stay as `taxonomy/term/%`
> 2 votes

# Answer
Unfortunately looks like there isn't a term machine name contextual filter option. There is one, but only for vocabulary machine name.

If you really want this, you will have to get your hands dirty.

Create a custom module with a custom page that has a variable url. ex: `/taxonomy/%` the `%` being a place holder for the machine name.

Then on page load using using current\_path() along with some php function (perhaps str\_ireplace() to remove the `taxonomy/` part), you grab machine name from the url. Then you query the database, using db\_query(), to grab the term id that belongs to that machine name.

Once you have the term id you can render the view on your screenshot using php. So you just pass the term id as the argument.

```
<?php
print views_embed_view('my_view', 'block_1', $arg,);
?>

```

so in your case it would be:

```
<?php
print views_embed_view('taxonomy_term', 'page', $term_id,);
?>

```

---

### Update:

> After looking at the taxonomy term table (taxonomy\_term\_data) turns out that there is no machine name column for taxonomy terms (which explains why there is no contextual filter in views).

Therefore, the only alternative would be to use the taxonomy term name. As long as you have unique term names, this will be fine.

First, you need to go to the taxonomy term view (the one in your screenshot) and press on  and add a block and save.

Here is a working module I created called term finder.

```
/sites/all/modules/term_finder

```

**term\_finder.info**

```
name = Term Finder
description = Creates variable pages for taxonomy term names and shows a view.
core = 7.x

```

**term\_finder.module**

```
<?php

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

  $items['taxterm/%'] = array( // this will be our custom page url. The % allows us to put anything after, ex: taxterm/[anything can go in here]
    'title' => 'Your Title Goes Here',
    'access callback' => TRUE,
    'page callback' => 'term_finder_page', // the name of the function that gets runed when we visit our taxterm/[anything] page.
    'type' => MENU_NORMAL_ITEM,
    'menu' => 'navigation',
  );

  return $items;
}

/**
 * Page callback for taxterm/%.
 */
function term_finder_page() {
  $path = current_path(); // gets the current page url. ex: taxterm/hello-world and saves it on a variable
  $path = str_ireplace('taxterm/','', $path); // removes the taxterm/ from our variable, so we are left with hello-world
  $path = str_ireplace('-',' ', $path); // replaces the - with a space, so we have hello world
  $term_id = db_query("SELECT tid from {taxonomy_term_data} WHERE name = :name LIMIT 1", array(":name" => $path))->fetchField(); // queries the DB to find the tid that belongs to hello world.
  if ($term_id != '') { // we check if grabbed a term id, is not empty.
    $show_view = views_embed_view('taxonomy_term', 'block_1', $term_id); // creates the view, which passes the tid we got from the DB as an argument.
    return $show_view;
    }
  else { // if the term id is empty, then we show "not found".
  return 'not found';
  }
}

```

Lets assume you have a term called Hello World.

What this does is if you go to `/taxterm/hello-world` or (in firefox) `/taxterm/hello world`

It will look up in the DB for Hello World and get the term id and pass it to the view.

**PS:** In case you are wondering why the mysql query looks the way it does, see Writing secure code and How do I get only one result using db\_query()
> 1 votes

---
Tags: 7, views, path-aliases
---


# Question
Title: Install Drupal 8 on MAMP: can't detect version of Apache
I'm trying to install Drupal 8 on my mac using MAMP Pro. I get this error message when Drupal tries to verify I have the proper configuration:

```
Apache Version:
Due to the settings for ServerTokens in httpd.conf, it is impossible to accurately
determine the version of Apache running on this server. The reported value is
Apache, to run Drupal without mod_rewrite, a minimum version of 2.2.16 is needed.

```

I have the latest version of MAMP Pro which is running 2.2.29.

# Answer
Drupal uses Apache's `ServerTokens` in `system_requirements()` to determine the version number. You currently have that set to "Prod", which just reveals "Apache" as the token, without any version number.

For Drupal to detect the major and minor versions, plus revision, you need to update the config setting to one of:

* **Full** \- Server sends (e.g.): *Server: Apache/2.4.2 (Unix) PHP/4.2.2 MyMod/1.2*.
* **Min** \- Server sends (e.g.): *Server: Apache/2.4.2*.
* **OS** \- Server sends (e.g.): *Server: Apache/2.4.2 (Unix)*.
> 6 votes

---
Tags: 8
---


title: Problem with submenus

text:
# Question
Title: Problem with submenus
I am new at Drupal , and I am using version 7.43. I have already installed Bootstrap, and now I am defining the menus. But to realize Multilevel submenus I need the folder of `bootstrap_subtheme`

I searched but I couldn't find that folder, I found just the Bootstrap folder.

Any hints?

# Answer
> 1 votes
Create such sub-theme folder manually. The folder name you'd use for it will be the machine name of your subtheme.

For more details, refer to:

If you prefer to look at a great (I think) example of a (contributed) Bootstrap sub-theme, then have a look at the Bootstrap Business theme.

---
Tags: 7, theming
---


# Question
Title: How to allow for manual HTML & CSS changes?
I'm using CK Editor to insert a table into my content (**Body** field).

I would like to set a background color, so I extended the `style="width:100%"` to be `style="background-color: #FFEEE4; color: black;width: 100%"`. And this by clicking on `Switch to plain text editor`.

But now, once I save, the `background-color` style disappears again (Test Format FULL HTML). How can I make it stick?

# 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 full html) You need to go to

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

OR

/admin/config/content/formats/full\_html

### **Uncheck the correct faulty and chopped off html box.**
> 1 votes

---
Tags: 7, theming, wysiwyg
---


# Question
Title: Is it safe to use a custom value for users.status column
Currently `status` column can have only 2 values:

* 0 - inactive
* 1 - active

I need to add a new status for the user: temporarily inactive. Will it be safe if I use `status` = 2 for it?

# Answer
> 0 votes
long story short: no, never

why: user-\>status is deep bound into drupal core, so in order to handle status=2 you will have to hack the core

there are alternatives: you could use another field or expand user entity

# Answer
> 1 votes
Why would you need to?

You can attach a boolean or numeric field to the user entity.

Navigate to Admin -\> Configuration -\> Accounts -\> Add Field.

---
Tags: users, database
---


# Question
Title: How to use Font Awesome with Bootstrap LESS theme?
I have created a sub-theme, using the LESS Starterkit, of the Bootstrap theme. I would like to self host the Font Awesome icons and make them available to a custom module.

I have downloaded the Font Awesome project to: `sites\all\themes\MYBOOTSTRAPTHEME\font-awesome`.

Following these instructions, I have added the following (last four) lines to: `sites\all\themes\MYBOOTSTRAPTHEME\less\variables-overrides.less`:

```
//== Iconography
//
//## Specify custom location and filename of the included Glyphicons icon font. Useful for those including Bootstrap via Bower.

//** Load fonts from this directory.
@icon-font-path:          "../fonts/";
//** File name for all font files.
@icon-font-name:          "glyphicons-halflings-regular";
//** Element ID within SVG icon file.
@icon-font-svg-id:        "glyphicons_halflingsregular";

//** Load Font Awesome fonts from this directory.
@fa-font-path:            "../../font-awesome/fonts/";
//** File name for all Font Awesome font files.
@fa-font-name:            "fontawesome-webfont";

```

I have added the following line to my custom module:

```
<button type="button" class="btn btn-default btn-lg">
  <span class="fa fa-camera-retro" aria-hidden="true"></span> Camera
</button>';

```

After recompiling my LESS: nothing. What am I missing. Thanks.

# Answer
> 2 votes
Figured it out. Add:

```
@import "../font-awesome/less/font-awesome.less";

```

to `sites\all\themes\MYBOOTSTRAPTHEME\font-awesome\less\font-awesome.less`.

---
Tags: theming
---


# Question
Title: Custom html.tpl.php from module for custom type
I have built a module that adds a new custom content type. I need to use my own html.tpl.php for that content type, and the html template sits on my module folder.

I have done somee xperiments, I was able to replace the template of the node content, but it's not enough, and I can't seem to find some examples or explanatory documentation about it.

If my module is called "tomato" and my custom type is called "sauce", and I already have a file called html--sauce.tpl.php on my module folder, how do I tell Drupal to use that template when a "sauce" node is loaded?

# Answer
Modules can use `hook_preprocess_html()` to override theme templates. You need 3 things:

Using a module called `MYMODULE`, with a new node type `mynodetype`, & a template in the module dir named **templates/html--mynodetype.tpl.php**, we can add the following hooks to `MYMODULE`.

```
/**
 * Implements hook_preprocess_html().
 */
function MYMODULE_preprocess_html(&$vars) {
  $node = menu_get_object();

  // Add a new theme suggestion when viewing node's of mynodetype.
  if ($node && $node->nid && $node->type == 'mynodetype') {
    $vars['theme_hook_suggestions'][] = 'html__mynodetype';
  }
}

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {
  $theme = array();

  //Add our templates/html--mynodetype.tpl.php to the theme registry
  $theme['html__mynodetype'] = array(
    'template' => 'html--mynodetype',
    'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
  );
  return $theme;
}

```
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Add conditional redirect to Views exposed filter (using BEF)
I have a view showing a select list of locations. Upon selecting a location the View shows a Google Map with the locations of the current selection.

For certain items in the select list I would like to redirect away from the View to another page.

I have looked at these discussions:

https://www.drupal.org/node/1379492#comment-6273188

How to change programmatically exposed filters in views

But none of them mentions my specific case of conditional redirection.

Any clues very welcome!

# Answer
A sketch of an idea, for prototyping.
Once this works for you, you could move this javascript code into a render array via form alter. Here are some links for that:

Prototyping: Inside the header area of your view you can insert a js snippet inside of a 'Global: Text area' field (use the full html text format to avoid stripping of html tags):

And here is an example snippet to get you started, I am targeting the node's status exposed filter from my sample view:

```
<script>
(function($) {
  $( document ).ready(function() {
    $('#edit-status').change(function() {
      switch($(this).val()) {
        case 'optionA':
          window.location = "https://www.drupal.org";
          break;
        case 'optionB':
        case 'optionC':
          // grouping option together if they have the same target url
          window.location = "https://petrakis.design";
          break;
        default:
          // default code block, simply exit
      }
    });
  });
})(jQuery);
</script>

```

Hope this helped!
> 0 votes

# Answer
This is an alternative answer, not javascript based and much closer to the "best practices" way.

The most important piece of information lies inside the ctools/js/auto-submit.js file of CTools. This is the verbatim comment in the beginning of that file:

> To make a form auto submit, all you have to do is 3 things:
> ctools\_add\_js('auto-submit');
>
> On gadgets you want to auto-submit when changed, add the ctools-auto-submit
> class. With FAPI, add:
>
> '#attributes' =\> array('class' =\> array('ctools-auto-submit')),
>
> If you want to have auto-submit for every form element,
> add the ctools-auto-submit-full-form to the form. With FAPI, add:
>
> '#attributes' =\> array('class' =\> array('ctools-auto-submit- full-form')),
>
> If you want to exclude a field from the ctool-auto-submit-full-form auto submission,
> add the class ctools-auto-submit-exclude to the form element. With FAPI, add:
>
> '#attributes' =\> array('class' =\> array('ctools-auto-submit-exclude')),
>
> Finally, you have to identify which button you want clicked for autosubmit.
> The behavior of this button will be honored if it's ajaxy or not:
>
> '#attributes' =\> array('class' =\> array('ctools-use-ajax', 'ctools-auto-submit-click')),
>
> Currently only 'select', 'radio', 'checkbox' and 'textfield' types are supported. We probably
> could use additional support for HTML5 input types.

Following that, you need to implement a custom module and using \_form\_alter:

1. Disable auto-submit for your exposed filter using the 'ctools-auto-submit-exclude' class
2. Attach a javascript that will do something similar to the alternative answer's javascript, namely, redirect to another url.

In the following example code, I use a simple redirect based on an exposed filter of the basic content types, article and page. Tested and it worked!

A sample form\_alter implementation:

```
function somemodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  // This is the name of the FAPI exposed filter element
  $filter_exposed_select_name = 'type';

  // This is the name of the select values and their respective target url
  $target_urls = array(
    'page' => 'http://www.drupal.org',
    'article' => 'http://drupal.stackexchange.com'
  );

  // This will disable auto-submitting the form for our filter element
  $form[$filter_exposed_select_name]['#attributes'] = array('class' => array('ctools-auto-submit-exclude'));

  // This will attach a javascript to the element for handling the redirects
  $form[$filter_exposed_select_name]['#attached']['js'][] = drupal_get_path('module', 'somemodule') . '/somemodule.js';
  $form[$filter_exposed_select_name]['#attached']['js'][] = array(
    'data' => array(
      'bef_custom_redirect' => array(
        'target_name' => $filter_exposed_select_name,
        'target_urls' => $target_urls,
      )
    ),
    'type' => 'setting'
  );
}

```

and the accompanying javascript file (somemodule.js).

```
(function($){

Drupal.behaviors.BEFCustomRedirect = {
  attach: function(context, settings) {
    $('.ctools-auto-submit-exclude.form-select[name=' + settings.bef_custom_redirect.target_name + ']').change(function() {
      window.location = settings.bef_custom_redirect.target_urls[$(this).val()];
    });
  }
}

})(jQuery);

```

Hope this does the trick for you, let me know how it went!
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I grant permissions for translating block content?
I used the Block Image module to create some content. I want to give the site's editor the permission to translate the blocks, but I don't understand how to achieve that. Apparently, there isn't a permission that allows users to translate a block content.

How do I grant the permission to translate block content?

# Answer
I hope I got the question right, it seems pretty simple (@Volker almost got it in his comment):

1. Install i18n\_block
2. Give the target user role the permissions: "Administer blocks", "Translate interface texts" and optionally "Use contextual links"
3. Configure the target block to be translatable by selecting "Make this block translatable" in the block's configuration
4. Click on the "Translate" tab (or the "Translate" contextual link); this is a new option available only after you do step 3

Here are three example screenshots:

---

## Configure block to be translatable, optionally picking target languages

---

## After saving the configuration, the block's contextual link has the "Translate" option

---

## ... which eventually leads you to the Block's translation page

Good luck!

P.S.: Whether you use the Image Block module or not, should not really make a difference, this was a red herring if I am not mistaken. ;-)
> 2 votes

# Answer
Block level permissions for administration is not provided in core. There is a module Block Access which provides block level permissions for admin interface.

> This module adds a set of global permissions for creating, viewing, moving, enabling, disabling and configuring blocks as well as permissions at the individual block level. These permissions only affect the admin interface, front-end view access is handled in core.

### UPDATE:

Blocks are not content, so the permission to translate content won't help here. To be able to translate blocks you need to download Internationalization and Variable modules and enable the module **Block languages** *\[i18n\_block\]* which ships with Internationalization module.
> 2 votes

# Answer
To my knowledge there is no such permission you can use for translating blocks. Any user who has permission to administer blocks, will also have access to the "translate" link that is typically used to translate blocks in other language. However there are 2 possible work arounds you may want to consider, as further detailed below ...

# Option 1: using the Rules module

But, the paths of such block translation links, typically include the language code (fr, nl, es, etc) as part of their paths. With that, you should be able to get it to work (or at least have some type of work around) by using the Rules module, using a variation of what is described in my answer to the question "How to make the permissions of a module more granular?".

You could start from the very same Rule (in export format) in that answer, and tune it to fit your exact needs. If you have a lot of such blocks, then probably the toughest part would be to tune the regular expression so that it matches the URLs of your blocks for which you want to restrict access. If you only have a few blocks you want to restrict access to, you shouldn't need the Rules Condition with the regular expression. Tuning the roles to be checked, and or the Rules Action should be straight forward.

# Option 2: using the BEAN module

You could use the Bean module for this. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

Here are the steps you'd have to complete:

* Create 1 **Block Type** for each of your languages, say `en`, `fr`, `es`.
* Create 1 **Block** for each of those Block Types, say `MyEnBlock`, `MyFrBlock`, `MyEsBlock`.
* Adapt the Block Visibility settings for each of those 3 blocks (using the Languages tab), so that they are only shown in the language they correspond to. E.g. for block `MyFrBlock` you only show it for language `fr`.
* Grant the appropriate **Bean permissions** (= which roles can perform which operations for which Block Types, aka language with the above Block Types configured).

With that in place, it appears to me that you would have a possible solution. Actually from then on your remaining todo is a variation of the question about "How to limit block management by role?". Refer to my answer to that question for more details about this great module (which by the way has been moved to core in D8 ...).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.
> 0 votes

---
Tags: 7, blocks, i18n-l10n
---


title: Change page title output

text:
# Question
Title: Change page title output
How can I change the page title output?

```
<title>{{ head_title|safe_join(' | ') }}</title>

```

in html.html.twig changes the mark/letter which creates: `<pagetitle> | <sitename>`, but I want to change this order to `<sitename> | <pagetitle>`

# Answer
Another option without the extra module overhead (still a valid option):

```
<title>{{ head_title|reverse|safe_join(' | ') }}</title>

```

Simply add the reverse filter to that part of your html.html.twig file

Twig rulez! Cheers!
> 5 votes

# Answer
You can accomplish this using the Meta Tag module

Click on override and switch it.
> 2 votes

---
Tags: theming, 8
---


# Question
Title: How do I remove or hide the Permalink in comments?
How do you remove or hide the 'Permalink' in comments? There is no tpl.php in Drupal 8. I remove `<p class="comment__permalink">{{ permalink }}</p>` from comment.html.twig, refresh, close and open my page, but nothing happens.

How I can edit the comment template file?

# Answer
Just tried your idea (remove `<p class="comment__permalink">{{ permalink }}</p>` from comment.html.twig) and it works as expected.

Important: Don't forget to rebuild your cache:

```
drush cache-rebuild

```

or through the UI

```
admin/config/development/performance > "Clear all caches"

```

Good luck!
> 4 votes

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