title: Using Git with a Drupal site

text:
# Question
Title: Using Git with a Drupal site
May we use git with a Drupal Site ?

Because I'm trying to use Git with a Drupal site and it seems that not all the information that are pushed !!!

Thank you

# Answer
> 3 votes
Git is a source code management (SCM) system. There are many different source code management systems out there and Git fall into the category of a distributed version control system (DVCS). It takes a "peer-to-peer" approach to version control as opposed to a "Client-Server" approach like version control systems like Subversion (SVN).

Yes we can use GIT with drupal.

To setup a GIT repository in drupal project please visit below link.

Git Setup

# Answer
> 3 votes
Yes. It is typical practice to manage Drupal with a VCS, with Git being the defacto option; Drupal core, as well as all projects on drupal.org, uses Git as its VCS.

Drupal includes some default git configurations. D7 has a default .gitignore config. D8 has an example.gitignore config which isn't applied by default. There is also a default .gitattributes for white space settings.

You'll have to troubleshoot what is/is not include in your codebase. Typically, the gitignore settings exclude content & settings data from the code repo.

---
Tags: version-control
---


# Question
Title: How do I update a field to use a different field_type?
I have created custom field\_type for a field in my content type. The field 'field\_content\_category' already exists and is an entity\_reference. Changing the yml file and importing doesnt work because there is already data for the field.

My custom field\_type is an entity reference and a field to type in an integer.

How do I change the field field\_type without creating a new field?

# Answer
To change the field type you would have to write an update\_hook:

Example:

```
function entity_test_update_8001() {
  // To update the field schema we need to have no field data in the storage,
  // thus we retrieve it, delete it from storage, and write it back to the
  // storage after updating the schema.
  $database = \Drupal::database();

  // Retrieve existing field data.
  $user_ids = $database->select('entity_test', 'et')
    ->fields('et', ['id', 'user_id'])
    ->execute()
    ->fetchAllKeyed();

  // Remove data from the storage.
  $database->update('entity_test')
    ->fields(['user_id' => NULL])
    ->execute();

  // Update definitions and schema.
  $manager = \Drupal::entityDefinitionUpdateManager();
  $storage_definition = $manager->getFieldStorageDefinition('user_id', 'entity_test');
  $storage_definition->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
  $manager->updateFieldStorageDefinition($storage_definition);

  // Restore entity data in the new schema.
  $insert_query = $database->insert('entity_test__user_id')
    ->fields(['bundle', 'deleted', 'entity_id', 'revision_id', 'langcode', 'delta', 'user_id_target_id']);
  foreach ($user_ids as $id => $user_id) {
    $insert_query->values(['entity_test', 0, $id, $id, 'en', 0, $user_id]);
  }
  $insert_query->execute();
}

```
> 1 votes

---
Tags: entities, 8, configuration
---


# Question
Title: Drush error — missing module Console_Table
I want to know how may I resolve this issue !!! I'm using Centos Machine and drush

```
  $ drush status
    Drush needs to download a library from                               [error]
    http://download.pear.php.net/package/Console_Table-1.1.3.tgz in order
    to function, and the attempt to download this file automatically
    failed because you do not have permission to write to the library
    directory /usr/local/share/drush/lib. To continue you will need to
    manually download the package from
    http://download.pear.php.net/package/Console_Table-1.1.3.tgz, extract
    it, and copy the directory into your /usr/local/share/drush/lib
    directory.

```

I've done what it is said in the request but it still give me the same error :

```
$ sudo wget http://download.pear.php.net/package/Console_Table-1.1.3.tgz
$ sudo tar -xzf Console_Table-1.1.3.tgz
$ sudo mv Console_Table-1.1.3/Table.php usr/local/share/drush/lib/table.inc

```

# Answer
> 2 votes
Drush 5 is no longer supported. Install Drush 8 using the standard installation instructions.

---
Tags: drush
---


title: How do I show the site slogan?

text:
# Question
Title: How do I show the site slogan?
I am trying to set up my first web site using Drupal 8 an Bootstrap. Unfortunately I wasn't able to show the site's slogan in Bootstrap theme. The slogan is set in `/admin/config/system/site-information` but is not shown. So I thought by my self, it may not be printed in page.html.twig and tried to include it there. It's preamble says:

```
 * Available variables:
 * Site identity:
 * - front_page: The URL of the front page. Use this instead of base_path when
 *   linking to the front page. This includes the language domain or prefix.
 * - logo: The url of the logo image, as defined in theme settings.
 * - site_name: The name of the site. This is empty when displaying the site
 *   name has been disabled in the theme settings.
 * - site_slogan: The slogan of the site. This is empty when displaying the site
 *   slogan has been disabled in theme settings.

```

So I tried to print the slogan by including

```
{{ site_slogan }}

```

But this does not have any effect at all.

Can somebody please tell me, how to print the site slogan in Bootstrap?

\[The lack of documentation and stable modules and themes should have been considered a release blocker for Drupal 8, but this is only my opinion and off topic here!\]

# Answer
> 16 votes
After some desperate digging I found the solution (come on Drupal guys, don't be shy, give us some documentation!): Go to `/admin/structure/block` and click the 'configure' button of the block named 'Site branding'. There you can choose which parts of site branding are shown.

# Answer
> 9 votes
This is how to get the site slogan to pring in your theme page template without using the branding block (bootstrap or not):

```
function THEME_preprocess_page(&$vars) {

    $site_config = \Drupal::config('system.site');

    $vars['site_name'] = $site_config->get('name');
    $vars['site_slogan'] = $site_config->get('slogan');

}

```

---
Tags: 8, bootstrap-theme
---


title: Change entity bundle on update?

text:
# Question
Title: Change entity bundle on update?
Is it safe to change the entity bundle (e.g. node type or commerce product type) when updating an entity with Migrate API?

Specific use case:

The site already contains plenty of commerce\_product entities with `$product->type === 'product'`, that were imported with something other than Migrate API.

I now want to re-import these entities with Migrate API, updating the existing entities. Custom MigrateMap to sync by field or property, e.g. SKU

The product type should be changed to something else by the update, let's say `$product->type === 'othertype'`.

Some of the fields are the same in both bundles. Other fields only exist in one of the bundles. Data from obsolete fields should be discarded / deleted. This includes images from an image field.

---

So, I wonder if all of this will happen painlessly, or if I need to do something special to make it work.

I will try this anyway and see what happens, but I think it is useful to have this documented here on stackexchange.

# Answer
That seems dangerous to me - a node's bundle is fundamental to its identity, and has repercussions well beyond the node's data itself. You're on Drupal 7, presumably? Simple way to test would be a script like:

```
$node = node_load(5);
$node->type = 'other_type';
node_save($node);

```

If it breaks there, it'll break with migration too. And if it works there, it should work with migration.
> 1 votes

---
Tags: 7, migrations
---


# Question
Title: In using the rule "OG new content notification," (rules_og_new_content) how can I insert the group name in the outgoing email
In using the rule OG new content notification (admin/config/workflow/rules/reaction/manage/rules\_og\_new\_content) for a site using Organic groups. However, I'd like add in the name (and URL) of the parent group. However, I'm not seeing these options in the tokens ("replacement values").

The Content Type in question has the field `og_group_ref` for which I'm trying to target.

## What I've tried so far (update):

On a dev instance, as per Pierre's recommendation below, I've added the following 'fetch entity' to the rule.

But the email comes in blank, without title on the subject line

# Answer
Add Action \>\> Get group members from group audience \>\> node

Add Loop \>\> node:og-group-ref

* Add Loop inside loop \>\> group-members \>\> rename list\_item to list\_item2

+ Add Action \>\> Fetch entity by property \>\> User \>\> Mail \>\> list-item2:mail
    + Add Action \>\> Fetch entity by property \>\> OG Memembership \>\> field\_name \>\> list-item:title \>\> rename entity\_fetched to entity\_fetched2
    + Add Action \>\> Send Mail \>\> list-item2:mail \>\> list-item:title

### End Result:

(click image to enlarge)
> 4 votes

# Answer
The accepted answer didn't work for me. This is the configuration I ended up using to get the group name in the email.
> 1 votes

# Answer
to insert the name of group in the mail, you need to use ***\[node:og-group-ref\]*** replacement token.
> 0 votes

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


title: Flexslider as field

text:
# Question
Title: Flexslider as field
I have the following requirement and i wanna know the best approach for it I have a content type that has a field of multiple images. Is there a way to make these images appear as a slideshow when that node is viewed?

# Answer
It looks like you're looking for Field Slideshow.

This project provides a Slideshow formatter for Image fields, using JQuery Cycle plugin.

It builds the slideshow from a single node, with a multi-valued Image/Media/Field Collection field.
> 0 votes

# Answer
For that use the Views Galleriffic and the documentation is click here and a simple tutorial is here
> 1 votes

# Answer
You can use Flexslider or any other view filters as field by installing the EVA (https://www.drupal.org/project/eva) module in Drupal. The EVA (Entity Views Attach) will create a pseudo-field that you can attach to any entity and use it as if it was a field.
> 0 votes

---
Tags: entities, javascript
---


title: Remove classes in hook_preprocess_block

text:
# Question
Title: Remove classes in hook_preprocess_block
In Drupal 8 I'm struggling to *remove* classes from a given block. Here's a quick snippet from a preprocess function:

```
function mytheme_preprocess_block(&$vars) {
  $block_classes = array(
    'block_id' => array('custom-class'),
  );
  $id = $vars['elements']['#id'];
  if (isset($block_classes[$id])) {
    $vars['attributes']['class'] = $block_classes[$id];
  }
  return $vars;
}

```

Interestingly this works, and adds `custom-class` to the block, but even though it is overriding the existing class array, all the default Drupal classes are still added (later on maybe?). I know that I can remove classes in twig with `{{ attributes.removeClass('class-to-remove') }}`, but ideally I would like to have a preprocess function that doesn't require exposing more template files.

# Answer
> 2 votes
You can't do that. You can see node and file template. Unless, in your theme you set

```
base theme: stable

```

or when you don't define a base theme.

---
Tags: 8, theming
---


# Question
Title: Populate a Chosen select list from a view
We have a request from a client to create an interface where they select nodes in a Chosen box. We have the Chosen module on the site and have successfully implemented features with it.

In this case, they want to have an admin interface where they choose which nodes populate a javascript image slider. I thought to simply make them a custom view where they can check a checkbox field to indicate whether to include the node or not. However, because they want the Chosen functionality, I need to populate a select box with the values from a view.

How can I create a select box that's populated by values from a view I've already defined? I've done some searching and found the Entity Reference View Widget module, but that doesn't seem to do what I am looking for.

**Edit** I'm not so concerned about the Chosen functionality, I can handle that. What I really want to know is how to get the values from a view to populate a select box, either with a widget, or defining a select box in an form array.

# Answer
> 1 votes
You can programmatically invoke a view to retrieve data and process it as needed:

```
  // Example select form array
  $form['my_selectbox'] = array(
    '#title' => t('My Select Label'),
    '#type' => 'select',
    '#description' => t('My select label.'),
    '#options' => array(),
  );

  $view = views_get_view("my_view_machine_name");

  //use "default" for default display
  $view->set_display("my_view_display_machine_name");

  // @TODO: Alter any other view properties
  // (e.g. exposed_input, offset, etc.) as needed

  // Pre execute & execute view query
  $view->pre_execute();
  $view->execute();

  // $view->result contains an array of row objects inside the view.
  // the properties will vary based on your view
  foreach ($view->result as $row) {
    $form['my_selectbox']['#options'][$row->nid] = $row->node_title;
  }

```

---
Tags: views
---


# Question
Title: How to add number of records per page filter in views
I want to add a filter to customize the number of records to be show on per page in views.

Can anyone assist me on this?

# Answer
> 1 votes
I found the answer.

You can add items per page filter from pager option views

Views-\>pager options-\>EXPOSED OPTIONS

---
Tags: 7, views
---


title: Get Node Author's Name in Custom Block

text:
# Question
Title: Get Node Author's Name in Custom Block
In the admin area, to create a custom block, I go to:

```
Structure, Block layout, + Add custom block.

```

Once I create the custom block in the UI, I see a textarea field called "Body" where I can enter content.

How can I dynamically render the node author's name and profile picture in my custom block. I know I can type it in, but I would like to be able to insert some code (PHP, Twig or token) so that it pull's the author's name and profile image dynamically and prints it on the block. I do not want to use a views block, but a custom block instead.

# Answer
One way to go about this is block preprocess function to retrieve the block's current node context & insert the relevant variables to be used by your Twig template. For example:

```
/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function MYTHEME_preprocess_block(&$variables) {
  $node = \Drupal::request()->attributes->get('node');
  if (!is_null($node)) {
    $uid = $node->getOwnerId();
    $user = \Drupal\user\Entity\User::load($uid);
    if (!is_null($user)) {
      $username = $user->getDisplayName();
      $variables['$username'] = $username;
      // {{ username }} will be available within block.html.twig.
    }
  }
}

```
> 7 votes

# Answer
It's never being a good practice to add php code in block. You can use the below mention code to print a user image on nodes.

```
<?php
   $nid =  arg(1);
   if($nid){
     $node = node_load($nid);
     $user = user_load($node->uid);
     print $user->name;
     print theme('user_picture', array('account' =>$user));
   }
?>

```
> 0 votes

---
Tags: nodes, 8, blocks
---


# Question
Title: hook_form_alter() "og_group_ref" editable field's #options?
I've hit a problem using one **og\_group\_ref** field over multiple content types. I need to have the field **editable for one content type in a view** and provide the **select list options from another view**.

At the moment, I have the editable field in the view showing all nodes for all content types as options which isn't acceptable. A new field isn't an option.

Editable Fields
Content type: course\_students
Field: og\_group\_ref
View: resources \> panel\_pane\_2
View providing nodes: abc \> def

I've been away from Drupal for a couple of months and am completely lost so any help with a custom module to give this functionality would be greatly appreciated.

The below image shows the current problem where two content types are in the drop down list. This list instead needs to have nodes provided by a view.

# Answer
It's not a form alter but it's an easy solution using rules.. I added a second entity reference field that only listed the nodes I wanted. Then I used two rules to make sure the two fields always match, whichever is updated.

This is one of the rules for when og\_group\_ref changes. The other one is the same except for when the second entity reference field changes.

Why am I posting this as a solution when it's different to the question? Because it's very quick, most people use rules and it's applicable in many situations.
> 0 votes

---
Tags: views, forms
---


# Question
Title: How can I let users create new drafts for *existing* content?
We have two roles of user: **Admins** and **Content Creators** (basically Authenticated with a few more permissions to create content). We'd like to have Content Creators be able to create new drafts from existing content and let the Admins approve to publish.

While this approach sounds straight forward, I've hit a number of road blocks and have tried multiple approaches:

* Workbench Moderation: I've failed to install this to any working degree. Each time an admin approves a piece of content it's permanently unpublished. I describe the issue better here. If an Admin tries to publish their own content it falls into an endless cycle where WB sees the item as published but Drupal reports otherwise. Others seem to have similar problems.
* Draft: Looked promising but there is no D7 release
* Save Draft: Works nicely on *new content*, but doesn't offer to create a *new draft of an existing item*.

Other things we consider:

* Workflow: I'm hopeful but there is a lot of configuration to set up for such a seemingly simple work flow. Also it appears a bit overwhelming. I hoped Workbench to be a simplified version of this.

We see that this feature is built into D8. Infact, this very ticket explains what we're trying to do:

> Ideally, I should be able to assign an arbitrary state to any revision. I could have a published revision, a revision pending approval, and a draft revision beyond that.

Is there a way to make this happen in Drupal 7?

# Answer
> 2 votes
# Option 1: Revisioning

A possible alternative could be the Revisioning module. Some more details (from its project page):

> ... a module for the configuration of workflows to create, moderate and publish content revisions.
>
> For the majority of use-cases configuration is straight-forward. The tricky bit are the permissions. To get you up and running quickly (D6 or D7), follow the steps described here: Revisioning at its simplest.

Here's a screenprint about it (from its project page):

# Option 2: Combining some popular modules

Use a combination of these modules (and regular content types):

Below are some details to implement your workflow with a similar approach:

* A content creator creates a node of content type (say) "Request".
* Use Content Access to finetune all sorts of permissions about "which role is allowed to create such types, if you have multiple types of requests you just extend to multiple content types.
* Use Rules to "send an eMail" (= action) to Admin "After content of type 'Request' gets saved" (= event). In the (custom) eMail for the Admin, include all relevant details about the Request (depending on the various data that are available to Rules). Such as an URL of the node to be reviewed.
* To ensure the content creator cannot change the Request data (while the review process is outstanding), add an extra action to the same (previous) rule which updates the access to the Request (to make it read only for content creator).
* Use the Flag module to enable the Admin to mark the submitted node with flags such as 'Approved (by Admin)' or 'Denied (by Admin)' (Rejected?). The permission to set these flags is limited to the Admin.
* After the submitted node is approved, use Rules to perform the actions required to consider the node (request) as the new version that replaces the prior version (which you could unpublish and/or delete). If the request includes an entity reference to the version it will be replacing, you could also have Rules take care of replacing the prior version automagically.
* If needed, use Rules to "send an eMail" (= action) to content creator "After content of type 'Request' gets flagged" (= event). Variation: create an appropriate view so that each content creator has some sort of dashboard to monitor the approval process.
* Add the Node Convert module also if you want to further refine the above with specific "fields" that some of the workflow participants should not "see" at all (to avoid you'd have to use "field permissions", which could be an alternative to that.

# Answer
> 5 votes
We use the Workflow module and have found it to be pretty stable, and we use it exactly as you have described, to allow a content person to edit content, then for an admin to approve it.

Configuring the workflow module is a bit complicated, but it is worth doing as it will provide you the functionality you need. Generally it has the following steps:

1. Install the workflow module.
2. Configure the workflows:
    * Create a new workflow.
    * Make some states.
    * Assign the workflow to a content type (the tutorial below calls it a node).
3. Set the permissions for each type of user to use each state of the workflow.

Creating a Workflow for Drupal Users contains a good tutorial.

---
Tags: 7, workflows, nodes
---


# Question
Title: How to email individual content to email field?
I have a content type that contains information about people, if these people want this information forwarded to them, I'd like to be able to capture an email in an email field and send the published content to them in an email.

I've been hunting around for a way to do this but can't find anything. Is there a way to do this?

# Answer
> 1 votes
If you're looking for existing module to base a solution on. The Print module has a **Send by email** submodule that supplies a form (**/printmail/node/NID**) that you can tweak for sending out emails and capturing the supplied emails.

```
/**
 * Implements hook_form_print_mail_form_alter().
 */
function MYMODULE_form_print_mail_form_alter(&$form, &$form_state, $form_id) {
  // Add a custom submission handler for your functionality.
  $form['#submit'][] = 'MYMODULE_form_print_mail_form_submit';
}

function MYMODULE_form_print_mail_form_submit($form, &$form_state) {
  // @TODO: process $form_state['values']['txt_to']['addrs'] for email addresses to store.
  // Use $form_state['values']['path'] to the load relevant node & save data to its fields.
}

```

# Answer
> 0 votes
Below is a sample of a rule (in Rules export format) that will send an eMail "After updating existing content" , and which is similar to what is asked in the question:

```
{ "rules_notify_author_of_selected_field_updates" : {
    "LABEL" : "Notify author of selected field updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-optionlist" ],
          "value" : [ "node:field-optionlist" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:current-user:mail]",
          "subject" : "Notification about a node with a special field value",
          "message" : "Go checkout the node with nid [node:nid] and title [node:title]: it has a field with a value (which is [node:field-optionlist]) you asked to be informed about ..."
        }
      }
    ]
  }
}

```

Some more details to further explain the above above sample:

* In my case I have a selection list field with machine name `field_optionlist`, and a few possible values.
* The Rules Condition checks if the "The selected value changed". You may want to adapt and/or extend this condition to something like "some eMail field is not blank".
* If the Rules Condition is true, then (as Rules Action), an eMail will be triggered to the editing user.

Change the field name of `field_optionlist` to match the field name of your content type, and adapt the actual eMail details (subject, etc) to fit your needs. Then import it in your own site (using the Rules UI). That's it.

PS: If you want to send such eMails to somebody who is not logged in, just change the "to" value to the eMail ID specified in your eMail field in the node. However (**red flag!**): I would not recommend you to allow this feature for anonymous users. Because spammers would love it: they would only have to edit such nodes, and then type any eMail Id they want to the content of your node to be spammed about ... not a good idea, right?

---
Tags: 7, emails, notifications
---


title: Prevent SQL injection

text:
# Question
Title: Prevent SQL injection
One of the security principles is sanitize string and variables passed from client to server; SQL injection is one of the way to hack a website. in plain PHP there are some functions to prevent SQL injection:

What is Drupal 8 strategy to prevent SQL injection? How can I clean up client data post in my Controller to protect my site from SQL injection?

# Answer
Drupal 8 (like Drupal 7) uses PDO to communicate with databases.

With PDO, the DB API makes use of prepared statements, specifically to avoid SQL injection attacks.

Practically, this means that you should use the database API methods. If you use the `select`, `update`, `delete` methods directly, you have a better chance of avoiding SQL injection as everything will be parameterised.

If you use `query`, you need to be more careful, as the API can only protect you so much. For example, if you do this:

```
$sql = "SELECT uid FROM users WHERE name = '$_GET[name]'";
\Drupal::database->query($sql);

```

Then you deserve what you get :) You should always use this instead:

```
$sql = "SELECT uid FROM users WHERE name = :name";
\Drupal::database->query($sql, [':name' => $_GET['name']]);

```

Aside: In reality, you'll only see the 2 functions you mentioned being used in very old, practically obsolete code these days. The MySQL extension has been removed now, and `stripslashes` was traditionally used with magic quotes, which were deprecated in PHP 5.3. SQL injection is still very much a problem, but those 2 perhaps aren't the best to use for comparison in this day and age.
> 17 votes

---
Tags: 8, security
---


# Question
Title: Export Drupal Commerce Checkout Settings
I'm wondering if there's a way to export Drupal Commerce's checkout pane settings to code? I've tried commerce\_features but it doesn't appear to do it.

For other commerce related things, like payment rules, I've been able to export them using features and using hook\_default\_default\_rules\_configuration\_alter to make sure only the proper rules are in place.

However for checkout I've not been able to find anything.

# Answer
The checkout configuration is all managed via standard Drupal variables, so the Strongarm module with Features is all you should need. All variables in our modules will be prefixed with commerce\_\* and typically with the module name (e.g. commerce\_checkout\_\*).
> 3 votes

# Answer
Have you tried the Commerce Migrate module?

> Commerce Migrate is a general-purpose migration framework extending Migrate Module for bringing store information into Drupal Commerce.
>
> * Migrate destination field handlers for commerce fields (reference fields, price field)
> * Migrate destination plugin for commerce product types.
> 0 votes

# Answer
Commerce features has now support for this since a few months... https://www.drupal.org/project/commerce\_features

See the related issue at: https://www.drupal.org/node/1973602
> 0 votes

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


# Question
Title: Is it possible to trigger a webform submit via url?
I have set up a webform for simple user polling with an yes/no option, with a submit button.

```
  [ ] Yes
  [ ] No

  Submit

```

and the parameter is pass via URL as default, e.g.:

```
 http://example.com/event_form?option=y

```

Currently, the webform link is sent via email. So users click the link, open a browser, select an option or use the default, press submit, and see the confirmation message.

Is it possible to automate the submit click? Such that the submit button is automatically clicked after clicking on the link in email?

# Answer
Inject some javascript into the body using PHP can make auto submit to work by a param in URL:

```
 http://example.com/event_form?autosubmit=yes&option=y

```

For example, the webform node ID is 101:

```
<?php if ($_REQUEST['autosubmit']) { ?>

    <script>
    (function ($) {
        $(document).ready(function(){
            $('form#webform-client-form-101').submit();
        });
    })(jQuery);
    </script>

<? } ?>

```
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: What is the purpose of the "Links" field in the "Manage Display" UI?
In admin/structure/types/manage/my\_content\_type/display, you can hide/show the fields to display.
There is a *Links* field that you can also hide/show.

What is the purpose of this field? Nothing is changing in my output when I hide it.

# Answer
> 5 votes
The Links section is used normally in **Teaser** section/display to display links like add comment, read more, etc.

On **Node Full Display**, it is depending on configurations we do. Such as "**Add new comment**" link will only be visible when we disable "**Show reply form on the same page as comments**" check-box in comment field settings. You can also give a try to Flag Module or other contributed modules which adds links on Node display.

Please check screenshot below (Teaser Display):

The above screenshot is of default Teaser Display of node type *article*, which is being displayed on site home page. When we hide *Links* from teaser display, these links are no more visible in node teaser.

Following screenshot shows links working in Node Full Display: Depending on **configuration we do in comment field (check screenshot below)**, comment link will be visible on Full Display.

Comment link visible, when **checkbox is disabled**.

Comment link is not visible, when **checkbox is enabled**.

---
Tags: 8, entities
---


title: problem in passing Data ajaxly

text:
# Question
Title: problem in passing Data ajaxly
I want to do some tasks with ajax in drupal, in client side I passed data with

```
                jQuery.ajax({
                    url: '/rest/session/token',
                    method: 'GET',
                    success: function (token, status, xhr) {
                        var postData = {}
                        postData= {'name': 'user','pass': 'pass'};
                        jQuery.ajax({
                            url: "/mylogin",
                            method: "POST",
                            data: postData,
                            dataType: "json",
                            headers: {"Accept": "application/json", "X-CSRF-Token": token, "Content-Type": "application/json"},
                            success: function (data, status, xhr) {
                                console.log(data);
                            }
                        });
                    }
                });

```

and ccording How to get $\_POST parameters in my controller I try to catch posted data with

```
public function login(){
    //return new JsonResponse( \Drupal::request()->request->all()); // form param);
    return new JsonResponse( \Drupal::request()->request->get('name')); // form param);
}

```

I reutrn empty, ( JsonResponse work correctly, I test it with example data ).

what is the problem and why I can't get Posted data in my controller's method?

# Answer
> 4 votes
If you're POSTing a JSON string, it won't be available as key/value pairs in Symfony's request object.

You could parse it yourself:

```
$json_string = \Drupal::request()->getContent();
$decoded = \Drupal\Component\Serialization\Json::decode($json_string);
$name = $decoded['name'];

```

---
Tags: 8, ajax
---


# Question
Title: Displaying the data export/feed icon only when there are search results
I've got a data export attached to my view. Although it works what I want it to do... it displays under the search form even when there are no search results... How do I get around this?

# Answer
You can override the template for the views.

There is a variable called `$empty` this field contains the text to be displayed if the node is empty. You can use this to check if view is empty or not.

If you have placed the attachment before the node then you would edit the below section.

```
<?php if ($attachment_before): ?>
    <div class="attachment attachment-before">
      <?php print $attachment_before; ?>
    </div>
  <?php endif; ?>

```

You can change this to

```
<?php if ($attachment_before && !$empty): ?>
    <div class="attachment attachment-before">
      <?php print $attachment_before; ?>
    </div>
  <?php endif; ?>

```

This would make sure that the attachment is printed only if the view has a result.
> 1 votes

# Answer
Without templating/theming, just using Views UI and having little skills on HTML, you can do next:

1. Open your page "my view". There you'll see export icon.
2. Copy source code of export icon, it should be like next: `<a href="url_of_export"><img src="icon_url" /></a>`. In firefox/chrome just right click on icon, and click View source, copy it.
3. Goto "my view" views editing.
4. Remove attachment from "Export" display to main view.
5. In main view display, add Footer and paste your html code from above. "Show even no results" should be unchecked.
> 1 votes

# Answer
```
function custom_views_pre_render(&$view) {
    if($view->name == 'xxx')  {
        if($view->total_rows < 1) {
            unset($view->feed_icon);
        }
    }
}

```
> 0 votes

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


# Question
Title: How to translate a word in <a title (tpl)?
How to translate the word Menu ? `t('Menu')` (after class="tb-main-menu-button ...) doesn't work in this case.

```
<?php
if($menu_bar = render($page['menu_bar'])): ?>
<!-- MAIN NAV -->
<div id="menu-bar-wrapper" class="wrapper">
<div class="container <?php print $grid; ?>">
<div class="grid-inner clearfix">
<a title="Navigation Icon" href="javascript:void(0);" class="tb-main-menu-button responsive-menu-button">Menu</a>
<?php print $menu_bar; ?>

```

# Answer
> 1 votes
Try: `<?php print t('Menu') ?>`

Like so:

```
<a title="Navigation Icon" href="javascript:void(0);" class="tb-main-menu-button responsive-menu-button"><?php print t('Menu') ?></a>

```

This will make the string translatable in the admin interface.

---
Tags: i18n-l10n
---


title: Theming a webform file upload widget

text:
# Question
Title: Theming a webform file upload widget
I'm trying to replace the upload and remove buttons in a webform file upload widget with visual icons.

I'm having trouble for a number of reasons but the most confusing is this:

I don't see where in the markup the "Browse..." and "no file selected" text is coming from? I've tried altering the `$variables['element']['upload_button']['value']` in `hook_preprocess_webform_element` and I didn't see any change in the value of the button or description.

If I remove `type="file"` and change the type to text, the "no file selected" note disappears too.

I have no idea what's going on.

For reference here's what I'm going for (left is after file upload, right is before file upload):

I'm using Drupal 7, Webform with Civicrm, and AutoUpload.

# Answer
> 1 votes
It is more likely a Javascript / jQuery related questions rather then Drupal.

The button label and text is defined by the browser which you cannot tweak in Drupal. But with Javascript / jQuery, you can override and take over event for creating your own file upload button.

Since jQuery is included in Drupal, a jQuery library should be suitable for you. jQuery File Upload is one of the best library for this purpose.

I found there are 2 contrib modules. They are jQuery File Upload and jQuery Upload FAPI.

---
Tags: theming, forms, webforms, files
---


# Question
Title: Can you retrieve the Omega breakpoint settings?
As the title suggests, is it possible to retrieve the Omega breakpoints you set in the settings for your subtheme via any kind of function or call? Like the ones from the picture.

# Answer
For anyone interested in the answer to this, it's retrievable but if you want to use it for adding your own stylesheets in at the same breakpoints (like I did) you have to do it in the template.php file

This is what I did

```
$theme = alpha_get_theme();
$layouts = $theme->grids['alpha_default']['layouts'];
$keys = array_keys($layouts);
for ($i = 0; $i < 3; $i++) {
    return $layouts[$keys[$i]]['media'];
}

```

This will return (or print, whatever you want it to do) the media-queries/breakpoints to use for your own sake.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to use $variables from theme setting in main menu
I make some field in theme setting and can use them normali in block, page, but when I want to use them in main menu its dont work.

```
function saka_theme_preprocess_menu__main (&$variables, $hook) {

    $variables['social_url_fb'] = theme_get_setting('social_url_fb','saka_theme');

}

```

and in menu--main.html.twig I write this..

```
{% for item in items %}
                <li {{ item.attributes }} >
                    <a  href="{{ item.url }}"  {{ item.attributes }} > {{ item.title }}</a>
                </li>
                <li>
                    <a href="{{ social_url_fb }}" class="btn-social-menu"><i class="fa fa-2x fa-facebook"></i></a>
                </li>
        {% endfor %}

```

# Answer
> 2 votes
You can't use name suggestions with double underscore in preprocess function names.

You have to replace this with an if statement in code:

```
function saka_theme_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
    $variables['social_url_fb'] = theme_get_setting('social_url_fb','saka_theme');
  }
}

```

---
Tags: 8, theming
---


# Question
Title: Additional custom Omega breakpoint CSS files
I'm looking to add my own custom wide, normal and narrow CSS files additional to the ones Omega will already look for. I'm aware that by default it'll already search for

YOURSUBTHEME-alpha-default-wide.css

etc

But I was wondering is there anywhere/anything I can set that will allow me to ask it to look for another set of wide, normal and narrow CSS files?

eg: custom-alpha-default-wide.css

And have these automatically be included within the default breakpoint configuration?

I know that I could manually declare all the stylesheets in the .info file, and then copy the media queries into each applicable CSS sheet, however I'm interested to know if it can be done by default

# Answer
> 0 votes
I found out how to do it, you can do it like this in the template.php file of your theme

```
// Adds the Delta responsive stylesheets
$theme = alpha_get_theme();
$layouts = $theme->grids['alpha_default']['layouts'];
$keys = array_keys($layouts);
for ($i = 0; $i < 3; $i++) {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . '/css/CUSTOM-' . $keys[$i] . '.css', array('group' => CSS_THEME, 'weight' => (120 - $i), 'media' => $layouts[$keys[$i]]['media']));
}

```

This will now look for your own CSS files called

* /css/CUSTOM-narrow.css
* /css/CUSTOM-normal.css
* /css/CUSTOM-wide.css

And call them in the same way your other breakpoints are called, and if you're looking for the ability to add your own separate stylesheets separate to the normal ones, this'll do it.

---
Tags: 7, theming
---


# Question
Title: List the hooks that can be used in .install file?
I have found only few hooks that can be used in the .install file. They are:

* hook\_enable
* hook\_disable
* hook\_install
* hook\_uninstall
* hook\_requirements
* hook\_update\_N
* hook\_schema
* hook\_schema\_alter
* hook\_update\_last\_removed
* hook\_field\_schema

Please tell me if I have left any hooks.

# Answer
I think you are missing function

hook\_field\_schema

This hooks are mentioned in the "list" and "number" default module which is in "field" module.
> 2 votes

# Answer
There is no official list of the hook which can only be used in .install file. But I can give you a hint how to find some of them.

You can try to search `module_load_install` in Drupal project. Some of the hook function is called immediately after calling this function.

> This method can help to find out those hook functions which requires loading of the .install file. Not only for core, but also the functions provided by contrib modules .
> 0 votes

---
Tags: 7, hooks
---


title: Send Email with Different Accounts

text:
# Question
Title: Send Email with Different Accounts
I've been searching but didn't find much.

Is there any module or way to send emails with Drupal, but using different email accounts?

For example, I have a site which will have 3 different email accounts to send email. User A creates a node, the user will receive an email from the email account 1. User B takes an action, he or she will receive an email from the email account 2. Etc.

To sum up:

Is there any module to hold different email accounts in one drupal site and send email with them?

I've seen some modules to hold different email accounts for the users, but not for the site.

Thanks in advance.

# Answer
> 2 votes
Nice question you are right no module for that . but you can configure it by rules like
after saving node add action - sand e-mail userA on this add conditions according to your need like account type userA I think this is the possible way for that

# Answer
> 1 votes
You can use hook\_mail\_alter() for altering the from email address. You can check the message id accordingly and change the from address.

```
function MODULE_NAME_mail_alter(&$message) {
  if (isset($message['id']) && !empty($message['id'])) {
    if ($message['id'] == 'your condition') {
      $message['from'] = $message['headers']['From'] = 'your email address';
    }
  }
}

```

---
Tags: 7, emails
---


title: Place block region in node template

text:
# Question
Title: Place block region in node template
I am trying to place a block region inside a news content type but it is not rendering.

node--news.html.twig:

```
<article{{ attributes }} class="portal-article">

  <h1 class="article-title">{{node.label}}</h1>

  <p class="article-date">{{ date }}</p>

  <div class="article-main-content">
    {{ content }}
  </div>

  <div class="article-sidebar">
      {{ page.article_sidebar }}
  </div>

</article>

```

How can I get the block to render inside of a node?

# Answer
This is probably the solution, "Making region content available to node templates in Drupal 8": http://atendesigngroup.com/blog/making-region-content-available-node-templates-drupal-8

---

Replace “THEME” with your theme name below:

```
/**
* Implements hook_preprocess_node() for NODE document templates.
*/
function THEME_preprocess_node(&$variables) {
  // Allowed view modes
  $view_mode = $variables['view_mode']; // Retrieve view mode
  $allowed_view_modes = ['full']; // Array of allowed view modes (for performance so as to not execute on unneeded nodes)

  // If view mode is in allowed view modes list, pass to THEME_add_regions_to_node()
  if(in_array($view_mode, $allowed_view_modes)) {
    // Allowed regions (for performance so as to not execute for unneeded region)
    $allowed_regions = ['primary_content'];
    THEME_add_regions_to_node($allowed_regions, $variables);
  }
}

/**
* THEME_add_regions_to_node
*/

function THEME_add_regions_to_node($allowed_regions, &$variables) {
  // Retrieve active theme
  $theme = \Drupal::theme()->getActiveTheme()->getName();

  // Retrieve theme regions
  $available_regions = system_region_list($theme, 'REGIONS_ALL');

  // Validate allowed regions with available regions
  $regions = array_intersect(array_keys($available_regions), $allowed_regions);

  // For each region
  foreach ($regions as $key => $region) {

    // Load region blocks
    $blocks = entity_load_multiple_by_properties('block', array('theme' => $theme, 'region' => $region));

    // Sort ‘em
    uasort($blocks, 'Drupal\block\Entity\Block::sort');

    // Capture viewable blocks and their settings to $build
    $build = array();
    foreach ($blocks as $key => $block) {
      if ($block->access('view')) {
        $build[$key] = entity_view($block, 'block');
      }
    }

    // Add build to region
    $variables[$region] = $build;
  }
}

```

After clearing caches, I can now print content specified in Drupal’s block layout using my node template files. For example, if I’ve specified primary\_content in $allowed\_regions, then I can access it via node--node\_type.html.twig with:

```
{{ primary_content }}

```
> 9 votes

---
Tags: 8, blocks, theming
---


# Question
Title: Documentation or Tutorial on using Batch or Queue Services API Programmatically
I am working on importing content into my drupal 8 website from an external API that returns XML data. The calls to the API take a long time to process. When I make too many queries at once it takes that much longer and it causes my site to timeout.

I have been trying to find online some direction on how to use the Batch API Service or the Queue Service programmatically in D8 but haven't as of yet found any good tutorials or documentation on this. Anyone have any good suggestions on where I can look or direction on where to start to use batch or queue services in D8? I have found many tutorials for D7 but haven't been successful in getting those two work with my D8 code.

Any suggestions would be greatly appreciated!

# Answer
I have made an example module to help understanding the Queue API and the Batch API. It also shows how to use them together.

I show you here the files and its contents. I have made a lots of comment, so i think, it is easy to understand.

**xml\_import\_example.info.yml**

```
type: module
name: XML import example
package: Examples
description: "This module helps understanding the Batch API and Queue API with an XML import example"
core: 8.x

```

**xml\_import\_example.permissions.yml**

```
import content from xml:
  title: 'Import content from xml'
  description: 'With this permission user can import contents from a XML source'
  restrict access: TRUE

```

**xml\_import\_example.routing.yml**

```
# Get contents from the xml source
xml_import_example.get_contents_from_xml:
  path: '/get-contents-from-xml'
  defaults: { _controller: '\Drupal\xml_import_example\Controller\ImportContentFromXML::getContentsFromXMLPage' }
  requirements:
    _permission: 'import content from xml'
# Process all queue items with batch
xml_import_example.process_all_queue_items_with_batch:
  path: '/process-all-queue-items'
  defaults: { _controller: '\Drupal\xml_import_example\Controller\ImportContentFromXML::processAllQueueItemsWithBatch' }
  requirements:
    _permission: 'import content from xml'

```

**src/Controller/ImportContentFromXML.php**

```
<?php
/**
 * @file
 * Contains \Drupal\xml_import_example\Controller\ImportContentFromXML.
 */

namespace Drupal\xml_import_example\Controller;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Queue\QueueWorkerManager;
use Drupal\Core\Queue\QueueFactory;

/**
 * You can use this constant to set how many queued items
 * you want to be processed in one batch operation
 */
define("IMPORT_XML_BATCH_SIZE", 1);

class ImportContentFromXML extends ControllerBase {

  /**
   * We add QueueFactory and QueueWorkerManager services with the Dependency Injection solution
   */

  /**
   * @var QueueFactory
   */
  protected $queueFactory;

  /**
   * @var QueueWorkerManager
   */
  protected $queueManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(QueueFactory $queue_factory, QueueWorkerManager $queue_manager) {
    $this->queue_factory = $queue_factory;
    $this->queue_manager = $queue_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $queue_factory = $container->get('queue');
    $queue_manager = $container->get('plugin.manager.queue_worker');

    return new static($queue_factory, $queue_manager);
  }

  /**
   * Get XML from the API and convert it to
   */
  protected function getContentsFromXML() {
    // Here you should get the XML content and convert it to an array of content arrays for example
    // I use now an example array of contents:
    $contents = array();

    for ($i = 1; $i <= 20; $i++) {
      $contents[] = array(
        'title' => 'Test title ' . $i,
        'body' => 'Test body ' . $i,
      );
    }

    // Return with the contents
    return $contents;
  }

  /**
   * Page where the xml source is preprocessed
   */
  public function getContentsFromXMLPage() {
    // Get contents array
    $contents = $this->getContentsFromXML();

    foreach ($contents as $content) {
      // Get the queue implementation for import_content_from_xml queue
      $queue = $this->queue_factory->get('import_content_from_xml');

      // Create new queue item
      $item = new \stdClass();
      $item->data = $content;
      $queue->createItem($item);
    }

    return array(
      '#type' => 'markup',
      '#markup' => $this->t('@count queue items are created.', array('@count' => count($contents))),
    );
  }

  /**
   * Process all queue items with batch
   */
  public function processAllQueueItemsWithBatch() {

    // Create batch which collects all the specified queue items and process them one after another
    $batch = array(
      'title' => $this->t("Process all XML Import queues with batch"),
      'operations' => array(),
      'finished' => 'Drupal\xml_import_example\Controller\ImportContentFromXML::batchFinished',
    );

    // Get the queue implementation for import_content_from_xml queue
    $queue_factory = \Drupal::service('queue');
    $queue = $queue_factory->get('import_content_from_xml');

    // Count number of the items in this queue, and create enough batch operations
    for($i = 0; $i < ceil($queue->numberOfItems() / IMPORT_XML_BATCH_SIZE); $i++) {
      // Create batch operations
      $batch['operations'][] = array('Drupal\xml_import_example\Controller\ImportContentFromXML::batchProcess', array());
    }

    // Adds the batch sets
    batch_set($batch);
    // Process the batch and after redirect to the frontpage
    return batch_process('<front>');
  }

  /**
   * Common batch processing callback for all operations.
   */
  public static function batchProcess(&$context) {

    // We can't use here the Dependency Injection solution
    // so we load the necessary services in the other way
    $queue_factory = \Drupal::service('queue');
    $queue_manager = \Drupal::service('plugin.manager.queue_worker');

    // Get the queue implementation for import_content_from_xml queue
    $queue = $queue_factory->get('import_content_from_xml');
    // Get the queue worker
    $queue_worker = $queue_manager->createInstance('import_content_from_xml');

    // Get the number of items
    $number_of_queue = ($queue->numberOfItems() < IMPORT_XML_BATCH_SIZE) ? $queue->numberOfItems() : IMPORT_XML_BATCH_SIZE;

    // Repeat $number_of_queue times
    for ($i = 0; $i < $number_of_queue; $i++) {
      // Get a queued item
      if ($item = $queue->claimItem()) {
        try {
          // Process it
          $queue_worker->processItem($item->data);
          // If everything was correct, delete the processed item from the queue
          $queue->deleteItem($item);
        }
        catch (SuspendQueueException $e) {
          // If there was an Exception trown because of an error
          // Releases the item that the worker could not process.
          // Another worker can come and process it
          $queue->releaseItem($item);
          break;
        }
      }
    }
  }

  /**
   * Batch finished callback.
   */
  public static function batchFinished($success, $results, $operations) {
    if ($success) {
     drupal_set_message(t("The contents are successfully imported from the XML source."));
    }
    else {
      $error_operation = reset($operations);
      drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE))));
    }
  }
}

```

**src/Plugin/QueueWorker/ImportContentFromXMLQueueBase.php**

```
<?php

/**
 * @file
 * Contains Drupal\xml_import_example\Plugin\QueueWorker\ImportContentFromXMLQueueBase
 */

namespace Drupal\xml_import_example\Plugin\QueueWorker;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\Core\Queue\SuspendQueueException;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\node\Entity\Node;

/**
 * Provides base functionality for the Import Content From XML Queue Workers.
 */
abstract class ImportContentFromXMLQueueBase extends QueueWorkerBase implements ContainerFactoryPluginInterface {

  // Here we don't use the Dependency Injection,
  // but the create method and __construct method are necessary to implement

  /**
   * {@inheritdoc}
   */
  public function __construct() {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static();
  }

  /**
   * {@inheritdoc}
   */
  public function processItem($item) {
    // Get the content array
    $content = $item->data;
    // Create node from the array
    $this->createContent($content);
  }

  /**
   * Create content
   *
   * @return int
   */
  protected function createContent($content) {
    // Create node object from the $content array
    $node = Node::create(array(
      'type'  => 'page',
      'title' => $content['title'],
      'body'  => array(
        'value'  => $content['body'],
        'format' => 'basic_html',
      ),
    ));
    $node->save();
  }
}

```

**src/Plugin/QueueWorker/ImportContentFromXMLQueue.php**

```
<?php

namespace Drupal\xml_import_example\Plugin\QueueWorker;

/**
 * Create node object from the imported XML content
 *
 * @QueueWorker(
 *   id = "import_content_from_xml",
 *   title = @Translation("Import Content From XML"),
 *   cron = {"time" = 60}
 * )
 */
class ImportContentFromXMLQueue extends ImportContentFromXMLQueueBase {}

```

So this is the working module, you can test it in you site.

If you visit the **/get-contents-from-xml** URL 20 queue items are made from a contents array.

The **src/Plugin/QueueWorker/ImportContentFromXMLQueue.php** contains this annotation: **cron = {"time" = 60}**

So if you run cron, the queue items are processed for maximum 60 seconds. You can increase or decrease this time, with that annotation.

If you remove the **cron = {"time" = 60}** line, cron do nothing with your queue items.

If you would like to process all the queue items in you browser, you have to visit the following url: **/process-all-queue-items**

It will collect all of your queue items, creates batch operations from them, and after that it process one after another.

I hope you and others with the same question understand the usage of the Queue API and Batch API with the help of this module.

Have a nice day!
> 27 votes

# Answer
Batch in Drupal 7 and 8 works pretty much the same way. If you found tutorials and tried it you should post the code you have and then you will get more specific help.

Did you try the official API documentation: https://api.drupal.org/api/drupal?

It has links to the batch and Queue API's on the frontpage.

https://api.drupal.org/api/drupal/core%21includes%21form.inc/group/batch/8.2.x and https://api.drupal.org/api/drupal/core%21core.api.php/group/queue/8.2.x.

Batch is pretty complete, the main decision is between multiple operations (if you know which operations you need to make, e.g. by having a count from your external system) or use the $context variable to keep doing it until you no longer get any results.

Queue documentation is a bit short, without examples, but the basic idea is that you set enqueue tasks and those get processed during cron runs. By default, that's rather limited as it will only be called when cron is called, which usually only happens every few hours (since you don't want to call some cron hooks too often). Modules like Ultimate Cron help with that, as they allow you to configure how often each cron hook is called and then you can call it every minute if you wish and have it work on the queue if there is something.

A simple example for queue is aggregator\_cron() which enqueues feeds that need to be checked and the corresponding queue plugin AggregatorRefresh.

As you can see in those examples, Drupal Core is often a good or even the best resource for examples, as they are guaranteed to be up to date and working.
> 6 votes

# Answer
Ok so main problem you are facing is timeout , that is why you were not been able to complete your task. Similar problem happens in drupal upgrade, if you try to use webpage to update site.

A solution to that is Command Line Interface. So since you are using Drupal8, there is a symfony component avilable called "Console"

> Location : \vendor\symfony\console

Now if you look at this url: Symfony Console you will figure out how to use that.Even namespace are same!! Create a module based on it and use it. Let me know if that helps.
> 0 votes

---
Tags: 8, batch-operations
---


# Question
Title: How to automatically update field values for all translated nodes
I have original node which is in english. Then I have another node which is a translation of the original node. Both of these nodes have the same image field. When I update the value - change the image for the original node and save it, the change doesn't apply to the second node (the translation of the original node). How do I make the field changes sync across the translated nodes?

Thanks.

# Answer
> 0 votes
There is a *Synchronize Translations* module which is part of the Internationalization Module and which allows you to synchronize one (or more) fields across translations.

Once you have the module installed and enabled you can navigate to the content type in question and in the *Synchronize Translations-tab* check all fields you want to synchronize.

Check the Documentation here: Synchronize translations.

---
Tags: 7, entities
---


# Question
Title: How to get Block Plugin Id? when block created using block type entity?
I have created the Block type entity using Drupal 8 UI. Now I have to Place that block entity programatically in theme region. The related question discussed. Here

As solution given by @Shawn Conn is fine when we define our own block plugin class. As in my case I don't. I created Block type using UI

# Answer
> 7 votes
You use the custom block uuid:

```
'plugin' => 'block_content:' . $custom_block->uuid(),

```

---
Tags: 8, blocks
---


# Question
Title: How to add destination parameter in hook url_inbound_alter
Hi I have used hook\_url\_inbound\_alter to alter the URL. When I access user/%/order anonymously it should redirect ti user/login. I have used below code

```
 function module_url_inbound_alter(&$path, $original_path,
 $path_language) {
  $argument = explode('/', $path);
  if (!user_is_logged_in() && isset($argument[0]) && $argument[0] == 'user' && isset($argument[2]) && $argument[2] == 'orders') {
      $path = 'user/login';

   }
}

```

It redirects the user to login page but my question is how to add destination parameter. Above code redirects `localhost/drupal/user/login` but I want to add destination paramater such as `localhost/drupal/user/login?destination=user/1/order`

When I tried to add the desination variable in `$path` variable

> $path = '/user/login?destination=user/1/order;

I am getting the url like this

> http://localhost/drupal/user/login%3Fdestination%3Duser/1/order

Instead it should be like this.

> http://dt.drop/user/login?destination=user/1/order

How can I achieve this.

# Answer
> 0 votes
For your particular problem (redirect an anonymous user to user/login), it can be better to redirect on form submit. So, on hook `form_submit()` you check whether `user_is_logged_in()`, if not `drupal_goto('user/login')`.

# Answer
> 0 votes
Try adding the destination parameter to $\_GET as such:

```
$path = 'user/login';
$_GET['destination'] = 'user/1/order';

```

The parameter will be picked by whatever interested parties as if it was a part of the original URL. Since the $path is already parsed it doesn't seem to allow to add the ?parameters. This is acceptably clean as all the code is one place, no need to alter the form elsewhere.

---
Tags: 7, uri
---


# Question
Title: Installed Boost Caching, but now my dynamic blocks and webforms are also cached
I just installed Boost module for Drupal 7, but now my Webforms and dynamic blocks like commerce shopping cart block isn't working. It's most likely cached, but what are some methods of getting these dynamic blocks to work? I already added exclude paths for `admin/*`, `user/*` and `checkout/*` so it doesn't cache those pages.

# Answer
As @duckx said, the problem was in the .htaccess file. Because he posted an image, I found it hard to compare it with my file. Here's the final .htaccess I'm using, that so far it works.

List of modifications:

1. I've added the GZIP lines as I found that in another post (in the Drupal forums)
2. Changed `RewriteRule .* - [S=2]` to `RewriteRule .* - [S=3]`. The `[S=N]` part specifies how many lines to skip. So if you remove the GZIP part, you might need to change that number.

On an unrelated topic, I'm also using the v2 of ReCaptcha (No-Captcha ReCaptcha) and it does *not* need the Boost Captcha module.

.htaccess file as I'm using it, doing Copy&Paste should work just fine:

```
    ### BOOST START ###

  # Allow for alt paths to be set via htaccess rules; allows for cached variants (future mobile support)
  RewriteRule .* - [E=boostpath:normal]

#  # Apache 2.4 bug workaround
#  # Enables Search from home page https://drupal.org/node/2078595#comment-8724321
#  RewriteCond %{REQUEST_METHOD} ^(POST)$
#  RewriteCond %{REQUEST_URI} /
#  RewriteRule .* / [S=3]

  # Caching for anonymous users
  # Skip boost IF not get request OR uri has wrong dir OR cookie is set OR request came from this server OR https request
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]
  RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]
  RewriteCond %{HTTPS} on [OR]
  RewriteCond %{HTTP_COOKIE} DRUPAL_UID [OR]
  RewriteCond %{ENV:REDIRECT_STATUS} 200
  RewriteRule .* - [S=3]

  # GZIP
  RewriteCond %{HTTP:Accept-encoding} !gzip
  RewriteRule .* - [S=1]
  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html\.gz -s
  RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html\.gz [L,T=text/html,E=no-gzip:1]

#  # Apache 2.4 bug workaround
#  # Enables caching of index/ home page
#  RewriteCond %{REQUEST_URI} ^/index\.php$
#  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}/\_%{QUERY_STRING}\.html -s
#  RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}/\_%{QUERY_STRING}\.html [L,T=text/html]

  # NORMAL
  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
  RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html]

  ### BOOST END ###

```
> 1 votes

# Answer
It seems you check `Cache blocks`(block caching) in `config/development/performance`. Try to uncheck that. When you work with Boosts it is not require use that feature.
> 1 votes

# Answer
It helps to look at the big picture of what Boost does to understand the problem; Boost is storing compressed rendered HTML pages and bypassing Drupal to serve them directly to anonymous users. It's a good server-centric solution for content delivery to a mostly anonymous userbase. What you're looking to do is identity when/where Drupal needs to take over to render dynamic content.

You could try some sort of progressively decoupled path. You can identity the blocks of content that need to be evergreen and try to work your site to load those dynamically on the frontend. It sounds like you new a few contrib module blocks to be dynamic. You might get by with AJAX Blocks configured on the contrib blocks, just note that they might not be compatible AJAX Blocks and you might have to figure out why and perhaps debug/implement your own solution.

Another path is to just quickly identify when Boost is no longer needed based on some user intent and disable it. For example, once gets redirected to the cart page or browses to a user login page, you should redirect the user to the secure version of your site; Boost can be configured to bypass the cache on a SSL request.

There's no one-size-fits-all solution; depending on your userbase, caching requirements, etc., one path might work better than another.
> 1 votes

# Answer
Forms not submitting was due to boost v1.1 generating the wrong .htaccess data. I reverted to 1.0 and then grabbed that code and used that instead. Then switched back to 1.1

http://prntscr.com/b8qnym -- comparision of the 1.1 and 1.0 .htaccess code generated.

I can also confirm that the 1.0 version's htaccess code works on 1.1

The 1.1 generates an incorrect .htaccess code which renders all forms nonfunctioning even in the admin screens.
> 1 votes

---
Tags: 7, performance, caching
---


title: Disable select option

text:
# Question
Title: Disable select option
I have a select list in my registration form here. The user can select 3 options to register for the event. For now the user has the ability to choose an early bird registration. After the periode they shouldn't be able to select that option. Is there a way to disable that option?

I have the following options:

1. EARLY BIRD REGISTRATION (now - Nov 1)
2. REGULAR REGISTRATION (Nov 1 - Mar 1)
3. LATE REGISTRATION Mar (1 - to conference)
4. SPEAKERS REGISTRATION ( now to Apr 2)
5. STUDENT REGISTRATION (breaks only)

After the 1nov I should be able to disable the early bird registration in the select list.

# Answer
> 3 votes
Disabling single options from select lists is currently not that easy in Drupal. There are some open issues regarding the topic and a couple of suggested patches, but so far neither made it into core:

---

That said, there is a tutorial on Exove which works around the issue, by implementing the `THEME_select()` hook to enable theming of individual select options using a `#options_attributes` key: Drupal 7 Form API select element option attributes

Using the code for your theme's `template.php` from the tutorial, you can disable options in your form using hook\_form\_FORM\_ID\_alter().

```
function hook_form_FORM_ID_alter() {
  $today = date("Y-m-d H:i:s");
  $date = "2016-11-01 00:00:00";

  if ($date > $today) {
    //replace 0 with the actual index for Early Bird
    $form['your_select_field']['#option_attributes'][0] = array('disabled' => 'true');

    //set the other fields based on dates here
  }
}

```

There is also a module which seems to offer the same functionality as the theme code from the tutorial, but I have not yet tested it: Form Options Attributes. It seems to work in a similar fashion however and might be even a little easier to set up (since you don't need to write that theme function).

---
Tags: forms
---


title: entity_form removes uid

text:
# Question
Title: entity_form removes uid
So i have defined a block

```
case 'foo_post':
    global $user;
    $values = array(
        'type' => 'foo',
        'uid' => $user->uid,
        'status' => 1,
        'comment' => 0,
        'promote' => 0
    );
    $entity = entity_create('node', $values);

    $ewrapper = entity_metadata_wrapper('node', $entity);
    $ewrapper->og_group_ref->set(menu_get_object()->nid);

    $block['subject'] = t('Create a new foo');
    $block['content'] = entity_form('node', $entity, 'add');
    $block['content']['#attributes']['class'][] = drupal_html_class('panel-body');
    $block['content']['title']['#access'] = FALSE;
    $block['content']['form_title'] = ['#markup' => sprintf('<h4>%s</h4>', $block['subject']), '#weight' => -1];
    $block['content']['form_advanced'] = [
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#type' => 'fieldset',
        '#title' => t('Advanced settings'),
        'additional_settings' => $block['content']['additional_settings'],
        'og_group_ref' => $block['content']['og_group_ref']
    ];
    unset($block['content']['og_group_ref']);
    unset($block['content']['additional_settings']);
    break;

```

Most of the things work already, except the form wouldn't take the user ID of the user submitting the form. What did I do wrong here?

# Answer
> 0 votes
The $user variable may not be set in this context - it is not automatically available as a local variable.

Try adding `global $user;` before the code.

---
Tags: 7, entities
---


# Question
Title: Changing '#view_mode' in content type's render array
I have a content type in Drupal 8 project that has image, name, info and body field as a default display, and image,name and information as a teaser display. I am able to display this content type with teaser view at the page, but right under that i would like to get the default display along with body field so i can create a bootstrap modal with that.

I am using hook\_node\_view in the module level to change the #view\_mode of that render array to 'full' instead of 'teaser'.

```
function team_bio_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

if($entity->bundle() == 'about_us'){
 if($view_mode == 'full'){
  if($display->getComponent('field_team_bio')){
    $build['full_view'] =  $build['field_team_bio'];
     $build['full_view'][] = array(
       'full_view' =>array(
         '0'=>array(
            '#view_mode'=>'full'
         ),
         '#weight'=>'103'
       )
    );
    kint($build);

  }
 }
}
}

```

i can display the content type right under teaser views, but i can't change the view\_mode to full. This is what i see when i kint($build):

Current contents have name like '0','1','2','3','4', and they have the view mode that are 'teaser' but i dont how to pass 'view\_mode' to 'full'in render array, I am not sure if there is specific name for that or not. Trying this:

```
     $build['full_view'][] = array(
       'full_view' =>array(
         '0'=>array(
            '#view_mode'=>'full'
         )

```

didnt change the view\_mode neither. So my question: What is the best way to change these view modes to full for the contents? Should I search these numeric keys in the array and pass them to another array then change view\_mode like that? Or is there an easier way to approach the problem?

# Answer
> 0 votes
```
function team_bio_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if($entity->bundle() == 'about_us'){
    if($view_mode == 'full'){
     if($display->getComponent('field_team_bio')){

       $team_bios_full = [
        '#theme' => ['team_bio_full_wrapper'],
        '#weight' => $build['field_team_bio']['#weight'] + 1,
       ];

    foreach(Element::children($build['field_team_bio']) as $delta){
      $team_bio_full = $build['field_team_bio'][$delta];
      $team_bio_full['#view_mode'] = 'default';

      $team_bios_full['#team_bios'][] = $team_bio_full;
    }

    $build['team_bios_full'] = $team_bios_full;
  }
 }
}
}

```

Then I passed team-bios-full-wrapper into class and render it.Like this:

```
{%
  set classes = [
  'team-bios-full-wrapper',
  ]
%}
<div{{ attributes.addClass(classes) }}>{{ team_bios }}</div>

```

Sorry i have different variables, i just rethought and rewrote the code. Hope this helps out someone.

---
Tags: 8, hooks
---


title: CRUD API from article

text:
# Question
Title: CRUD API from article
I would like to create 4 api calls (GET/POST/PUT/DELETE) for the basic node article. I'm a real noob in this. Can someone help me on my way? Where do I go for information?

# Answer
> 2 votes
You will need the Services module, together with the REST Server submodule.

The two will allow you to create a new "server" and configure which entities can be retrieved via REST, what the authentication should be and which exactly calls are allowed (get, post, delete, etc.).

---
Tags: 7, nodes
---


title: How do I style a navigation block menu?

text:
# Question
Title: How do I style a navigation block menu?
I am having a pretty base navigation menu in d8 .But compared to d6 its style is pretty basic . How can i have a decent navigation menu ?

**navigation menu in d8**

**navigation menu in d6**

How can i have a styled navigation menu in d8 ?? I blurred it because content not to be exposed ;) .

# Answer
You can style it by writing css that target the elements of the navigation menu. If you use the inspector in your browser you should be able to figure out what classes the menu is wrapped in so you can properly style it.

If you are using a custom theme you can start by adding a css file to a css folder. In this case I named mine style.css.

/path/to/custom/theme/css/style.css

```
.menu li{
    background: blue;
}

```

Then I came up with a name for my css library in mytheme.info.yml

```
name: MyTheme
description: My custom Theme
type: theme
core: 8.x
libraries:
  - mytheme/global-css

regions:
  header: 'Header'
  content: 'Main Content'
  footer: 'Footer'

```

Then I made sure that the library included our style.css file. In mytheme.libraries.yml I had

```
global-css:
  css:
      css/style.css: {}

```
> 2 votes

---
Tags: 8, navigation
---


# Question
Title: How to execute javascript within drupal for a specific field on a specific page?
**The Initil question** I have a input field which should activate a function on the onfocus javascript event on a field on the user page.

Step 1 Add code to a custom module:

```
(function ($) {
  $(document).ready(totalname(){
    document.getElementById("fullname").style.background = "yellow";
  });
})(jQuery);

```

The currently HTML is:

```
<input type="text" id="fullname"><br>

```

And it should become like this:

```
<input type="text" id="fullname" onfocus="totalname()"><br>

```

How to get the onfocus=... inside the input element? Is the custom code ok?

## **Addition to this question.**

Thxs you so much for all the comments. Based on that I learned i few things more so I now understand what the real question should be.

To understand how I can executed javascript code in a certain field on a certain page in drupal.

I assumed this was needed by a callback but this is not encoured according to @Jimmy so I'm trying to understand the way it should be according to drupal standards. Also I was suprised that no change in HTML was needed as @Adrian gave an example. I could not get it run because of the typo :-( So in mean time I made another solution.

The script is basicly just a real time concatination of first, middle and last name into a fullname field.

```
(function ($) {
  $(document).ready(function(){

        function setFullName() {
            var nameParts = [document.getElementById("edit-field-voornaam-und-0-value").value,
                             document.getElementById("edit-field-tussenvoegsel-und-0-value").value,
                             document.getElementById("edit-field-achternaam-und-0-value").value],
                name = nameParts.join(" ").trim();

            document.getElementById("edit-field-naam-und-0-value").value = name;
        }

        var fields = [document.getElementById('edit-field-voornaam-und-0-value'),
                      document.getElementById('edit-field-tussenvoegsel-und-0-value'),
                      document.getElementById('edit-field-achternaam-und-0-value')];

        for (var i = 0; i < fields.length; i++) {
            fields[i].addEventListener("keyup", setFullName);
        }

  });
})(jQuery);

```

So this is working and I put it in a custom module.

I still do not understand how I should be if I rewrite the code following the example of @adrian as this code is still executed on every page and not a specific page.

Thank you for learning !! and not using the correct words. I'm not native english ...

# Answer
Your jQuery:

```
//Making a focus over the element
(function ($) {
    $('#fullname').blur(function() {
        $(this).removeClass("color");
      })
      .focus(function() {
        $(this).addClass("color");
      });
})(jQuery);

```

Your HTML:

```
<input type="text" id="fullname"><br>

```

Your CSS:

```
.color {
  background-color : yellow;
}

```

**EDIT:** To attach the js code to your page you can use `#attached` in a renderable array (this is the recommended way). I think that you should read: How to add jQuery UI libraries to a page.
> 3 votes

---
Tags: javascript, forms
---


# Question
Title: Using Views API to create a status field based on other field values (Sortable and Filterable)
I need a status field to appear in a view with a table format that has values like "Needs Attention", "Awaiting Payment", "Not Interested", etc...

These values are based on values of other fields attached to the node such as a date field indicating the last time of interaction, payment received toggle, etc...

This field needs to be sortable and filterable for good reporting; so, I've started reading-up on the Views API to create custom Views Data, but I'm having trouble figuring-out where to attach the SQL expression that calculates the value. I've seen some tutorials that are close, but they talk more about getting your custom SQL table into views and using expressions on those, but not one working with existing node field values.

Does anyone know how and where to set this up, or has anyone found something on the web describing this?

# Answer
> 1 votes
I had started in the right direction this morning Thanks to this article: Drupal 7: Using SQL Expressions in Views 3

This afternoon, after some digging, I found that you can manually join the tables that you need to work with in the same handler as mentioned in the article, and this expression field can be added to the "views" index of the data variable, and it will still be added to the base query.

So in, mymodule.views.inc

```
function mymodule_views_data() {
    $data = array();

    $data['views']['student_status'] = array(
        'group' => 'Content',
        'title' => t('Student Status'),
        'help' => t('The current status of a student based on when they we last interacted with, paid, etc...'),
        'field' => array(
          'handler' => 'mymodule_views_handler_field_expression',
          'click sortable' => TRUE,
          'expression' => "
                CASE
                    WHEN
                        field_data_field_some_table.field_some_value = 1
                    THEN 'Registered'

                    WHEN
                         DATEDIFF(NOW(), field_data_field_last_interaction_date.field_last_interaction_date_value) > 30
                    THEN 'Needs Attention'

                    ELSE 'Unregistered'
                END
            ",
      'expression_alias' => 'student_status',
    ),
   'filter' => array(
     'handler' => 'mymodule_views_handler_filter',
     'allow empty' => TRUE,
   ),
    'argument' => array(
      'handler' => 'mymodule_views_handler_argument',
     'allow empty' => TRUE,
    ),
   'sort' => array(
     'handler' => 'views_handler_sort',
   ),
  );

 return $data;
}

```

And then in mymodule\_views\_handler\_field\_expression.inc

```
class mymodule_views_handler_field_expression extends views_handler_field {
  var $expression_alias = 'unknown';
  var $expression = NULL;
  /**
   * Construct a new field handler.
   */
  function construct() {
    parent::construct();
    if (!empty($this->definition['expression'])) {
      $this->expression = $this->definition['expression'];
    }
    if ( !empty($this->definition['expression_alias']) ) {
      $this->expression_alias = $this->definition['expression_alias'];
    }
  }

  /**
   * Called to add the expression as a field to a query.
   * Overrides and based on views_handler_field->query().
   */
  function query() {
    // Make sure the table is available, and get the alias.
    $table_alias = $this->ensure_my_table();

    // Boilerplate from views_handler_field->query().
    $params = $this->options['group_type'] != 'group' ? array('function' => $this->options['group_type']) : array();

    //HERE'S THE NEW STUFF
    $this->query->add_table('field_data_field_last_interaction_date');
    $this->query->add_table('field_data_field_some_table');

    // Insert the table alias into the expression and its alias, and use the add_field method of the underlying query object.
    // See add_field() in views_plugin_query_default.inc
    $this->field_alias = $this->query->add_field(NULL, $this->expression, $this->expression_alias, $params);

    // More boilerplate.
    $this->add_additional_fields();
 }

}

```

ALSO NOTE: In order to use this custom field in the Context Filter and Filter Criteria, I had to create custom argument and filter handlers to replace the WHERE statement with a HAVING statement, as well as, clean-up the alias that it uses.

Argument

```
class mymodule_views_handler_argument extends views_handler_argument {
     /**
   * Set up the query for this argument.
   *
   * The argument sent may be found at $this->argument.
   */
  function query($group_by = FALSE) {
    $this->ensure_my_table();
    $this->query->add_having('Content', $this->real_field, $this->argument);
  }
}

```

Filter

```
class mymodule_views_handler_filter extends views_handler_filter_string {

     /**
   * Add this filter to the query.
   *
   * Due to the nature of fapi, the value and the operator have an unintended
   * level of indirection. You will find them in $this->operator
   * and $this->value respectively.
   */
  function query() {
    $this->ensure_my_table();
    $field = $this->real_field;

    $info = $this->operators();
    if (!empty($info[$this->operator]['method'])) {
      $this->{$info[$this->operator]['method']}($field);
    }
  }

  function op_equal($field) {
    $this->query->add_having($this->options['group'], $field, $this->value, $this->operator());
  }

  function op_contains($field) {
    $this->query->add_having($this->options['group'], $field, '%' . db_like($this->value) . '%', 'LIKE');
  }
}

```

---
Tags: views
---


title: Deleted term shown in exposed filter

text:
# Question
Title: Deleted term shown in exposed filter
I'm using exposed simple hierarchal select module for a taxonomy in my exposed filter, i have deleted some terms from the taxonomy but the filter still showing the deleted terms.

I tried clearing caches and cron and even waited one day with no luck!

Any ideas what is the problem??

❤

# Answer
> 0 votes
disabling the 'JavaScript callback handler' module solved the problem.

# Answer
> 0 votes
I think it may be revisions or taxonomy revisions issue module documentation says This module enables revisions for the taxonomy terms.

The users will have an option to create new revision for a taxonomy term as for nodes. This means when a taxonomy term is edited in the default form, a new checkbox is displayed for revision creation. If clicked a textarea will appear to fill a revision log message.

Also on the taxonomy term edit page a new menu tab appears after the module installation which will list all of the taxonomy term's revisions and provides

---
Tags: 7, views
---


# Question
Title: Get body summary in field's replacement pattern
Is it possible to get the body's summary within a view field's replacement pattern?

What I am doing right now is this:

```
{{ field_icon }}

<div class="description">
    {{ title }}
    {{ body }}
</div>

```

As the body text is too long I tried using `{{ body.summary }}` instead of `{{ body }}` but that didn't work at all..

Could you tell me whether there is a possibility to do this inside of a replacement pattern?

Thank you!

# Answer
You need to select `Summary or trimmed` as your formatter, then `{{ body }}` will print out your summary.
> 2 votes

---
Tags: views, 8
---


# Question
Title: Trying to use drupal_http_request to get an admin page
I would like to render an admin page in a popup, I thought I'd use the ctools api to render the popup and drupal\_http\_request to get the data for the page, however even when logged in all I get is an 'unauthorized' error. Looking deeper, I think there might be a way, as the function is reputed to support basic authentication, but I can't figure out how to make it work. This is for Drupal 7.x Or if there's a different way to render an admin page in a popup that'd be nice too. It's for a client who doesn't want to go back and forth between admin pages so the popup would solve the problem.

# Answer
> 1 votes
The Overlay module in the core is built to do exactly this, to open admin pages in an overlay popup. You can enable it directly from `/admin/modules`.

---
Tags: 7
---


title: Will a patched up Zopim Chat work?

text:
# Question
Title: Will a patched up Zopim Chat work?
I want to use Zopim chat for Drupal 8, but there is no version for it. However, I see something is done about it on https://www.drupal.org/node/2624230.

Does it mean I can use it safely on Drupal 8? Is it OK to use patched up Drupal 7 third-party modules on Drupal 8?

# Answer
> 4 votes
> Does it mean I can use it safely on Drupal 8?

This is subject to the code written to port the module, and might be prone to some issues. The best way to find that out is by testing the patch and reporting back (on the same drupal.org thread) if you find it to be working or if you come across any issues.

> Is it ok to use patched up Drupal 7 contrib modules on Drupal 8?

Again, IMHO the best way is to work with collaboration here:

* If you are a developer, help contribute the code.
* If you are a tester, help with testing the solutions; and contributing to tests.
* If you are good a documentation, write about the solution.
* Many more ways to contribute... Check the "contributed projects" section from https://www.drupal.org/8/ready for good resources.

As per your main question:

> Will Zopim Chat work with Drupal 8?

It surely will, if those who require it help make it work!

---
Tags: 8
---


# Question
Title: Drupal prevents file save on chunked upload because of php.ini max upload size
I'm encountering a tricky problem with my custom file widget (which extends the core file widget). It chunks files so that I don't have to raise upload\_max\_filesize and post\_max\_size in php.ini, and puts them together. The problem is, even though the files now exist remotely (and have also been saved as file entities in Drupal) it refuses to save them into the field, because even though the file field's settings are set to 500 MB, php.ini's uploads are maxed at 20 MB.

The problem is in FileItem.php:

```
public function getUploadValidators() {
  $validators = array();
  $settings = $this->getSettings();

  // Cap the upload size according to the PHP limit.
  $max_filesize = Bytes::toInt(file_upload_max_size());
  if (!empty($settings['max_filesize'])) {
    $max_filesize = min($max_filesize, Bytes::toInt($settings['max_filesize']));
  }

  // There is always a file size limit due to the PHP server limit.
  $validators['file_validate_size'] = array($max_filesize);

  // Add the extension check if necessary.
  if (!empty($settings['file_extensions'])) {
    $validators['file_validate_extensions'] = array($settings['file_extensions']);
  }

  return $validators;
}

```

Which calls file\_validate\_size in file.module. I've already tried using ini\_set() to change the file size ini values, but that doesn't seem to work.

So, to recap:

Drupal has the file

My widget tells it to save the file by its fileID for the file field

Drupal tells me it won't save the file that it already has because of php file upload limits

---

Can anyone think of something I can do to get around this without modifying core?

# Answer
> 0 votes
Just a guess, but this may have something to do with `max_file_uploads` in php.ini. Perhaps chunking it counts as multiple files?

---
Tags: 8, files
---


# Question
Title: How do I get all the menu items below a certain parent?
I am currently working on a module that finds out the parent menu item by path, then displays the current tree structure of that related menu by finding the top parent and most important only displaying that menu item and submenus from within that menu.

```
path = "/system/menu/submenu";
parent = 'system';
output = parent + parent submenus. (other menu items excluded)

```

All menu items in "Custom menu":

```
- System
   - Menu wrapper
     - SubMenu 1A
     - SubMenu 2A
     - SubMenu 3A
- Main
  - SubMenu 1B
  - SubMenu 2B
  - SubChildMenu 3B

```

PHP code should return this:

```
- System
   - Menu wrapper
     - SubMenu 1A
     - SubMenu 2A
     - SubMenu 3A

```

My code (currently not working) is the following.

```
 $menu = 'custom_menu';
 $title = 'System';
 $tree = menu_tree_all_data($menu);
    foreach ($tree as $branch){
      if ($branch['link']['title'] == $title){
        $childtree = $branch['below'];
        break;
      }
    }
 return $childtree;

```

Notice: This needs to be PHP code only; all other modules don't support this only through manual selection.

People have asked this before but i've tried their solutions and no success.

Your help is very much appreciated.

https://stackoverflow.com/questions/5218861/restrict-menu-tree-to-first-level

https://stackoverflow.com/questions/2716787/how-to-get-all-the-menu-items-below-a-certain-parent-in-drupal

How do I display submenus separately from their menu tree?

# Answer
I am using this function in my code for D7 to do this exact thing. Your code looks like it should work, but it is slightly different than what I have. Honestly I haven't visited this part of my code in a while. Hope this helps.

```
/**
* Returns an array of all menu items under a parent.
* @param string $title Menu item title.
* @param string $menu Menu name.
* @return array
*/
function MODULE_submenu_tree_all_data($title, $menu = 'main-menu') {
  $tree = menu_tree_all_data($menu);
  foreach ($tree as $branch) {
    if ($branch['link']['title'] == $title) {
      return $branch['below'];
    }
  }
  return array();
}

```
> 1 votes

---
Tags: 7
---


# Question
Title: How can I disable theme update notifications?
How can I disable Drupal update notifications for certain themes?

I am using the Drupal Bootstrap 7.x-3.0 Theme which is not the latest version. That is why Drupal sends out a email Update notifications and shows a update warning. I don’t want to miss any module updates, thus I would like to keep update notification enabled. However I don’t want receive theme update message all time.I didn’t know that this is such difficult approach.

I was looking for a easy solution e.g. theme .info settings or on/off option in Drupals settings.php.

# Answer
The Update Status Advanced Settings enables you to disable any project, including themes, that you don't want to be alerted about updates for.

> Extends the administrative interface for Drupal core's "Update status" module (added to core in 6.x).
>
> Users of the 5.x Update status contrib module will probably want to use this once they upgrade to 6.x, since some of the functionality in the contrib version was deemed too complicated to include in core. In particular, the per-project settings to ignore certain projects or even specific releases, is absent in the core version of the module. The "Update status advanced settings" module restores these settings, and might eventually provide additional functionality for the core "Update status" module.
> 2 votes

---
Tags: 7
---


title: How to create a Question/Answer block?

text:
# Question
Title: How to create a Question/Answer block?
I want to create a question/answer block.

I guess I need to create a content type, turn comments on, and in page.tpl.php display nodes with comments. It should appear as in the image below.

What's the easiest way to get that block?

***Update***:

I decided to use 2 content types, one for question and another for answers, and link each other with node reference.

For example any registered user on the site can write a question, but only moderators can make answers on their questions. When moderator does node/add/answer he/she chooses with a select list to which node the answer would be linked.

Is this a right solution?

# Answer
> 1 votes
If you just want to create a node where a user writes a question to which the other users answer using comments, then you can use a content type that Drupal has by default. For example, with Drupal 7 the "Article" content type has already what you need; an article appears as in the following screenshot:

The only things that would need to be changed are the subject of the comment, that should not be entered, and the string "Add new comment" that should be changed in "Add new answer."
For the first, you need just to change the settings for the content type.

If you deselect the highlighted checkbox, the user will not be able to enter a title for the comment.
The other option to which you could be interested is the following one:

When it is selected, any comment for a comment is shown indented. As the comments for the node are the answers given to the question, any comment for the answer should be indented, or it would not be possible to understand when a comment is an answer, or a comment for an answer (or a comment to a comment given to an answer).

For changing the string from "Add a new comment" to "Add a new answer," you need a custom module that changes that string. For this reason, I would create a content type copying the setting used for the "Article" content type.

You don't need to alter the page.tpl.php file to show the comments together the node: That is what Drupal normally does. There is a module that allows to shows the comments in a different tab, but without that module, Drupal shows the comment in the same page where a node is shown. You will eventually need to change a template file to change the layout of the comments, though.

If you are using the word *block* to mean *Drupal block* (e.g. you want to show a block for asking a new question), then that is not possible without using third-party modules. I am not sure there is already a module for that.

# Answer
> 0 votes
This question dates from the D6 days. These days, for D7, "*there is a module for it*", which IMO does what you're looking for, and actually much more, as further detailed below: the Answers module. Here are some details about it (from its project page):

> Answers enables the implementation of a Question & Answer system in a Drupal site. Users can post questions and other users can answer them.

Head over to its project page for more details.

At its core, this module exists of 2 typical content types:

* Question.
* Answers.

The "Best Answer" submodule can be used so that the question author can "accept" one of the answers as the best one. And you could make the Rules module to either trigger all sorts of subsequent things to happen "when an answer gets marked as best answer", or to add all sorts of validations when posting an answer (or question).

The Answers module comes with integrations with other modules such as the Rules module and the Userpoints module and supports voting.

# Demo

Have a look at the (new) demo site of the Answers module. This link shows various menu options within the block with title ***Answers Menu***, i.e.:

* **Questions** (= a view):
    + **All**: of all existing questions (= default tab).
    + **Answered**: all questions which have a "best" (= accepted) answer (= sub-tab).
    + **Unanswered**: all questions which do not yet have a "best" (= accepted) answer (= sub-tab).
* **Answers** (= a view): lists all existing answers for any of the existing questions and which does not (yet) have any submenu options (implemented as tabs).
* **Rankings** (= a view): contains a list of users with their actual ranking (= reputation points implemented via user points), and with each user a link to either the questions or answers from that user.
* **Ask Question**: to post a new question (the equivalent of `node/add/question`), which is only shown for authenticated users though.

These views also use the dataTables format, but you could easily replace that with any views display format you'd want. And because of the search box that comes with dataTables, there is no need for extra menu links to search within questions, answers or rankings.

These new/enhanced views were created starting from the 7.x-4.x-rc2 release of Answers, and will be included in the next release of it also (together with various other enhancements not yet visibile in the demo site).

# Release recommendation

To decide between the **7.x-3.2** and the **7.x-4.0-rc2** release, I would recommend the 7.x-4.0-rc2 . Even though it is not yet an official release, it is fairly stable/functional, and only has a few more minor glitches to be resolved. Pretty soon an rc-3 (the last 'rc' release?) should become available also, which will include the newest features as you can see in the demo site already.

Disclosure: I'm a (co-)maintainer of this module.

---
Tags: blocks, nodes
---


# Question
Title: How do I use Path Matcher for front page?
I have used the following code in a Drupal 8 theme file.

```
$current_path = \Drupal::request()->getRequestUri();
$path_alias = Unicode::strtolower(\Drupal::service('path.alias_manager')->getAliasByPath($current_path));
$visiblity = \Drupal::service('path.matcher')->matchPath($path_alias, $pages);

```

`$pages` contains values like `'<front>'` or `'/blog'`.

`$visiblity` is set to `FALSE` for /, but to `TRUE` for /node; Both are the front page.

What is the wrong with my code?

# Answer
Your code is assuming that the request URI for / will retrieve /node on the `getAliasByPath()` method call. It won't. Setting the Drupal front page isn't the same as setting a path alias in the Path module.

Use the following code, which will return Drupal's internal /node path even on / requests.

```
$current_path = \Drupal::service('path.current')->getPath();

```
> 8 votes

---
Tags: 8
---