# Question
Title: Trying to create a static page for my module using page callback in hook_menu
I’m taking first steps in building a module for Drupal 7 and am trying to create a static page within hook\_menu function. In the $items array, for ‘page callback' I create an very simple function named ‘semi\_static\_page’. This simple function returns some html. the code is below.

```
$items['admin/config/media/tsoundcloud/config/soundcloud_static'] =             array(
    'title' => t('Semi Static Page'),
    'description' => 'Temp page to show data',
    'page callback' => 'semi_static_page',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
    );

function semi_static_page(){
  $output = 'this is some output, etc…….’;
  return $output;
}

```

But this page generate the following error.

**Fatal error: Unsupported operand types in /Users/tomcarden/Sites/sweetteas/includes/form.inc on line 1079**

How can this be resolved? Ultimately I want to load an .inc in the semi\_static\_page function.

thanks in advance!

# Answer
$output = 'this is some output, etc…….;

If you see in the above line, you are using wrong sign, which I have highlighted after ...... That is wrong. It should be `'`

Above isuue is for sure!!!!

---

Other just my suggestion, As I am also learning Hooks, may be TOTALLY WRONG but for your attention.

I have changed code as below and after that, I have written my point..

```
/**
 * Implements hook_menu()
 */
function mymodule_menu() {
  $items['admin/config/media/tsoundcloud/config/soundcloud_static'] = array(
    'title' => 'Semi Static Page',
    'description' => 'Temp page to show data',
    'page callback' => 'mymodule_semistaticpage',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
    );
    return $items;
 }

/**
 * Page callback
 */
function mymodule_semistaticpage(){
  $output = 'this is some output, etc…….';
  return $output;
}

```

The following points are for code which you have posted in main-question, and I have corrected those in above code,

* See function name, it should start with module name.
* The \_page(), may creating confusion as some hook has `_page()` part..so I did change function name to mymodule\_semistaticpage()
* where is return $items;?
* I think `title` do not need, t()?
> 0 votes

# Answer
Your current problem is very clearly mentioned in error statement , you need to replace (’) with (') without parentheses of-course.

other suggestions: 1: Title field do not require t() function 2: Description field should be written in t() function 3: Never ever forget to return $items array. 4: It is customary to start call back function names with your module name. 5: Always document your code for future purposes. 6: Your call back function should return content in a theme-able formate for example ('#type' =\> 'markup') etc
> 0 votes

---
Tags: 7
---


# Question
Title: The directory public://xmlsitemap was not found or is not writable by the server
I have just installed XML Sitemap on a EC2 drupal 8 instance. I am seeing the following error message in the admin report status page:

```
XML sitemap cache directory
Not found or not writable
The directory public://xmlsitemap was not found or is not writable by the server.
See http://drupal.org/node/34025 for more information.

```

The provided link is broken. I have done some reading and created a `/xmlsitemap` directory in `/var/www/html` (which is the root of my drupal installation). I `chmod` it to give `rwx` access to everyone (`a+`).

But, the issue remains. I cannot generate the cache files.

How can I solve this issue?

# Answer
> 0 votes
I found the `file_public_path` value from the `/admin/config/media/file-system` page. It was set to `sites/default/files`, relative to the installation path.

I checked permissions and noticed some writting permissions were missing (the directory was already created). I `sudo chmod a+w xmlsitemap/` and that solved the issue.

---
Tags: 8, caching, xml-sitemap
---


title: How to remove 'Submitted By'?

text:
# Question
Title: How to remove 'Submitted By'?
Although there are many answers for earlier versions of Drupal 8, I could not find a way to remove 'Submitted by' information displayed with Articles.

How can one achieve this with Drupal 8?

# Answer
This is in the settings of the content type:

> /admin/structure/types/manage/article

Here you'll find in the tab **Display settings** the checkbox:

> \[x\] Display author and date information
> 16 votes

---
Tags: nodes
---


# Question
Title: Custom form with multiple textarea fields
How can I create a textarea field in a custom module which has multiple (unlimited) fields? It should be the same result as selecting unlimited amount of values when adding a textarea fields to a content-type.

# Answer
There is no property in Drupal's Form API to create multi value fields. You have to create that functionality manually. Check this tutorial.

\[Edit\] the tutorial seems to have a couple errors (e.g. the values entered in names are not inherited as default\_value when the form is rebuilt when adding a field). But it can give you a general idea on how do this.
> 1 votes

---
Tags: 7, forms
---


title: Get child page content based on menu

text:
# Question
Title: Get child page content based on menu
So I have a website structure as follows: Homepage \> Level 1 \> Level 2 \> Level 3 (Article)

On display of a Level 1 page I want it to print out all of the level 2 articles that are a child of that content (relationships taken from the main menu). Information that needs to be printed is title, body summary, plus a custom image field that I have added.

This image shows the desired effect: the user is in About Us (Level 1), and so the main body of the site displays teasers of the level 2 pages (Who we are, what we do etc.) that have been set as children to About Us in the main menu.

Is it possible to take the parent/child relationships from the main menu, then on a page print the content of the child pages in this way?

Or, if not using the menu, is there a more appropriate/logical way to do this in Drupal?

I have lots of experience in using MySQL/PHP and writing custom modules in other content management systems however new to Drupal. Thank you for your help!

# Answer
I managed to do this in the following way:

```
function theme_get_page_children($nid) {
         $parentPath = 'node/'.$nid;
          $parentId = db_query("SELECT mlid FROM {menu_links} WHERE link_path ='".$parentPath."'");

      foreach($parentId as $pid){
         $finalID = $pid->mlid;
      }

        $getChildren = db_query("SELECT link_path FROM {menu_links} WHERE plid='".$finalID."' ORDER BY weight");

      foreach($getChildren as $child){
          $nodeID = str_replace('node/', '', $child->link_path);
          $children[]= $nodeID;
      }

        if(isset($children)){
             foreach($children as $nid){
                 $node = node_load($nid);
                 if($node->status ==1){ //check node is published
                      print render(node_view($node, $view_mode = 'teaser'));
                 }
            }
        }
    }

```

And on the template files where to call it:

```
innovista_get_page_children($node->nid)

```

I think using `foreach` to get $finalID was bad practice. I also think I should have used drupals menu API to call the child links instead of querying the database. So if anyone knows how to improve this in these ways, or tidy up the code in general then comment below :)
> 1 votes

# Answer
I've did it by adding a new variable for the menu to the page template in `template.php` with the `theme_preprocess_page` function:

```
function YOUR-THEME_preprocess_page(&$variables){

  // new theme variables for  child page menu

  // get the main menu variable
  $pid = variable_get('links__system_main_menu', 'main-menu');

  // get the main menu tree
  $main_menu_tree = menu_tree_page_data($pid);

  // iterate over the active menu and add each submenu item
  foreach ($main_menu_tree as $item) {
      if ($item['link']['in_active_trail']) {
            $submenu = $item['below'];
        }
  }

  // create new page variable for the menu
  if (!empty($submenu)){
      $variables['page_nav'] = menu_tree_output($submenu);
  }
}

```

After this clean template cache and add the following to your page template, im my case, `page.tpl.php`:

```
<?php print drupal_render($page_nav); ?>

```
> 1 votes

---
Tags: 7, theming, routes
---


title: npm install errors

text:
# Question
Title: npm install errors
I'm having difficulties with setting up Drupal 8 and `Bootstrap SASS` (sandbox project).

When following the documentation for setting up Bootstrap SASS at https://www.drupal.org/sandbox/wrender/2627564, when I reach point #2, "run npm install" I get lots of errors and can't proceed.

*My versions*

* Mac OS X 10.11.6
* node v0.12.7
* ruby 2.1.3p242 (2014-09-19 revision 47630) \[x86\_64-darwin13.0\]

*Terminal output*

➜ bootstrap\_sass git:(master) npm install

> bootstrap\_starter\_theme@1.0.0 postinstall /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass find node\_modules/ -name '\*.info' -type f -delete
>
> npm WARN unmet dependency /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass/node\_modules/grunt requires minimatch@'~0.2.12' but will load npm WARN unmet dependency /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass/node\_modules/minimatch
> npm WARN unmet dependency which is version 3.0.2
> npm WARN unmet dependency /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass/node\_modules/gulp-sourcemaps requires strip-bom@'^2.0.0' but will load
> npm WARN unmet dependency /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass/node\_modules/strip-bom
> npm WARN unmet dependency which is version 3.0.0
> npm WARN unmet dependency /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass/node\_modules/gulp-watch requires vinyl@'^0.5.0' but will load
> npm WARN unmet dependency /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass/node\_modules/vinyl
> npm WARN unmet dependency which is version 1.1.1
> npm WARN unmet dependency /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass/node\_modules/gulp requires vinyl-fs@'^0.3.0' but will load
> npm WARN unmet dependency /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass/node\_modules/vinyl-fs
> npm WARN unmet dependency which is version 2.4.3
> npm WARN unmet dependency /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass/node\_modules/gulp-sass/node\_modules/gulp-util requires object-assign@'^3.0.0' but will load
> npm WARN unmet dependency /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass/node\_modules/object-assign
> npm WARN unmet dependency which is version 4.1.0
> npm WARN unmet dependency /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass/node\_modules/gulp-sass/node\_modules/gulp-util requires vinyl@'^0.5.0' but will load
> npm WARN unmet dependency /Users/chandeepkhosa/w/pantheon/my-website/themes/bootstrap\_sass/node\_modules/vinyl
> npm WARN unmet dependency which is version 1.1.1
>
> ```
> gulp-autoprefixer@2.3.1 node_modules/gulp-autoprefixer
> ├── object-assign@2.1.1
> ├── through2@0.6.5 (xtend@4.0.1, readable-stream@1.0.34)
> ├── vinyl-sourcemaps-apply@0.1.4 (source-map@0.1.43)
> ├── postcss@4.1.16 (js-base64@2.1.9, source-map@0.4.4, es6-promise@2.3.0)
> └── autoprefixer-core@5.2.1 (num2fraction@1.2.2, browserslist@0.4.0, caniuse-db@1.0.30000518)
>
> ```

# Answer
I fixed this by updating my versions of NPM & Node to match the requirements stated on the project page (silly me).
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Why does the count of the Menu badge not decrease after page is viewed?
I have created a view, which shows activity logged by Message module.

I then created a menu badge which shows the numbers on the menu item. - In start, when there is no activity, it shows 0, After there is some activity it shows the count, but when the page is viewed the count remains the same and does not decrease or disappear.

When the whole activity page is viewed, the numbers should disappear.

# Answer
### Part 1 - It does seem to work as designed

Since your question is about a "Menu badge", I'm assuming you are using the (great!) Menu Badges module to create such badge, whereas you also created a view (using the Views module).

To make it all work, your view should show the number of rows corresponding to the "*activity logged by the Message module*" (as in your question).

And the view seems to be OK if there is no activity (it shows "O"). However, if the count remains the same later on, then it must be because the result of your view doesn't change either. If you want that number produced by the Menu Badges module to change, then you must make sure that the view produces the correct number. So if that number doesn't change, it is about sure (not just probably ...) because something in the filter of your view is not correct. Like does your view only select the rows which have some kind of "new activity" indicator? If not, what other filter do you have to make that number decrease?

So IMO this is not a bug in the module, but rather just a customization error in your view (head over to **Part 2** for more details on that).

### Part 2 - What you're missing in your view

I think **Part 1** of my answer is "the" answer to your question, but here is an attempt to also, partially, answer your additional comment (which is really a new question I think):

> If there is new activity, the number does increase, but do not decrease or disappear as in case of private messages. What I have understood so far of menu badges is that you have to put something in the fields section and turn on aggregation so that it knows what to count. Currently I am using Message:Message ID in the field. What filter I should use?

Not sure where the "private messages" refers to (I'm just going to consider that as "a" type of messages). But you're right about that "***you have to put something in the fields section and turn on aggregation so that it knows what to count***": that is the "*clue*" about what the Menu Badges is all about. Let's consider the Message View (where the below screenprints originate from) that comes with the Message module, i.e.:

Here is a screenprint with the design details of that view:

If you'd use the `Add` button for "fields", and then filter the available fields for "Message:", you would only get these fields:

* Language
* Message ID
* Render message (Get text)
* Rendered Message
* Timestamp
* Type
* User uid

Obviously, none of these fields contain any information if it is yes or no a "new" message. So that's what you're missing and why out-of-the(-message)-box you cannot get this to work. To better explain this (what you're missing): have a look at the "`tracker`" view (disabled by default), which has the fields "***Content:Has new content***" and "***Content:Has new comments***". Those are 2 perfect fields to use if you want to use Menu Badges to get notified whenever there is new content, or new comments.

A possible compromise, and maybe partial solution for your scenario could be that you'd use the `Timestamp` field as your filter. E.g. if you'd filter it like "only the ones from the last 24 hours", that should have some effect.

### Part 3 - How to get it to work anyway

There is a way to get this to work anyway ... Because messages are fieldable. So simply (hm, hm) add a boolean field like "Message is new" (Yes/No). It'll then also show up in the list of fields you can select from in your view (in the list of available fields as in **Part 2**). And with that you have a perfect solution for what you're trying to get to work.

However, there is one more challenge left: add appropriate logic to maintain the value of that boolean field. If you wonder how to do that (also), just ask a new question.
> 1 votes

---
Tags: 7, views, notifications, message-subscribe
---


title: what does Drupal API mean?

text:
# Question
Title: what does Drupal API mean?
What does it mean when someone says Drupal API? Does that phrase include drupal hooks, theme functions and every other drupal term or is it used as a synonym for api.drupal.org

I am really confused please define it for me to understand it easily.

Many thanks

# Answer
It's a generic term to encapsulate all the programming interfaces Drupal provides. Any further meaning would have to be inferred from the context of how it was used (FWIW, I've never heard "Drupal API" to refer to the documentation site **api.drupal.org**).

When specifying a particular component of the Drupal API, you'll often see it labeled with its functionality (e.g. Drupal Routing API, Drupal Batch API, etc.) to clarify what part of Drupal's API is being discussed.
> 8 votes

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


# Question
Title: How to get access all images of custom directory in twig template?
I intend to create a slideshow in front page of my theme to show **all images in custom directory**, I try to use file\_scan\_directory and drupal\_get\_path in below codes to get any non static images path and display that images automatically without any need to calling each one of them separately:
**Theme Name.theme:**

```
function MyThemeName_preprocess_page(&$variables) {
$mask = '/\.(?:jp[e]?g|gif|png)$/i';
$files = file_scan_directory(drupal_get_path('theme', 'Theme Name') . '/assets/img/orbit', $mask);
ksort($files);
$variables['files'] = $files;
}

```

**page.html.twig:**

```
{% for file in files %}
<img src="{{ file.uri }}" width="100%" height="100%" alt="{{ file.name }}"/>
{% endfor %}

```

I would be happy to hear what is the problem with the codes and what is the right way to load that slideshowe pictures?

# Answer
The path will be wrong, `file_scan_directory()` will return a relative path, you need to add the `base_path()`, you can set a variable in preprocess:

```
$variables['base_path'] = base_path();

```

So...

```
<img src="{{ base_path }}{{ file.uri }}" width="100%" height="100%" alt="{{ file.name }}"/>

```
> 0 votes

---
Tags: theming, 8, media
---


# Question
Title: How to implement side-by-side translation?
How can you set up a translation system in Drupal which displays, for example, the English and the French node edit forms side-by-side? Is this possible using any of the contrib modules?

Additionally, how would I go about setting a requirement that a translation must always be entered when entering English content. Eg, to publish a piece of content, it must have both an English and French translation. Maybe through rules?

# Answer
There hasn't been a whole lot of public work on this that I can find.

Some module options:

1. Side-by-Side Translation (no code)
2. Entity Translation Side-by-side Editor (code, no release)
3. Dual-Language Editor (code, no release)

liquidcms helped me find that last one.

I'd recommend trying the latter two and seeing how far you get. Post patches for missing functionality as necessary.

Also, see the issue Create Node With Multiple Translations Using Single Form.
> 1 votes

# Answer
This is very easy to do using Views + Editable Fields \+ Entity Reference \+ Panels (Optional).

1. Forget about the /edit page. Create a new /node/%node/translation page in Page Manager. All the translations will be viewed on the parent's page.
2. Add an entity reference field to the content type so that non-English nodes can link back to their parent English node. In the screenshot, "Translation Node Spanish" references node 1.
3. Create two views. English Edit View: Contextual Filter: Provide Default: Content ID.
4. Spanish Edit View: Content\>English Node (Entity Reference field): Provide Default: Content ID.
5. For both views, add a Content Pane and change the required fields to Editable in their settings. In the screenshot, I just have the body. (Note the two Save buttons). Add the content panes to the /node/%node/translation panel.
6. If you have lots of languages, each extra view can have a "Content: Language" Contextual Filter as well with a fixed value of es or de etc. All of these views can then be added to the panel. (This is really just for layout reasons).
7. Create an extra block to list the English nodes by only showing nodes in that content type whose English Node (Entity Reference field) field is empty in the filter settings. Rewrite the field so that the url is node/\[nid\]/translation and only let content editors see it.

Unless I'm mistaken, this should pretty much deal with the side-by-side thing.. Panels are unnecessary but it was easier for me to demonstrate with them. You can find out how to use Entity Reference elsewhere.
> 1 votes

# Answer
I have not tried this, but you may be able to do this with Panels and Form Block module. I have not used panels in a while, but I know it has the ability to pick up context or parameters from the node object. If the translated node id not already available, you might need to use entity relation and manually set a reference to the translated node. The field value should be available in the panel.

Only thing I'm really not sure about is if form block can pick up the node id dynamically from the Panel context. If it can, then you might be able to do without modifying any of the modules.

Another caveat, I haven't used the d7 versions of panels or form block. I used these much more in drupal 6, but I remember panels having a lot of power to pick up and reuse these parameters in the different panes.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: How to add multiple products to cart at the same time with attributes
I have different view blocks that display multiple products on the same page, each product has their own attributes such as product bundle and custom line item, these serves as an option set / criteria of the main product. The results of the options slider will be the value of the customs line item that is hidden.

What I plan to accomplish is to add all these selected products with the selected attributes on the cart at the same time with just one button.

Example:

**Product 1:**

**Product 2:**

These are the methods/modules I have tried:

The first two methods work for the main product only, no attributes of the customs line item and bundle products. I tried including the *add to cart form* in the view with the **VBO** or **commerce product: quantity field** of commerce add to cart extras but it doesn't work maybe because it's a form within a form.

Does anyone have any suggestion on how to make this work?

Thank you in advance!

# Answer
I suggest writing a custom `hook_submit()` who will add all the items of your views to the shopping cart.

Something like that should do the job.

```
 global $user;

 $results = views_get_view_result('view_name', 'block_1');

 foreach($results as $item) {
 // Create new line item:
 $line_item = commerce_product_line_item_new($product, $quantity);

 // Add to current user's cart
 $line_item_added = commerce_cart_product_add($user->uid, $line_item);
 }

```

Good luck.

Cheers
> 0 votes

---
Tags: 7, commerce, javascript, rules, views
---


title: What session are better to use?

text:
# Question
Title: What session are better to use?
i already tried the private tempstorage class on local it is working. but when i put it on cloud it was not working anymore.

```
use Drupal\user\PrivateTempStoreFactory;

$session = \Drupal::service('user.private_tempstore')->get('my_modules');
$session_id = $session->set('session_id');
$session_uname = $session->set('session_username');

$session_id = $session->get('session_id');
$session_uname = $session->get('session_username');

```

Please help me with this.

# Answer
Use sessions. This is how to access sessions inside classes:

```
class MymoduleSessionCounter {
  function increment(Request $request) {
    $session = $request->getSession();
    $value = $session->get('mymodule_count', 0);
    $session->set('mymodule_count', $value + 1);

    return $value;
  }
}

```

Change note: https://www.drupal.org/node/2380327

If you have procedural code in hooks, you can still use the D7 way and store the data in `$_SESSION[]` or get the session with:

```
$session = \Drupal::request()->getSession()

```
> 1 votes

---
Tags: 8, sessions
---


# Question
Title: how to update quantity of products in the cart via javascript?
I have the module that changes the quantity of products inside the card via ajax but I need to change it also outside, as on the picture,

the code that changes the quantity after reload of the page are as follows

```
$variables = array(
        'order' => $order,
        'contents_view' => commerce_embed_view('commerce_cart_block', 'defaults', array($order->order_id), $_GET['q']),
      );
      $count = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());

      $quantity = 0;

      foreach ($wrapper->commerce_line_items as $line_item) {
        if (!$line_item instanceof EntityMetadataWrapper) {
          $line_item = entity_metadata_wrapper('commerce_line_item', $line_item);
        }
        $types = array('product');

        if (empty($types) || in_array($line_item->type->value(), $types)) {
          $quantity = $quantity + $line_item->quantity->value();

        }
      }

      $prod_count = t($quantity);

      if ($prod_count > 0){

        $icon = '<div class="cart-icon"></div><span class="cart_popup_count">'. $count . '</span>';
        $content = '<div id="cart-popup" style="display:none;">' . theme('commerce_cart_block', $variables) . '<div class="popup-arrow"></div></div>';
        $content = '<div class="wrapper">' . $icon . $content . '</div>';
      }elseif (variable_get('commerce_popup_cart_show_empty_cart', 0) == 1){
        $content = commerce_popup_cart_block_view_get_empty_cart($variables);
      }

```

The problem is that I don't know how to changes this numbers simultaneously inside and outside the card.

This is the code that changes quantity inside the card

```
  function _commerce_popup_cart_add_to_cart_ajax_callback($form, $form_state) {
  commerce_cart_add_to_cart_form_submit($form, $form_state); //Call the add to cart form to actually add the product
  $res = _commerce_popup_cart_ajax_cart_reload(); //Retrieve the new cart view

  $commands = array();
  $commands[] = ajax_command_replace("#block-commerce-popup-cart-commerce-popup-cart .cart-empty-block", "<div class='cart-contents'></div>");
  $commands[] = ajax_command_html('#block-commerce-popup-cart-commerce-popup-cart .cart-contents', $res);
  return array('#type' => 'ajax', '#commands' => $commands);
}

function _commerce_popup_cart_ajax_cart_reload() {
  global $user;
  $view_name = 'commerce_cart_block'; // The name of the view we are going to load commerce_cart_block
  $args = array(commerce_cart_order_id($user->uid));  // Array of arguments we set for the view. Only one argument in our example. your actual view may require additional

  //arguments which you may need to set
  $displayId = 'default'; // The display id of for the view.
  // Call the views_embed_view function to returned themed view output
  $res = views_embed_view($view_name, $displayId, $args);
  return $res;
}

```

# Answer
* Create new simple module like my\_updater\_card
* add hook\_menu
* add php function to update the card
* call this function from ajax

```
<?php
/**
 * Implements hook_menu().
 * see hook_menu()
 * see menu_example
 */
function my_updater_card_menu()
{
    $items['my_updater/card/%'] = array(
        'page callback'         => 'my_updater',
        'page arguments'        => array(2),
        'access arguments'      => array('put your permission here'),
    );
    return $items;
}

function my_updater($newTotal){
    //check if this request come from ajax => if not => ignore it
    //here put your php code to update the card
    //then return results true/false to ajax caller
}
?>

```

Ajax

```
        $.ajax({
               url: 'my_updater/card/[new total here]',
               type: "GET",
               success: function (data) {
                 //do total refresh here
               }
        });

```
> 1 votes

---
Tags: commerce
---


title: Drush installation in windows

text:
# Question
Title: Drush installation in windows
I'm unable to install drush in windows. I have searched a lot for it but unable to understand. I'm new to drupal.

# Answer
it's pretty simple in fact all you have to do is download and install Acquia Dev Desktop from this link dev desktop and you will have a local dev environnement for drupal with drush included
> 2 votes

# Answer
Here are some guide on how to install Drush on Windows.

From docs.drush.org

> Drush on Windows is not recommended, since Drush's test suite is not running there (help wanted).
>
> Acquia Dev Desktop is excellent, and includes Drush. See the terminal icon after setting up a web site.
>
> Or consider running Linux/OSX via Virtualbox. Drupal VM and Vlad are popular.
>
> These Windows packages include Drush and its dependencies (including MSys). 7.0.0 (stable). 6.6.0. 6.0.
>
> Or install LAMP on your own, and run Drush via Git's shell, in order to insure that all depedencies are available.
>
> When creating site aliases for Windows remote machines, pay particular attention to information presented in the `example.aliases.drushrc.php` file, especially when setting values for `'remote-host'` and `'os'`, as these are very important when running `drush rsync` and `drush sql-sync` commands.

http://docs.drush.org/en/master/install-alternative/

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

https://modulesunraveled.com/drush/installing-drush-windows
> 1 votes

---
Tags: drush
---


# Question
Title: Does a twig template know in which region it is?
Or: how do I output conditional classes depending on the region a twig template is being rendered?

# Answer
> 4 votes
No, it doesn't.

With render caching, it is even possible that the same template/thing is not rendered again and put into a different region (not directly a block, but for a example a rendered entity, in a view or so).

It's easy to do targetting in CSS based on a parent region class. I know there are some recommendations to avoid that, but that's not always possible, especially when working with a complex system like Drupal, where you don't have 100% control over the HTML output in every scenario.

---
Tags: theming, 8
---


title: How to add conflicts in D8 info.yml?

text:
# Question
Title: How to add conflicts in D8 info.yml?
I want to know how to add **conflicts** in D8 info.yml.

I tried like this in D8 .info.yml:

```
name: Example
type: module
description: some example.
core: 8.x
package: Other
dependencies:
  - menu_ui
conflicts:
  - module1
  - module2

```

and in .install file

```
<?php
/**
 * Implements hook_requirements().
 */
function example_requirements($phase) {
  $requirements = [];

  switch ($phase) {
    // Called while the module is installed.
    case 'install':
    if (\Drupal::moduleHandler()->moduleExists('module1')) {
        $requirements[] = [
          'title' => t('Module 1'),
          'value' => t('Module 1'),
          'description' => t('Module 1 conflicts with example.'),
          'severity' => REQUIREMENT_ERROR,
        ];
      }
      break;
  }

  return $requirements;
}

```

But in D7 it is working:

```
name = Example
description = some example.
core = 7.x
dependencies[] = menu
package = Other
conflicts[] = module1
conflicts[] = module2

```

While enabling my example module it is not showing any conflict error in D8.

> Installation Order:
>
> 1) Fresh Drupal installation.
>
> 2) Module 1
>
> 3) Module 2
>
> 4) Example module(here i need to show module1 and 2 are present while installing)

# Answer
It seems that this is not implemented yet. Related issue is here.

An alternative would be to use `hook_requirements()` in your module's `.install` file. You can check here if the conflicting module is present during the installation process and prevent the system from installing the module.

Here's example code that would go in your module's `.install` file:

```
/**
 * Implements hook_requirements().
 */
function YOUR_MODULE_requirements($phase) {
  $requirements = [];

  switch ($phase) {
    // Called while the module is installed.
    case 'install':
    // Called during regular use of the website.
    case 'runtime':
    // Called while the update.php is being executed.
    case 'update':
      // Do not allow administrators to install the module if conflicting module
      // is already installed.
      //
      // You can move this code to any other phase as well.
      if (\Drupal::moduleHandler()->moduleExists('ARCH_ENEMY_OF_YOUR_MODULE')) {
        $requirements[] = [
          'title' => t('Name of your module'),
          'value' => t('Arch enemy module'),
          'description' => t('Explain that administrators need to uninstall the module before proceeding.'),
          'severity' => REQUIREMENT_ERROR,
        ];
      }
      break;
  }

  return $requirements;
}

```

You can see a working example of `hook_requirements()` in my Drupal 8 boilerplate repo on Github.

Hope this helps.
> 3 votes

---
Tags: 8, .info
---


title: Render block via twig template

text:
# Question
Title: Render block via twig template
I have programmatically created a block. In my module folder I added all suggested templates in a templates folder(mymodule/templates/suggestedtemplatename.html.twig).

However the block is not using any of them! I have enabled the theme debugger which gives me all the suggestions and describes which part of the page is produced from which template. I can see only block.html.twig producing html. I tried drush cr and uninstalling/installing the module

# Answer
I was missing the implementation of hook\_theme. In order to use the template you need to declare it there. FX

```
/**
 * Implements hook_theme().
*/
function mymodule_theme() {
  return array(
    'block__newsletter' => array(
      'render element' => 'elements',
    ),
  );
}

```

You should then have a templates/block--newsletter.html.twig.
> 1 votes

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


# Question
Title: Installing a profile inherited from an existing distribution
I would like to build a distribution based on the Standard profile coming with Drupal 7, by inheriting all the features of the parent distro and changing some of them with custom code.

The title of this question sounds very similar to "Is there a way to inherit a Drupal installation profile?". While the referenced post deals with building the code base, ie a .make file, here I am interested in site installation of a distro made of *profilename*.info, *profilename*.install and *profilename*.profile.

There is a solution proposed in \[How to Write a Drupal 7 Installation Profile\]\[2\], that seems quite simple. So I tried the following code in mydistro.profile:

```
function mydistro_install() {
  include_once DRUPAL_ROOT . '/profiles/standard/standard.install';
  standard_install();
}

```

If this worked I could add custom features further down in the process. Then I ran site-install with drush:

```
drush -d si mydistro -y --db-url=mysql://root:secret@localhost/mydistro_com

```

The process installs the database with 43 tables (out of 74 that come with the standard profile), and enables the following modules:

user, field\_sql\_storage, filter, node, field, text

and then throws this error message:

```
exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table                              [error]
'mydistro_com.block' doesn't exist' in C:\xampp\htdocs\mydistro.com\includes\database\database.inc:2171
Stack trace:
#0 C:\xampp\htdocs\mydistro.com\includes\database\database.inc(2171): PDOStatement->execute(Array)
#1 C:\xampp\htdocs\mydistro.com\includes\database\database.inc(683): DatabaseStatementBase->execute(Array, Array)
#2 C:\xampp\htdocs\mydistro.com\includes\database\mysql\query.inc(36): DatabaseConnection->query('INSERT INTO {bl...', Array, Array)

```

saying that the block table is missing. All other tables belonging to the modules that are listed as dependencies in standard.info are also missing:

```
dependencies[] = block
dependencies[] = color
dependencies[] = comment
dependencies[] = contextual
dependencies[] = dashboard
.
.
.

```

I have tested with Drupal 7.38 on Windows 7, php 5.6.2.

Same test and same result also with minimal profile.

Any idea about what I am doing wrong?

# Answer
> 0 votes
Are you adding those dependencies to your `.info` file `mydistro.info`?

If not, you should. It looks like the install is getting to line 196 in the `standard.install` file and then trying to enable all those blocks, but the blocks module was never enabled and it doesn't test for that, which is breaking the install. @VanD

Basically you should add the same modules listed as dependencies in the standard profile, also to `mydistro.info` and re-run the installation.

---
Tags: 7, distributions, installation-profiles
---


# Question
Title: Can I add additional module to drupal distribution (all inclusive)?
I have a SSO module I need to add to Open Social distribution. Can I add this additional module to the distribution (all inclusive)?

# Answer
In your installation you can add the module just like any other module yes.

If you want to add id to the distribution itself, you would effectivly make a new distribution based on Open Social with the module added - please read the guidelines here to learn how to add it.
> 0 votes

---
Tags: distributions
---


# Question
Title: ajax callback on form element checkboxes
I am having some troubles with ajax on form element checkboxes, in ajax callback form\_state is without values and triggering element etc .. why is that?

The form is called with drupal\_get\_form and this is my element

```
$form['select_options'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#ajax' => array(
    'callback' => 'ajax_options_callback',
    'wrapper' => 'options-form',
    'event' => 'change',
    'method' => 'replace',
  ),
);

```

# Answer
> 1 votes
When you use a callback `$forms` and `$form_state` is available for use in your callback. But you should call them as parameters in your callback definition. So:

```
public function ajax_option_callback(array $form, FormStateInterface $form_state) {
  // get the id of the form
  $value = $form_state->getFormObject()->getFormId();
  // create a response object and return it
}

public function ajax_option_callback() {
  // $form and $form_state not available
}

```

Note that `&form_state->getTriggeringElement()` contains nothing as the form is not submitted.

I realize now the question is for D7. Maybe my answer is usefull for someone within the D8 context.

---
Tags: forms, ajax
---


# Question
Title: Unknown map column when migrating users from CSV file
I'm trying to import the users from CSV file, but the import fails with the following error:

> Migration failed with source plugin exception: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'map.sourceid4' in 'where clause', in includes/database/database.inc:2171

Migrate class is:

```
<?php

/**
 * @file
 * Class for migrating users from a CSV file.
 */

/**
 * Class FooMigrateUsers.
 */
class FooMigrateUsers extends Migration {

  /**
   * Constructor.
   *
   * @inheritdoc
   */
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->description = t('Foo users from CSV file');

    // Create the migrate source.
    $import_path = drupal_get_path('module', 'foo_migrate') . '/import/users.csv';
    $options = array(
      'header_rows' => 1,
    );

    $this->source = new MigrateSourceCSV($import_path, array(), $options);
    $this->destination = new MigrateDestinationUser();

    $this->map = new MigrateSQLMap($this->machineName,
        array(
          'Title' => array(
            'type' => 'varchar',
            'length' => 15,
            'not null' => TRUE,
            'description' => 'Title',
          ),
          'Firstname' => array(
            'type' => 'varchar',
            'length' => 35,
            'not null' => TRUE,
            'description' => 'First name',
          ),
          'Lastname' => array(
            'type' => 'varchar',
            'length' => 35,
            'not null' => TRUE,
            'description' => 'Last name',
          ),
          'Primary email address' => array(
            'type' => 'varchar',
            'length' => 80,
            'not null' => TRUE,
            'description' => 'Primary email address',
          ),
        ),
        MigrateDestinationUser::getKeySchema()
        );

    // Mapped fields

    // We must have a unique username in the Drupal 'users' table.
    // dedupe() takes the Drupal table and column for determining uniqueness.
    $this->addFieldMapping('name', 'Primary email address')
         ->dedupe('users', 'name');
    $this->addFieldMapping('mail', 'Primary email address')
         ->dedupe('users', 'mail');

    //$this->addFieldMapping('pass', 'password');

    // Apply default role.
    $this->addFieldMapping('roles')
         ->defaultValue(DRUPAL_AUTHENTICATED_RID);

    $this->addFieldMapping('field_user_first_name',      'Firstname');
    $this->addFieldMapping('field_user_last_name',       'Lastname');

    $this->addUnmigratedSources(array('Title'));

    $this->addUnmigratedDestinations(array(
      'access',
      'created',
      'data',
      'is_new',
      'language',
      'login',
      'pass',
      'picture',
      'role_names',
      'signature',
      'signature_format',
      'theme',
      'timezone',
    ));

  }

  /**
   * Modifies the row to be imported.
   *
   * @inheritdoc
   */
  public function prepareRow($row) {
    return parent::prepareRow($row);
  }

}

```

The CSV data is like:

```
"Title","Firstname","Lastname","Primary email address"
"Mr","Foo","Bar","foo@example.com"
"Mrs","Bar","Foo","bar@example.com"

```

# Answer
> 1 votes
The 'Column not found' (map.sourceid4) error sounds like migration table related to source mapping is not complete.

You should identify the table (e.g. using drush command):

```
drush sqlq "SHOW TABLES LIKE 'migrate_map_%'"

```

Note: You can also execute above in SQL editor by using quoted part only.

and check the list of available columns for that table:

```
$ drush sqlq "DESC migrate_map_foomigrateusers"
sourceid1   varchar(128)    NO  PRI NULL
sourceid2   varchar(128)    NO  PRI NULL
sourceid3   varchar(128)    NO  PRI NULL
destid1 int(10) unsigned    YES     NULL
needs_update    tinyint(3) unsigned NO      0
rollback_action tinyint(3) unsigned NO      0
last_imported   int(10) unsigned    NO      0
hash    varchar(32) YES     NULL

```

The number of `sourceidX` column should match with number of columns in CSV file. If they won't, probably you've modified the CSV file and after each structure change you have to re-register your migration class (see: `hook_migrate_api`).

So please reregister any statically defined migration classes by (check list by `drush ms`):

```
drush migrate-deregister FooMigrateUsers
drush migrate-register FooMigrateUsers

```

In case of further problems, these drush commands can be handy as well:

```
drush migrate-mappings --all # To verify mapping.
drush migrate-fields-source --all # To list source field mapping.

```

When ready, try re-importing the data again:

```
drush mi FooMigrateUsers

```

---
Tags: 7, migrations, importing-exporting
---


# Question
Title: Trying to have multiple source ids for xml import
In my continued frustration with trying to extend the wordpress\_migrate module, I have run into another problem with migrate.

Wordpress uses two unique identifiers in it's categories - nicename and term\_id. I don't know why. Nicename is used for matching parent categories, and as the unique identifier in blog posts. However, in custom content types that are exported, they use the term\_id in their fields. Here's an example:

```
<wp:category><wp:term_id>41069</wp:term_id><wp:category_nicename><![CDATA[daly]]></wp:category_nicename><wp:category_parent><![CDATA[nt2]]></wp:category_parent><wp:cat_name><![CDATA[Daly]]></wp:cat_name></wp:category>

```

Currently the nicename is being used as the source id, like so:

```
$this->map = new MigrateSQLMap($this->machineName,
      array(
        'wp:category_nicename' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'description' => 'WordPress category machine name',
        ),
      ),
      MigrateDestinationTerm::getKeySchema()
    );

$fields = array(
      'wp:category_nicename' => 'Unique "machine name" of the category',
      'wp:category_parent' => 'Category parent (nicename?)',
      'wp:cat_name' => 'User-friendly category name',
      'wp:category_description' => 'Description of category',
    );

// Construct the source and destination objects.
    $source_options = array(
      'reader_class' => 'MigrateXMLReader',
      'cache_counts' => TRUE,
    );
    $this->source = new MigrateSourceXML($this->wxrFile, '/rss/channel/category',
      'wp:category_nicename', $fields, $source_options, $this->arguments['namespaces']);
    $this->destination = new MigrateDestinationTerm($this->arguments['category_vocabulary']);

```

However, this is no good for the sourceMigration when I am trying to use the term id. In my head I thought it would logically work like so

```
$this->map = new MigrateSQLMap($this->machineName,
      array(
        'wp:term_id' => array(
          'type' => 'int',
          'not null' => TRUE,
          'description' => 'WordPress category term id',
        ),
        'wp:category_nicename' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'description' => 'WordPress category machine name',
        ),
      ),
      MigrateDestinationTerm::getKeySchema()
    );

$fields = array(
      'wp:term_id' => 'Unique id of the category',
      'wp:category_nicename' => 'Unique "machine name" of the category',
      'wp:category_parent' => 'Category parent (nicename?)',
      'wp:cat_name' => 'User-friendly category name',
      'wp:category_description' => 'Description of category',
    );

// Construct the source and destination objects.
    $source_options = array(
      'reader_class' => 'MigrateXMLReader',
      'cache_counts' => TRUE,
    );
    $this->source = new MigrateSourceXML($this->wxrFile, '/rss/channel/category',
      'wp:category_nicename', $fields, $source_options, $this->arguments['namespaces']);
    $this->destination = new MigrateDestinationTerm($this->arguments['category_vocabulary']);

```

and then on the mapping, something like:

```
->addMigration('Migration', $source_key = 'wp:term_id');

```

Or something like that. But there doesn't seem to be any way of doing this that I can figure out. When I create the migration with the two columns as above it creates the source1 and source2 columns as I would expect, but I get a series of these errors:

```
Could not save to map table due to NULL value for key field wp:category_nicename
Undefined property: stdClass::$wp:category_nicename File /app/docroot/sites/all/modules/contrib/migrate/includes/migration.inc, line 943(file: /app/docroot/sites/all/modules/contrib/migrate/includes/migration.inc, line 943)

```

Even then, I don't think there's a way to specify which source key to use in addMigration. I can't find an issue that is related that helps me here, trust me I've read them.

# Answer
> 1 votes
The 'Undefined property' during migration errors are usually related wrong passing of unprepared rows, sometimes because of typos in the field name. By default `prepareKey()` is called before `prepareRow()` and you can specify which source key to use by overriding the default behaviour and by defining your own `prepareKey()` method in your class. This is especially needed when your source data doesn't have any primary key and you need to define one.

See this post explaining that by the following example:

> What the MigrateSQLMap constructor means:
>
> ```
> $this->map = new MigrateSQLMap($this->machineName,
>              array(
>                'muid' => array(
>                  'type' => 'int',
>                  'not null' => true,
>                ),
>              ),
>              MigrateDestinationUser::getKeySchema()
>
> ```
>
> What this is saying is, take the `muid` value from your source row and use that to populate sourceid1 in the map table. If you source query has a column which is a unique identifier for each row, you should be using the name of that column instead of muid here. If your source data doesn't have a handy primary key and you need to construct one name `muid`, then you would do that in `prepareKey()` instead of prepareRow (NOT by doing it in `prepareRow` and calling that).

---
Tags: 7, migrations
---


# Question
Title: Add bootstrap icons next to fields in node page
In my views I can do this easily using the rewrite results and writing this line

```
<span class="glyphicon glyphicon-earphone list-icon"></span>  [field_business_phone]

```

How can I do the same with the node page. It doesn't necessarily have to be a rewrite method but I am looking for an easy method of doing this. The end result I am looking for is something like this.

# Answer
> 2 votes
Use the preprocess function, like:

```
function YOUR_THEME_preprocess_field(&$variables) {
  $element = $variables['element'];

  if (isset($element['#field_name'])) {
    if($element['#field_name'] == 'field_business_phone') {
      foreach ($variables['items'] as $k => $value) {
        $variables['items'][$k]['#markup'] = '<span class="glyphicon glyphicon-earphone list-icon"></span>' . $variables['items'][$k]['#markup'];
      }
    }
  }
}

```

Or overwrite the field templates, in a file named **field--field-business-phone.tpl.php**, containing something like:

```
<?php

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field__items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field__item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><span class="glyphicon glyphicon-earphone list-icon"></span> <?php print render($item); ?></div>
    <?php endforeach; ?>
  </div>
</div>

```

---
Tags: 7
---


title: How can I search in another language?

text:
# Question
Title: How can I search in another language?
I have 2 languages in my site and a search view for **property search** and I am using the Search API module.

When I try to search in English (default language), the search is working. But when I try to search in the another language the search is not working.

I am searching by tittle.

Any suggestions?

# Answer
If you are using entity translation for translating the content, you will have to install the Search API Entity Translation module.

> *Search API Entity Translation* module provides multilingual support for the *Search API* module through integration with *Entity Translation*.

This module provides a new index type : "multilingual node index", similar to the "default node index" which is provided by default by Search API.
You can use this to create the views and they will honor the language selected from the language switcher.
> 2 votes

---
Tags: i18n-l10n, search
---


title: How to expand menu items by default?

text:
# Question
Title: How to expand menu items by default?
We are having an issue where the "Show as expanded" checkbox is false whenever a new link is generated regardless of menu link weight.

Using the Superfish module we are displaying the menu block and tried to the following below to see if we can have the menu links expanded by default. However, during testing this is failing. We are using the latest Bootstrap theme as our base theme.

**Test case:**

1) Create a menu link for custom-menu
2) Navigate to admin page to view all the menu links
3) Click on edit on the menu link item
4) The Show as Expanded is disabled

**Code (only hook in my .module file):**

```
function mymodule_menu_link_alter(&$item, $menu) {
  if($item['menu'] == 'custom-menu')
  {
    $item['expanded'] = 1;
  }
}

```

# Answer
I tried your custom hook call, just to be sure it was called as you imagine, and to see how the $item array was build.

First, according to the hook\_menu\_link\_alter() documentation, their is only one argument to this method in Drupal 7 (&$item).

And when I print the $item element, I can see that the name of the menu of the current element is not 'menu' but 'menu\_name'.

Then your code must be something like :

```
function mymodule_menu_link_alter(&$item) {
  if($item['menu_name'] == 'custom-menu')
  {
    $item['expanded'] = 1;
  }
}

```

It is an interesting hook, because it is also called when a user add a menu directly from a node form options.
> 2 votes

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


# Question
Title: Create a new content type with a custom field ( author )
I want to create a new content type " News " with a custom field Author which refers to the author-of-the-content(taxonomy reference or user reference).

This is my .module file:

```
<?php
/**
 * Implements hook_node_info()
 * Drupal calls this hook when it’s discovering which node types are available. You’ll
 * provide some metadata about your custom node.
 */
function news_node_info() {
    return array(
        'news' => array(
            'name' => t('News'),
            'base' => 'news',
            'description' => t('You can add  News here'),
            'has_title' => TRUE,
            'title_label' => t('News title')
         )
    );
}

/**
 * Implement hook_form()
 */
function news_form($node, $form_state) {
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('news Title'),
    '#default_value' => !empty($node->title) ? $node->title : '',
    '#required' => TRUE,
    '#weight' => -5
  );
  return $form;
  }

```

This is my .install file:

```
<?php
/**
 * Implements hook_install().
 */
function news_install() {
    node_types_rebuild();
    $types = node_type_get_types();|
      node_add_body_field($types['news']);
    add_custom_fields();
}

function _news_installed_fields() {
  $t = get_t();
  return array(
    'news_title' => array(
      'field_name' => 'news_title',
      'label' => $t('Title'),
      'type' => 'text',
      ),
    'news_image' => array(
      'field_name' => 'news_image',
      'label' => $t('Image'),
      'type' => 'image',
    ),
    'news_tags' => array(
      'field_name' => 'news_tags',
      'label' => $t('Add Tags'),
      'type' => 'taxonomy_term_reference',
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => 'news_tags_vocab',
            'parent' => 0,
            ),
          ),
        ),
      ),
    ),
  );
}

function _news_installed_instances() {
  $t = get_t();
  return array(
    'news_title' => array(
      'field_name' => 'news_title',
      'type' => 'text',
      'label' => $t('The heading of the news topic'),
      'widget' => array(
        'type' => 'text_textfield',
      ),
      'display' => array(
        'news_display_option' => array(
          'label' => $t('The heading of the news topic (display option)'),
          'type' => 'text',
          ),
        ),
      ),
      'news_image' => array(
        'field_name' => 'news_image',
        'type' => 'image',
        'label' => $t('Add Image'),
      ),
      'news_tags' => array(
        'field_name' => 'news_tags',
        'type' => 'taxonomy_term_reference',
        'label' => $t('Add Tags'),
        'widget' => array(
          'type' => 'taxonomy_autocomplete'
        ),
        'display' => array(
          'default' => array('type' => 'hidden'),
          'teaser' => array('type' => 'hidden')
        ),
      ),
    )
  );
}
function add_custom_fields() {
    foreach (_news_installed_fields() as $field) {
        field_create_field($field);
    }
    foreach (_news_installed_instances() as $fieldinstance) {
        $fieldinstance['entity_type'] = 'node';
        $fieldinstance['bundle'] = 'news';
        print_r($fieldinstance);
        field_create_instance($fieldinstance);
    }
}

/**
 * Implements hook_uninstall().
 */
function news_uninstall() {
  // Delete the taxonomy with its terms
  $vocab = taxonomy_vocabulary_machine_name_load('news_tags_vocab');
  taxonomy_vocabulary_delete($vocab->vid);

  // Gather all the example content that might have been created while this
  // module was enabled.
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
  $result = db_query($sql, array(':type' => 'news'));
  $nids = array();
  foreach ($result as $row) {
    $nids[] = $row->nid;
  }

  // Delete all the nodes at once
  node_delete_multiple($nids);
  // Loop over each of the fields defined by this module and delete
  // all instances of the field, their data, and the field itself.
  foreach (array_keys(_news_installed_fields()) as $field) {
    field_delete_field($field);
  }
  // Loop over any remaining field instances attached to the news
  // content type (such as the body field) and delete them individually.
  $instances = field_info_instances('node', 'news');
  foreach ($instances as $instance_name => $instance) {
    field_delete_instance($instance);
  }
  // Delete our content type
  node_type_delete('news');
  // Purge all field infromation
  field_purge_batch(1000);
}

```

# Answer
The following code should get you started. Got this here. I suggest you check there first in the future.

```
$myField_name = "my_new_field_name";
if(!field_info_field($myField_name)) // check if the field already exists.
{
    $field = array(
        'field_name'    => $myField_name,
        'type'          => 'image',
    );
    field_create_field($field);

    $field_instance = array(
        'field_name'    => $myField_name,
        'entity_type'   => 'node',
        'bundle'        => 'CONTENT_TYPE_NAME',
        'label'         => t('Select an image'),
        'description'   => t(''),
        'widget'        => array(
            'type'      => 'image_image',
            'weight'    => 10,
        ),
        'formatter'     => array(
            'label'     => t('label'),
            'format'    => 'image'
        ),
        'settings'      => array(
            'file_directory'        => 'photos', // save inside "public://photos"
            'max_filesize'          => '4M',
            'preview_image_style'   => 'thumbnail',
            'title_field'           => TRUE,
            'alt_field'             => FALSE,
        )
    );
    field_create_instance($field_instance);
    drupal_set_message("Field created successfully!");
}

```

You can execute this code countless ways. I am not privy to the requirements of your project so its hard for me to make a recommendation. You could hook this into the update/install functions, or you could build it into a page hook in a module, or you could just bootstrap any new php file in the root directory with this:

> require\_once DRUPAL\_ROOT . '/includes/bootstrap.inc'; drupal\_bootstrap(DRUPAL\_BOOTSTRAP\_FULL);

And you can also refer this.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: How can I get public files path in javascript files?
I want to display files present in the public folder(sites/default/files). So in the module file when I click on a link it will call to js function, How can I get all file names which are present in the public folder in js file.

# Answer
It depends where you are storing all your files, to use the base url of your site you need to do this:

```
$base_url."/sites/default/files/xxx.jpg"

```

If your files are inside some theme:

```
$base_url."/".drupal_get_path('theme', 'name_theme')."/images/xxx.png

```

If you are using files with **public://**, use this:

```
$uri = $your_file_name; // Example "public://xxx"
$path= file_create_url($uri);

```

I hope it works in your case
> 0 votes

---
Tags: 7, javascript, files
---


# Question
Title: How to show popup for save or view the file?
I am displaying file names as links on the page, when I click on particular link, it should ask the user that, save file or view file something like below image.

In my case this popup is not coming, directly the file content is displaying on browser. So how can I achieve this. Thanks for your any suggestions.

My code to display dynamic links as follow:

```
$uri = 'public://';
  $path= file_create_url($uri);

$data .= '<div class = "public-file-names"><a href="'.$path . $foldnames .'/'. $filenames.'">' ."--". $filenames .'</a><br></div>';

```

# Answer
> 1 votes
The browser you are using recognise the linked document format and try to show it directly. It is mainly true with images and PDF files.

If you want to force the browser to download the file (or to open it with a local application), as explain in this answer, you can use the HTML5 download attribute.

```
$uri = 'public://';
$path= file_create_url($uri);

$data .= '<div class = "public-file-names"><a href="'.$path . $foldnames .'/'. $filenames.'" download>' ."--". $filenames .'</a><br></div>';

```

---
Tags: 7, navigation, files
---


# Question
Title: View test result of BrowserTestBase based test?
How can I setup my Drupal config to be able to view the results of failed tests using the new BrowserTestBase class in 8.2.x?

I don't see any files generated and the phpunit.xml config does not seem to be getting respected:

```
<!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output -->
    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value="/var/www/testing" />

```

The command I am using is:

```
vendor/bin/phpunit -c core/phpunit.xml --group tvi

```

I have some failing tests but I can't see what the test sees.

# Answer
> 1 votes
Figured it out. Before calling parent::setUp(), I set:

```
$this->htmlOutputEnabled = true;

```

---
Tags: 8, testing
---


# Question
Title: How to import multi-value fields into profile2 using the Migrate module
I have users each with a profile using the profile2 module. I am using a cookbook based on the Migrate framework to create the users and import profile data.

Sample CSV data would be:

```
"member_nr","email","username","tel_1"
"1001","new.tester@example.com","new tester","00000 12345-213"

```

But one of the profile fields is a text list using the checkboxes / radio buttons widget. According to the GUI, the values are stored in the format key|label.

So the field has values:

```
soccer|soccer
weight lifting|weight lifting
boxing|boxing
tennis|tennis
cooking|cooking

```

So I am trying to import data similar to:

```
"member_nr","email","username","tel_1", "interests"
"1001","new.tester@example.com","new tester","00000 12345-213", "soccer, weight lifting, boxing, tennis, cooking"

```

However, when running the import, I get an error that says:

> SQLSTATE\[22001\]:String data, right truncated: 1406 data too long for column field\_interests' at row 1: INSERT INTO... \[the data from the CSV file\]

How should multi values be formatted in the CSV file to be accepted?

# Answer
Make sure you're mapping the field using the right separator, e.g.

```
$this->addFieldMapping('field_interests', 'interests')
     ->separator(',');

```

Then make sure you've the right length in the source field (`$this->map`) and your Drupal field support such lengths as well.

If this does not help, increase the length of the destination field by SQL, drush or `hook_update`.
> 0 votes

---
Tags: 7, users, migrations, importing-exporting
---


title: Authentication Services module

text:
# Question
Title: Authentication Services module
I use ***services*** with ***drupal 7***, here the ***services resources*** function :

```
function custom_api_services_resources()
{
    return [
        'res' => [
            'create' => [
                'callback' => 'custom_api_create_user',
                'access arguments' => array('administer access control'),
                'access arguments append' => FALSE,
                    'args' => [
                    [
                        'name' => 'data',
                        'type' => 'struct',
                        'description' => 'data',
                        'optional' => FALSE,
                        'source' => 'data'
                    ]
                ],
            ]
        ]
    ];
}

```

Here the ***node access*** function (empty) :

```
function custom_api_node_access($op, $data) {
}

```

For Authentication I use ***HTTP basic authentication*** and/or ***Session authentication***

I don't know what I have to do to limit access only for admin. I've tried a lot but never work with authentication.

I feel like it's very easy to use it, but I don't understand it.

I've already posted a message about this issue but differently. Can someone delete the first one, please ? How do I use the access arguments?

---

# Edit

## custom\_api.module file :

```
             'create' => [
                'callback' => 'custom_api_create_users',
                'access callback' => 'custom_api_access_callback',
                'access arguments' => array('administer create field_projects'),
                'access arguments append' => TRUE,
                'access callback file' => array(
                  'type' => 'inc',
                  'module' => 'support',
                  'name' => 'custom_api.resource',
                ),
                    'args' => [
                    [
                        'name' => 'data',
                        'type' => 'struct',
                        'description' => 'data',
                        'optional' => FALSE,
                        'source' => 'data'
                    ]
                ]

```

## custom\_api.resource.inc :

```
function custom_api_access_callback($permission) {
  return user_access($permission);
}

```

## Permission from Database, role\_permission table :

**Permission :** access comments **Module :** comment

**Permission :** access content **Module :** node

**Permission :** access news feeds **Module :** aggregator

**Permission :** access site map **Module :** site\_map

**Permission :** create field\_credits **Module :** field\_permissions

**Permission :** create field\_credit\_level\_1 **Module :** field\_permissions

**Permission :** create field\_credit\_level\_2 **Module :** field\_permissions

**Permission :** create field\_credit\_level\_3 **Module :** field\_permissions

**Permission :** create field\_level **Module :** field\_permissions

**Permission :** create field\_number\_of\_credit\_remove **Module :** field\_permissions

**Permission :** create field\_projects **Module :** field\_permissions

**Permission :** create field\_remove\_credit **Module :** field\_permissions

**Permission :** search content **Module :** search

**Permission :** subscribe to newsletters **Module :** simplenews

**Permission :** use advanced search **Module :** search

**Permission :** use custom search **Module :** custom\_search

**Permission :** use custom search blocks **Module :** custom\_search\_blocks

**Permission :** use text format guestbook\_txt **Module :** filter

**Permission :** access comments **Module :** comment

**Permission :** access content **Module :** node

**Permission :** access news feeds **Module :** aggregator

**Permission :** access site map **Module :** site\_map

**Permission :** administer custom search **Module :** custom\_search

**Permission :** administer custom search blocks **Module :** custom\_search\_blocks

**Permission :** administer search **Module :** search

---

I have link to add data (client and node : *project and client*) in drupal website. Only administrators can add data.

# Answer
Drupal Services is a bit strange in that it doesn't seem to fall back to calling the `user_access()` function. Instead, I always provide a custom `access callback` function, and in it usually just make a call to `user_access()`. Try this:

```
'doli' => [
        'create' => [
            'callback' => 'custom_api_create_user',
            'access callback' => 'example_access_callback',
            'access arguments' => array('administer access control'),
            'access arguments append' => TRUE,
            'access callback file' => array(
              'type' => 'inc',
              'module' => 'example',
              'name' => 'example.resource',
            ),
                'args' => [
                [
                    'name' => 'data',
                    'type' => 'struct',
                    'description' => 'data',
                    'optional' => FALSE,
                    'source' => 'data'
                ]
            ],
        ]
    ]

```

Then make a file called `example.resource.inc` in your module's folder, and place this code into it:

```
function example_access_callback($permission) {
  return user_access($permission);
}

```
> 0 votes

---
Tags: 7, services
---


# Question
Title: Startup Growth Lite - How To Set Width For Content Type
I'm using the theme Startup Growth Lite for which we've created a content type but I can't find how/where to set it's default width. We want it to be the same width as the 'Basic Page' but for some some reason our content type is always much narrower as if it's expecting left & right sidebar content (I've checked the blocks and there are none assigned).

Pulling my hair out on this one!

Thanks

# Answer
> 0 votes
Typical, minutes after posting the question I finally found the answer.

What has worked for me was adding my content type to the template.php file startupgrowth\_lite\_preprocess\_page function, our content type was called 'client\_work' which once added set it to display the same as the 'page' content type.

I added the following

```
&& $variables['node']->type != 'client_work'

```

to the end of the first *if* statement in the function below (around line 494).

```
function startupgrowth_lite_preprocess_page(&$variables) {

    /**
     * Insert variables into the page template.
     */
    if (isset($variables['node']) && $variables['node']->type != 'page' && $variables['node']->type != 'client_work') {

```

---
Tags: 7, theming
---


# Question
Title: How to check if Drupal user is logged in via htaccess?
Is there a specific cookie Drupal uses to determine if a user is logged in or anonymous?

I need to check the cookie, and create a rewrite condition based on whether or not the user is logged in.

In the end, I would like something like this:

```
RewriteCond %{HTTP_COOKIE} !drupaluser=1 [NC]
RewriteRule ^(.*)$ /$1?no-cookies-for-you=%1 [R,QSA,L]

```

Thanks.

# Answer
> 2 votes
Drupal does store the session value in the cookie variable after the user is logged in. However, the name of this cookie is not fixed. It is basically a string that comes from the value returned by PHP function session\_name; and starts with `SESS`. It would be hard to find and I would not recommend using regex, as I personally don't like it much.

If you really want to implement a solution with the cookie, I would suggest the following:

1. Implement hook\_user\_login() in a custom module:

```
function MODULE_user_login() {
  // set a new cookie here, with static name and value.
}

```
2. Implement hook\_user\_logout() and delete the cookie by setting an expiry date of past.

You can now use this cookie in your .htaccess!

---
Tags: .htaccess
---


# Question
Title: How do I alter the complete url, not just the path, of nodes?
When a node's field "External URL" is filled, I want the URL of this node to be that field's value wherever it is rendered/ teasered.

Writing my own service and class using (implementing) `InboundPathProcessorInterface` and `OutboundPathProcessorInterface` I can only alter the *path*, but the base url still gets prepended.

So, whats the correct way?

I thought maybe extending the entity and extending the `toURL()` function might be the trick, but that seems like a lot of work for a simple feature, does it not?

Edit: I know I can just setup redirects, but for the sake of completeness I'd like to know.

# Answer
> 2 votes
InboundPathProcessorInterface can't do it, that's an incoming request, it has no way of redirecting to another site, because that's what you have to do.

Implement something similar to redirect.module: a request subscriber that sets a redirect response.

For outbound processing, that definitely works, but you have to set the right options. Have a look at how `\Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl::processOutbound()` sets the language domain.

---
Tags: 8, path-aliases
---


title: Where is the "auto submit" option?

text:
# Question
Title: Where is the "auto submit" option?
I have an exposed filter for one of my views and I added a drop-down select for the users to pick from.

In Views for Drupal 7 there was an Auto-Submit check box, but I can not seem to find it in Drupal 8 at all. Does anyone know where it may be hiding or how I can get the filter to auto-submit.

# Answer
While tracking the above issue is good for long-term success... if you need this functionality ASAP, here's a tiny bit of a hack to get it working with some custom javascript. Inside your theme's JS, add something like the following:

```
// Autosubmit 'view-class-here' views exposed form.
$("div.view-class-here").find("form.views-exposed-form").find("select").bind("change", function () {
  $(this).closest("form").trigger("submit");
}).end().find("input[type='submit']").addClass("visually-hidden");

```

This will do the following:

1. Look at any `select` item in a given views exposed form (for a view with a class `.view-class-here`), and trigger a submit whenever the select list is changed.
2. Hide the 'Submit'/'Apply' button associated with the exposed form.

If you want to trigger the submit on `input` fields, change the `.bind()` to use something like `input:checkbox` or `input` for any kind of input (though that might need more tweaking to make sure things don't go crazy!).
> 5 votes

# Answer
This functionality is currently in flux, and may eventually be moved to CTools, Core, or a small module. Track issue https://www.drupal.org/node/2475595 for updates.
> 2 votes

---
Tags: views, 8
---


# Question
Title: How do I get a freshly updated value (i.e. not the cached value) using entity_metadata_wrapper?
In my code I am inserting a new value into the database directly using db\_insert (i.e. inserting an entirely new row). The type of field, however, already exists in Drupal which is called "field\_data\_field\_email\_address". Previous to the insert call no value existed in the database which is associated with an entity.

Later in code I am relying on entity\_metadata\_wrapper to retrieve the values associated with the entity. The problem is that the wrapper doesn't retrieve the most recently inserted value but instead returns nothing. Yet when I look in the database table I can clearly see the existence of the newly inserted value.

As you may have already guessed I narrowed the issue down to a caching issue because if I clear the Drupal cache the wrapper returns the newly created value just fine.

My question is this: How can I force the entity\_metadata\_wrapper call to not retrieve the cached version but refresh and return to me the actual current values that exist in the database. I need my wrapper to represent the freshest data and not the cached version.

Thank you in advance!

# Answer
> 2 votes
The cache can actually be cleared using the entity\_load function and passing a value of true for $reset which will clear the cache and update future references to it including wrappers retrieved from entity\_metadata\_wrapper:

```
entity_load("node", array($nid), null, true);

```

# Answer
> 0 votes
For nodes, I found this snippet on hook\_node insert helpful:

`entity_get_controller('node')->resetCache(array($w->getIdentifier()));`

---
Tags: entities, caching
---


# Question
Title: How can I execute a custom code on node edit/add page during hook_page_build?
I'm seeking to show an extra form on node edit/add page. My function is this:

```
function mymodule_page_build(&$page) {
  $node = menu_get_object();
  if($node && $node->type == "object") {
    $page['page_bottom'][] = drupal_get_form('mymodule_form');

```

How can I check that current page is node edit/add page with a specific type like `object`?

# Answer
The `request_path()` function can lookup the current path to determine what page is being rendered.

```
  if (request_path() == 'node/add/object') {
    // @TODO: Add code
  }
  else if (preg_match('/node\/\d+\/edit/', request_path())) {
    $node = menu_get_object();
    if ($node->type == 'object') {
      // @TODO: Add code for editing node
    }
  }

```
> 1 votes

---
Tags: 7, hooks
---


# Question
Title: form submit hook handler not getting called in drupal
I have `Drupal 7` site. It has custom module named say `myproducts`. This module has following hook

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

if(isset($form_id) && $form_id=='product_node_form')
{
   $form['#submit'][] = 'myform_form_submit';
}

}

function myform_form_submit(){
 echo 'test submit handler'; exit();
 }

```

### But \`myform\_form\_submit\` is not getting called.

Any help highly appreciated.

# Answer
The submit for the node form is attached to a specific button, so something like this should work:

```
$form['actions']['submit']['#submit'][] = 'myform_form_submit';

```
> 1 votes

---
Tags: 7, forms, hooks
---


# Question
Title: Field values added programmatically dispear after a certain time
I created a module that creates a block to show a schedule information. I need taxonomy terms to configure the block. I want that those terms are filled with preconfigured values when I install the module.

I have in my config/install folder the definition of my taxonomy:

```
core.entity_form_display.taxonomy_term.schedule_channels.default.yml
core.entity_view_display.taxonomy_term.schedule_channels.default.yml
field.field.taxonomy_term.schedule_channels.field_channel_id.yml
field.storage.taxonomy_term.field_channel_id.yml
taxonomy.vocabulary.schedule_channels.yml

```

Here the content of the file field.storage.taxonomy\_term.field\_channel\_id.yml:

```
langcode: en
status: true
dependencies:
  module:
    - taxonomy
id: taxonomy_term.field_channel_id
field_name: field_channel_id
entity_type: taxonomy_term
type: string
settings:
  max_length: 50
  is_ascii: false
  case_sensitive: false
module: core
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

```

Also in my schedule\_block.install I have:

```
class schedule_block_class{

  const schedule_block_channels_terms = array(
    array(
      'name' => 'Brava',
      'field_channel_id' => 'BRA001'
    ),
    array(
      'name' => 'DJazz',
      'field_channel_id' => 'DJA001'
    ));
  const schedule_block_channels_vid = 'schedule_channels';
}

function schedule_block_install(){
  $schedule_block_terms = schedule_block_class::schedule_block_channels_terms;
  $schedule_block_vid = schedule_block_class::schedule_block_channels_vid;
  foreach($schedule_block_terms as $schedule_block_term){
    $term = Term::create(array(
      'name' => $schedule_block_term['name'],
      'field_channel_id' => $schedule_block_term['field_channel_id'],
      'description' => '',
      'parent' => array(0),
      'vid' => $schedule_block_vid
    ));
    $term->save();
  }
}

function schedule_block_uninstall(){

  $schedule_block_terms = schedule_block_class::schedule_block_channels_terms;
  $schedule_block_vid = schedule_block_class::schedule_block_channels_vid;
  $terms = array();
  foreach($schedule_block_terms as $schedule_block_term){
    if($terms_name = taxonomy_term_load_multiple_by_name($schedule_block_term['name'], $schedule_block_vid)){
      $terms = array_merge($terms, $terms_name);
    }
  }
  foreach($terms as $term){
    $term->delete();
  }
  $taxo = \Drupal\taxonomy\Entity\Vocabulary::load(schedule_block_class::schedule_block_channels_vid);
  if(!is_null($taxo)){
    $taxo->delete();
  }
}

```

When I install my module, my taxonomy vocabulary is created and my terms are loaded with my values

... BUT ...

After about 24h the values have disappeared. Checking in the table taxonomy\_term\__field\_channel\_id confirms that there is no more any values. I still have my taxo vocab, and all the needed tables are present.

Why the values are not permanent?

# Answer
(Re comments)

That's the reason then. Those fields being in state, which means drupal thinks they were deleted and is trying to delete conent in them.

Remove them from there. Probably OK to drop the whole rows, check all the other fields in there. You might have some deleted field tables that you need to clean up manually.

I've seen someone else have this problem, what we couldn't figure out is how it happened. Please open a core issue (probably critical) and try to describe what you did.. delete fields, config import, create through manual config import. Anything you can think of that might have caused this.
> 0 votes

---
Tags: entities, taxonomy-terms, installation, 8
---


# Question
Title: Why does my 'UUID, Webform, Node' Feature remain overridden?
The Feature I have created is stuck in the "Overridden" state. (I have also deployed the Prod Environment's database to the Dev Environment's database to ensure that everything was in sync during this test).

I am using Drupal 7 and am using the following modules in this situation:

* Webform
* Context
* UUID
* Features
* UUI Features

Here are the additional dependencies:

Under "Configuration \> Content Authoring \> UUID Features Integration", I have selected the "Webform" Content Type as one of the "Exportable Node bundles" and "Files exported for Node bundles" on both my Prod and Dev environment.

When viewing the overridden page, the only component that is stuck in the "Overridden" state is the "Content" section (with the UUID of the two nodes listed):

When clicking "Revert components", it actually does revert the two nodes listed back to the state in the features. (Tested it by modifying the nodes and then clicking "Revert components" to see it revert back.

Despite that, it remains in the "Overridden" state.

In this particular situation, why does this remain Overridden?

# Answer
> 2 votes
FWIW, features should only be used to export configuration, and not content. I have audited a site which used UUID features and was not able to find a solution for reverting it. Exporting content (nodes, taxonomy terms, etc.) also makes the feature heavy.

Some things which you could do to :

**Have multiple instances:** (approach 1)

1. Dev : continuous deployment happens here. E.g. After every commit or pull/merge request.
2. Stage : Intermediate deployment; maybe after some feature is done completely. Think of this as a release. Or at every sprint end. When the code deployment happens. Database from the production instance is copied to this instance. So, that the testing can happen on live data.
3. Live : Sometimes called production instance. Data is only created here. Deployment to this instance happens very infrequently.

These are all servers located on internet. Then, each of the developers have their own "local" site setup. Database from the live site should be used to test new features being developed (or bug fixes). This will ensure more accurate results, as testing happens on latest content.
**Note:** You can use features in this case **only to export configuration**.
If you do not want direct addition of content to live environment, try modules like Workflow, Workbench, or Workbench Moderation; which enables you to empower checking of content before the actual publish happens.

**Important note:** If you are using live database make sure you sanitize it. drush sql-san commands can come in handy.

**Use Deploy module:** (approach 2)

> The Deploy module is designed to allow users to easily stage and preview content for a Drupal site. Deploy automatically manages dependencies between entities (like node references). It is designed to have a rich API which can be easily extended to be used in a variety of content staging situations.

Using this module, you can create content on one environment and push it to others. It is pretty easy to setup, with extensive documentation available.

In a nutshell -\> **KEEP "CONFIGURATION" AND "CONTENT" SEPARATE TO MAKE YOUR LIFE EASY!**

# Answer
> 1 votes
In general I agree with @AjitS - content probably should not go in a feature.

But to answer your actual question - sometimes Features just gets stuck as overridden even if everything actually matches. There is a good series of troubleshooting steps to clean it up, see here: https://www.drupal.org/node/986932

I would suggest: 1. Make sure you have Diff module, then you can click on "overridden" and see if there are any differences you missed between your module and the feature. 2. Disable and re-enable the Feature 3. Try the other steps if those don't work.

---
Tags: 7, webforms, features, entities
---


# Question
Title: How to hide a field group fieldset programmatically in drupal 8?
I have a Field Group fieldset named **`group_p_payment`** as machine name. I want to hide this based on the user. I tried the following code:

```
        $user = \Drupal::currentUser()->getRoles();
        if(!in_array("Administrator", $user) ||  !in_array("administer", $user)) {
         $form['group_p_payment']['#access'] = FALSE;
        }

```

But it didn't work it. How can I hide the fieldset?

# Answer
The field group module is no longer storing grouped fields as a fieldset in Drupal 8. It's storing metadata on each group in an array called `#fieldgroups` which is used in a pre-render function.

The logic of the module doesn't render the fieldset if all its children elements aren't visible. Hence, you can hide all the children elements to have the same effect. For example:

```
foreach ($form['#fieldgroups']['group_p_payment']->children as $form_element_id) {
  $form[$form_element_id]['#access'] = FALSE;
}

```

The logic will have to change if you have nested groups, but the approach will remain the same.

Note that the above code can go in a form alter, but you should ensure that your form alter runs after Field Group does its work.

Here is complete working code, for a module named example in the `example.module` file:

```
/**
 * Implements hook_module_implements_alter().
 */
function example_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter' && isset($implementations['example'])) {
    $hook_implementation = $implementations['example'];
    unset($implementations['example']);
    $implementations['example'] = $hook_implementation;
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form.
 */
function example_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  foreach ($form['#fieldgroups']['group_b_payment']->children as $form_element_id) {
    $form[$form_element_id]['#access'] = FALSE;
  }
}

```
> 8 votes

---
Tags: 8, users, entities
---


# Question
Title: How to create a basic message - notifications system displaying a real time message counter badge?
I'm looking for a way to create a basic current user notifications system for my site, e.g.:

* "some user" has created a new "group"
* "some user" has joined your "group"
* "some user" has posted a node in your "group"
* "some user" has written a "review" for your "article"
* "some user" has commented your "review"
* etc...

I imagine this system as a simple menu link with a counter badge attached to it showing the number of new unread notifications just like this site or linkedin.com site.

When clicking upon this link current user will be directed to a page showing the user's new notifications and the counter will be then set to 0.

I believe what I need is the Heartbeat or Message module, combined maybe with Menu badges. But I'm not sure what to choose and how to start. Any advice?

# Answer
> 3 votes
For real time messages, you will need the Node.js integration module. You can use Heartbeat, the Taskbar and the Message modules together to show notifications.

# Answer
> 3 votes
# Part 1 - Messages module

Use the Message module to create "Messages" for each of the message types (bullets) in your question, similar to what is detailed in the answer to "How to get notifications in a new window when using the Mentions module?".

The Message module uses so called "Message types" (which you have to configure within admin). It seems that you should just create 1 such Message type for each of the variations of messages in your question.

# Part 2 - Make messages manageable

The Message module is great, but it doesn't really come with some UI where each user can manage (view, mark read, etc) their messages. That why you may want to also perform the steps explained in "How to allow users to manage their own Message Stack messages?", which can be summarized like so:

1. Create a flag (using the the Flag module).
2. Create a view 'Messages by user'.
3. Use Rules to flag/unflag messages.
4. Trigger the Rules Component to mark messages (using the VBO module).
5. Create notifications about Unread Messages (using the "Menu Badges" module, further detailed below).

# Part 3 - Menu Badges module

The Menu Badges module is all you need to add such notifications, which you can add to any **menu item** and/or **menu tab** of your choice.

Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)
>
> ### Adding Badges to Menus
>
> Once enabled, go to `Administration > Structure > Menus`, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
>
> ### Adding Badges to Tabs
>
> For adding badges to menu tabs, there is a tab under `Administration > Structure > Menus` called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
>
> ### Badge Types
>
> The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".

However, there is a small caveat: if you really want the actual number (shown in the red circle) to be accurate, make sure you have some field in your view that will actually correspond to the "new" part of your question. To better explain this: have a look at the "`tracker`" view (disabled by default), which has the fields "***Content:Has new content***" and "***Content:Has new comments***". Those are 2 perfect fields to use if you want to use Menu Badges to get notified whenever there is new content, or new comments.

### Video tutorials:

---
Tags: 7, notifications
---


# Question
Title: Add fields to entityform, when it's created
Is that possible that I set default fields for entityform types when it's created? There will be site admin users. They will create registration forms for events, but there are 2 mandatory fields that they forget about sometimes, but they have to add it, because it breaks a few modules. Like voucher code and the email fields. Also, they sometimes recreate a field with different names. Like they add a new email field, with the name "field\_email" address, but the field I'm checking is the "field\_email\_address". I want to add these fields to the form programmatically, right after the site admin clicks the "Save entityform type" button, but only when he creates it first. Is it possible to add a field programmatically to an entityform? And if it is, then how? Thanks in advance!

# Answer
Yes it's possible here's the steps on how to achieve that functionality.

1. First you need to alter the entityform and add your custom submit handler

Example:

```
/**
 * Implement hook_form_alter().
 */
function example_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'entityform_type_form') {
    $form['#submit'][] = 'add_new_fields';
  }
}

```

2. Create your custom submit handler, you need field\_create\_field(), field\_create\_instance() in creating your field, define all the details of your field inside the $field and $instance array

```
/**
 * Submit callback adding custom field when saved entityform type.
 */
function add_new_fields($form, &$form_state) {
  // Create email address field.
  if(!field_info_field('field_email_address')) {
    // Create your new field.
    $field = array(
      'field_name' => 'field_email_address',
      'type' => 'text',
    );

    field_create_field($field);

    // Create field instance.
    $instance = array(
      'field_name' => 'field_email_address',
      'entity_type' => 'entityform',
      'bundle' => $form_state['values']['type'],
      'label' => 'Email address',
      'settings' => array(
        'entityform_type_form' => 1,
      ),
      'widget' => array(
        'type' => 'textfield',
      ),
    );

    field_create_instance($instance);
  }
   // Create voucher code field.
  if(!field_info_field('field_voucher_code')) {
    // Create your new field.
    $field = array(
      'field_name' => 'field_voucher_code',
      'type' => 'text',
    );

    field_create_field($field);

    // Create field instance.
    $instance = array(
      'field_name' => 'field_voucher_code',
      'entity_type' => 'entityform',
      'bundle' => $form_state['values']['type'],
      'label' => 'Voucher code',
      'settings' => array(
        'entityform_type_form' => 1,
      ),
      'widget' => array(
        'type' => 'textfield',
      ),
    );

    field_create_instance($instance);
  }
}

```

Here's the link of working custom module that i created https://github.com/umandalroald/entityform-custom-callback
> 3 votes

---
Tags: 7, entities
---


# Question
Title: Why are two url aliases being generated for some users?
I have a site under development, that is a migration from an different cms via the Migrate module. I noticed that the links for a lot of my user profiles are not `staff/lastname-firstname` as I set in the pathauto settings, but `/firstname-lastname`.

Looking in the `url_alias` table I see one alias for `staff/lastname-firstname` (pid 1644030) and another one (pid 1644031) for `firstname-lastname`. I point out the pids just because it appears that they are probably being created one after the other. They are both marked as language undefined, most likely due to the neutral path module. I suspect that one of the aliases was originally meant to be for English and the second for Japanese, but there is no setting in pathauto for different language paths for users. I can try disabling the neutral path module and rerunning my migration to confirm that they were each meant for different languages, but how can I fix it? I do not need a `/firstname-lastname` path in the system. I only want `/staff/lastname-firstname` to be generated.

# Answer
Then first go to `/admin/config/search/path/delete_bulk` and delete the aliases in question.

Disable Pathauto for the migration process.

Once your site has been migrated, then enable pathauto and do a bulk update `/admin/config/search/path/update_bulk`
> 1 votes

---
Tags: 7, i18n-l10n, migrations, path-aliases
---


title: I can't import images

text:
# Question
Title: I can't import images
I'm using the Feeds and Feeds XML XPath Parser modules on Drupal 7. While there is no problem importing all other fields (Title, body, etc.), it does not populate the image field in my nodes.

Feeds debug mode shows all paths to be relative, so I'm using Feeds Tamper to rewrite the relative paths to absolute paths (all on the same domain). Still, no images are being saved.

There are no errors displayed on the import page, nor in Drupal logs.

**UPDATE: After some more altering the image paths via Feeds Tamper, now the following error is shown in the logs: Invalid enclosure ""**

Where should I start debugging this?

Thanks!

# Answer
I had a similar issue while using Feeds, Feeds XLS and Feeds Tamper. I solved it by copying the images in the path mentioned before importing using Feeds.

I am not sure but I think you should first run a script that copies the images onto the path mentioned in the Image field and then import nodes using Feeds.

For example, if your path to images is 'sites/default/files/myimages', you should first copy the images to 'myimages' folder and then run Feeds because Feeds/Feeds Tamper simply populate the file path AFAIK. These modules do not actually save the images.

Let me know if this helps.

Regards,

Supriya Rajgopal
> 1 votes

---
Tags: 7, feeds, debugging
---


title: Change table class in view block

text:
# Question
Title: Change table class in view block
Is it possible to change the table class when using drupal's format table for view. It seems to allow me to only change the row class.

# Answer
go to `core\themes\stable\templates\views` folder and copy views-view-table.html.twig or .tpl.php (depending if you are on Drupal 8 or 7)

copy the file and re-name it **views-view-table--\[view-name\]--\[machine-name\].html.twig** or **.tpl.php**

Then edit the file and add the class

**If Drupal 8**

```
{%
  set classes = [
    'cols-' ~ header|length,
    responsive ? 'responsive-enabled',
    sticky ? 'sticky-enabled',
    'my-custom-class',
  ]
%}
<table{{ attributes.addClass(classes) }}>

```

**If Drupal 7**

```
<table <?php if ($classes) { print 'class="'. $classes . ' . ' ' . 'my-custom-class"'; } ?><?php print $attributes; ?>>

```

Now place your template file in your theme's template folder.

Clear/flush the cache to see changes.
> 1 votes

---
Tags: views
---


# Question
Title: How to enable template while creating node
I want to enable different template for different node while creating node. for eg: I am creating blog1 node, then while creating blog1 node I should be able to choose template in drupal 7.

Please help to achieve these functionality

# Answer
Create a **node--\[content-type\].tpl.php** file.

Add select list field as new field to your content type.

Then in the template file you just check with an if statement.

If select list field = x then ...

. . . .

else if select list field = y then...

. . . .
> 1 votes

---
Tags: 7, theming
---