# Question
Title: How to disable a form button in DrupalGap after it is clicked?
I am experimenting with the Stripe Cordova plugin that seems to provide for an easy addition of Stripe payments to a Phonegap app.

I have created a form with the necessary fields (name, amount, CC numer, CVC, expiration month and year). It is of course important to prevent double clicking/double charging.

**What is the most reliable way to disable the submit button immediately after it is clicked and prevent double charges?**

**Scenario 1:**

```
/**
 * Define the form's submit function.
*/
function stripe_payment_form_submit(form, form_state) {
  try {
    var points = form_state.values['points'];
    var number = form_state.values['number'];
    var exp_month = form_state.values['exp_month'];
    var exp_year = form_state.values['exp_year'];
    var cvc = form_state.values['cvc'];
    var fullname = form_state.values['name'];
    chargeCard(points, number, exp_month, exp_year, cvc, fullname);
}
  catch (error) { console.log('stripe_payment_form_submit - ' + error); }
}

function chargeCard(points, number, exp_month, exp_year, cvc, fullname){
  stripe.charges.create({
  amount : points,
  currency : 'usd',
  card : {
    number : number,
    exp_month : exp_month,
    exp_year : exp_year,
    cvc : cvc,
    name : fullname
    },
   description : "Stripe Test Trasnfer"
},
  function(result){
    // asynchronously called
  });

```

}

**Scenario 2:**

```
/**
 * Define the form's submit function.
*/
function stripe_payment_form_submit(form, form_state) {
 try {
   stripe.charges.create({
   amount : form_state.values['points'],
   currency : 'usd',
  card : {
   number : form_state.values['number'],
   exp_month : form_state.values['exp_month'],
   exp_year : form_state.values['exp_year'],
   cvc : form_state.values['cvc'],
   name : form_state.values['name']
  },
  description : "Stripe Test Trasnfer"
 },
 function(result){
  // asynchronously called
 });
   }
  catch (error) { console.log('stripe_payment_form_submit - ' + error);   }
 }

```

# Answer
Senario 1 or 2 would both be fine, the trick is to disable the button immediately before the ASYNC call begins. This can be easily accomplished with a little jQuery:

```
$('#my-submit-button').prop('disabled', true);

```

Then I'd recommend re-enabling it in the *success* and *error* handlers for the ASYNC call to Stripe:

```
$('#my-submit-button').prop('disabled', false);

```
> 1 votes

---
Tags: forms, javascript
---


# Question
Title: How to access phone contacts from PhoneGap in DrupalGap?
I'm really new to DrupalGap and PhoneGap. I have a question, how can we access the phone contacts in DrupalGap? I want to list the mobile numbers and other contact details in the application. Then select some of the contacts and store in the Drupal database.

The steps I followed:

1. Installed PhoneGap
2. Created PhoneGap project
3. Contacts pulgin installed for the project
4. Copied the DrupalGap to the www folder of the project
5. Done the necessary settings changes
6. Created a custom module to access the contacts from PhoneGap in laptop

I found some code snippet to access the contacts in PhoneGap as follows:

```
function sync_contacts_get_contacts() {

    // specify contact search criteria
    var options = new ContactFindOptions();

    options.filter = "";      // empty search string returns all contacts
    options.multiple = true;  // return multiple results
    filter = ["displayName"]; // return contact.displayName field

    // find contacts
    navigator.contacts.find(filter, onSuccess, onError, options);
}

function onSuccess(contacts) {
    for (var i=0; i<contacts.length; i++) {
        if (contacts[i].displayName) {  // many contacts don't have displayName
            alert(contacts[i].displayName);
        }
    }
};

// onError: Failed to get the contacts
//
function onError(contactError) {
    alert('onError!');
}

```

How can I access this in DrupalGap module I created and store in Drual database?

SOLUTION:

Later in my research I realized one of my misunderstanding. Contacts, camera etc. are work only in device. That means "navigator.contacts" cannot test in the web browser. we have to build the .apk file and install that in the device and test.

Instead of writing the contacts getting code, we can use the PhoneGap plugin from this location: https://github.com/dbaq/cordova-plugin-contacts-phone-numbers.

Using the custom service I stored the contacts in Drupal database. Link: http://docs.drupalgap.org/7/Services/Create\_a\_Custom\_Service

To create the .apk file we have to follow the URL: http://docs.drupalgap.org/7/Compiling\_a\_Mobile\_Application/Preparing\_PhoneGap/Installing\_PhoneGap/index

# Answer
Here's the approach I would take:

1 - Build a custom DrupalGap module.

2 - Implement `hook_install()` in the module:

```
/**
 * Implements hook_install().
 */
function my_module_install() {
  sync_contacts_get_contacts();
}

```

3 - Create a Custom Service Resource Endpoint

4 - In your `onSuccess` function is where you would send the **contacts** JSON data up to your Drupal resource.

What (and how) you store the data in Drupal is up to you and your custom Drupal module(s).
> 0 votes

---
Tags: javascript
---


# Question
Title: How can I get Autocomplete behave as in most of the sites out there?
I have a form built with `FORM Api`. It has a text field, with Autocomplete. I also have another form, with several fields, some of them with Autocomplete.

It works well, but I have to press Enter Key twice to send the form.

The first Enter key is to select an item. The second Enter key sends the selected item for process.

The behaviour that I have seen outside, in the wild, and which is customary in thousands of millions of sites is this:

1. If only one field form (search form, for example), once you click or press enter with the suggested term highlighted, the form will be sent (let's call this behaviour One-Clik). Note: there are no multiple selections option, if not, this behaviour would have to be different.
2. In several fields form, you just select and press ENTER, and can continue filling other fields. If you want to submit the form, you press the Go button or just click Enter in the autocomplete field if that is the last one you used. This is called Two-Clicks, except that: you can write some words in the autosuggest field, and not choose anything. The desired behaviour would be that just clicking ONCE the Enter key, you would submit the form. So this behaviour is really One-Click, with the only exception that selecting an item by pressing Enter key does not qualify as a click.

In order to have it working, I had to rewrite the autocomplete.js. Is there another solution?

I cannot understand how Drupal cannot manage by default such an easy behaviour, seem in millions of sites. And I can assure that for normal users this is very frustrating and irritating and very counterintuitive.

# Answer
I think this is a JQuery problem rather than a Drupal problem.

You should be able to add a JavaScript function, something like the following:

```
$("#searchField").select(function(event, ui) {
    $("#searchField").val(ui.item.label);
    $("#searchForm").submit();
});

```

It's necessary to assign the value before submitting the form because if the user clicked on a list entry with the mouse, the value won't have been assigned before the select event occurs.

I haven't actually tested this, but hopefully this will send you in the right direction.
> 1 votes

---
Tags: 7, ajax
---


title: Simple confirmation popup dialog box

text:
# Question
Title: Simple confirmation popup dialog box
How is it possible to create simple confirmation popup dialog boxes in Drupal 7?

I've searched a lot, but I found tons of non-working suggestions and code.

# Answer
I got it!!!

Here's a simple 100% functioning exmple:

```
$form['delete'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#attributes' => array('onclick' => 'if(!confirm("Really Delete?")){return false;}'),
);

```

I hope this helps.

Happy coding :)
> 8 votes

# Answer
Drupal has a native confirm\_form() function, but it is server side rather than Javascript based, which is what I assume you mean.
> 2 votes

# Answer
There is a sandbox module which enables this type of functionality to be built relatively easily: https://www.drupal.org/sandbox/cmcintosh/2644004
> 0 votes

---
Tags: forms
---


# Question
Title: How to show pop up message "Are you sure ......?" with "OK" button before save the content
I have a image field on profile content type. And when users try to save the content without uploading images I would like to show pop up confirmation message "Are you sure you want to save your profile without photos?" with "OK" button. And I need the content to be saved only after the users click the "OK" button.

I thought I could do this with Rules module however it look like there is no action for showing popup message with "OK" button of confirmation.

Is there any way to achieve this?

# Answer
> 2 votes
The custom way to do this would be to use hook\_form\_alter to add some jquery into the form you are targeting that would bind to the submit action of the form and execute some javascript function (ex. an alert) if a form field value is not filled out.

The key library for this is the jquery validation library here:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

There are also a couple modules you could try and install that implement this library and offer direct integration with your field through the form api. I've used this one:

http://drupal.org/project/clientside\_validation

To achieve a similar validation effect as what you're looking for.

# Answer
> 1 votes
There is also a sandbox module to achieve this using rules + actions : https://www.drupal.org/sandbox/cmcintosh/2644004

---
Tags: forms, javascript, nodes, rules
---


# Question
Title: How do I allow users to import Youtube videos?
How do I allow users to import Youtube videos into their profile using the video URL?

I've no idea which module can do this.

# Answer
Install media\_youtube. Add a field to user profiles of this type.
> 1 votes

---
Tags: media, files
---


title: Determine if this should be a group

text:
# Question
Title: Determine if this should be a group
When anonymous users are registering and creating a group - the field:

Determine if this should be a group.

Shows up on registration.

In the field settings on the content type I'm using I have the values checked to "Hide" this portion. I've even hid the values on Manage Display.

Screen shots attached. All I want to do with is hide the field to NOT show to users. There's no reason for this field to be visible in my scenario.

I don't want to hide it with css if at all possible.

Any guidance is appreciated.

# Answer
> 1 votes
You could use `hook_form_alter()` to change the field type for the field you want to hide to "hidden". The code would be something like this:

```
mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case "user_register_form":
      $form["fieldname"]["#type"] = "hidden";
      $form["fieldname"]["#value"] = $form["fieldname"]["#default_value"];
      break;
  }
}

```

This function will get called for every form displayed, so the switch statement makes sure it's the right form. That being the case, the next line changes the type of the field to a hidden field. Finally, it copies the default value of the field into the actual value (hidden fields don't have a default value).

Unfortunately I don't know what the name of the field you want to change is, so you'll have to investigate that.

Hope this gets you on the right track.

---
Tags: users, organic-groups
---


# Question
Title: Using entity reference field as filter in view
I have a content type 'Player' which has an entity reference field to the content type 'Tournament'. The entity reference field allow multiple values (a player can join several tournament).

I'd like create a view of all Player nodes filtering on the 'Tournament' field. When i try to add the entity reference field as filter nothing happens (I have installed the 'Views Reference Filter'). I need also to expose the filter to the users using a droplist.

Can someone help me? Thanks

# Answer
Follow the following steps.

1) First create an entity reference field in your content type (player) and in the Entity Selection Mode select (Simple(with optional filter by bundle) and then check Tournement checkbox, And in Additional Behaviors check (Render Views filters as select list) and save your content type.

2) Create view of type Players

3) Add new filter and choose your reference field and apply

4) Check (Expose this filter to visitors , to allow them to change it) checkbox.

6) Select Operator (Is one of) and in options check (Select all) checkbox

7) Click on Apply button and save your view.

That's all, now you are ready to filter the view using your reference field.
> 0 votes

---
Tags: views, entities
---


# Question
Title: How to convert location module data to geofield?
I need to switch my mapping implementation from Gmap to OpenLayers. I have a site with 1000+ users that already have data stored with the location module, and user locations. Is there an easy way to transfer the address/location to geofield?

# Answer
> 2 votes
So, I haven't found a way to convert it, but I did do the following.

1. Update content with Addressfield and Geofield
2. Set geofield to code from addressfield
3. used views data export to export the data
4. used feeds to spit the data into addressfield.

This basically met my requirements, pretty laborious and had to do a lot of data integrity checking, but it did what I wanted it to do.

Just as a heads up, Addressfield is very specific with it's term, which are internationalized. The fields you have to map have different field names, and different requires fields for each country, so be cautious with the spelling and fulfilling all the required fields. You can use Feeds Tamper if it's all single-country data. Just for example here are a few:

1. Province = Administrative area
2. Street = Thoroughfare
3. City = Locality

---
Tags: google-maps, javascript, location
---


# Question
Title: Can't install modules in Drupal 8 Ubuntu - Should I change owner?
Its not the first time I install Drupal 8 on Ubuntu 15.10 (which I'm very new to) but it is indeed the first time when I can't install modules at it.

I ran the error at Google and After reading this document regarding to a similar problem in Drupal 7, and a few other docs, It seems I should do in terminal:

```
sudo chown -R www-data sites

```

Since I am new to Linux and I also know that Drupal 8's folder hierarchy has been changed a bit, and I'm not sure if its the right move (I'm afraid to make mess); Thus, I dedicate this question to senior developers which are also Linux veterans...

# Answer
go to the folder where you installed Drupal 8. Ex:

```
cd /var/www/drupal

```

In you case, it looks like it's:

```
cd /var/www/html/benia

```

then

```
sudo chown www-data -R modules

```

Now try installing again.

To prevent other conflict, I would www-data all of your Drupal

```
cd /var/www/html/

sudo chown www-data -R benia

```
> 2 votes

# Answer
If you are running the site on a developer machine then changing the owner (and permissions) is not that harmful (as your IP is not public knowledge).

However if this is your production (/staging/QA/whatever) server you should keep the permissions as they were.

### Sugestion:

Download contributed modules and themes via Drush, Drupal console or GIT.
*With command line you can always sudo the permissions away* :)
> 1 votes

# Answer
I would prefer you to use Drush and Composer to install modules. They minimize your chances of messing up. To download Composer go to getcomposer.org To download drush type:
`composer global install drush/drush`
Navigate to your Drupal 8 installation's modules folder by typing:
`cd /var/www/html/benia/modules`
then
`drush dl module_name`
Navigate into the module's directory
`cd module_name`
Install dependencies of the module by typing:
`composer install`
Finally enable the module by typing:
`drush en module_name`
> 0 votes

---
Tags: 8, files
---


# Question
Title: Frontpage is a menu item...title won't change
When I access site via / or /fp, I always get 'Home', this only happens for the home page...How can I change the title?

```
$items['fp'] = array(
    'title' => 'Front Page',
    'page callback' => 'rocdocs_main_view',
    'access arguments' => array('access content'),
    'title callback' => 'rocdocs_main_view_title',
    'type' => MENU_CALLBACK
);

function rocdocs_main_view_title()
{
    return 'THIS IS A TEST';
}

```

# Answer
> 0 votes
Just deactivate the predefined menu link and add a new one - use

```
<front>

```

as path.

In Drupal 7 and 8 go to

```
Home > Administration > Structure > Menus > Main menu > Add link

```

Drupal 7

See tooltip for details (using Rubik Theme)

---
Tags: 7
---


# Question
Title: How to map different entity types as layers with OpenLayers?
My implementation requires the mapping of multiple entity types, which is difficult to achieve in vanilla Gmap with Views.

In the documentation, OpenLayers states that layers can produced from views of OpenLayers data type. Is it really as simple as specifying a few layer views and adding them to a map?

If so, and multiple views can be served as data sources to OpenLayers, what does one have to do to convert a Location/Gmap set up to OpenLayers?

# Answer
So, OpenLayers requires Geofield as a spatial data format, which is better than the Location Module for spatial formats. There's no simple solution to convert the data, so you spatial content will have be updates with Address or Geofield formatted data. I used Views CSV export and Feeds to dump and spit back the data to the right fields. From there, I followed the tutorial here Multiple Layer Maps with OpenLayers creating multiple data overlay views to a build a map based on layers of different views. This let me overlay my users over my other spatial nodes.
> 1 votes

---
Tags: google-maps, javascript, location
---


title: Explain the N-rules in hook_update_N

text:
# Question
Title: Explain the N-rules in hook_update_N
On hook\_update\_N() the documentation says:

> mymodule\_update\_7000(): This is the ***required*** update for mymodule to run with Drupal core API 7.x **when upgrading from Drupal core API 6.x**.

> mymodule\_update\_7200(): This is the first update to get the database ready to run mymodule 7.x-2.*. **Users can directly update from 6.x-2.*** **to 7.x-2.\* and they get all 70xx and 72xx updates**, ***but not 71xx*** updates, because those reside in the 7.x-1.x branch only.

Is it really mandatory to define an 7000 update hook? I saw some contributed module updates that starts with 7300, when the module version for Drupal 7 is 7.x-3.x.

I am a bit confused, because I read before the UPGRADE.txt file for Drupal 7 core that says:

> MAJOR VERSION UPGRADE
> To upgrade from a previous major version of Drupal to Drupal 7.x, after following the instructions in the INTRODUCTION section at the top of this file:
>
> 3. In addition to updating to the latest available version of Drupal 6.x core, you must also **upgrade all of your contributed modules for Drupal to their latest Drupal 6.x versions**.

For me, it means that users can't directly update from 6.x-2.x to 7.x-2.x unless 6.x-2.x module was the latest in the Drupal 6.x versions. Is this correct?

What about eventual database updates defined by 7.x-1.x branch? Do they have to be reported in the 70xx updates?

Can a module version 7.2.x keep any other updates (e.g. 60xx, 71xx) or it should be clean and defined **only** updates about 70xx and 72xx?

# Answer
> 2 votes
Basing on the documentation, 70xx updates are only necessary if there are updates from Drupal 6.x to Drupal 7.x that are necessary for any branch the Drupal 7 module has (e.g. 7.x-1.x, 7.x-2.x, 7.x-3.x). If that is not the case, then you don't need to use 70xx as update numbers.

As said in the documentation, updates numbered 72xx allows updating from the 6.x-2-x version of the module to the 7.x-2.x version, but not from the 6.x-3.x version. This is generally not a problem, since project maintainers normally create a version 7.x-3.x together a version 6.x-3.x.

As the documentation reports, updates numbered 71xx are for updated from version 6.x-1.x to 7.x-1.x; updates numbered 70xx are for updates from Drupal 6 to any branch of the module for Drupal 7.x. You don't copy the 70xx updates in 71xx updates, since those are already executed for the 7.x-1.x branch.

As for the updates to keep, the documentation says:

> A good rule of thumb is to remove updates older than two major releases of Drupal.

So, updates for a 7.x-1.x version should still be kept for a 7.x-2.x version.

Keep in mind that, as far as I recall, what described in the documentation about which updates are run when updating from Drupal 6 to Drupal 7 doesn't describe what the code actually does. For what I recall, Drupal code simply run any updates higher than the last executed update. For example, if a module last time ran its 6123 update, Drupal will run any update higher than that number, such as 7000, 7100, and 7200, if they are defined.

---
Tags: 7, updating
---


title: User create its content type

text:
# Question
Title: User create its content type
I created a content type called *successful story*; in this content type, there is a title field and a text field.

I have two types of users, Role1 and Role2; Role2 can only create or delete a *successful story*.

For example, The user called Michael is a Role2 user and can create its successful story

But how can I make this relation works between a content type and an user?

# Answer
> 2 votes
Your question is not clear but I think you want to know how to set the right access to the different Roles

1. Go to your\_site/admin/people/permissions
2. Search from the successful store content type
3. For Role 2 check the "Create new content" and "Delete own content"
4. Click save at the end of page

Now users of Role 2 can create and delete their own content.

You can also create a link for Role 2 users to access their own content.

1. Go to your\_site/admin/people/permissions
2. Search from the Access the content overview page
3. For Role 2 check the box for Role 2
4. Click save at the end of page
5. Create a menu item and add the link as admin/content

# Answer
> 0 votes
Go to admin/people/permissions where you can set permissions for every content type - creating/deleting/modifiyng own/any content

---
Tags: nodes, users
---


# Question
Title: using hook_node_submit to create an alternate upload method
We have a problem where we are uploading a number of files on a regular basis, the files need to be kept outside of the document root.

Each file is attached to a node.

I created a folder `/documentstore` and all the files are uploaded to there.

To enable submission of documents I added a symlink `sites/default/files/documentstore -> /documentstore`

Unfortunately drupal does not allow files uploads to a symlinked folder :( I have modified core to solve the issue as a temporary fix.

For a more permanent fix I'd like to add a module hook node submission and then copy the file to the symlinked folder avoiding drupals core upload function. I am trying to use `hook_node_submit()`.

I would like some hints as to how I can go about this or whether there is a better way to store files outside of the docroot (yes it must be done that way)

# Answer
> 0 votes
Please use the copy function to store the files to different location other than drupal root or files folder.

Alter `hook_node_submit` function using copy instead of `file_save_upload`.

Try referring Drupal S3 module code, which copies the files to AWS S3 storage.

# Answer
> 0 votes
The solution to my dilemma was simpler than I had imagined.

The problem of saving into symlinked folders is discussed here.. https://www.drupal.org/node/1008402 with a few patches to fix `getlocalpath()`. This was the basis for my temporary fix.

5 years and no patch has made it to production!

After posting here and struggling to get the solution working, which was being complicated by the module `filefield_paths` altering the workflow somewhat (files aren't save to the final location till later). I realised if I can create my own streamwrapper I can save the files where I like.

This turned out to be very easy and worked a treat.

I will post a link to the streamwrapper module when I have cleaned it up and submitted it to drupal.

I have created a sandbox project for this module here https://www.drupal.org/sandbox/developerchris/2644230

---
Tags: hooks, files
---


title: Image style not loading on first load

text:
# Question
Title: Image style not loading on first load
I have images of a certain image style that only show up after reloading the page. I can see the image created in the style directory after the first page request. Its like the browser is not waiting for the image to be created.

I wrote a curl script to request all the images of that style on the site, which works. But I'm worried that when new images are added they won't show on first request. Any idea what would cause that?

UPDATE:

I spent most of the day yesterday working on this. It happens when the derivative image is first created and served by Drupal. I found an extra new line character at the beginning of the image. If I save it to my desktop and remove the newline it works fine.

I read elsewhere that this can be caused by an extra space in a file like settings.php or template.php, usually before the `<?php` or after the `?>` if it has one. I checked and rechecked those files and I've also been using `find` and `grep` to try and find the offending file but so far no luck.

I also tried adding `header("Fake: fake");` to different files to see if I could generate a "headers already sent" error. But the output buffering Drupal uses seems to prevent that from working. Also I added $conf\['image\_allow\_insecure\_derivatives'\] = TRUE;\` to settings.php but that didn't fix it either.

# Answer
There was extra space before the `<?php` in index.php. Not sure how I missed it with all my searching before.
> 2 votes

# Answer
I had a similar issue but it was a database setting that was causing this. If my page had multiple images, it would load one image style per load.

To fix this I updated /usr/local/mysql/my.cnf and set:

```
max_allowed_packet = 128M
wait_timeout=3600

```
> 0 votes

---
Tags: 7, media
---


# Question
Title: Unable to save field collection order of collection that includes entity reference anymore
I have a Drupal 7 site using field collection and entity reference. The collection includes one entity reference and a boolean checkbox. It is used to related "news" nodes to a page. The checkbox determines if it should show up in a carousel/slider.

We use this collection on a landing page and set it to an unlimited number of these field collections.

This used to work just fine. No idea what changed over the holidays but I came back in today with a message from the client about it. I got on the line with him and he showed it to me. I tried from my admin login and had the same problem.

No errors on the server or in watchdog. I checked apache, php, and mysql error logs. No errors on the page. This is hosted on Acquia for now.

I have cleared cache from the admin and drush. No luck. I am having the same problem with other nodes of this type. We do not use this for any other types of nodes though.

Any ideas as to what could be going on? This did work at one point. And it is clearly not saving these changes.

# Answer
Actually found that this was caused by a JS error on the page. That explains everything. Fix the JS error, fix the problem.
> 0 votes

---
Tags: 7, nodes, entities
---


# Question
Title: Allow admin to discount line item price or give a user credit
I have a client who'd like to give certain users an arbitrary discount or credit to be used to pay for a class. In these situations an admin will create the registration (using the Registration module) which will automatically create a cart with this class as a line item. I'm having trouble figuring out what process to use to (from the user's perspective) correct the price for the course in cart.

My understanding is that there's no way to modify the price for the line item directly. Assuming this is correct (if this isn't please let me know!), my research indicates I'll need to add a line item to the order that will (from the user's perspective) reduce the price to where they want it.

What should this line item be? A discount? A coupon? Something else? And, whatever the right "thing" is, how does it get applied?

I've tried installing commerce\_discount and have set up a discount, but I cannot for the life of me figure out how to apply it to an order. I've read through the info on this page --\> https://drupalcommerce.org/user-guide/discounts-and-coupons, but if the answer I'm looking for is in there, I'm not finding it.

I've also just installed commerce\_account\_balance thinking that might work, and I am still testing it, but it isn't clear it will be a good fit for my use case either.

My assumption is that others must be doing this and I just don't know enough about Commerce pricing to recognize the one or more helpful answers that are already out there (stack exchange or elsewhere)...

Any direction / thoughts / help on this will be much appreciated.

Thanks

*(question originally posted here \- it was suggested there that I post questions like this here...)*

# Answer
This sounds like a good use case for commerce\_coupon \+ commerce\_discount.

1. Add these two modules (and dependencies).
2. Add a new discount for an arbitrary % or $ off.
3. Add a new coupon code for a particular user.

*If the client wants to lock it down even more, you can modify the discount to specify a particular course/product that it applies to. You can also modify the coupon code to only apply to a particular user with a limited number of uses, date range it's valid for, and more.*

You'll definitely want to add an "**Order discount condition**" to the discount to ensure that other products, shipping costs or donations are not discounted.

Once the client has set up the discount and coupon code, they can send this to the user they need to give the discount to.

---

It's difficult to say where you're getting stuck applying the discount to the order, but I'd guess it has to do with the relationship between discount + coupon. At first I found it really confusing why discounts and coupons needed to be set in two different places.

It also appears that the commerce\_discount module is incompatible with default configuration of commerce\_account\_balance. No matter how a coupon code is applied or how much of the total it supposedly reduced, it still requested a downpayment to cover the total (undiscounted) balance. It's likely this could be fixed by changing the order that the rules are executed so that the discount is run before the balance is checked.
> 0 votes

---
Tags: commerce
---


title: Adding a counter within Rules

text:
# Question
Title: Adding a counter within Rules
I have created an endless loop within Rules that will evaluate nodes after they are created and reschedule itself as shown here:

I would like the loop to close after three emails have been sent. A counter could be added to the action set under "Send Email" then the conditions could include a Data Comparison to see if the counter is less than 3.

I have tried creating fields within the content type that would have the Rule Component increase the counter field by one every time the email section was executed then have a data comparison between the counter field and a Email Max field that had a default value of 3. I wasn't able to get this to work because the counter would not be increased.

Could this be done with an "Execute Custom PHP Code" action?

# Answer
Going off memory here:

For both if and else, Add Action \>\> Set a Data Value \>\> node:field-email-max \>\> OFFSET: +1 `(To get the offset, you will have to click the switch data selection button)`

For both if and else \>\> Add Conditional \>\> Data Comparison \>\> node:field-email-max \>\> Less than 3
> 3 votes

---
Tags: 7, rules
---


# Question
Title: How can I set only a view of two views added to a panel to be shown as accordion?
I have a panel page which contains 2 views. I only want a single view to display as accordion. If I set the style setting of that view to *Accordion*, nothing happens; if I set the style setting of the panel to *Accordion*, both the views become accordions.

How can I set only a view of two views added to a panel to be shown as accordion?

# Answer
> 0 votes
You can do it by using these modules :

Panels Accordion

> Panels Accordion provides an accordion display within Panels. By using accordions you can fit more content into smaller areas and allow your users to expand each section as needed. This uses the existing jQuery file for the accordion effect. The layout settings allow you to choose the action, effect, and speed for accordions.

views Accordion

> Views Accordion provides a display style plugin for the Views module. It will take the results and display them as a JQuery accordion, using the first field as the header for the accordion rows.

---
Tags: views, panels
---


# Question
Title: Use node custom field to choose my posts background
I'm building my first Drupal 8 theme and I'd like to add the possibility to change the page background header when editing a post.

I've added a custom field in my post type to provide an image to each post. It works, I can add an image and access the image url on my page.

The problem is that I can't find a way to add inline css to my page to add the background-image property.

Here's my code, located in my .theme file :

```
function hugo_preprocess_page(&$variables) {

  $node = \Drupal::request()->attributes->get('node');

  if($node->field_image_de_fond->entity) {
        $image_url = $node->field_image_de_fond->entity->url();
        $css_code = ".header-bg-home { background-image: url('" . $image_url . "'); }";
        $page['#attached']['css'][] = array(
              'data' => $css_code,
              'type' => 'inline',
              'scope' => 'header'
            );
  }

}

```

Any help would be really appreciated!

As it's my first D8 theme I'm really not sure about the way am doing that, it would probably be better to write a custom css stylesheet with the image url as a parameter, but I've no idea how to do that. Also, I'm not sure about the `\Drupal::request()->attributes->get('node');` in terms of performances.

# Answer
> 0 votes
Why use a preprocess function ? Instead use a template =).

Here is an example of how I achieve this functionality for the content type "Article" + the image field.

**node--article.html.twig**

```
  <header class="main-header post-head " style="background-image: url({{ file_url(node.field_image.entity.fileuri)}})"> </header>

```

I added the image on the header on top of my template and use the file\_url to get the image from the field\_image.

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

```

This will allow you to get the image URL.

Few wrappers + classes to make it this image as background image. And every node will have a custom image background.

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


# Question
Title: Comments not displaying for node that was added to a custom page
I’m attempting to make it possible for users to add comments to a custom page that was created via Page Manager. My understanding is that it is not possible to set up and allow commenting for page but only for nodes. Therefore i created a special content type and corresponding node and added it to the page. i added via ‘Add existing node’ option.

I’ve added comments to this special node but they are not being displayed when viewing the node in context of the custom page. Does anyone know how i can get these comments to display?

# Answer
> 0 votes
My suggestion is to use the default 'Basic page' content type to create page and allow comments there. If you need to have custom path for it, you can setup url alias. Also for additional customization or theming, you can opt for node specific template.

I hope my answer applies to your situation :)

---
Tags: comments
---


title: How do clean_class and clean_id work?

text:
# Question
Title: How do clean_class and clean_id work?
I am new to Drupal 8 and Twig syntax. I am not able to understand how the *clean\_class* filter works in `region|clean_class`. What is *clean\_class*? I have added the following code in the page.html.twig file.

```
{%
  set classes = [
    'region',
    'region-' ~ region|clean_class,
  ]
%}

{{ dump(classes) }}

```

It prints this.

```
array (size=2)
  0 => string 'region' (length=6)
  1 => string 'region-' (length=7)

```

# Answer
`clean_class` is a filter which invokes the `\Drupal\Component\Utility\Html::getClass()` method on the string, which:

> Prepares a string for use as a valid class name.

Basically it removes invalid characters from HTML classes in preparation for rendering. `clean_id` is the equivalent for HTML IDs.

There are other filters registered by core too, see TwigExtension::getFilters for more details.
> 25 votes

---
Tags: 8, theming
---


title: Display node in user profile page

text:
# Question
Title: Display node in user profile page
I created a content type called `successful story`.

In user profile page `user-profile.tpl.php`, I have inserted a link to create a `successful story`

```
<?php print l(t('Add a successful story'), "node/add/successful-story"); ?>

```

For example, an user called `user1` clicks on the link, and creates a successful story. **I want to display the successful story the user created into their respective profile page**

I add this code into `template.php`

```
<?php

function mytheme_preprocess_page(&$variables, $hook) {
  global $user;
  $uid = $user->uid;
  $nid = db_query("SELECT nid FROM {node} WHERE uid = :uid AND type = :type", array(":uid" => $uid, ":type" => 'successful story'))->fetchCol();
  $variables['ss_node'] = drupal_render(node_view(node_load($nid)));
}

?>

```

Then I add this code into `user-profile.tpl.php`

```
<?php

  global $user;
  $user_id = arg(1);

print $ss_node;

?>

```

I hope I'm clear. Thanks for your help !

# Answer
> 0 votes
It won't be available directly in the template. First you should query the content created by that user and then pass it to template file using preprocess function. Finally render the node.

First to find the node created by the user

```
$nid = db_query("SELECT nid FROM {node} WHERE uid = :uid AND type = :type", array(":uid" => $uid, ":type" => 'successful_story'))->fetchCol();

```

(Hope the user creates only one node or else you got to check it)

Then get the node content

```
$variables['ss_node'] = drupal_render(node_view(node_load($nid)));

```

The final code should be like

```
function template_preprocess_page(&$variables, $hook) {
  global $user;
  $uid = $user->uid;
  $nid = db_query("SELECT nid FROM {node} WHERE uid = :uid AND type = :type", array(":uid" => $uid, ":type" => 'successful_story'))->fetchCol();
  $variables['ss_node'] = drupal_render(node_view(node_load($nid)));
}

```

Finally you can just print the `$ss_node` in `user-profile.tpl.php`

---
Tags: theming, users, nodes
---


title: Admin toolbar doesn't appear

text:
# Question
Title: Admin toolbar doesn't appear
My admin toolbar doesn't showing up. `$page_top` in html.tpl.php doesn't have any value.

Why doesn't `$page_top` have any value? How do I fix this?

# Answer
> 0 votes
I just solved it.

Stupid mistake by me. I'm new to Drupal. I tried to create user (admin) directly from the database. Yes, I can login, but the admin toolbar(menu) will not appear.

How to solve the problem?

* Just create user with the normal(correct) way - from the website.
* Don't create user directly from the database.

# Answer
> 0 votes
Try this CSS.

```
#admin-menu, #admin-menu .dropdown {
  z-index: 9999;
}

.logged-in #oa-navbar {
  top: 25px;
}

```

---
Tags: 7, toolbar
---


# Question
Title: How to partial search in taxonomy terms and entity references with Views Exposed Filter?
I have a content type and the content type has a taxonomy term field (**tags**) and a entity reference field (**author** as another content type).

I'm trying to create an "advanced search" with **views exposed filter**.

What I want to do is to allow users to search in node titles and inside these fields without an autocomplete function. I don't want to force the users to write and select an author, but I want to let them to write a word and then search.

## For example:

**If a user enter *John* in the author field then search; all the nodes should be listed with the authors name that include "*John*": John A., Michael John, Another John etc.**

**How can I do this?**

# Answer
Use relationships to expose the exact field, for instance use taxonomy relationship and then instead of the taxonomy field expose taxonomy term name with the relationship selected. Do the same for entity reference.
> 2 votes

# Answer
I think the best way to achieve you goal is to use search\_api module that provides a rich set of options alongside **views**, besides indexing based on the fields that you need to search by which increase performance especially in case of your data becomes big over time and have millions of records.

It provides faceted search that lets you create a facet search easily or use views if you need.

The default search server will be your DB or you could use **apachesolr** or **elasticsearch** if you need high performance search.

Good tutorial on using search api found here
> 1 votes

# Answer
I believe that what you need is: Global: Combine fields filter. This is a filter provided by Views out of the box. In this filter's settings you can (1) add your 'author field', or even more fields (2) set the `Operator`, provided by that filter, to: `Contains all words` so to return results like you said:

> If a user enter John in the author field then search; all the nodes should be listed with the authors name that include "John": John A., Michael John, Another John etc.

and (3) it is working as a simple text field, not as an auto-complete field.

I Hope that helps!

**Update:**

I admit that my answer is incomplete but it is working, however there is a peculiarity: if you look closely the View's query that is being constructed , and especially the `where` clause, for that particular field type (entity reference or term reference) you will see that includes the `field_name_target_id/field_name_tid` field instead of the `field_name_value` field and while you are searching for text it's reasonable that you get no results, but if you search with the `nid/tid` you will get the desired results. So all you have to do is to include in the `where` clause the field you want to search at and hook\_views\_query\_alter is the most appropriate hook. Of course the use of relationships is acceptable, but I just wanted to make it clear that it is working and that it is not a bug, in my humble opinion.
> 1 votes

# Answer
Combined fields filter with Entity Reference does not work, I found **Combined fields filter not working with entity reference.**

Therefore, you will have to use it as a standalone, not combined, filter until this bug is fixed, which does not look like it will be any time soon.
> 1 votes

---
Tags: 7, views, entities
---


# Question
Title: Store all images uploaded to website in specific directory
I have been using various image gallery modules, customised views galleries/ slideshow and my images are ending up in multiple directories also stored as different sizes e.g. thumbnail, medium, large...

Is there also a way (maybe a script) to delete the file from anywhere in the directory when the node that holds the images is deleted?

# Answer
> Is there also a way (maybe a script) to delete the file from anywhere in the directory when the node that holds the images is deleted?

They get auto deleted when cron runs.
> 0 votes

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


title: Referencing Entity

text:
# Question
Title: Referencing Entity
Is there no current way to get a referencing entity from a view? When clicking on relationship it only shows content referenced from the field, not from the referencing entity.

# Answer
This is not ready yet:

Implement Entity Reference Backreferences

But you can start from the other side. Start in views with the referencing entity and use a contextual filter with the referenced entity nid and then make the relationsship to get the fields of both entities.
> 2 votes

---
Tags: views, 8
---


# Question
Title: Unable to rebuild a form in submit handler
I don't have much experience in drupal development. So for the purpose of learning, i have made a custom module and trying to implement various functionalities in drupal 8 module development. I want to rebuild a form on submission of the form. I took help from here and here and drupal.org's this node. How can i rebuild the form on clicking on the button 'Click Me'. It is not throwing any error but the form is not getting rebuild in the following piece of code :

```
function say_hello_submit(&$form, &$form_state) {

    $form_state->setRebuild();
  }
public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('hugs.settings');

    $form['default_count'] = [
        '#type' => 'number',
        '#title' => $this->t('Default_hug_count'),
        '#default_value' => $config->get('default_count'),
    ];
    $form['mytable'] = [
        '#type' => 'table',
        '#header' => [t('Name'), t('Value')],
        '#rows' => array(),
    ];
    for ($i=1; $i<=2; $i++) {
        $form['mytable'][$i]['name'] = array(
            '#type' => 'textfield',
            '#size' => 40,
            '#maxlength' => 40,
            '#title' => t('Name'),
             '#title_display' => 'invisible',
     );

        $form['mytable'][$i]['value'] = array(
            '#type' => 'textfield',
            '#size' => 40,
            '#maxlength' => 40,
            '#title' => t('Value'),
            '#title_display' => 'invisible',
     );
    }
    $form['submit'] = array('#type' => 'submit', '#value' => 'Click Me');
    $form['#submit'][] = 'say_hello_submit' ;

    return parent::buildForm($form, $form_state);

}

```

# Answer
> 2 votes
What exactly do you expect to happen when it's "rebuilding"?

I should simply call buildForm() again, but that will build the same form, so visually, you won't see a difference. The only ondication would be that it's doing only a POST request, while a non-rebuilding form submission does a redirect to the same page after submitting.

If you e.g. want to see additional rows in your list, you need to store the desired max with `$form_state->set('max_rows, 5)` and then in your buildForm() method, read it again from there with get()

# Answer
> 1 votes
I haven't tried this if Drupal 8, but if `say_hello_submit` is a member of your form class, you'll need to link it to the class instance. This notation works for me for other form callbacks, but if haven't tried it for a submit handler yet:

```
$form['#submit'][] = array($this, 'say_hello_submit');

```

Also, the handler will need to be a public function.

---
Tags: forms, 8
---


# Question
Title: Node Metatag data migration with the Migrate-Update\Drupal-Upgrade module
I ask this for freshmen like myself, and others, who want to make sure they are making the best migrate-update possible:

I have created a local copy of a Drupal 7 site and have also created a brand-new Drupal 8 site. I have no content to migrate-update into the Drupal 8 site besides Nodes, their Metatag data, and a list of Redirects. I've already installed the modules Migrate update, Metatag, and Redirect (via GitHub) in the Drupal 8 site as well.

Is here something special that needs to be configured after the installation and enabling of the module in the Drupal 8 site to which I plan to migrate and upgrade content?

In other words, should I configure something in the D8 site Metatag module settings to insure a stable and correct migration of each node's meta title, description, and keywords from the D7 site?

# Answer
> 2 votes
Both redirect and Metatag have to provide their own migrations (migration templates), it's not something that you can just configure.

All you can do, if you don't know how to do it yourself is open issues for those projects and hope someone will do it. Or find someone you can pay that does it for you.

---
Tags: 8, migrations, meta-tags
---


# Question
Title: How to hide non-editable profile fields in DrupalGap?
In the Drupalgap user profile there is a field that should be viewable, but not be editable by the user. I am using field permissions and the permissions are respected - the user cannot change/save/update the value.

But the field is shown in the edit view of the profile a looks editable. Is this intended?

How can I hide the field in the edit user view? Is targeting the specific field(s) individually with hook\_form\_alter the best way?

```
/**
* Implements hook_form_alter().
*/

function my_module_form_alter(form, form_state, form_id){
 try {

console.log("Form ID " + form_id); // Use to see the form id.
console.log("FORM: " + JSON.stringify(form));    // Use to inspect the form.

if (form_id == 'user_profile_form') {
   $('#edit-user-profile-form-field-points-und-0-value').css("background-color","yellow"); // not working
   $('#edit-user-profile-form-field-points').css("background-color","yellow"); //not working
   $('#edit-user-profile-form-field-points-und-0-value').hide(); //not working

// not working from: https://www.drupal.org/node/2170427:
 form.elements.edit-user-profile-form-field-points-und-0-value = {
 // type: 'textfield',
 // title: 'My Text Fied',
  options: {
    attributes: {
      disabled: 'disabled'
    }
  },
  access: false /* use this to completely hide the form element */
};

console.log("this is user_profile_form");
}
}
 catch (error) { console.log('my_module_form_alter - ' + error); }
}

```

# Answer
> 1 votes
During `hook_form_alter()` implementations in DrupalGap, the form hasn't yet been rendered into the DOM, so at that point it is not yet possible to use jQuery selectors on the form.

Instead use an inline JS event (attach it to the form's prefix or suffix during the form alter). Your inline JS page event handler can have a custom function, and that custom function can do the custom jQuery selectors. Also, that appears to be the incorrect usage of the `access` property. Try this instead:

```
// During hook_form_alter()...
form.elements['field_points'].access = false;
form.suffix += drupalgap_jqm_page_event_script_code({
    page_id: drupalgap_get_page_id(),
    jqm_page_event: 'pageshow',
    jqm_page_event_callback: 'my_user_profile_form_pageshow',
    jqm_page_event_args: JSON.stringify({
        hello: 'Hi!'
    })
});

```

Then make a custom function:

```
function my_user_profile_form_pageshow(options) {
  $('#edit-user-profile-form-field-points-und-0-value').css("background-color","yellow");
  $('#edit-user-profile-form-field-points').css("background-color","yellow");
  $('#edit-user-profile-form-field-points-und-0-value').hide();
}

```

---
Tags: users, javascript
---


# Question
Title: Views: count and filter by entity field value
I have many nodes of type 'Players' and 'Match'. In the 'Match' node there is an entity field 'Strikers' referenced to 'Players' which allow multiple values.

I'd like to create a player page that shows information about that player searching all occurrence of that player in the 'Match' nodes (inside the 'strikers' field of each node).

I tried with the contextual filter but I don't know if it is the correct way..

# Answer
> 0 votes
Going of memory here, this might be wrong:

Add contextual filter of node id (nid) (so the player nid goes here)

Add a RELANTIONSHIP of Strikers Referencing Entity and checkmark the box that says, "force relantionship" or something along those lines.

---
Tags: views
---


# Question
Title: Change field type from "text field" to "integer"
I have a field that is numerical in nature and it was setup as text field. The problem is that sorting by ascending, the number 111 comes before 20.

# Answer
One option could be to create another field, of integer format.

Then using PHPMyAdmin (or similar) copy the contents of the field\_data\_field\_FIELDNAME\_TEXT\_FIELD into your newly created field\_data\_field\_FIELDNAME\_INTEGER\_FIELD.

If that works you can then delete the original text field.
> 4 votes

# Answer
**Updated answer:** You could try and use the following module. https://www.drupal.org/project/helper

The function that you are interested is called changeType() inside the FieldChangeHelper class.

The way to go here is implementing an update hook. Things can vary in your implementation. Haven't tested this particular implementation. This is just a guideline. Assume your field is called test. Put this snippet in a custom module. Run update.php . Flush caches (x2) and you're done. Regards.

```
/**
 * Change field_test field from textfield to integer
 */
 function mymodule_update_7001() {
 // Manual database changes to the field config table. Sometimes there is serialized data to take into account.
   db_query("UPDATE {field_config} SET type = 'integer' WHERE field_name = 'field_test'");
 // drupal internal function that takes care of changing the field's attributes
 db_change_field('field_data_field_test', 'field_test_value', 'field_test_value', array(
 'type' => 'integer',
 'length' => '10',
 ));
//revision field
 db_change_field('field_revision_field_test', 'field_test_value', 'field_test_value', array(
 'type' => 'integer',
 'length' => '10',
 ));
 // Clear caches.
 field_cache_clear(TRUE);

```

}
> 0 votes

# Answer
This worked for me and its based on the previous answer but its tweaked with the right parameters. Using drupal 7.34

Keep in mind that this can only be achieved if you have no values in the field or you KNOW that all values are just numbers(integers in this case). Otherwise you have to do some data manipulation prior to changing the field type.

```
function MYMODULE_update_7001() {
  // Manual database changes to the field config table. Sometimes there is serialized data to take into account.
  db_query("UPDATE {field_config} SET type = 'number_integer', module = 'number' WHERE field_name = 'field_name'");
  // Text fields have an aditional column for format which number doest have. We drop those.
  db_query("ALTER TABLE field_data_name DROP field_name_format");
  db_query("ALTER TABLE field_revision_name DROP field_name_format");
  // Change all empty values to 0 otherwise we get an error.
  db_query("UPDATE field_data_name SET field_name_value = '0' WHERE field_name_value =''");
  db_query("UPDATE field_revision_name SET field_name_value = '0' WHERE field_name_value =''");

  db_change_field('field_data_name', 'field_name_value', 'field_name_value', array(
    'type' => 'int',
    'length' => 11,
    'not null' => FALSE,
    'default' => NULL
  ));

  //revision field
  db_change_field('field_revision_name', 'field_name_value', 'field_name_value', array(
    'type' => 'int',
    'length' => 11,
    'not null' => FALSE,
    'default' => NULL
  ));

  field_cache_clear(TRUE);
}

```
> 0 votes

# Answer
I had the same problem today, but I cannot create a new field, too much business logic on that.

I did like @mask-ota, but I had to add more code because some of the field settings are stored in a php-serialized form in field\_config.data and field\_config\_instance.data fields.

So I ended like this:

```
function MYMODULE_update_7101() {

    // Manual database changes to the field config table. Sometimes there is serialized data to take into account.
    db_query("UPDATE {field_config} SET type = 'number_integer', module = 'number' WHERE field_name = '[FIELD_NAME]'");
    // Text fields have an aditional column for format which number doest have. We drop those.
    db_query("ALTER TABLE field_data_[FIELD_NAME] DROP [FIELD_NAME]_format");
    db_query("ALTER TABLE field_revision_[FIELD_NAME] DROP [FIELD_NAME]_format");
    // Change all empty values to 0 otherwise we get an error.
    db_query("UPDATE field_data_[FIELD_NAME] SET [FIELD_NAME]_value = '0' WHERE [FIELD_NAME]_value =''");
    db_query("UPDATE field_revision_[FIELD_NAME] SET [FIELD_NAME]_value = '0' WHERE [FIELD_NAME]_value =''");

    db_change_field('field_data_[FIELD_NAME]', '[FIELD_NAME]_value', '[FIELD_NAME]_value', array(
      'type' => 'int',
      'length' => 11,
      'not null' => FALSE,
      'default' => NULL
    ));

    //revision field
    db_change_field('field_revision_[FIELD_NAME]', '[FIELD_NAME]_value', '[FIELD_NAME]_value', array(
      'type' => 'int',
      'length' => 11,
      'not null' => FALSE,
      'default' => NULL
    ));

    // field_config.data serialized field
    $result = db_select('field_config', 'c')
        ->fields('c')
        ->condition('field_name', '[FIELD_NAME]','=')
        ->execute()
        ->fetchAssoc();
    $data = unserialize($result['data']);
    unset($data['settings']['max_length']);
    $num_updated = db_update('field_config')
        ->fields(array(
          'data' => serialize($data),
        ))
        ->condition('field_name', '[FIELD_NAME]','=')
        ->execute();

    // field_config_instance.data serialized field
    $result = db_select('field_config_instance', 'c')
        ->fields('c')
        ->condition('field_name', '[FIELD_NAME]','=')
        ->execute()
        ->fetchAssoc();
    $data = unserialize($result['data']);
    unset($data['widget']['settings']['size']);
    $data['widget']['type'] = 'number';
    $data['widget']['module'] = 'number';
    $data['widget']['active'] = 0;
    unset($data['settings']['better_formats']);
    $num_updated = db_update('field_config_instance')
        ->fields(array(
          'data' => serialize($data),
        ))
        ->condition('field_name', '[FIELD_NAME]','=')
        ->execute();

    field_cache_clear(TRUE);
}

```

You canfind useful this site to serialize/unserialize data field and compare it with an existing integer field.
> 0 votes

---
Tags: entities
---


# Question
Title: How do I disable Commerce cart order refresh to preserve custom prices on line items?
The goal is to allow the user to select the quantity they want, hit Add to Cart, then have the script separate the Line Item into individual Line Items with the Quantity of 1. I have accomplished this using Rule which works great but we also use Commerce Pricing Attributes which allows you to alter the price of a product before adding to cart. The altered price does not carry through to the split Line Items using this Rule. My script so far does keep that price.

This works for the first time the cart is loaded. The second time the cart is loaded, the original price is not applied to the added line items. Instead they remain in tack but get their default price applied.

Here is the shopping cart when it's first loaded after clicking the Cart link in the popup message. Everything appears OK with price across all items.

Here is what it looks like when I refresh the page, update cart, proceed to next step - pretty much anything that will trigger the commerce\_cart\_order\_refresh().

As you can see the original item retains it's altered price, but the others that were added now default back to their original price.

Here is my code:

```
function ces_line_items_commerce_cart_line_item_refresh($line_item, $order_wrapper){
    // set the global user
    global $user;
    // load the entity wrapper of the line item
    $line_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    // get the quantity of the line item
    $quantity = (int)$line_wrapper->quantity->value();
    // get the product id to use later
    $product_id = $line_wrapper->commerce_product->product_id->value();
    // set the altered price or current price of line item
    $newPrice = $line_wrapper->commerce_unit_price->amount->value();
    // get the original line item
    $old_line_item = $line_wrapper->line_item_id->value();
    // load the original line item -- need to do this for rewriting later
    $original_line_item = commerce_line_item_load($old_line_item);
    // set our index
    $i = 1;
    // only do the following if the original line item has a quantity above 1
    if($quantity > 1){
        // loop until we are 1 below quantity
        while($i < $quantity) {
            // it the product can be loaded
            if ($product = commerce_product_load($product_id)) {
                // create new line item
                $new_line_item = commerce_product_line_item_new($product, 1, $order_wrapper->order_id, $original_line_item->data);
                // make sure to include any additional price calculations
                drupal_alter('commerce_product_calculate_sell_price_line_item', $new_line_item);
                rules_invoke_event('commerce_product_calculate_sell_price', $new_line_item);
                // reload the line item
                $new_line_item = commerce_cart_product_add($user->uid, $new_line_item, FALSE);
                // set unit price
                $new_line_item->commerce_unit_price['und'][0]['amount'] = $newPrice;
                // set base price
                $new_line_item->commerce_unit_price['und'][0]['data']['components'][0]['price']['amount'] = $newPrice;
                // set base total amount
                $new_line_item->commerce_total['und'][0]['data']['components'][0]['price']['amount'] = $newPrice;
                // save new line item
                commerce_line_item_save($new_line_item);
                // add line item to order wrapper
                $order_wrapper->commerce_line_items[] = $new_line_item;
            }
            // increment our index
            $i++;
        }
    }
    // alter line item quantity back to 1
    $original_line_item->quantity = "1.00";
    // save line item
    commerce_line_item_save($original_line_item);
}

```

So what I need is the ability to disable commerce\_cart\_order\_refresh from trying to default everything back.

# Answer
> 4 votes
You're approaching the problem incorrectly here. You shouldn't be trying to disable the cart order refresh. That includes things like discounts, taxes, etc. that may actually need to be applied to line items on the order in the future.

Instead, you should find a strategy to enrich the line item with the information it needs to reset the price to the proper custom price during the pricing process. This is the approach utilized in our old donation examples where customers can enter custom prices to donate:

https://drupalcommerce.org/videos/tutorials/donations-custom-line-item-types

I have no experience with the module you're using, so I can't say how to keep working within the framework it provides. Generally speaking, though, you could make this work by adding a price field to the line item called "Custom price" or something and then creating a pricing rule that sets the unit price of line items to the custom price at the appropriate point in time.

Alternately, you could store the necessary information in the data array of the line item, but then you'd still need a product pricing rule with a custom action that knows how to inspect the data array and reset the unit price to the appropriate amount.

---
Tags: commerce
---


title: Change teaser image size

text:
# Question
Title: Change teaser image size
I've noticed that the article images are sized to a width of 220px to be displayed in the teaser on the frontpage in Drupal 8. I'm wondering how to change that to 300px, for example.

I created an image style with the size I want with the image module at `admin/config/media/image-styles`, but how do I associate that with the teaser that's shown on the home page? I looked in the `Frontpage` view, but didn't see any way of editing the image style there.

What's the best way to do this?

# Answer
> 5 votes
This is in the view mode "teaser" of the content type "article":

```
/admin/structure/types/manage/article/display/teaser

```

Go there and click on the setting symbol in the field "image" and choose the new image style.

---
Tags: 8, media, nodes
---


# Question
Title: Display region's blocks into user-profile.tpl.php
I created a view listing content type called stories. Then I created a block with this view.

In mytheme.info file I have this code :

```
regions[header] = Header
regions[story] = Story
regions[content] = Content

```

**So I put the view into the Story region**

I want to display the region into `user-profile.tpl.php` so I add this code :

```
<?php print render($page['story']); ?>

```

If everything work, it should display all the stories via the view.

I don't know why it does not work.

Thanks for your help !

# Answer
> 0 votes
If you would like to show blocks only on the profile page and not on the user/register or user/login or or user/\*/edit, you can use the code for blocks visibility.

```
<?php
global $user;
if (arg(0) == 'user' && $user->uid == arg(1) && is_numeric(arg(1)) && (arg(2) == NULL) )
{
  return TRUE;
}

else {
  return FALSE;
}
?>

```

---
Tags: views, blocks, theming
---


title: Views, Taxonomy, Tokens and URL

text:
# Question
Title: Views, Taxonomy, Tokens and URL
I am building a website for multiple summer resorts. I am now concentrating on the restaurants section.

I have a content type - Restaurant.

It has multiple fields but I will just put down the ones that are connected to this question;

```
field_resort: Term Ref.
field_restaurant_category: Term Ref.

```

And then the url pattern;

```
[node:field-resort]/restaurant-guide/[node:title]

```

---

I need a block in the restaurant parent page \[node:field-resort\]/**restaurants** that then displays a grid with each individual taxonomy term \[field\_restaurant\_category\].

What the problem is is that I want to have a page that once you click on one of those categories, takes you to a page that displays teaser views of all the restaurants for that specific food categorie from only that resort while appending the url to keep the resort as the parent.

```
resort-1/restaurant-guide/[field_restaurant_category]
resort-2/restaurant-guide/[field_restaurant_category]
resort-3/restaurant-guide/[field_restaurant_category]

```

# Answer
> 0 votes
In Views the pattern for the path cannot have a contextual filter as the first part of the path.

Contextual filters and paths

> The normal way a view gets values for contextual filters is by the view path. The easiest way of doing this is to append filter values to the path, separated by slashes. It is also possible to have contextual filter values within a path. This is done by using a percent sign where the view expects a contextual filter value in the path of the view (for example user/%/comments).

So your pattern needs to change to something like this:

```
resorts/%/restaurant-guide/%

```

as in resorts/\[resort\]/restaurant-guide/\[restaurant-category\]

Then two contextual filters:

```
**content resort (field resort)**
Taxonomy term ID from URL
Validator: Taxonomy Term
Vocabulary: resort
Filter value type: Term name converted to Term ID

**content restaurant category (field restaurant category)**
Same as above but with Vocabulary: restaurant category

```

Then keep in mind that you might need to deal with spaces in your taxonomy terms

# Answer
> 0 votes
I was a bit of a novice when it came to contextual filters.

Taxonomy term ID from URL Validator: Taxonomy Term Vocabulary: resort Filter value type: Term name converted to Term ID

**content restaurant category (field restaurant category)** Same as above but with Vocabulary: restaurant category

This worked

---
Tags: 7, views, uri, tokens
---


# Question
Title: Commerce functionality using Domain Access + i18n
I have several sites using modules Domain Access and i18n, using Drupal 7. I am completely newbie to commerce, and have read about the options of modules Ubercart and Drupal Commerce.

However, I want to have the flexibility of Domain Access, so I would like to have a store section which is different for any domain (at the least) and possible different for any domain-language combination (less likely).

What would be the best option of the above modules? Are they both compatible with Domain Access? How do I need to install Drupal, first the commerce or better (I guess so) the Domain Access + i18n and, after that, the module ( I had great problems with a module related to Domain Access just because of the order of installation, with no even the developer knowing what had happened or if it was a bug after all ).

# Answer
> 2 votes
The answer to your question: Can a Drupal Commerce catalog show different domain-aware products? is "yes." Mostly because Drupal Commerce simply uses content and Views to build catalogs, so if you can get Drupal to do something, Drupal Commerce is most likely along for the ride.

But I want to dig a little deeper to help you understand the problems you will uncover as you try to build something like this. Drupal Commerce 7 works on 2 levels (the version for Drupal 8 is much different):

1) **Node level** \- Content with a title, a url, and published settings are best kept as nodes in Drupal 7. That suits Drupal Commerce well, since if you want to display a product, you must do it with a product reference field on a node. Most of the content related to specific products (a specific size/color/configuration) are actually injected fields. Injected fields get replaced automatically using ajax when an attribute field (size/color/configuration) is changed. This presents the biggest challenge for domain/translation.

2) **Entity level** \- Lots of things in Commerce are simply implemented as custom entities. This includes products (not product displays), Orders, Line Items, etc. Products are the most likely to give you problems. For example, if you set a product display (node) to be certain domains, and products to be other domains, what do you expect to happen?

The Domain Access module is built to work with nodes exclusively. While some effort has been put into making a generic entity solution, it has many failings, most of which include a buggy and bloated data-entry interface. If I were to build such a thing, it would require a few patches to make it useable and understandable to the "store administrator."

For translation, you have a similar problem. You will need to decide whether you want to be able to translate certain fields (titles, description) or entire nodes/entities (a complete copy of the about us page, including attachments).

Most likely, you will want field-level translation. In that case, product pages that use product-level content (pictures or description that are a part of the attributes, like color/size/configuration) have a difficult problem to solve. The node would need to bring in a translated version of fields, and (optionally) bubble up product-level (read: entity-level, not node level) translated versions. If this sounds confusing, it's because it really is. We have multiple sources of content, all that would require some form of field-level translation.

**The good news** is, you can confirm this works in a matter of minutes with commerce\_kickstart version 1 plus your domain and translation modules of choice. Note that field-level translation is supported by search\_api, which means that your catalogs that should respond to domain and language, is possible and works without patches (this was not always the case).

**The bad news** is, while this is relatively easy to build as a demo, in practice, the resulting mess of products, translations, and page-level content becomes very hard to represent in a administrative interface in such a way that your average non-drupaler would know what's going on. For example, lets say you have a tshirt shop that sells shirts in two colors and two sizes. How do you describe to your store administrator that the color "red" is a taxonomy term that needs to be translated because it's connected to products which are connected to the page they are on? It's 3+ levels deep. Quite an abstract problem.

Your question isn't really suited for a "how to" because there many variations on your request that would completely change how I would set up the underlying information architecture. Something else you might consider adding to your architectural plan would be a comprehensive way to deal with multiple currencies in the face of domain/translation combinations.

// Edit: Here are some module recommendations:

* I wouldn't use Domain Access if you are trying to control product visibility with domains. It's too messy. It's much easier to simply create a taxonomy term and then build a custom views condition that compares the taxonomy term with the actively requested domain. I have built one store where this was a take-away after months of development.
* I recommend https://www.drupal.org/project/entity\_translation for field level translation
* You will still likely need https://www.drupal.org/project/i18n for menu and taxonomy (attribute) translation.
* I highly recommed you tell your designer you need an interface that helps selecting a domain, a language, and a currency. Or some combination. At the end of the day, there isn't one easy way to do this, especially important to nail the mobile-responsiveness of your visual solution. (Drop-downs don't make as much sense on a phone).

---
Tags: 7, i18n-l10n, commerce
---


title: How to debug ajax in form?

text:
# Question
Title: How to debug ajax in form?
I have a form that uses ajax submit "method", the ajax submit handler returns ajax response with complete form(the form has ajax wrapper outside of itself so no issue there) and it is not working for anonymous users. I am using dynamic\_page\_cache only at this point.

I am displaying this form via field formatter that I have on an entity(imagine comment form) and I am using lazy builder.

The thing is that the form works for anonymous users if there are multiple forms like this on a single page(imagine taxonomy term page listing entities) but it is not working when there is only one form(entity page..imagine node/1). By not working I mean the form will submit but not with ajax but traditionally via normal post method.

I have checked the form structure, wrapper, drupalSettings.ajax entries, JS errors, watchdog..everything, but I just cannot figure out why the form does not utilize ajax but will submit as normal form instead. I have compared loaded JS with anonymous and logged in user, nothing significant there. The only thing that I have found that differs is missing form\_token input in the form compared to logged-in user but I have checked the FormBuilder and this is on purpose + when I'm listing multiple entities with this form the ajax works just fine without it.

And so since there are no errors anywhere I have nothing to grab on to for debugging.

So my question is how could/should I try to debug this issue?

This question is a follow-up from Does caching has to be manually disabled for ajaxified forms?

# Answer
> 1 votes
Eureka!

So, I still am not sure what the issue was 100% but I am guessing that there was a name collision with multiple different forms and since Drupal uses name "op" for every submit button since the dark ages of the internet I guess the ajax was trying to get itself applied to the other form that had submit button as well(named op as well) but that did not work of course so that resulted in this weird behavior.

**So the way I have fixed this was by setting the #name AND #id attributes on the submit button in my form.** I have set the #id which I normally don't do in ajax forms because I would get wrong drupalSettings.ajax entry.

I didn't do this in the first place because the form was working just fine for logged-in users + just fine for anonymous users on entity listings so it didn't made any sense but hey, the more you know.

---
Tags: forms, ajax, 8, caching
---


# Question
Title: Commerce orders view for user and his subusers
The task is to create a view which will contain all orders of user and his subusers. I use the Commerce Kickstart and Subuser module. I have default view called "My orders" which prints all orders of the logged in user. I don't know, how to integrate the subuser relationship properly. How can I do it?

Added: this is the sample. it works only for one user. I need it to be worked for user and his subusers

The result should be the following: the one table like at the screenshot but with different (specified) users - the current user and his subusers...

# Answer
> 2 votes
Orders are entities. Views 3 on Drupal 7 fully supports entities.

Sub Users are entities as well, with the Relation module connecting the users.

The relationships that exist are deep and abstract to Views and, while it may be possible to do this with SQL, the resulting view would be very complex and inelegant.

So your question is more about how to construct a view with the right series of relationships so that you are given a complete list of orders out of a set of users. The most straightforward way to do this is to create a view of orders (so the base table is the order table) and then to use the contextual filters to provide a list of owner user\_id's based on the currently logged in user using PHP.

Hint: You could use the following (UNTESTED) php snippet that makes use of a subuser function to provide an array of user ids:

// Updated with a tested bit of code:

```
<?php
// never use the global $user variable directly.
$account = $GLOBALS['user'];
// the subusers module abstracts this relationship easily for us
$subusers_children = subuser_load_all($account);
// views requires a return statement.
// the subuser_load_all() returns full objects, we just need the uids
$allusers = array_keys($subusers_children);
$allusers[] = $account->uid;
return implode(',',$allusers);

```

Here's an export of a view that works (sort of). The user permissions for this would have to be reworked to make it secure. Works with user 1 if user 1 has subusers and those subusers have orders.

// Edit 2: Did some more testing, found the view wasn't working and after some debugging, it started working correctly, limiting the users to our sub users group. Sorry about the weird problems initially introduced.

```
<?php
$view = new view();
$view->name = 'user_orders_with_subusers';
$view->description = 'Display a list of completed orders for a user.';
$view->tag = 'commerce';
$view->base_table = 'commerce_order';
$view->human_name = 'User orders with subusers';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['title'] = 'All orders';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = 25;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
'order_number' => 'order_number',
'created' => 'created',
'changed' => 'changed',
'commerce_order_total' => 'commerce_order_total',
'status' => 'status',
);
$handler->display->display_options['style_options']['default'] = 'order_number';
$handler->display->display_options['style_options']['info'] = array(
'order_number' => array(
'sortable' => 1,
'default_sort_order' => 'desc',
'align' => '',
'separator' => '',
'empty_column' => 0,
),
'created' => array(
'sortable' => 1,
'default_sort_order' => 'desc',
'align' => '',
'separator' => '',
'empty_column' => 0,
),
'changed' => array(
'sortable' => 1,
'default_sort_order' => 'desc',
'align' => '',
'separator' => '',
'empty_column' => 0,
),
'commerce_order_total' => array(
'sortable' => 0,
'default_sort_order' => 'asc',
'align' => '',
'separator' => '',
'empty_column' => 0,
),
'status' => array(
'sortable' => 1,
'default_sort_order' => 'asc',
'align' => '',
'separator' => '',
'empty_column' => 0,
),
);
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['text']['id'] = 'text';
$handler->display->display_options['empty']['text']['table'] = 'views';
$handler->display->display_options['empty']['text']['field'] = 'area';
$handler->display->display_options['empty']['text']['content'] = 'You have not placed any orders with us yet.';
$handler->display->display_options['empty']['text']['format'] = 'plain_text';
/* Field: Commerce Order: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'commerce_order';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
/* Field: Commerce Order: Order number */
$handler->display->display_options['fields']['order_number']['id'] = 'order_number';
$handler->display->display_options['fields']['order_number']['table'] = 'commerce_order';
$handler->display->display_options['fields']['order_number']['field'] = 'order_number';
$handler->display->display_options['fields']['order_number']['link_to_order'] = 'customer';
/* Field: Commerce Order: Line items */
$handler->display->display_options['fields']['commerce_line_items']['id'] = 'commerce_line_items';
$handler->display->display_options['fields']['commerce_line_items']['table'] = 'field_data_commerce_line_items';
$handler->display->display_options['fields']['commerce_line_items']['field'] = 'commerce_line_items';
$handler->display->display_options['fields']['commerce_line_items']['settings'] = array(
'view' => 'commerce_line_item_table|default',
);
$handler->display->display_options['fields']['commerce_line_items']['delta_offset'] = '0';
/* Field: Commerce Order: Created date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'commerce_order';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = 'Created';
/* Field: Commerce Order: Updated date */
$handler->display->display_options['fields']['changed']['id'] = 'changed';
$handler->display->display_options['fields']['changed']['table'] = 'commerce_order';
$handler->display->display_options['fields']['changed']['field'] = 'changed';
/* Field: Commerce Order: Order total */
$handler->display->display_options['fields']['commerce_order_total']['id'] = 'commerce_order_total';
$handler->display->display_options['fields']['commerce_order_total']['table'] = 'field_data_commerce_order_total';
$handler->display->display_options['fields']['commerce_order_total']['field'] = 'commerce_order_total';
$handler->display->display_options['fields']['commerce_order_total']['label'] = 'Total';
$handler->display->display_options['fields']['commerce_order_total']['click_sort_column'] = 'amount';
$handler->display->display_options['fields']['commerce_order_total']['settings'] = array(
'calculation' => FALSE,
);
/* Field: Commerce Order: Order status */
$handler->display->display_options['fields']['status']['id'] = 'status';
$handler->display->display_options['fields']['status']['table'] = 'commerce_order';
$handler->display->display_options['fields']['status']['field'] = 'status';
/* Contextual filter: Commerce Order: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'commerce_order';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'php';
$handler->display->display_options['arguments']['uid']['default_argument_options']['code'] = '$account = $GLOBALS[\'user\'];
$subusers_children = subuser_load_all($account);
$allusers = array_keys($subusers_children);
$allusers[] = $account->uid;
return implode(\',\',$allusers);';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['uid']['break_phrase'] = TRUE;
/* Filter criterion: Commerce Order: Order state */
$handler->display->display_options['filters']['state']['id'] = 'state';
$handler->display->display_options['filters']['state']['table'] = 'commerce_order';
$handler->display->display_options['filters']['state']['field'] = 'state';
$handler->display->display_options['filters']['state']['operator'] = 'not in';
$handler->display->display_options['filters']['state']['value'] = array(
'cart' => 'cart',
'checkout' => 'checkout',
);

/* Display: User Orders */
$handler = $view->new_display('page', 'User Orders', 'order_page');
$handler->display->display_options['path'] = 'orders-subusers';
$handler->display->display_options['menu']['title'] = 'All Orders';
$handler->display->display_options['menu']['weight'] = '15';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$handler->display->display_options['tab_options']['type'] = 'normal';
$handler->display->display_options['tab_options']['title'] = 'Orders';
$handler->display->display_options['tab_options']['description'] = 'User orders in the store.';
$handler->display->display_options['tab_options']['weight'] = '';
$handler->display->display_options['tab_options']['name'] = 'user-menu';

```

---
Tags: commerce, users
---


# Question
Title: Add different classes to the images that where uploaded with multi-upload
I'm looking for the best solution to add different classes to images that where multi uploaded to one field.

So not a class to the field, but a possibility to add different classes to each single image...

So my client will be able to add for ex. the class 'right' that will let the image float to the right and be only 60% width. And then for a other image add the class 'left' for example...

So if you look at the image above, you see my client can add for each image a different alt and title. There should show up there a space where he can add for each image a different class.

Any tips, links or other sulotions to reach my goal are welcome! Thanks in advance.

# Answer
> 0 votes
Go to admin/structure/file-types/manage/image/fields. Add a text field for the class.

Now the difficult part is how you are going to get the class as an attribute into the img tag, or into a wrapper div.

If you are using Views you can easily 'rewrite the output of this field' and do it in there.

If you want to render by view mode you can use Display Suite and a custom field template, or you can just forego Display Suite and implement your own custom template file for the file display : Displaying Media

And perhaps rethink your methodology. You can let your client use CKEditor and set the classes to the images right there where he has a proper preview of how it is going to display. You can add your own custom predefined styles that is selectable from a select list. It is also possible to right click on an image and set the classes on.

# Answer
> 0 votes
I want to add what I did to help out anyone else looking for alternatives.

I used the function `hook_preprocess_image`. In it, I took the file name and added it to the *attributes \> class* array. This way it shows up as `<img class="img-responsive image-name" src="/path/to/image-name.png" width="300" height="400" alt="">`.

```
function template_preprocess_image(&$variables)  {
  // take image path and save image file name
  $image_name = str_replace(array('public://', '.png', '.jpg', '.svg'), '', $variables['path']);

  // add name as class for image
  $variables['attributes']['class'][] = $image_name;
}

```

---
Tags: theming, media
---


# Question
Title: How to expose variable from php to js - and keep it updated?
drupal\_add\_js works to pass variables from php to javascript, and there are plenty of examples. But I want the variable to update without a new page request.

I have a page request that kicks off some long-running code in the background (using background\_batch and the Batch API), during which a variable is updated occasionally. When it changes, calling drupal\_add\_js again doesn't do anything. Then I tried to implement this but it doesn't seem to work either. I've use ajax with the Form API, but that is a specific request that returns to an element just once - this is going the other way (php to js ad-hoc).

Summarizing: How to push a php variable to be available in javascript **at any point it time, from any Drupal code**?

# Answer
> 2 votes
You have two options, depending on how responsive you need it to be, and how complex you're willing to get:

1) You can add Javascript to your page that will continually send AJAX requests to the server in the background, essentially asking for the value of that variable. You would achieve this by creating a new menu path with the sole purpose of serving the value of that variable in JSON. The JS that sits on the page could then be set up to ask for that variable every X seconds until it changes (or it could just keep doing it forever if you wanted).

2) You could write a separate Node.js application that runs on your server, which listens for updates to the variable from the background task and then pushes a notification to the JS in your page via websockets. That's obviously a lot more complex. But potentially more performant, and the updates would be instant. See this module for an example of a Node.js chat application: https://www.drupal.org/project/nodejs

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


# Question
Title: What is the best practice or easiest way to import product types from their content type derivatives?
I'm new to Drupal Commerce, and I want sell clothing articles. For the clothing articles, I created a view with a content type including fields like name, price, article-number, etc.

Now I want to create a shop with product types. Can I just import the content types into the product types or do I have to add new product types and then create all the articles over again? What is the best way to add products to my shop?

# Answer
It sounds like you have your "content type" confused with your "product type". With Drupal Commerce, you need to add "products" which are of a particular "Product Type". Each product has at least a title, a SKU, and a price, but you could have more fields like size for example. You then attach the products to a product display node so that they are visible in the shop. A Product Display Node is a regular content type node with a product reference field that points to the product type entity.

You may be asking why do I need both product entities and product display entities? This is for the situation where you have multiple products included with each display. So if you have a clothing article that comes in small, medium and large sizes and is also available in either blue or green, then you have 6 SKUs for this clothing article. You would have 1 product display entities with product references to the 6 SKUs.

Your content type that is the product display should include the name of the product, the general description of the product and maybe an image of the product, etc. Your product type will have the SKU, the price, and any other fields that are unique to the SKU.

Read more (and probably better constructed examples) at the Commerce Guys site
> 2 votes

---
Tags: views, commerce
---


# Question
Title: How can I force administrator to provide a reason when cancelling a user account
I would like to find a way for drupal site administrator to provide a reason when an account has been cancelled / blocked.

I would need a radio list such as below, then an automatic email is sent with the details of the option chosen by the admin.

* Your email address is not a personal address issued by your company E.G. a.name@yourcompany.co.uk
* You did not supply your full name
* You did not supply your company name
* You did not supply a full address
* You did not supply your telephone number

# Answer
> 0 votes
In User fields, add field of type: List Text with checkboxes radio button as widget

Use the Filed Permissions module so only admins can see this user field.

Download Rules and enable Rules UI

### Create a New Rule

React on: After Updating an Existing User Account

Add Condition: Data Comparison \>\> account-unchanged:status \>\> Operator: Equals **DATA Value: Blocked**

Add Action \>\> Send Mail \>\> Body: \[user:name\] was blocked because \[user:field-example\]

---
Tags: users
---


title: taxonomy manager

text:
# Question
Title: taxonomy manager
I want to allow users to add taxonomy terms for a particular taxonomy. I added a menu item to link to the taxonomy manager. The problem is -

1. I'm not able to restrict the user to add terms to only one taxonomy (based on his role).
2. Alternatively, I tried to hide "switch vocabulary" drop down by editing the theme css (not module css. I want the behavior to be same even after module updates). That didn't work either.

Any suggestions on -

1. how to give users access to add taxonomy terms. (or)
2. restrict access in taxonomy manager (or)

Thanks

# Answer
> 0 votes
If you add a **Term Reference** field to your node with **auto complete widget**

When you type something that is not in the vocabulary, it will auto create/add it to your vocabulary as a new tax term when you hit save node.

# Answer
> 0 votes
Vocabulary Permissions Per Role module.

> You have set up some vocabularies (with some terms) like Color (Red, Green, Blue) and Shape (Toroid, Cube, Sphere). Maybe you even have a vocabulary that controls who can view a specific node (with terms) like Access control (Editors, Colleagues, World). Here comes trouble: your precious editors want to add more Colors, or reorder the terms of the Shape vocabulary (probably they want to see Sphere before Cube, who knows,) and you do NOT want to grant your editors the administer taxonomy permission, as it grants too much power (and that implies too much sharing of responsibility). Without this permission they were NOT able to do the mentioned tricks: adding terms to a vocabulary but not to another, reordering/editing terms of a vocabulary but not another's, etc.

Looks like this does exactly what you need.

---
Tags: taxonomy-terms
---


title: Where is the jquery.cycle.all.js file?

text:
# Question
Title: Where is the jquery.cycle.all.js file?
So i have install views\_slideshow\_cycle module, and it always shows "cycle" is not a function. after some googling, I found out I have to install jquery\_cycle.

In views\_slideshow\_cycle.libraries.yml file, I found this section:

```
jquery_cycle:
  remote: http://malsup.github.io/jquery.cycle.all.js
  version: 3.0.3
  license:
    name: MIT
    url: http://jquery.malsup.com/license.html
    gpl-compatible: true
  js:
    /libraries/jquery.cycle/jquery.cycle.all.js: {}
  dependencies:
    - core/jquery

```

Where is that *libraries* directory?

# Answer
> 3 votes
OK, I have found out, you have to create a libraries folder under web root.

# Answer
> 0 votes
Also you can fine this `library` folder in `/sites/all/libraries`. If it is not present then you have to create this folder because it is not created by default.

---
Tags: javascript, 8
---


# Question
Title: How to run a drupal application in github?
I am trying to setup Drupal Application in **Github** and was able to successfully setup the instance and moved the project to github.

Can anyone help me with as **how to execute a drupal application in github**,as I am finding tools to run html files but executing a drupal files seems to be a tedious task.

# Answer
> 1 votes
You can not execute Drupal in Github, just because Drupal requires a server running PHP, which isn't supported by github.

> Github Pages is not a full-featured web host. It will not execute PHP, or any other arbitrary code.
> Source

You could convert your Drupal site into a static site and upload it on github, but the website would not be dynamic anymore. If you decide to do this, you could host it using Github pages, but you would not be executing Drupal; instead, you would be going to show a static version of your Drupal website.

If you wish to add a static version of your website for Drupal 7, you can look at the Static Generator module. If you are running Drupal 8, you can use `wget --mirror http://example.com` and this will provide copy of your site's HTML.

---
Tags: 7
---


# Question
Title: How to create pop up window for login page
I want something like if i click on the login then pop window should open where in i should able to enter my Id and password to login, as as of now i tried with modules like

Fancy Login

Ajax Register

Modal Forms

above module i just installed and enabled.

But no luck can anyone tell me how to achieve this?

# Answer
1)use this module https://www.drupal.org/project/modal\_forms

2)create a block and put this code in it :

```
 <?php
global $user;
 global $base_url;
if($user->uid == '0')
{
?>
<a class="ctools-use-modal" href="<?php print $base_url; ?  >/modal_forms/nojs/login">Login</a>
 <?php
}
else
 {
 echo '<p><a href="'.$base_url.'/user/logout">Logout</a></p>';
}
?>

```
> 0 votes

---
Tags: users, javascript
---