title: Menu with contextual links from view

text:
# Question
Title: Menu with contextual links from view
Each user, lets say performer has profile page (which is node, not default user page) which is visible and can be made once..
Band (for example "Cool Band") can create image gallery, video gallery, bio, concerts etc...
On registration each user has to enter unique profile name (field\_profile\_name, in our case Cool Band)

After registering, user picks band node and path is created as his main profile page with pathauto (sub-pathauto is installed too):
example.com/performer/\[node\_author\_field\_profile\_name\] = performer/cool-band

After saving the node he gets new role which can not make new nodes of this type, and link can not be changed.

Views contextual are setup to show different content made by user, resulting in paths:
example.com/performer/%/photo-gallery = performer/cool-band/photo-gallery example.com/performer/%/video-gallery = performer/cool-band/video-gallery example.com/performer/%/concerts = performer/cool-band/concerts

What i can not figure out is how to create sidebar menu block which will lead to those pages, so when site visitor lands on any bands page he can see sidebar with links to other part of bands pages. Sidebar menu should show link like this:

example.com/performer/cool-band/photo-gallery
example.com/performer/cool-band/video-gallery
example.com/performer/cool-band/concerts

I have tried to create view (users) with "overwrite this field as a link" and link is: performer/\[field\_profile\_name\]/photo-gallery etc., but i can not get the contextual right way.

# Answer
Considering your previous question and our conversation you left out quite some details ;)

The sidebar should appear on the band-page (and the child pages `photo-albums`, etc) only right?

* Create a Views block (type: content) with a contextual filter `Content: nid` and choose **Provide default**: `Content ID from URL`.
* Then under format make sure it is set to `fields` not to content.
* Add a field `Content: path` and hide it from display.
* Add a field `Global: textarea`, enable replacement tokens and use the path as a base path, so you enter all your urls like:

```
<a href="[path]/photo-gallery">Photo gallery</a>
<a href="[path]/video-gallery">Video gallery</a>
...

```

This should give you a list of links that all use the path alias of the band-page node, and then attach another path item to it.

The only thing you won't have is an active trail, so the active page will not be highlighted in the menu. I don't know how to achieve that.

And finally make sure to only display this block on band pages and direct child pages, otherwise you'll get some strange links. Since you are using Sub-pathauto all links should continue to work even if you are visiting a child page, as long as you don't use a stand alone node as child (in this case the path will resolve to that node page).
> 2 votes

---
Tags: 7, views
---


# Question
Title: How to add more than one tags for content?
For example, I want to create two tag, one is "new", the other is "test"，Now tags is "new test" Screenshot:

# Answer
> 1 votes
You already seem to have 1 field for this content type that is a term reference, whereas the corresponding taxonomy has at least 2 terms (i.e. "test" en "new").

**Solution 1**:

Allow "multiple" or "unlimited" values for the term reference you're already using, which is an option with the field settings of your existing term reference. Which you'll find at `/admin/structure/types/manage/mycontenttype/fields/field_term_ref`, assuming `field_term_ref` is the machine name of your term reference, and `mycontenttype` is the machine name of your content type.

**Solution 2**:

Create an additional term reference field for this content type, and add one of those 2 terms to the new field, and delete it from the term reference field you already have.

**Note**: Which solution to choose depends a bit on your use case:

* If the terms are somehow "related", then solution 1 is what you should use. E.g.: *Target audience* with terms like *visitors, members, editors, administrators*.
* If the terms are not at all "related", then go for solution 2. E.g. *Topic* and *Target audience*.

# Answer
> 0 votes
I know this is a bit old but the final and ultimate solution is simply setting the Widget type to Auto Complete in the widget setting

1. Set up number of values to unlimited in the field setting of the Taxonomy term/ tag of interest.
2. Then Use a comer to separate the tags as you in put them. eg Drupal, modules, etc.

---
Tags: taxonomy-terms
---


title: Pass Parameters to views via Ajax

text:
# Question
Title: Pass Parameters to views via Ajax
While viewing a views generated page, like for instance a taxonomy term page, is there a way to update the views generated content by passing it some parameters, like for instance a new taxonomy term.

The purpose of this would be to update a view page content via an ajax request.

Thanks

# Answer
> 4 votes
You can easily execute and render a view with arguments in a custom module.

I would:

1 - Set up some JS code to trigger an AJAX call to the server

2 - Use `hook_menu()` to define a custom menu callback on a specific URL, ie: `/views/ajax/view_name/view_display/view_arguments`

3 - Create your callback function()

4 - Load and render the view with arguments: (this is From Views 2 API):

```
$view = views_get_view('foobar');  // get the view named `foobar`
$view->set_display('page_1');  // Set the view display you want to use
$view->set_arguments(array($foo));  // Pass an array containing one or several variables you want to use as arguments in the view
$result = $view->render(); // Returns HTML

```

5 - Return your result in JSON (practical sometime if you want to pass more information than the view itself). You can use `drupal_json_output()` in D7.

# Answer
> 0 votes
Here is the javascript I ended up using to load the views block with ajax and pass in the contextual filter from the href value of a list of links I created on page. Hope this helps someone!

```
function getInfo(args) {

  $.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'post',
    data: {
      view_name: 'agent_lookup',
      view_display_id: 'agent_lookup_block', //your display id
      view_args: args,
    },
    dataType: 'json',
    success: function (response) {
        if (response[1] !== undefined) {
        var viewHtml = response[1].data;
        $('#ajax-target').html(viewHtml);
        //Drupal.attachBehaviors(); //check if you need this.
      }

    },
        error: function(data) {
         alert('An error occured!');
        }
  });
}

$('.ajax_button').once().click(function(e){
    e.preventDefault();
    var the_id = $(this).attr('href');
    noSlashes = the_id.replace(/\//g,'');
    getInfo(noSlashes);

});

```

---
Tags: 7, views, ajax
---


# Question
Title: Cannot bind delegate onClick event on .use-ajax elements
I have a view, that is refreshed with ajax. I'm using Jquery 1.7.2

You click a button, that call a javascript function :

```
$(view_identifier).trigger('RefreshView');

```

Before this refresh, I've attached on click handler to an ajax link. The link call a modal popup and must trigger a javascript function. The link contains a picture, but I have tested with just text and I get the same result. So I'm trying to attach an handler to an ajax link.

Here is the html :

```
<body>
 //lot of things ....
   <a class="use-ajax">
      <img width="25" height="25" src="/sites/default/files/picture.png">
   </a>
 //lot of things
</body>

```

And here is the javascript :

```
$('a.use-ajax > img').on('click',function(){
  console.log('test');
  foo();
});

```

That work fine, until the view is refreshed. After the refresh, the function foo isn't being called anymore. Thats because the handler is not being attached to dynamic elements.

So I change the part above to this :

```
$(document).on('click','img',function(){
  console.log('test');
  foo();
});

```

So that I can use the event delegation provide by Jquery.

And it isn't working. When I click on the link, nothing is happening. The strange part is when I remove the use-ajax on the link (become a normal link without the Drupal ajax part), it works.

I've tested a lot of variation and nothing seems to work.

I've used an old jquery code :

```
$(document).click(function(event){
   //check if its a click on the link with event
   console.log('test');
})

```

and It doesn't trigger either. If I click anywhere on the page, the 'test' show up in console, but not when I click an ajax link. I don't understand this because, it would mean that the link isn't in the dom.

Does anyone have an idea ?

# Answer
Thanks to Clive, I've found one way to make it work : wrap the code into a drupal behavior.

It look like this :

```
(function($) {
  Drupal.behaviors.refresh_views = {
    attach: function () {

        var view_identifier = '#view_id';

        //attach the on click handler to all links of class 'use-ajax'
        $('a.use-ajax').on('click',function(){
            $(view_identifier).trigger('RefreshView');
        });
    }
  };
})(jQuery);

```

I'm attaching an handler with my first version of the onclick function :

```
$('a.use-ajax').on('click',function(){
    foo();
});

```

So without the delegate part (does not work when an element is created after the script execution). In my case, I'm reloading the view with an ajax request. And in drupal 7, each time a request finishes the ajax behavior is called again. So the code is executed and it bind the on click event into the new elements.

I'm leaving a little warning here : This script is executed on every ajax request (if you open a modal popup in the ajax way, it will add an event into the click handler). So it might bind a lot of time the same event ! So don't forget to control the amount of events that your are adding to the same handler.
> 0 votes

---
Tags: 7, javascript, ajax
---


# Question
Title: Adding more Data to a Commerce Feed Upload
Currently I'm working on a Commerce Kickstart 2 storefront, to remake our company website in Drupal, a store front for selling Television Repair parts. I have a little HTML/CSS experience under my belt, but no real experience with Drupal outside of a couple tutorials. While I have figured out how to upload listings from the old website through tutorial videos and the Commerce Feed module, I could use a resource on how to add more information a CSV upload, more than a SKU, Name, Price, Image and a Description. Is it possible to add data to the CSV regarding Manufacturers, Part Number, intended TV Model, Condition of the part, and other useful information that users could sort and search for products with, or would any sorting and tagging have to be done after the objects are uploaded into the system? If there is a common method, where would be a good resource to start with to figure out what I need to do?

# Answer
> 0 votes
A Commerce feed fundamentally isn't any different to a regular feed so if you need additional data attached to your product you should be able to create the additional fields you need on your product type and in Feeds map the data from your CSV to the Product Type fields in Commerce.

With regards to sorting, wouldn't you be doing that in Views when you're actually displaying the imported products?

---
Tags: commerce, feeds, importing-exporting
---


# Question
Title: How to use autocomplete text field in fieldset?
I want to use a textbox with autocomplete features. I have gone through the drupal form API and found the solution at here.

It's working fine if I am using this directoly in the form fields. But it's not working if I am using this any ***Field collections*** item in profile2 fields.

I am using ***profile2*** fields with fieldscollection and following is my code.

```
/*profile_2_type is id for profile 2 module and it's not working for me*/
$form['profile_2_type']['field_test_auto_cmplete']['#autocomplete_path'] = 'user/autocomplete';

/*Here is the code which is working for me for node fields */
$form['title']['#autocomplete_path'] = 'user/autocomplete';

```

# Answer
finally got the solution here is updated code

```
$form['profile_2_type']['field_test_auto_cmplete']['und'][0]['value']['#autocomplete_path'] = 'user/autocomplete';

```

and "user/autocomplete" only works for admin users
> 2 votes

---
Tags: ajax
---


# Question
Title: How to use Services Basic Authentication?
How to use Services Basic Authentication module?

I want to add http basic auth for my service. I have installed it and enabled it on my end point configuration. I got this "HTTP basic authentication Services\_basic\_auth has no settings available" in my end point configuration. where is the setting page?

# Answer
> 11 votes
The module authenticates a web service call against drupal accounts.

1. Enable the module
2. Setup a drupal user
3. Make the web service call with the credentials of the user.

Note that with basic auth, the credential can be intercepted if SSL isn't used.

The module uses the standard PHP authentication headers and submits the standard drupal login form, without checking for any specific roles or permissions. So any drupal user will work.

Make a test web-service call with curl or wget to test it. There are also instructions in how to call with PHP in the call with curl stackoverflow answer.

# Answer
> 4 votes
Above module is used to authenticate services calls using Basic access authentication technique.. You will use your Drupal Username and password to authenticate services calls by adding Authorization header to service call as follows

When the user agent wants to send the server authentication credentials it may use the Authorization header.

The Authorization header is constructed as follows:

> Username and password are combined into a string "username:password"
>
> The resulting string literal is then encoded using the RFC2045-MIME variant of Base64, except not limited to 76 char/line The authorization method and a space i.e. "Basic " is then put before the encoded string.
>
> For example, if the user agent uses 'Aladdin' as the username and 'open sesame' as the password then the header is formed as follows:.
>
> Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

For Example below is the call using curl..

```
curl -H "Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" http://www.example.com/endpoint/yourservice

```

# Answer
> 2 votes
1. Once the module is enabled go to Structure \> Services
2. Select your **Endpoint** and click **Edit**
3. Use a tool such as https://addons.mozilla.org/fr/firefox/addon/restclient/ to test your client:

**Note:** I've been having problems with it as even though the option **HTTP basic authentication** was marked calling a resource of this endpoint was returning **200** instead of **401**. Is to say, the module failed to secure my endpoint.

The problem appears in:

```
https://www.drupal.org/project/services_basic_auth
version: 7.x-1.4

```

I solved it doing a patch for the module:

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

# Answer
> 1 votes
What's can be wrong: After set all settings:

1. enable services-basic-authentication module
2. create services api end-point, for example: get all nodes by
3. set "HTTP basic authentication" checkbox on the edit page
4. create a user

And noticed, that if you won't disable the "View published content" permission any user can has an access to service api end-point with returned result.

# Answer
> 0 votes
After installing the `Services Basic Authentication` module go to REST settings of Your server:

`/admin/structure/services`

Enter `Edit` option and at the bottom there is an an checkbox:

`HTTP basic authentication`

Enable it and hit Save button.

# Answer
> -1 votes
Don't forget to use content access module.

Adding additional details per MPD's request.

If you are not using the content access module then the user will see all the content including created by others which they were not supposed to see. For example, user A has stored personal data that user B is not supposed to see or wise versa. The Services Basic Authentication module enables the auth but doesn't enforce the content access. Content Access module enforces that. If you are not using the content access control then there is no point in authenticating a user.

---
Tags: 7, services
---


# Question
Title: How to hide webform block for users who submitted the form already?
I have created an inquiry form using the Webform module. I displayed it using block by enabling **Available as block** (`Form Settings -> Advanced Settings`) which is working fine and the form submitted by all (Anonymous, Authenticated user).

I want to add a visibility that if a user has already filled the form, the form should not be visible to that user until the site is close.

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

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

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you may have a possible solution for your question, provided you can think of an appropriate rule to be used for it. Using the Webform integration with Rules, you should be able to catch (=Rules Event) the submission of a form by a user. And combine this with some type of Rules Action so that the form is no longer visible to that user.

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".
> 2 votes

---
Tags: 7, blocks, webforms
---


# Question
Title: warning message after uprgraded to drupal 6.38
I upgraded drupal 6.2 to drupal 6.38 to apply the security patch to ignore the vulnerabilities as mentioned in https://www.drupal.org/drupal-6.38-release-notes .

But after updating to 6.38 when i checked the status report am getting the following result .

How could i resolve this ? is there need to install any additional modules to ignore this warning ?

**UPDATE**

After enabling the module i got this

# Answer
> 1 votes
`system_requirements` will raise this warning if the core Update status module is not installed.

To 'fix', enable the core Update status module.

---
Tags: 6, security, upgrading, version-control
---


# Question
Title: Returning the form in form_alter function
I have a doubt that is, can i use `return $form;` in `hook_form_alter` function. When i used some callback function inside the form, its not calling to that particular function. Thatsy i confused whether the form is returning or not.
i tried this thing but its not calling to custom\_form\_reset function

```
function cap_academy_contactus_form_alter(&$form, &$form_state, $form_id) {
       if ($form_id == 'webform_client_form_860'){
        $form['actions']['reset'] = array(
          '#type' => 'submit',
          '#value' => t('Reset fields'),
          '#submit' => array('contact_form_reset'),
          '#prefix' => '<div class="contactform">',
                '#suffix' => '</div>'
        );
        return $form;
      }
    }

    function contact_form_reset($form, &$form_state){
      $form_state['rebuild'] = FALSE;
    }

```

# Answer
You can use it, sure. But it won't do anything.

The `$form` is passed by reference, precisely so that it can be altered in-place. Core never does anything with the return value from form alters, so there isn't much point doing it.

Your code looks right, put a `drupal_set_message`/`dpm` in the submit handler to confirm whether it's actually being called or not, or whether it's your one-liner that's not doing what you're expecting.
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: How to get the users who did not submit articles?
Every day people are expected to post 1 node of content type "Article" on my site. If they missed to post such article, then I need to somehow produce a message "Your article is pending" to those users.

Additionally, I need to be able to check which date a user did not submitted such article.So how can I get all users who did not submit articles? And also filter them on which date they have missed the submission of an article node?

# Answer
> 0 votes
# Part 1 - Create an appropriate list of users

You could use an approach similar to my answer to "How to create a list of users who did not submit some webform?", i.e.:

1. Use the Flag module to introduce an article submission flag (similar to Step 1 in the above answer).
2. Register article submissions, using a Rules Event like "After saving content (of type article)", probably you don't need any special Rules Conditions.
3. List the users who have yes or no flagged "an" article with the flag from Step 1, using Views (similar to Step 3 in the above answer).

The above steps will allow you to create a list that is close to what you're looking for.

# Part 2 - Filtering the list

To also *filter them on which date they have missed the submission of an article node* (as in your question), you would need to further enhance the view created in step 3. For that, there are various ways to do so. One of the possibilities is to use the DataTables module, and use its on-the-fly-filtering facility. This facility becomes available after you enable the "search" widget (somewhere within the datatables settings for your view). Refer to my answer to "How to display the data of a View in table format?" for way more details about DataTables.

# Part 3 - Producing a message

To *produce a message "Your article is pending" to those users* (as in your question), you could enhance the view by adding the Views Bulk Operations (VBO) module to it, so that for the selected users you trigger a Rules Component which actually sends an appropriate eMail to those users. For an example of such rules component, refer to my answer to How to send an email notification when a subcription renewal is due? (within Step 2 of it).

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO.

---
Tags: 7, users
---


title: Uncaught TypeErrors have me baffled

text:
# Question
Title: Uncaught TypeErrors have me baffled
This is my first Drupal 8 site but I have been building Drupal sites since Drupal 6. I am getting lots of Uncaught TypeErrors in the JavaScript console that I can't figure out. I have spend hours searching and have not found an answer. What am I missing?

>

I am developing a custom theme. The site is on Mamp. Any insight would be helpful.

# Answer
> 0 votes
I think I found the answer. I believe the page.html.twig file I was using had a hidden character that was causing problems. I am using the same code in a new theme and everything is fine, but I had to type the code again instead of copying it. When I copied it, the errors returned. It helped to test each block of code at a time with code that I knew worked.

# Answer
> 1 votes
It seems like all js variables are missing, that are in:

```
<script type="application/json" data-drupal-selector="drupal-settings-json">{...}</script>

```

This json array is on every page drupal delivers. You can check this on a fresh drupal install.

There can be a problem with your theme, probably with the html template.

---
Tags: 8, javascript
---


# Question
Title: How can I display seveal menus with different classes
I have the "joy" to upgrade a Drupal 6 site to Durpal 8. In my Drupal 8 site I have three different menus, which each display different types of nodes. I want to display them in the region of the sidebar\_first, but each of them should have a different background colour. E.g. menu A is red, Menu B is blue and so on. This colour should be in the background if the menu is collapsed and expanded.

I tried it this way:

```
        {% if page.sidebar_first|render %}
            <div class="sidebar_first">
                <aside id="sidebar-first" class="column sidebar first">
                    {{ page.sidebar_first }}
                </aside>
                <aside id="sidebar-first-person" class="column sidebar first">
                    {{ menu-person }}
                </aside>
                <aside id="sidebar-first-kinder" class="column sidebar first">
                    {{ menu-kinder }}
                </aside>
                <aside id="sidebar-first-kunst" class="column sidebar first">
                    {{ menu-kunst }}
                </aside>
                <!-- /#sidebar-first -->
            </div>
        {% endif %}

```

But instead of displaying the menu I get a 0. So my guess is that I have to fill the twig placeholder with values somewhere first. Which would be the approach for this? Write a module? Including other Twig templates?

Here you can see the old Drupal 6 site, which I try to rebuild with Drupal 8. http://claudiazeppenfeld.de/kunst/fadenerzaehlungen-fuer-porzellan

In Drupal 6 I achieved this with Blocks and Context. I am not sure to solve that in Drupal 8.

# Answer
Why not just add each menus through block layout interface? visit `admin/structure/block`.

You will get unique id each.
> 0 votes

---
Tags: theming, blocks
---


# Question
Title: Field widget value not able to save via ajax
I am trying to create a custom field type widget with a ajax submit handler to save the value of the field to the database without saving the whole node.

Here is my code hook\_field\_field\_info().

```
function mymodule_field_info() {
  return array(
   'time_logger_time' => array(
   'label' => t('Time loger'),
   'description' => t('Custom Poutine Field'),
   'default_widget' => 'time_logger_time_widget',
   'default_formatter' => 'time_logger_default_formatter',
   ),
  );
 }

```

Than this is my hook\_field\_widget\_info()

```
function mymodule_field_widget_info() {
   return array(
   'time_logger_time_widget' => array(
   'label' => t('Default'),
   'field types' => array('time_logger_time'),
  ),
 );
}

```

And finally my hook\_field\_widget\_form() looks like

```
function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
    $value = isset($items[$delta]['id']) ? $items[$delta]['id'] : '';
     $element['id'] = array(
       '#type' => 'textfield',
       '#size' => 6,
       '#default_value' => $value
      );

     $element[submit] = array(
      '#type' => 'button',
      '#value'=>'Save',
      '#name' =>  'submit-'. $delta,
      '#ajax' => array(
        'callback' => 'mymodule_ajax_handler',
        'effect' => 'fade',
       ),
   );
   return $element;
 }

```

Idea is when I click the save button in my widget form it will call my ajax callback load the node, set the value of my field and save the node as follows-

```
function mymodule_ajax_handler( $form, &$form_state){
     $node = node_load(22);
     dsm( $node);
     $node_wrapper = entity_metadata_wrapper('node', $node);
     $node_wrapper->field_log->set(1);
     $node->save();
 }

```

But when I click button I am getting some error saying "Notice: Undefined index: field\_log in EntityStructureWrapper-\>getPropertyInfo() (line 334 of /var/www/html/mysite/sites/all/modules/contrib/entity/includes/entity.wrapper.inc)."

If I change my field in the ajax callback to some other field in my content type its saving fine. Like below-

```
function mymodule_ajax_handler( $form, &$form_state){
 $node = node_load(22);
 $node_wrapper = entity_metadata_wrapper('node', $node);
 $node_wrapper->some_other_field_from_my_content_type->set(1); //This works fine
 $node->save();
}

```

Is there anything wrong in my widget form.

Here is my field scheme if someone want to refer-

```
function mymodule_field_schema($field) {
$schema = array();
$schema['columns']['id'] = array(
    'type' => 'varchar',
    'length' => 50,
    'not null' => FALSE
);
  return $schema;
}

```

# Answer
> 0 votes
Finally I am able to do this with "property\_type" in my hook\_field\_info(). Posting it here hope someone will get some help someday.

Following is my updated hook\_field\_info -

```
function mymodule_field_info() {
  return array(
  'time_logger' => array(
  'label' => t('Time loger'),
  'description' => t('Field that keep track time loged on work items.'),
  'default_widget' => 'time_logger_time_default_wedget',
  'default_formatter' => 'time_logger_default_formatter',
  'property_type' => 'my_property_type',
  'property_callbacks' => array('my_property_info_callback'),
  ),
 );
}

```

Than my property type callback _

```
function time_logger_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
   $property = &$info[$entity_type]['bundles'][$instance['bundle']] ['properties'][$field['field_name']];
   $property['getter callback'] = 'entity_metadata_field_verbatim_get';
   $property['setter callback'] = 'entity_metadata_field_verbatim_set';
   unset($property['query callback']);
  $property['property info']['lid'] = array(
    'type' => 'text',
    'label' => t('Log id'),
    'setter callback' => 'entity_property_verbatim_set',
  );
  $property['property info']['total_loged_time'] = array(
    'type' => 'text',
    'label' => t('Total logged time.'),
    'setter callback' => 'entity_property_verbatim_set',
   );
}

```

Than finally my ajax callback is here\_

```
function time_logger_log_time( $form, &$form_state){
   global $user;
   $parents = $form_state['triggering_element']['#array_parents'];
   $values = $form_state['values'];
   $field_name = $parents[0];
   $language_code = $parents[1];
   $delta = $parents[2];
   $nid = $form_state['values']['nid'];
    $node_wrapper->$parents[0]->set(array('field1'=>'something','field2'=>'something'));
    $node_wrapper->save();
 }

```

Thanks to @Neograph734 for pointing me to the right direction.

# Answer
> 0 votes
There might be a few issues, but it hard to tell.

First make sure the field is actually on the node. (Source https://www.drupal.org/documentation/entity-metadata-wrappers):

```
function _wrapper_debug($w) {
  $values = array();
  foreach ($w->getPropertyInfo() as $key => $val) {
    $values[$key] = $w->$key->value();
  }
  return $values;
}

dpm(_wrapper_debug($some_wrapped_object));

```

If it is there, perhaps you made the field a multi value field (it can hold more then 1 value), in this case you need to assign it like this:

```
 $node_wrapper->field_log[]->set(1); // Note the extra []

```

If this does not solve the problem, have a look at the above metadata wrapper page. It comes with a lot of examples en explanations.

---
Tags: 7, entities
---


# Question
Title: Do I need to install Drupal using Drush in order to use Drush?
I installed Drush and then I installed Drupal using the regular installer/method.

When I type `drush cc all` on my terminal I get this message:

> No Drupal site found, only 'drush' cache was cleared.

# Answer
**No**, you do not need to install Drupal using Drush in order to use Drush. All you need is to make sure that while running `drush cc all`, you are in the Drupal directory.

For example, if your Drupal lies under `/var/www/Projects` with root name as `drupal` then first you need to move inside `/var/www/Projects/drupal` and then run the `drush cc all` command.

**The reason being, Drush can be executed inside a Drupal environment only.**
> 9 votes

# Answer
No, drush is independent of each drupal install. But you need to run the command from within the project root, or using a drush alias.

To test if drush is picking up your site properly, you can run

```
drush st

```

This will output information about your site, or will let you know if you are not within a site.

If you are connected, you should see database information like this:

```
 Database username               :  root
 Database name                   :  mydatebasename
 Drupal bootstrap                :  Successful

```

Then your cache clear will work with

```
drush cc all

```

If you run

```
drush st

```

from outside of a drupal project, it will not show the database information.
> 1 votes

---
Tags: drush
---


# Question
Title: How to display search results within the same Panels page
I have front page with exposed filters and search results block on it within panels. In my case search results are displayed on a map. When i specify something in filters and push "Search", i'm directed on search results page that has no panels and has path of front page's view. I want search results to stay within same panels as before i push "Search". How can i do it?

# Answer
> 1 votes
Do you use *Content pane* with Views? If so, under **Pane settings** make sure `Use Panel path: Yes`.

---
Tags: panels
---


# Question
Title: Referencing a paragraph field in a field--node template
I need to reference field\_role from a paragraph inside of a field--node template. The paragraph is an unlimited repeating field in the content type. The field template I am working with is the field in the content type which references the paragraph entity.

In the field template:

```
{% for item in items %}
  <li>
    <a href="#">{{ paragraph.field_role }}</a>
  </li>
{% endfor %}

```

I've tried {{ content.field\_role }} and {{ item.field\_role }} as well.

Separately, I've also tried creating a preprocess hook for the field.

```
function theme_preprocess_field(&$variables, $hook) {
  $paragraph = $variables['paragraph']->field_role->value;
  $variables['var_role'] = $paragraph;
}

```

```
function theme_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    if(isset($variables['elements']['field_role']['#items'][0]['value'])){
      $variables['var_role'] = $variables['elements']['field_role']['#items'][0]['value'];
    }
  }
}

```

(I know this would only pull the first item from the repeating field, but I'm just trying to get anything to render at this point.)

How can I achieve what I am trying to do?

# Answer
> 4 votes
I was able to solve this by using the following in the field template:

```
{% for item in items %}
  {{ item.content['#paragraph'].field_role.0.value|striptags }}
{% endfor %}

```

# Answer
> 1 votes
It's because you're operating a field, but not a paragraph entity. In the preprocess hook you can get specific paragraph field view, like this:

```
$paragraphField = $variables['paragraph']->get('field_role');
$variables['content']['field_role'] = $paragraphField->view();

```

Then render in field template:

```
{{ content.field_role }}

```

---
Tags: theming, entities, 8
---


# Question
Title: How to integrate messaging into a custom module?
I'm working on a custom module to handle time off requests for an intranet site and I'd like to be able to have the module fire off email notifications to a configurable list of users -- specifically, the requesting user's supervisor and also CC: an HR representative.

I've looked at Notify and Notifications and I assume that one or both of those expose an API but I can't find any documentation about how to integrate that into a custom module. I also looked at Rules, though I'm not sure that's the best solution.

I could always do a completely custom job but I'd hate to reinvent the wheel if there's a better Drupal-style solution like hooking into one of these existing notification modules.

# Answer
> 2 votes
Have a look at the Message Stack, these are the basic components and dependencies of it:

Some more details about the Message-related modules (=quotes are from the module's project page):

* Message:

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.
* Message Notify.

> This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
* Message Subscribe.

> With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.

If you'd rather look at an existing module as an example, then checkout the 7.x-4.x version of the Answers module (disclosure: I'm a co-maintainer) and its **Answers Notification** sub-module. This sub-module allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.

---
Tags: rules, emails, notifications
---


# Question
Title: Enable drupal_add_tabledrag on dynamically added rows
I have used `drupal_add_tabledrag` to get Drupals sorting feature for a table, however, I cannot find any function to add the dragging feature to `<tr>` dynamically added with JavaScript to this table.

Does anyone know function Drupal provides to do this, or how you are supposed to do it?

# Answer
> 1 votes
In case anyone else stumbles across this, because of how Drupal handles forms, rows should be added in an AJAX callback, and the table should be replaced with the newly themed table. There are plenty of examples of adding new fields to a form using ajax.

If for some reason you are using the tabledrag feature outside of the form API (I don't know why you would), here is a quick method I wrote to add a row to a table, and make it draggable if the table is:

```
(function($){
    $.fn.addTableRow = function(row){
        // We can use this later to see if the row has been added to the table yet
        var added = false;

        // Get the ID of the table
        var tid = $(this).attr('id');

        // See if the table is set as a tableDrag table
        if(typeof Drupal.tableDrag[tid] != 'undefined'){

            // initialize order variable
            var order = false;

            // Set some variables for easier access
            var tableDrag = Drupal.tableDrag[tid];
            var settings = tableDrag.tableSettings;

            // Loop through the classes in the settings for the table
            for(var aClass in settings){

                // Loop through the settings for the class
                for(var i in settings[aClass]){

                    // check which action the class uses, we could add the other actions
                    // here if we are worried about heirarchy or matching
                    switch(settings[aClass][i].action){
                        case 'order':

                            // if this class is used for ordering, assign it to order
                            order = aClass;
                            break;
                    }
                }
            }

            if(order){

                // find the max weight currently avaiable in the table
                var max = $(this).find('td.'+order).sort(function (a, b) {
                    return +a.value - +b.value;
                }).last().val();

                // Make sure the row has the draggable class
                row.addClass('draggable');

                // Add the row to the table, we don't do this earlier so that if
                // there is a value set in the weight field it is not included in the max
                // This could be done earlier, and setting the value could be ommitted
                // if you wanted to add the row to a specific locaiton in the table
                added = $(this).append(row);

                // Set the value of the order field to max+1
                $('.'+order, row).val(max+1);

                // Add the row so that tableDrag knows about it and can run it's
                // own hooks accordingly
                tableDrag.rowObject = new tableDrag.row(row);
                tableDrag.makeDraggable(row);
            }
        }

        // If the row wasn't added, order handling isn't used, just add it to the table.
        if(!added) $(this).append(row);
    }
})(jQuery);

```

Pretty straight forward usage:

```
var newRow = $('<tr class="tabledrag-root">'+
                '<td>Column 1</td>'+
                '<td>Column 2<input class="sort-order" type="hidden" value="1"/></td>'+
                '</tr>');

$('#my_table').addTableRow(newRow);

```

---
Tags: 7, javascript
---


# Question
Title: Display only selected term from content type in Views
maybe this is duplicate but I cant find solution and answer for this one, maybe its so basic buy I need little help about.

I have content type with: 1. Title 2. Body 3. Category (Category field is Vocabulary check box with two taxonomy terms called 1. Yes 2. No

So I have contents some are with selected yes and some one are selected with no, I want to create a view and display only with the selected (Yes) contents. Any idea how should I do it. Thank you for reading this.

# Answer
Under your Views,

Add *filter criteria* \> *Has taxonomy term* \> *apply*

**Vocabulary**: *your vocabulary in question* \> *Apply*

**Is one of**: *Yes* \> *Reduce duplicates* \> *Apply*

Save your Views.

HTH
> 0 votes

# Answer
1. Create a view with show ***Content*** of type your ***content type*** and continue and edit
2. Add a filter under ***Filter criteria*** select ***content : field*** (ie a taxonomy term reference field)
3. Select terms from vocabulary having yes value with operator ***Is one of***

**Result** : Content listed with terms tagged with yes
> 0 votes

---
Tags: views
---


# Question
Title: How can I extract and print specific field values from $page['content'] in page.tpl.php (vocabulary page)
I am trying to print some specific fields on a **vocabulary term page** in order to lay the page the way I want. `<?php print render($page['content']); ?>` prints the entire content but I want to extract specific values like `title`, `field_photo` etc. so that I can put them where and the way I want!

Here is an example how I want this to work:

I am creating a movie database website where each movie has casting associated with it. Each casting (actor or actress) is a vocabulary term. When I click on a term it takes me to a page (example URL: `http://localhost/moviedb/tags/kate-winslet`) where movies associated with that actor/actress are listed. The list is coming fine but I want to customize the look-n-feel of this page.

I overrode `page.tpl` with `page--vocabulary--tags.tpl.php`. Also I created a `template.php` file and written this function inside:

`function introduction_preprocess_page(&$vars) {
 $vars['temp_var'] = $vars['page']['content'];
}`

which is equivalent of using `$page['content']` directly inside `.tpl` file. I also used

`<pre><?php print var_export(get_defined_vars(),TRUE) ?></pre>` to get a the nested structure of `nodes` array. Based on that I tried to access a specific field like `<?php print render $temp_var['title'] ?>`, nothing is showing up.

I am definitely doing something wrong, but don't know where to check and what to change! I have started learning Drupal just a few weeks back.

**UPDATE**

I also tried the following code but no luck yet.

`function introduction_preprocess_page(&$variables) {
 if (arg(0) == 'node') {
 $variables['node_content'] =& $variables['page']['content']['system_main']['nodes'][arg(1)];
 }
}`

**INTRODUCTION is the name of my theme.**

In .tpl file I tried to access title the following way:

`if (isset($node_content) && $node_content['title']) {
 print render($node_content['title']);
}`

I have referred the following URLs:

https://www.drupal.org/node/2288941 and https://www.drupal.org/node/223430

Please help me understand what wrong I have done.

**EDIT (27.05.2016)**

I tried the solution but it did not work. By doing some trial and error I noticed that my `node--film.tpl.php` template is actually being used even on taxonomy page. In my application `film` is a content type I created and there is a field called "cast" which is eventually a vocabulary called "tags". I am putting names of actors by using this vocabulary when adding a "film" type content.

My intention was to show a list of films where an actor is associated when a tag (actor) is clicked. The functionality works OK but I don't understand why this page is also using `node--film.tpl.php` template file and not `taxonomy-term.tpl.php`. I copied `taxonomy-term.tpl.php` to my theme folder, took out the line which is rendering the content, cleared cached but nothing happened. But when I take out the same code snippet from my `node--film.tpl.php` file, the content disappears! Which confirms that `node--film.tpl.php` is the template being used!

I then renamed the file as `taxonomy-term--vocabulary-tags.tpl.php` just as a random test, but nothing changed either!

I am still unable to customize the look-n-feel and field display in my vocabulary page.

# Answer
> 0 votes
There are a few things here:

Taxonomy term pages are not nodes, and on a taxonomy term page you are going to have the following args:

* arg(0) ~ taxonomy
* arg(1) ~ term
* arg(2) ~ tid (taxonomy term ID)

To override term pages copy site\_root/modules/taxonomy/taxonomy-term.tpl.php into your theme templates folder to override all taxonomy term pages. You will also find really helpful instructions in that template file.

---
Tags: taxonomy-terms, theming
---


title: Where do I translate a string?

text:
# Question
Title: Where do I translate a string?
Where is the page in the administrative section where I can put the translations in Drupal 8?

# Answer
If you mean the "Interface Translation", it should be available under this URL =\> http://foo.bar/admin/config/regional/translate

If you clear the cache after activating the Interface Translation module, you could also see this option under "Configuration" \>\> "Regional and language" \>\> "User interface translation" menu
> 2 votes

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


# Question
Title: Drupal 8: Best practice to get nid in form_submit
I can get nid from within form\_submit by using one of those snipet:

```
$form_state->getFormObject()->getEntity()->id()

```

or

```
\Drupal::routeMatch()->getParameter('node')->id()

```

If feel this is a little bit overkilling... what is the best way?

# Answer
You're looking for `$node = $form_state->getFormObject()->getEntity()`.

Oh, saw that you actually mentioned that. This is the correct way to do it.
> 3 votes

---
Tags: 8
---


# Question
Title: How get Superfish to display on mobile device?
I installed the Superfish Module and Library and it works on a desktop/laptop/tablet. It collapses correctly when I re-size the screen. But it won't display at all on a mobile device. I tried different settings on the Config page and tried adding the recommended code in html.tpl.php: meta name="viewport" content="width=device-width, initial-scale=1.0" I enabled SF-Smallscreen with the jQuery sf-Smallscreen plugin. Made sure it was weighted to appear at the top of all the blocks. Still no luck.

# Answer
My bad, I discovered my .css for the page was HIDING Superfish. Removed the offending code and Superfish on mobile works fine.
> 0 votes

---
Tags: 7, navigation
---


# Question
Title: programmaticaly extract the shipping service name
Through following code in a custom sub module for commerce\_cybersource\_sawm I am able to pass shipping information to merchant like name, address, country

```
$shipping_address = $order_wrapper->commerce_customer_shipping->commerce_customer_address->value();
 if (!empty($shipping_address['first_name'])) {
    $form['ship_to_forename'] = array(
    '#type' => 'hidden',
    '#value' => $shipping_address['first_name'],
  );
}

```

I want to know how can we extract the shipping service name. Since I have Free Shipping and Standard Shipping which I want to pass to the merchant.

# Answer
> 0 votes
I am not a developer, just found a code sample from @googletorp on the link below. Just modified that and got the result.

https://www.drupal.org/node/1555994#comment-5963680

```
    foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    if ($line_item_wrapper->type->value() == 'shipping' ){
    $form['merchant_defined_data6'] = array(
    '#type' => 'hidden',
    '#value' => $line_item_wrapper->commerce_shipping_service->value(),
  );

  break;
  }
}

```

---
Tags: 7, commerce
---


# Question
Title: Parent theme hook is still being called when overwritten
I have a theme called **hasta**, and created a sub theme to customize certain aspects of it. One of the things I wanted to do is change the behavior of one of the hooks, **hook\_element\_info\_alter**. The hasta theme defines this as **hasta\_element\_info\_alter** in template.php.

My sub theme is called **hasta\_sub**, and in that template.php I have overwritten this hook as **hasta\_sub\_element\_info\_alter**.

I put some debug statements, and I can see that my new hook **hasta\_sub\_element\_info\_alter** is being called, but the parent theme hook, **hasta\_element\_info\_alter**, is still being called as well right before this.

Drupal helps says:

> Theme functions are called through theme('\[hook\]', $var, ...). When a sub-theme overrides a theme function, no other version of that theme function is called.

So according to this only the sub theme version of that hook should be getting called. Can anyone please tell me what I am doing wrong?

Thanks!

# Answer
Yes **theme functions** when overridden stay overridden in the sub-theme, but this is not a theme function, but rather a hook function used in a theme.

So hook\_element\_info\_alter() whenever it is implemented will run.
> 1 votes

---
Tags: theming
---


# Question
Title: What are some specific reasons NOT to share a users database table between sites?
I'm building a site for a client, and surprise! Turns out they're using a shared users table between multiple Drupal 7 sites (completely different code bases, different config, etc). I'm only supposed to be working on the one new site, but obviously this new wrinkle has me considering how these other sites will mess me up.

In my heart of hearts I know this is a terrible, very bad, no good idea. I don't want to launch a new site with this timebomb lurking under the hood. But I can only think of one scenario where things go hideously wrong. Deleting users could lead to major complications.

Other than that, what are specific scenarios that you have faced, or that you could think of arising when sharing a users table between Drupal sites?

# Answer
Almost any problem you see will be similar to content cache problems on a Drupal site.

The database represents your site's canonical state. Sharing a user table between 2 different sites means canonical user data reads/write can become invalid without each site knowing it, since they aren't coordinating their actions.

For example, Site A is doing a bulk operation (e.g. add Role X to all selected users) on users. It loads all users from a DB query into memory, changes a property on each user object, then executes a save to the DB. Meanwhile, Site B has a user who wants to update his email. He visits his user page, updates his email only to see it change back a few minutes later because Site A, still working through its bulk operation, has an old version of the user account and saved it *after he updated his email*.

Depending on the size of your site, just like with content caching, this invalid state problem might never show up. If Site A & B represent 2 different sub-sections (e.g. a blog site & commerce site) with users seldom using both, the scenario where the user state becoming invalid might never happen. But as your site grows (i.e. the number of user DB transactions) this invalid state problem will likely show up eventually.
> 2 votes

---
Tags: users, database
---


# Question
Title: Custom submit handler for theme settings form
I am creating a new D8 theme and having slideshow functionality in it. For slideshow, we have title, description and image field in the theme settings form. I am able to alter the theme setting form using `THEME_NAME_form_system_theme_settings_alter`, but when I add a custom submit handler the form seems to break and get internal server error.

My objective for adding custom submit is to make the uploaded files status as permanent.

Here is my code,

```
function THEME_NAME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // $form['#submit'][] = 'custom_settings_form_submit'; //tried this as well
  $form['actions']['submit']['#submit'][] = '_custom_settings_form_submit';
}

function _custom_settings_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $account = \Drupal::currentUser();
  $values = $form_state->getValues();
  for ($i = 0; $i <= SLIDESHOW_COUNT; $i++) {
    if (isset($values['slide_image_path' . $i]) && !empty($values['slide_image_path' . $i])) {
      // Load the file via file.fid.
      $file = file_load($values['slide_image_path' . $i][0]);
      // Change status to permanent.
      $file->setPermanent();
      $file->save();
      // $file_usage = \Drupal::service('file.usage');
      // $file_usage->add($file, 'user', 'user', $account->id());
    }
  }
}

```

NOTE: This is the error present in apache error log: `PHP Fatal error: Invalid placeholder (!message) in string: %type: !message in %function (line %line of %file). in /core/lib/Drupal/Component/Render/FormattableMarkup.php on line 240`

Does anyone have any idea where I'm doing it wrong? or is there any workaround for making the file status permanent?

# Answer
> 1 votes
From Drupal 8: Use Custom Submit Handler for Theme Settings Form:

Use this method to add custom submit handler for theme settings form in drupal 8.

```
/**
 * Implements hook_form_system_theme_settings_alter().
 */
function MY_THEME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $theme_file = drupal_get_path('theme', 'MY_THEME') . '/MY_THEME.theme';
  $build_info = $form_state->getBuildInfo();
  if (!in_array($theme_file, $build_info['files'])) {
    $build_info['files'][] = $theme_file;
  }
  $form_state->setBuildInfo($build_info);

  $form['#submit'][] = 'MY_THEME_form_system_theme_settings_submit';
}

function MY_THEME_form_system_theme_settings_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // TODO: Extra submssio logic.
  // This submit handler will be called before default submit handler for this form.
}

```

---
Tags: theming, 8
---


# Question
Title: Function not working in contextual filter
I have a function in my custom module that return the nids for drafts in array.

```
function get_all_drafts(){
    $query = db_query("select bid from kom_draft");
    $res = $query->fetchAll();
    foreach($res as $bid){
        $output[] = $bid->bid;
    }
    return $output;
}

```

and following code is used in contextual filter nid ( php code text area )

```
$nids = get_all_drafts();
return implode('+',$nids);

```

and checked the multiple value checkbox but its not working, i checked the query and there in not value to compare.

when i use the same code on tpl file i am getting proper output that is + separated nids.

# Answer
I just get it done by enabling validation criteria, I selected content validation with node content type and its working fine.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Adding a join in a Views field handler class constructor?
In a Views field handler, one can define additional fields to accompany the base field defined in hook\_field\_data. These field values are based on database columns on the same row, and they can be used in the render function. Somewhat like this:

```
my_views_field_handler extends views_handler_field {

  function construct() {
    parent::construct();
    $this->additional_fields['property2'] = 'property2';
  }

  function render($values) {
    return $this->get_value($values) . $this->get_value($values, 'property2');
  }

}

```

But is it also possible to define a join in the constructor? One of my database columns is an id of another entity. I have been using it somewhat like this, but this generates quite a lot of overhead (loading an entire entity for each row).

```
  function render($values) {
    $id = $this->get_value($values, 'property2');
    $entity = entity_load_single('my_type', $id);

    if ($entity->some_other_field == TRUE) {
      return $this->get_value($values);
    }
    else {
      return 'none';
    }
  }

```

So is there something like a join I can use in the constuctor, so I can query the other entity table directly instead of having to load the entity?

# Answer
Yes, but you need to have already defined that relationship in the view. Per the docs for `views_handler_field::add_additional_fields($fields)`:

> @param $fields
> An array of fields. The key is an identifier used to later find the field alias used. The value is either a string in which case it's assumed to be a field on this handler's table; or it's an array in the form of
> @code **array('table' =\> $tablename, 'field' =\> $fieldname)** @endcode

Thus, say you had a field handler for a field on the `node` table with a defined *author relationship* to the `users` table. You could do this:

```
  function construct() {
    parent::construct();
    $this->additional_fields['mail'] = array(
      'table' => 'users',
      'field' => 'mail',
    );
  }

```

Which would allow you to do this:

```
function render($values) {
  //Get the mail column from the users table.
  $this->get_value($values, 'mail');
}

```

For your case, you'll need to define the entity relationship to your base table before you can do this.
> 1 votes

---
Tags: 7, views
---


title: Logo is not displaying

text:
# Question
Title: Logo is not displaying
This is the code I used in Drupal 7.

```
            <a href="<?php print $base_path ?>" title="<?php print t('Home') ?>">
                <img src="<?php print $logo ?>" alt="<?php print t('Home') ?>" />
            </a>

```

This is the code I am using for Drupal 8.

```
           <a href="{{ base_path }}" title="{{ 'Home'|t }}">
    <span>{{ logopath }}</span>
                <img src="{{logo}}" alt="{{ 'Home'|t }}" alt="T.M. Patel International School"/>
            </a>

```

If I upload the logo, it doesn't display. What should I do now?

# Answer
This Link might be helpful : http://www.lohmeyer.rocks/blog/2015/01/14/00187-print-your-themes-logo-path-drupal-8-twig.

I think you should define the logo path variable first into `template.tpl` in `MyTheme_preprocess_page` function.

One More thing you are trying to use `{{logopath}}` in 'span' tag and into 'src' its `{{logo}}`.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Multiple Values in Custom Template Field
I have a custom template for a node, and a field which has the possibility of having multiple pieces of data. In this case:

* There is an Author node
* There are Publication nodes
* Publications are being Entity Referenced on the Author node

The custom template then prints the publications to the node

```
<?php print render($content['field_publications']); ?>

```

I know that adding `['1']` displays the first publication if multiple publications are attached to the same author, however, how would I display the top 5 publications, if say, there was 10 publications by the same author?

# Answer
Slice the array?

```
foreach(array_slice($content['field_publications'], 0, 5) as $field_publication):

```
> 0 votes

---
Tags: 7, theming, nodes
---


# Question
Title: Adding a loading indicator to form submission module
I have a custom module that is altering a webform to add custom submission handling using:

```
$form['#submit'][]='paymentComplete';

```

From the time the user clicks the submit button, until the paymentComplete() function completes it takes 2-3 seconds, but the user experience doesn't really indicate what is going on. How can I add some type of 'waiting indicator' that starts right BEFORE the request to execute paymentComplete()?

# Answer
AFAIK there are no OOTB features in Drupal yet but perhaps you can implement ProgressButtonStyles by Codrops. See https://github.com/codrops/ProgressButtonStyles for more info...
> 0 votes

---
Tags: webforms
---


# Question
Title: How to check if a user has any previous order?
I am working on Drupal Commerce site. Want to know if the customer is new or old. If customer has previously ordered any item from our website we can consider him old customer else if he is ordering first time he will be considered the new customer.

How can I get these values in a custom module?

# Answer
Try this method. commerce\_order\_load\_multiple will return order

```
function module_user_has_order() {
    $order = commerce_order_load_multiple(array(), array('uid' => 'user_id','status' => 'completed'));
  if(empty($order)) {
    //user has no previous order.
  }
  else {
    // user has previous order.
  }
}

```

Hope it works for you.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: How to include desktop css file only on desktop & mobile css file only on mobile?
I have two different css files in my theme, one for Desktop and other for Mobile version. I want to render Desktop css file only for desktop mode and Mobile css file only for mobile mode. Do I need to make any modification in .info of my Theme?

# Answer
> 1 votes
Yes, you can do this with media queries in your info file.

Change...

```
stylesheets[all][] = css/style.css

```

to...

```
stylesheets[all and (min-width: 960px)][] = css/style.css

```

That being said, you can repeat a lot of work doing it that way. It might be easier to declare all of your styles that you know will change in a responsive.css style sheet, and use

```
@media all and (min-width: 768px) { /* all of your styles here */ }

```

At the bottom to change the values for a mobile version.

---
Tags: theming
---


# Question
Title: Is it possible to avoid using Views PHP?
I have a number of values that I need to run a bit of logic on to get a value for a views math expression further down the chain. Im going to provide a much simpler example of what I am actually doing...

Variables set on custom module admin page...

* twoyr\_a = 5.4
* twoyr\_b = 12.4
* threeyr\_a = 5.6
* threeyr\_b = 12.7
* fouryr\_a = 5.8
* fouryr\_b = 13.3

**Contract term (Factor A) - Overidden with views-views-field--factor--a.tpl.php**

```
if ($output == '24') {
    print variable_get('twoyr_a');
} elseif ($output == '36') {
    print variable_get('threeyr_a');
} elseif ($output == '48') {
    print variable_get('fouryr_a');
} else {
    print '0';
}

```

**Contract term (Factor B) - Overidden with views-views-field--factor--b.tpl.php**

```
if ($output == '24') {
    print variable_get('twoyr_b');
} elseif ($output == '36') {
    print variable_get('threeyr_b');
} elseif ($output == '48') {
    print variable_get('fouryr_b');
} else {
    print '0';
}

```

**Views Global:Math Expression**

\[factor\_a\] + \[factor\_b\] = result

However, the result is always wrong. Instead of using the result from the PHP template, it is adding the Contract terms (24 + 24 = 48).

Im guessing this is because the math expression runs before the template files do.

So my question is, is there anyway to avoid using Views PHP for this? Or is there a fix for my current solution?

**Note**: `$output` is already defined in the database as 24, 36, or 48 in a "Contract Term" column. It relates to just a normal field in an ECK entity type called "Deal". It's an integer value to define the length of a contract for that deal. Each contract term has its own A and B factors to calculate my clients profit percentage when borrowing from a loan company.

# Answer
> 3 votes
A possible solution that might help to simplify the challenge in your question, is to use the fairly new Math Field module (for D7). Some more details about this module (from its project page):

> The Math Field module defines a new field type to dynamically calculate values on entity forms. **This is an alternative to Computed Field that does not require the use of PHP Filter.**
>
> Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

By creating some auxiliary field(s) (calculated via the Math field), you may be able to complete your puzzle. Possibly via some additional logic implemented via the Rules module, to implement logic that is similar to what I described in my answer to "How to set the values of some fields depending on the value of a list box?".

For more details (step-by-step instructions) about Math Field, refer to either of these links:

---
Tags: 7, views, theming
---


title: Put a Form in the Site's Homepage

text:
# Question
Title: Put a Form in the Site's Homepage
I have the item menu in my hook\_menu.

```
//Calls a function that enables creating, updating and deleting ID Templates.
$items['user/%user/myid_templates'] = array(
    'title' => 'MyID Templates',
    'description' => 'Configuration for ID Templates',
    'page callback' => 'myid_templates',
    'page arguments' => array(1),
    'access arguments' => array('manage_templates'),
    'file' => 'includes/myid_templates.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -18,
);

```

It's working fine:

I want it to appear in the home page of my site. What shall I edit my code above? I tried the code below with no luck.

```
//Calls a function that enables creating, updating and deleting ID Templates.
$items[''] = array(
    'title' => 'MyID Templates',
    'description' => 'Configuration for ID Templates',
    'page callback' => 'myid_templates',
    'access arguments' => array('manage_templates'),
    'file' => 'includes/myid_templates.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -18,
);

```

# Answer
This should work

```
  $items['node'] = array(
    'title' => 'MyID Templates',
    'description' => 'Configuration for ID Templates',
    'page callback' => 'myid_templates',
    'access arguments' => array('manage_templates'),
    'file' => 'includes/myid_templates.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -18,
);

```
> 0 votes

# Answer
Create a block for that form and place it on your home page. I haven't actually tried it with argument but something like that should work, give it a try.

```

$items['homepage/%'] = array(
  'title' => t('My form'),
  'page callback' => 'drupal_get_form',
  'page arguments' => array('hook_myform_form',1),
  'access callback' => 'myform_custom_access_callback',
  'access arguments' => array(1),
  'type' => MENU_CALLBACK,
);

function hook_myform_form ($form, &$form_state,$user_id) {

}

function hook_BLOCK_myform_CONTENT() {
  return drupal_get_form('hook_myform_form');
}

function hook_block_info() {
  $blocks = array();

  $blocks['custom_myform_for_homepage'] = array(
    'info' => t('Details'),
  );
  return $blocks;
}

function hook_block_view($delta='') {
  $block = array();
  switch($delta) {
    case 'custom_myform_for_homepage':
      $block['subject'] = t("Details");
      $block['content'] = hook_BLOCK_myform_CONTENT();
      break;
  }
  return $block;
}

```
> 0 votes

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


title: How to add reset button in webform?

text:
# Question
Title: How to add reset button in webform?
I tried to use below code to add reset button in webform,but its not working.I think that is not calling to "contact\_form\_reset" this function.Please help me out..

```
function cap_academy_contactus_form_alter(&$form, &$form_state, $form_id) {
       if ($form_id == 'webform_client_form_860'){
        $form['actions']['reset'] = array(
          '#type' => 'submit',
          '#value' => t('Reset fields'),
          '#submit' => array('contact_form_reset'),
          '#prefix' => '<div class="contactform">',
                '#suffix' => '</div>'
        );
        return $form;
      }
    }

    function contact_form_reset($form, &$form_state){
      $form_state['rebuild'] = FALSE;
    }

```

# Answer
You should use #button\_type and #attributes onclick like this.

```

$form['reset'] = array(
    '#type' => 'button',
    '#button_type' => 'reset',
    '#value' => t('Reset'),
    //'#weight' => 9,
    //'#access' => FALSE,
    //'#disabled' => TRUE,
    '#validate' => array(),
    '#attributes' => array(
          'onclick' => 'this.form.reset(); return false;',
        ),
    '#prefix' => '',
    '#sufix' => '',
);

```

Another option is to use Ajax like this.In the callback we can reset all form elements to default.I tried using $form\_state\['rebuild'\] in there but it didn't work in my case.

```

 $form['reset'] = array(
     '#type' => 'button',
     '#value' => t('Reset all'),
     '#ajax' => array(
         'callback' => 'my_ajax_reset_all',
     ),
     //'#limit_validation_errors' => array(''),       // No validation.
);

```
> 1 votes

# Answer
Webform is a drupal form and you can use hook\_form\_alter: Lets say you have a custom module called **mymodule** and your webform id is '**webform\_client\_form\_XXXXX**'. Then use the sample code below.

Here, XXXX is the form-id used in webform.

```
/**
 * Implements hook_form_alter.
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'webform_client_form_XXXXX':
      $form['actions']['custom_submit']  = array(
        '#type' => 'submit',
        '#value' => t('Reset'),
        '#submit' => array('mymodule_custom_submit'),
      );
      $form['#validate'][] = 'mymodule_custom_validate';
      break;
  }
}
/**
 * Custom validation handler for your webform.
 */
function mymodule_custom_validate($form, &$form_state) {
  // your validation code
}
/**
 * Custom submit handler for your form
 */
function mymodule_custom_submit($form, &$form_state) {
  // your submit handler code
}

```
> 0 votes

---
Tags: forms, webforms
---


# Question
Title: How do I have a dropdown select list for an entity reference?
For Drupal 8, the entity reference field displayed in form is a textfield with auto-complete feature for you to select the entity, is it possible to have it be dropdown select list instead? I have tried using views as the reference method to check the possible solution, but without luck, someone can help me with this?

# Answer
> 5 votes
Yes, you can. Drupal 8 does it out of the box as D7. The only difference is you can now choose the *widget* for any field in the **Manage form display** tab of a entity type.

E.g. Try changing the widget of the entity reference field - Tags - for article content type from `/admin/structure/types/manage/article/form-display`

---
Tags: 8, entities
---


title: Create dynamic block instances

text:
# Question
Title: Create dynamic block instances
In Drupal 7, if we need to define multiple instances of blocks from a database table, we use a foreach loop to return the array key, and then we we get all the multiple instances of our block using `hook_block_info()`.

```
function mymodule_block_info() {
    $blocks = array();
    $add = db_select('mymodule_blocks_data', 'n')
                  ->fields('n', array('delta', 'title', 'content_type'))
                  ->condition('n.form_type', 'Add', '=')
                  ->execute();
    foreach ($add as $row) {
        $blocks[$row->delta] = array(
      'info' => t('@name (Add Form Block) Type: @type', array('@name' => $row->title, '@type' => $row->content_type)),
      'cache' => DRUPAL_NO_CACHE,
        );
    }

    $edit = db_select('mymodule_blocks_data', 'n')
                  ->fields('n', array('delta', 'title', 'content_type', 'nid'))
                  ->condition('n.form_type', 'Edit', '=')
                  ->execute();
    foreach ($edit as $row) {
        $blocks[$row->delta] = array(
      'info' => t('@name (Edit Form Block) Nid: @nid', array('@name' => $row->title, '@nid' => $row->nid)),
      'cache' => DRUPAL_NO_CACHE,
        );
    }

    return $blocks;
}

```

In Drupal 8, I suppose `hook_block_info()` is replaced by plugin derivatives. Though I found a way here where they display nodes by using the entity manager, I have still to understand what I need to do when I am using my custom database table, and not an entity.

What is the equivalent code in Drupal 8 for `hook_block_info()`?

# Answer
> 4 votes
Create a file ex : `YourBlock.php` in `Drupal\mymodule\Plugin\Derivative\YourBlock.php`

```
<?php

namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

class YourBlock extends DeriverBase
{
    public function getDerivativeDefinitions($base_plugin_definition)
    {
        $results = \Drupal::database()->select('mymodule_blocks_data', 'n')
                  ->fields('n', array('delta','title', 'content_type'))
                  ->condition('n.form_type', 'Add', '=')
                  ->execute();
        foreach ($results as $result) {
            $this->derivatives[$result->delta] = $base_plugin_definition;
            $this->derivatives[$result->delta]['admin_label'] = t('Title: @name content type: @ctype ', array('@name' => $result->title, '@ctype' => $result->content_type));
        }

        return $this->derivatives;
    }
}

```

> Also add the necessary annotation to display all the dynamic block instances in
>
> ```
> Drupal\mymodule\Plugin\Block\YourBlock.php
>
> ```

```
<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Display all instances for 'YourBlock' block plugin.
 *
 * @Block(
 *   id = "mymodule_block",
 *   admin_label = @Translation("Your block"),
 *   deriver = "Drupal\mymodule\Plugin\Derivative\YourBlock"
 * )
 */

```

Rebuild the cache as well

---
Tags: 8, blocks
---


# Question
Title: Combining HTML markup to display it from a controller
i am creating the custom html as follows and i am calling another form inside that form . But for the second form its only display as 'array' , and not displaying the entire form as expected .

in **module\_name\src\Controller\MyController.php**

```
public function my_function($node) {
  $arg1 = node_load($node);
// output node-information at the top of the page
  $result .= '<table>';
  $result .= html_create_tablerow(array('<b>nid:</b>', $arg1->nid->value));
  $result .= html_create_tablerow(array('<b>Name:</b>', $arg1->field_p_name[0]->value));
  $result .= html_create_tablerow(array('<b>Description:</b>', $arg1->field_p_description[0]->value));
  $result .= html_create_tablerow(array('<b>URL:</b> ', $arg1->field_p_url[0]->value));
  $result .= html_create_tablerow(array('<b>Proxy-ID:</b> ', $proxy_id));
  $result .= html_create_tablerow(array('<b>static html:</b> ', $htmlfolder_note));
  $result .= '</table>';

  #$param = gasf_get_parent_node($arg1->nid->value);
  $resultForm = \Drupal::formBuilder()->getForm('Drupal\module_name\Form\MyForm',$arg1);
  #print_r($resultForm);exit();
  $build = array(
       '#markup' => $result.$resultForm
      );
  return $build;

```

and in **module\_name\Form\MyForm.php**

```
/**
 * General form for showing the main functionlities.
 */
  public function buildForm(array $form, FormStateInterface $form_state,$arg1 = NULL) {

  #if (!isset($form_state['storage']['confirm'])) {
    // two ways to transfer the nid
    $form_state['storage']['nid'] = $param->nid;
    $form['hidden'] = array('#type' => 'value', '#value' => $param->nid);

    /**
     * Find matching RPM files
     * field_p_rpservicename
     * sfeproxyenvironment
     * field_p_proxyinstance
    */
    $rpmGlob = get_proxy_id($param, 0);

    $rpms = glob($Config::getRpmFolder() . $rpmGlob . '-*.noarch.rpm');
    // sort RPM list in a natural human way
    natsort($rpms);
    $form_state['storage']['rpms'] = $rpms;

    // BEPI
    // TODO: query engines DB for this proxy and check which of the existing RPMs is installed.
    // Highlight that one in the available RPM list
    foreach ($rpms as $key => $value ) {
      $rpms[$key] = preg_replace('#' . $Config::getRpmFolder() . '#', '', $value);
      $rpms[$key] = preg_replace('#.noarch.rpm#', '', $rpms[$key]);
      $rpms[$key] = $rpms[$key] . ' ' . date('F d Y H:i:s.', filemtime($value));
    }

    # check if static folder for node 1 exists but current node does not
    # in that case, offer to copy the master node's static html content
    # to a new folder for the current node
    if ($param->field_p_proxyinstance[0]['value'] > 1) {
      $rpmGlob_master = get_proxy_id($param,1);
      if ((file_exists($Config::getStaticHtml() . $rpmGlob_master)) && (! file_exists($Config::getStaticHtml() . $rpmGlob))) {
        $form['submit_copy_statichtml_from_parent'] = array(
          '#type' => 'submit',
          '#value' => t('Copy static HTML from master node'),
          '#validate' => array('copy_statichtml_fom_master_node'),
        );
      }
    }

    $form['rpms'] = array(
      '#type' => 'radios',
      '#title' => t('Available RPM files'),
      '#options' => $rpms,
      '#description' => t(
        'If you want to deploy a present rpm file, or you want to delete one,
        choose it from above list.'
      ),
    );

    /* Display result for tasks. Will only show up if there is
     something to show.
    */
    $form['result'] = array(
        '#type' => $form_state['storage']['result']=='' ? 'hidden' : 'item',
        '#title' => t('Result'),
        '#value' => '<pre>' .  $form_state['storage']['result'] . '</pre>',
    );

    $form['submit_create_rpm'] = array(
        '#type' => 'submit',
        '#value' => t('Create RPM file'),
        '#validate' => array('_rpmcreate_preview'),
    );

    $form['submit_delete_rpm'] = array(
        '#type' => 'submit',
        '#value' => t('Delete RPM file'),
        '#validate' => array('_rpmdelete_preview'),
    );

    $form['submit_deploy'] = array(
        '#type' => 'submit',
        '#value' => t('Deploy'),
        '#validate' => array('_deploy_preview'),
    );

    $form['submit_decommission'] = array(
        '#type' => 'submit',
        '#value' => t('Decommission'),
        '#validate' => array('_decommission_preview'),
    );

    $form['submit_migrate'] = array(
        '#type' => 'submit',
        '#value' => t('Migrate'),
        '#validate' => array('_migrate_preview'),
    );

    $form['submit_showlog'] = array(
        '#type' => 'submit',
        '#value' => t('Show deployment log'),
        '#validate' => array('_showlog_preview'),
    );

    return $form;
}

```

Here the table thats created via html markup is displaying . But next to that its only shows `'Array'`

# Answer
> 2 votes
You have to separate the table markup and the form render array:

```
  $resultForm = \Drupal::formBuilder()->getForm('Drupal\module_name\Form\MyForm',$arg1);
  $build = [
    'table' => ['#markup' => $result],
    'form' => $resultForm,
  ];
  return $build;

```

By putting the table html in markup it becomes a render element. As the result of formBuilder() already is a render array, you can put those two together in a combined render array.

---
Tags: forms, 8
---


# Question
Title: Change quantity of product kit based on attribute
It's a shop where you can buy drinks. For every bottle/can there has to be an extra item with bottle/can deposit visible to the user.

So for this I added the cans and the deposit as single items. Every can has 3 attributes for the packaging unit of the tray: 6x250ml (default), 12x250ml, 24x250ml.

After that I added a product kit with 1x "can tray 6x250ml" and 6x deposit. This works fine. But if the user selects 1x "12x250ml" the deposit will just calculates the normal 6x.

Now I thought about manipulating the cart before it is visible to the user. For example: Take the quantity of the item, calculate the deposit by the checked packaging unit and multiply by the item quantity. The calculation is pretty simple.

**What function/hook can I use to do this?**

I tried to deal with `hook_uc_cart_item_presave($entity)` but it seems, that the function gets triggered once for every product in the product kit. I can't find a solution to check the quantity on the main item as well as the checked attribute and then pass it to the second run for the deposit item.

# Answer
It seems that - against the official docs of ubercart - the hook `hook_uc_cart_alter` IS available for Drupal 7.

Found the answer here on Drupal Answers in an old question: https://drupal.stackexchange.com/a/94497/53491

With the available `$items`-object I iterate through my cart as I need it. Works perfect.
> 0 votes

---
Tags: 7, ubercart
---


title: Translate menu item made by view

text:
# Question
Title: Translate menu item made by view
Question is simple, in the views module you can add a normal menu item. But when in the menu itself it can't be translated. Is there anyway to do this, or should I just add the menu item myself instead of letting the view do that?

# Answer
After defining your menu item via views, you have to go back to the views list (/admin/structure/views). There is a "Translate" option under "Edit".

There, you can "Add" a translation, then choose your page display options and translate the menu item (applies for Drupal 8 only).

If the menu item is not showing up, clear the caches (e.g. cache rebuild using `drush cr`).
> 3 votes

---
Tags: views, 8
---


# Question
Title: How can I pass a variable to javascript from a preprocess function?
How do I pass `$variables['is_front'`\] from `template_preprocess_page()` to a jquery script in `Drupal8`?

# Answer
send it:

```
function mytheme_preprocess_page(&$variables) {
   $variables['#attached'] = [
        'drupalSettings' => [
          'myLibrary' => [
            'is_front' => $variables['is_front'],
          ],
        ],
    ];
}

```

access it in jquery:

```
  Drupal.behaviors.myBehaviour = {
    attach: function (context, settings) {

      console.log(settings.myLibrary.is_front);

    }
  };

```
> 4 votes

---
Tags: 8, javascript, theming
---


# Question
Title: How can I update the field of the entity?
I have an "Question" entity, and I need to updates its 'key' field (of string type):

My code isn't working:

```
  $storage = \Drupal::entityManager()->getStorage('question');
  $query = $storage->getQuery();
  $query
          ->condition('key', $key);

  $entity = $query->execute();

 $entity -> set ('key', 'new_value');
 $entity->save();

```

It returns the error Fatal error: Call to a member function set() on a non-object

# Answer
> 2 votes
The QueryInterface::execute() method returns either an integer or an array, not an object. It is a good idea to check api.drupal.org (if you don't use an IDE), or let your IDE do the work for you with intellisense.

It probably would be easier to use loadByProperties, which loads the entities for you. However it is definitely useful to get the query object, but you need to call loadMultiple.

```
$entities = \Drupal::entityTypeManager()
  ->getStorage('question')
  ->loadByProperties(['key' => $key]);

if (!empty($entities)) {
  $entity = reset($entities);
  $entity->set('key', 'new_value');
  $entity->save();
}

```

---
Tags: entities, 8, database
---


# Question
Title: Include specific stylesheet for specific language?
I have the following stylesheets:

```
stylesheets[all][] = AAA.css
stylesheets[all][] = BBB.css
stylesheets[all][] = CCC.css
stylesheets[all][] = chinese.css

```

AAA, BBB and CCC are fine. They should show for all languages. But I need english.css to ONLY show if the language code of the current page being viewed is:

```
cn-zh
tw-zh

```

The language code is retrieved from the i18n module:

```
$language = i18n_language();
$languageCode = $language->language;

```

How can I include this stylesheet for this case?

# Answer
So you will probably need to remove the style sheet from your info file and add it in a pre-processor.

I normally don't recommend using pre-processor functions but this is kind of the ideal exception to that rule. Checkout template\_preprocess\_html. In that hook you can pull the active language setting and conditionally add the language specific css file with drupal\_add\_css

```
function mytheme_preprocess_html()
{
  // Don't remember the code for this but you can figure that out.
  $language = getLanguage()

  if ($language == 'chinese_traditional')
  {
    drupal_add_css(drupal_get_path('theme', 'mytheme') . '/chinese.css');
  }
}

```

If the get language function uses a database call it would be better to do this in a custom module. DB calls in the theme are pretty much always a bad idea. You would in that case use the same code in hook\_preprocess\_page. At least that is what I was always told to do.
> 1 votes

---
Tags: theming, i18n-l10n
---


# Question
Title: How do I specify a parent domain in a multi-site install?
I'm not sure the best title for this question so sorry if it was confusing.

### Setup

I have a multi-site install that I regularly add new sites to.

They are generally in the format:

* example.com (default)
* sub1.example.com
* sub2.example.com
* sub3.example.com
* sub3.com

I also have a wildcard dns and vshost so I don't have to edit them every time I create a new site:

```
example.com my.ip.add.ress
*.example.com my.ip.add.ress
sub3.com my.ip.add.ress

<virtualhost *:80>
  Name example.com
  alias *.example.com
  alias sub3.com
</virtualhost>

```

Sites.php has a few entries like:

```
sites[sub3.com] = 'sub3.example.com'

```

All of this works great.

### The problem.

Most of these sites are not publicly visible. being disabled with robots.txt and permission preventing users from see them. So I could care less about those. However some sites are public. In the example above the example.com and sub3.com are both public facing sites.

When a user visits rando.example.com the multi-site will send them to example.com but the url will appear as whatever they typed in. Also the sub3.com site will be visible as both sub3.com and sub3.example.com.

### The question.

How do I, preferably using only Drupal, redirect the non-existent subdomains to the default. Not just show the default but actually do a 301 redirect to the url desired.

### My attempts.

To my knowledge I can not solve this with:
\- redirect module as it does not let me specify a subdomain or a wildcard. \- global redirect does not affect subdomains. \- sites.php as it does not redirect but a `sites[*.example.com] => example.com` would be cool.

### Qualifiers

* I understand that I could fix this in the vhost by removing the wildcard name and just adding a new entry for each sub-domain. I do not want to have to edit my vhost every time their is a new sub-domain.
* I understand I may be able to solve this with .htaccess files but I do not want to have to edit that file every time I create a new site either. And I don't really want it to be overridden from default. Plus I have my server pull the file only on reboot and I don't want to reboot apache just to add a site.
* I understand that canonical urls would prevent bots from indexing unused sub-domains but that's not good enough I don't want users using a subdomain that doesn't exist.

My ideal solution would be a redirect that supports sub-domains or something similar. Changes to sites.php or database changes are the goal.

# Answer
> 2 votes
It is called multi-site aliasing, hence the results. Drupal offers you to server multiple domains from the same folder in order to preserve the paths in the database. So you would use the same folder for example.com and sub3.com because you might want to disable one of them later on. Aliasing is meant on a file level here. What you need is a redirect.

A 301 redirect code can be issued by your webserver-software itself (e.g. Apache/nginx config or apache .htaccess) or by sending a header via the scripting software.

The "drupal-way" solution for you would of course be to use a module for sending that header. My recommendation would be multisite\_redirect, because it would only need a one time setup for your case outlined above.

---
Tags: 7, redirection, multi-sites
---


title: Attaching fields to files

text:
# Question
Title: Attaching fields to files
I have a couple of forms where I need to attach metadata fields to files (a description, and a category).

The file\_entity module alone lets me specify fields, but doesn't change the form fields.

When enabling the Media module, it sort of works, but the Media module

1. does its work in an overlay, which is unacceptable - I need something that looks like if you enable the "description" option in the core File element
2. breaks the look of the site as soon as I click on the "edit" button that opens the overlay - it loads the entire Bartik CSS even if the current theme is not related or using Bartik!
3. is way too overcrowded - I don't need support for youtube
4. is a security hole because people can browse all uploaded files!

So, basically, I need some way to attach a dropdown box to the standard file upload widget, nothing more - how do I achieve this? If possible, I'd prefer something that integrates at least with file\_entity, so I don't have to define the field in code.

# Answer
> 2 votes
Sounds like you are looking for something like https://www.drupal.org/project/file\_entity\_inline

---
Tags: 7, media, files
---


# Question
Title: Facing Repetition in records when I use multiple relations in Views
I am trying to use views fetch the News and Articles for display on my custom content type "Industries". On Industries content type I have node reference fields to the News and Articles content types.

I've added two relationships in 'advanced' section and in Contextual filter selected Content: NID. I also enabled Distinct \> pure distinct settings in the query settings section. View's Snap are Here : http://prntscr.com/b8mrmp

But still the records are repeating. If 6 news and 10 Articles, then each article is listed for each news node. Result : http://prntscr.com/b8mscg

# Answer
> 0 votes
Have a look at the Views Distinct module. From its project page:

> Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

---
Tags: 7, views
---


# Question
Title: How to set a default theme programmatically
I am trying to build an install profile and I want to have my custom theme enabled and set by default after the installation.

Adding in MYPROFILE.info.yml...

```
theme:
  - my_theme

```

...is not enough. This only installs it, but it is not set as the default theme.

I guess I have to do something else in the MYPROFILE.install file in

```
function MYPROFILE_install() {
  // how to set as default my custom theme
}

```

Thank you

# Answer
Looking at `ThemeController::setDefaultTheme` (the request handler for the /admin/appearance/default route), this should do the trick:

```
\Drupal::configFactory()
  ->getEditable('system.theme')
  ->set('default', 'machine_name')
  ->save();

```
> 11 votes

# Answer
You can create a site that has the correct default theme, and copy over the theme related config files into your profile's config directory (or all the files if it makes sense for your profile).

See https://www.drupal.org/node/2210443#config for more.
> -2 votes

---
Tags: theming, 8, installation-profiles
---


# Question
Title: Commerce Line Item Taxonomy Reference Filtered by Product Selection
Here's the scenario:

* I'm selling furniture. I have a chair we'll call Mission Chair.
* The Mission Chair comes in oak or maple, both are priced differently. I have a field in my product
* I have a product display created which references these 2 products
* Customers need to choose 1 of 5 stain colors, but each type of wood has 5 different choices (and they're not the same choices)
* The stain choice is required, but does not affect the price.

In my Product Variation Type, I have a term reference field which is referencing a Wood Species vocabulary.

I assume I would create a term reference field on the line item type where they would make the stain color choice. What I need to figure out is how do I do some kind of contextual filter to only show the stains available for the chosen wood species? (which is a taxonomy term on the chosen product - not the display, the product variation)

Should the stains be child terms in the same vocabulary as the wood species, or should it be a separate vocabulary with an additional term field that references a specific wood species (taxonomy reference, the same vocabulary the product variation uses) for each stain color term, and then filter on that somehow?

# Answer
You have two basic approaches you can use: either treat the stain color as a customization or treat it as a second attribute. Which you pick depends on a little on your backend process needs and the experience you want to provide.

If you use a second attribute and have a product variation for each stain in each wood, Commerce's default add to cart form should provide the user experience you are describing. You might find it helpful to take a look at this tutorial.

If you want to treat stain as a customization you'll likely want a couple extra modules -- in particular Commerce Customizable Product. Commerce Guys have a tutorial covering that scenario.
> 1 votes

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


title: Way To Search Content

text:
# Question
Title: Way To Search Content
I am new to Drupal and am currently trying to edit some pages on a site I inherited. The site does not seem well-organized as there is a panoply of URL redirects and aliases. As a result, I am having a difficult time finding the right pages to edit.

Is there a way to just search for the path and have it return the right content to edit? Perhaps there is a module for that?

As an example, I have a page www.example.com/donate which needs to be edited. When I look under aliases and URL redirects, "donate" returns nothing. How can I go about finding this particular page?

# Answer
First, sorry that your first experience is with a poorly organized site. Like any powerful tool Drupal can do some really annoying things when poorly setup, and it's frustrating when you start with a messy project.

A page may be pulling in content from a node, a view, a form, a block, or some other source. Depending on how careful the original theme developer was, for any page not providing an edit tab you may find there is a contextual menu (or several) hiding under a light grey gear icon (usually at the top right of the element is supports). Those will often provide hints about where the content is coming from, or even direct links to edit it.

It can also be useful to look over the list of views on the site (Structure --\> Views), which is Drupal's query builder. The displays frequently have headers and footers defined along side the query.

After that you'll probably want to figure out what is used to organize elements on the site's pages. Drupal 7 provides several tools to do that (sometimes used together which can cause confusion) check the modules list for Panels, Display Suite, and Context. Whichever is enabled you'll want to research a bit. Each can help pull content into a page, Panels may even be setup to provide some of that content itself.
> 0 votes

# Answer
Not all Drupal paths end with a content (or node) page. For example, the D7 core Contact module has the path **/contact**, but in order to "edit" it you need to change administration pages within the admin section (**/admin...**) or a theme template if you're wanting to change how the HTML is rendered.

The closest thing to what you're looking for is the `menu_router` (D7) or `router` (D8) database table. These DB tables contain static/dynamic paths (the `path` column) with additional metadata about what/how these paths rendered. They should help you discover what controls paths that aren't node or node alias paths.
> 1 votes

---
Tags: views, path-aliases, redirection
---


# Question
Title: How to programmatically add options to list_text field
I want to programmatically add a drop down list field to the user profile via a custom module. How do I go about adding select options for the field?

```
// Create Field
'suffix' => array(
  'field_name' => 'suffix',
  'type' => 'list_text',
),

//Create instance
'suffix' => array(
  'field_name' => 'suffix',
  'entity_type' => 'user',
  'label' => 'Suffix',
  'bundle' => 'user',
  'options' => array(
   '0' => 'Mr.',
   '1' => 'Mrs.',
  ),
  'widget' => array(
  'type' => 'list_text',
  );
),

```

The field shows up but the options do not. Anyone have a good guide they know of or tell me what I'm missing?

# Answer
> 3 votes
Your available widgets for a list field are these: `options_select`, `options_buttons` and `options_onoff`, not `list_text`, that is the field type.

The widget values can be found on `list_field_widget_info_alter()`, where the list types are coupled with the widgets.

So I suppose you should update your field instance to use:

```
'widget' => array(
  'type' => 'options_select', // Drop down button or multi-select
  // OR
  // 'type' => 'options_buttons', // Radio buttons or checkboxes.
);

```

The way the widget is rendered depends on the `cardinality` defined on your field. If cardinality is set to 1, the first type will be used (drop down or radio buttons), if cardinality \> 1, you'll get a multi-select field or checkboxes.

Assuming this field can only hold one value, you should also add

```
'cardinality' => 1,

```

To your field definition.

Leaving you with:

```
// Create Field
$field = array(
  'suffix' => array(
    'field_name' => 'suffix',
    'type' => 'list_text',
    'cardinality' => 1,
  ),
);
field_create_field($field);

//Create instance
$instance = array(
  'suffix' => array(
    'field_name' => 'suffix',
    'entity_type' => 'user',
    'label' => 'Suffix',
    'bundle' => 'user',
    'options' => array(
     '0' => 'Mr.',
     '1' => 'Mrs.',
    ),
    'widget' => array(
      'type' => 'options_select',
    ),
  ),
);
field_create_instance($instance);

```

---
Tags: 7, users
---