# Question
Title: Does user_is_logged_in() check if there is at least one user logged in?
Does the `user_is_logged_in()` method return TRUE if there is at least one user logged in? Or does it refer to the current session, and returns TRUE if the current user is logged in?

# Answer
By looking at the Drupal API, you can see the function itself:

```
<?php
function user_is_logged_in() {
  return (bool) $GLOBALS['user']->uid;
}
?>

```

Which shows that it returns TRUE if the current session is a logged-in user, or FALSE if the current session is an anonymous user.
> 10 votes

# Answer
It refers to the current session.
> 4 votes

# Answer
The function checks that the user who is viewing the page is not the anonymous user, not that between all the users currently viewing the site there is a logged-in user. So, four users seeing the site will get a different result, basing on the fact each of them is logged-in or not.
> 2 votes

# Answer
If you want to check which users or how many users are logged one option is to query the sessions table.
> 0 votes

---
Tags: 7, users, sessions
---


# Question
Title: How to prevent taxonomy terms being duplicated on node form?
I have a content type **book** and it has two taxonomy term reference fields (free tagging, autocomplete):

* author
* publisher

Both two taxonomy reference fields have taxonomy terms from the same vocabulary: **people**.

While creating new **`book`** content, if I enter the **same** taxonomy term for both author and publisher, it **double** creates the same taxonomy term (if entered taxonomy term didn't exist before).

I don't want to use different vocabularies for these taxonomy reference fields.

## How to prevent taxonomy terms being duplicated on node form?

# Answer
Though there is a module for help with taxonomy term being duplicate here, but like module page says, it doesn't work apart from *taxonomy term and vocabulary forms*.

So a solution I can think of in your scenario is to use hook\_node\_presave and compare value of both fields. If it match, you can think of some logic such as, create single term & set newly created tag for both fields.

Other hook can also help you such as hook\_node\_insert with your own logic to tackle this. Happy Coding !!
> 1 votes

# Answer
If you are using rules already, you could check if the term names are the same on node save. Conditions: Entity has field x 2 and Data comparison.

Then use actions to delete a term and set that field again with the other.
> 1 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: Change display order of View block in Content area of page
I have a dynamic view block that is set to display in "content" region of a Basic page. The Basic page has a field that i want to display at the bottom (i.e. after view block) Question: I cannot figure out how to change display order, so that page displays View block first, then a field from Basic page. Thanks in advance!

# Answer
Try out the Field as Block:

> Field as Block provides an easy way to display one or more fields of the current node in a block.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to change page.html.twig depending on the content type I am viewing in Drupal 8?
I was wondering how I would change `page.html.twig` depending on the content type of the node I am viewing?

For example I would like the title to be shown on pages with the article content type but be hidden on the site page content type.

# Answer
> 5 votes
Page title is available as a block, and you can control the visibility from there.

However, to answer your question, here's how to provide different template suggestions based on content type:

```
function YOUR_THEME_theme_suggestions_page_alter(array &$suggestions, array $variables, $hook) {
  // Try to get the node, so we can check if we're on the node page.
  $node = Drupal::request()->attributes->get('node');
  if ($node && $node->getType() == 'YOUR_CONTENT_TYPE') {
    $suggestions[] = 'page__NAME_OF_YOUR_TEMPLATE';
  }
}

```

This will allow you to use `page--NAME-OF-YOUR-TEMPLATE.html.twig` template in your theme only for specific content types.

You can read more about `hook_theme_suggestions_HOOK_alter()` here.

---
Tags: theming, 8
---


title: Page Not Found Old CSS References

text:
# Question
Title: Page Not Found Old CSS References
Recently, we did a complete overhaul of our theme. We have been working with a subtheme of Zen. We are still working with one, but we made it from scratch. Though it is now in place, we are receiving "Page Not Found" errors with calls to the old css files. Has anyone experienced this before, where could they be getting called from?

I've checked to make sure no css file is importing them and no info file is calling them.

# Answer
> 0 votes
You should do a search of the entire codebase (not just theme files), as well as a database search in all tables (it should only take about 3 minutes).

**UPDATE:**

Also, make sure you have taken any content delivery network (CDN) caching into account. Are these files causing "File-not-found" errors from a remote browser, or from a browser on the local machine (dev laptop, for instance).

If you do have a CDN in place (MaxCDN, CloudFront, Akamai, etc.) you can try uploading a mostly blank CSS file with the same name as the one that you're attempting to get rid of.

---
Tags: theming
---


# Question
Title: Creating a block programmatically in a theme on Drupal 8?
So I was hoping to have my theme create special blocks for different parts of the front page so that they can be moved around easily later. I added the files to *mytheme/src/Plugin/Block/BlockName.php* but they never show up anywhere on the site or the block manager even after clearing cache.

Here's the code for one of my blocks (MediaPanel.php):

```
<?php
/**
 * @file
 * Contains \Drupal\mytheme\Plugin\Block\MediaPanel.
 */

namespace Drupal\mytheme\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides my custom block.
 *
 * @Block(
 *   id = "media_panel",
 *   admin_label = @Translation("Media Panel"),
 *   category = @Translation("Blocks")
 * )
 */
class MediaPanel extends BlockBase {

/**
   * {@inheritdoc}
   */
  public function build() {
    return array('#markup' => 'hello world');
  }
}

?>

```

Do I *have* to use a module for creating Blocks? It would be inconvenient to have to make a module to create blocks that will be specific to my theme anyway.

# Answer
> 3 votes
Yes. Themes can't provide plugins.

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


title: Send form values to JS file

text:
# Question
Title: Send form values to JS file
As clearly titled I want to send a **form values** to js file in **Drupal 8**. I've made some researches and all I successfully coded was sending a PHP variable from a **Controller** to the JS file I'am using.

Here is the code:

*library\_name.libraries.yml*

```
library_name:
  version: 1.x
  js:
    js/<js_file_name>.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

*controller\_name.php (class)*

```
namespace Drupal\module_name\Controller;

use Drupal\Core\Controller\ControllerBase;

class <class_name> extends ControllerBase {

  public function <method>(){

      return array(
        '#attached' => array(
            'library' => array(
            '<module_name>/<library_name>'
            ),
            'drupalSettings' => array(
                '<module_name>' => array(
                  '<library_name' => array(
                      'foo' => 'bar'
                  )
                )
            )
        )
      );

  }

```

*js\_file\_name.js (under /js folder)*

```
console.log(drupalSettings.<module_name>.<library_name>.foo);

```

Everything works great!

But how about using a **form**? I've declared a form extending from **FormBase** and in the **submitForm()** overridden method I typed the same array:

```
return array(
        '#attached' => array(
            'library' => array(
            '<module_name>/<library_name>'
            ),
            'drupalSettings' => array(
                '<module_name>' => array(
                  '<library_name' => array(
                      'foo' => 'bar'
                  )
                )
            )
        )
      );

```

I know this won't work! But any ideas? I thought about using another library, point to a js file there, and use that js file to get the form values using the **#attached** tag like above, and then send those values to the other js file using **JSON**

If any one can provide me with a better **Drupal Standard**? that would be great! cause this my first time using Drupal.

---

***EDIT:***

I fixed this, using: the **module\_name.settings.yml** file under **module\_name/config/install** folder and also by using the **module\_name.module** file where I've implemented the **hook\_form\_alter()** method.

So,

From my **module\_name.module** file, here goes my code:

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

function modulename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

     if($form_id === your_form_id){

        $form['#attached']['library'][] = 'module_name/route_name';
    // that's the route name you've defined in your module_name.libraries.yml file
    // where you've located the js file you're going to use

        $form['#attached']['drupalSettings']
        [module_name][route_name][send_this_variable_to_js] = \Drupal::config(module_name.settings)->get(key);

        return $form;
    }

}

```

Now in your JS file, you can **console.log** like this:

```
console.log(drupalSettings.module_name.route_name.server.send_this_variable_to_js)

```

Hope this help!

# Answer
> 1 votes
You'll either need to add a js behavior that attaches itself to the normal submit event of the form, or create an AJAX Command that invokes a function in your script.

See: https://www.drupal.org/node/2290235

# Answer
> 1 votes
`#attached` only works on a page that is rendered. A form submission isn't, it's redirect and goes to some other page. It also doesn't have a return value.

You need to store this information somewhere, for example in the user session and then display it on the next page.

Alternatively, you could use $form\_state-\>setRebuild(TRUE), store it with $form\_state-\>set(), then buildForm() will be called again and you can add it there to $form. That's however usually only done when you actually explicitly want to keep the user "in" he form, somethink like an upload image or "add another" button.

---
Tags: forms, 8
---


# Question
Title: module to customization product in drupal commerce
Is there any module to let my shop customers design their own t-shirt, mugs, caps, mouse pads. They can upload an image to t-shirt, back and front side, or select existing image from the logo categories, and they can also write their text on the template shirt. and have below features

Features:

* Upload an image on the template t-shirt.
* List item
* Change t-shirt side, front or back.
* Select an Image from the existing logo categories, to put on the
* template t-shirt
* Write text on the template t-shirt
* Up to 4 text lines - New
* Change text size, color, font type

my shop is based on drupal commerce

anybody know module to provide something like this features, or any idea that how can I implement it?

# Answer
> 2 votes
You are looking for Commerce Customizable Products

> Drupal Commerce allows you to sell customizable products that require customer input when added to the cart. Use cases for this functionality include:

* Business cards that require contact information and a logo upload.
* Event registrations that require attendee information.
* Donations the allow the customer to specify a donation amount.

and especially for t-shirt design it is possible only through third party tools, we can integrate but it is not free, they have drupal support with their tool http://www.online-product-designer.com/online-advance-tshirt-design-tool.php and http://harboarts.com/shirtdesigner/

# Answer
> 2 votes
I think the best bet for user customized products for Drupal Commerce is to integrate the open source fabricjs.com library. This can then export as an image, svg or json data.

I did a quick fiddle mock-up here for a basic demo: http://jsfiddle.net/cdn256L6/1/

Is anyone keen to implement this for Drupal 8 / Commerce 2.0?

If not, perhaps as interested parties we can start a chip-in to get this done?

---
Tags: 7, commerce
---


# Question
Title: How to use entity form in pop-up window?
I have created a view, and there is one column named "forward to delete". I want to open an entity form in a pop-up after clicking on this link and get the node id of the clicked node so that I can use this node id for other purpose.

I am using the entity form module.

# Answer
1. Make sure you have 7.x-1.4 of the entityform module installed or this won't work.
2. Install the Modal operations module.
3. Install the Modal forms (with ctools)
4. Enable the **Modal entityforms** module that came as part of the modal module.
5. Create a link to your modal popup like this:

---

```
<a href="/modal/entityform/YOUR_FORM_IDENTIFIER/nojs/0" class="ctools-use-modal ctools-modal-modal-popup-small">Open Entity Form in Popup!</a>

```

I found this blog post very useful for figuring this out and getting it working.

If you cannot use version 7.x-1.4 for some reason then there is a patch here that some have had success with however I could not get it to work this method.
> 0 votes

# Answer
An easy example may be to use the Simple Dialog module. You can point it to an HTML ID of the form or any element on the original page and it pops up in a dialog box. I think this would be used if you are going for a simple solution.

```
<a href="path/to/target/page/to/load" class="simple-dialog" rel="width:900;resizable:false;position:[center,60]" name="id-of-element-on-target-page-to-load" title="My Dialog Title">Link</a>

```
> 0 votes

# Answer
I think what you are looking for is the ctools modal functionality. Without further digging into that - because I think the following tutorial is comprehensive, easy to understand and complete - here is a link that will help you: https://www.deeson.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7

Some important things you should not forget:

Add the ctools module as dependency. Add the callback to the menu. Include the ctools js files on the page where the link to the title popup is. ctools modal helped me a lot! Give it a try!
> 0 votes

# Answer
On a site where I used panels and colorbox + colorbox node already, I installed entity form block, placed it on a custom page and pointed a colorbox-node at it.

Gave a nice benefit of being able to place some other panes around the form in the modal.

The other answers are better if you don't really use those modules.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Commerce - how do I set a discount to a specific user's next order only?
I'm making an e-commerce site for a friend.

The point of his shop is to sell honey in jars. When people return the jars, they get a 2 euro discount on their next order.

I've tried several things so far but if I give the user a discount, it continues to give the discount. I only want it the discount for the next order. Same goes for other ways I've tried it. I'm not quite sure how to set these specific conditions.

# Answer
## Generic solution

I think you need to write some custom code to get a solution that will work automatically. This could be handled by a custom Rules condition - meaning `hook_rules_condition_info()` implementation. After you add the code below, make sure to add this condition through Rules interface as well. Here's example code that would go in `YOUR_MODULE.rules.inc`:

```
function YOUR_MODULE_rules_condition_info() {
  return array(
    'YOUR_MODULE_rules_condition_check_next_order_discount' => array(
      'label' => t('Sample condition'),
      'parameter' => array(
        'order' => array(
          'label' => t('Order')
          'type' => 'commerce_order',
        ),
      ),
      'group' => t('Custom'),
    ),
  );
}

function YOUR_MODULE_rules_condition_check_next_order_discount($order) {
  // Perform any checks you want here, load the owner, see previous orders, etc.
  $customer = user_load($order->uid);
  if ($whatever) {
    return TRUE;
  }

  // I recommend doing this the other way around: by default visitors shouldn't be
  // able to have the rights for this discount, but they can get it IF they fulfill
  // your rules above.
  return FALSE;
}

```

Note: the `YOUR_MODULE.rules.inc` file would be loaded automatically, and you don't have to include it in the `.info` file of your module.

## One-off solution

In case I misunderstood your question, here's how to configure the discount to have this work only once:

1. "Apply to" fieldset, add "User" and there select the target user.
2. Set the value of "Maximum usage per customer" field to 1.

Hope this helps.
> 0 votes

# Answer
I would take a different approach here, but just note that nothing that I know of would support this out of the box without additional code. The big issue is that your discount is a flat amount off of an order as opposed to an amount off of the unit price of a product, but the Commerce Discount module's order level discounts don't have the necessary conditions to set the price accordingly.

Basically, I'd add a field to the user that represents how many jars they've returned. Presumably, they might return multiple and get even more off of their next order. This field would need to be hidden from their edit form, though it's reasonable for it to appear when they view their own user profile so they know how much to expect off of their next order.

You then need to create new inline condition code in a custom module that can read this field and apply a discount if the value of the field is \> 0. This is actually pretty straightforward and could be done without using Commerce Discount / inline conditions, but the problem is you really need Commerce Discount to get the $ off the order total correct.

Then for actually applying the discount to the order, you can do one of two things: you can define a new offer type that knows how to look at the user's profile to determine how large the discount should be or you can is the $ off offer type but alter the line item after the fact to be the correct amount (presumably on pre-save).

Completing the process, you need a custom rule to fire when the order is first paid in full (this is the name of the relevant event) to set the user's jar count back to 0. Not sure how you process refunds, but you'll most likely just need to reset the jar count manually in the event of a refund.
> 0 votes

# Answer
I agree with Ryan's suggestion above, however if you don't want to write custom code, I recently provided a patch for Discount Extra that allows you to use a rules component as a discount condition. You could then just write the component to check that the user has returned jars \> 0 in the profile field Ryan mentioned.

The above assumes that the discount is a maximum of 2 Euro per order and not based on the number of jars they have returned. If you want it to be based on a discount for the number of jars returned (e.g 2 jars is 4 Euro discount), then you will need some custom code to look at the jar count and apply the discount accordingly.
> 0 votes

---
Tags: 7, commerce
---


title: Clarity on caching?

text:
# Question
Title: Clarity on caching?
Drupal 8 uses Opcache, while most people still use APC for Drupal 7. I am not sure what I should use for a Drupal 7 site, as there is no Opcache module for Drupal 7. There is the OPcache module, but I don't think that will do the trick as it is a development module.

Which of the two options should be used for Drupal 7 when I use at least PHP 5.5, which supports OpCache?

# Answer
> 5 votes
Drupal 8 recommend using Zend OpCache (a PHP extension), which is enabled at server side, and it caches PHP code; it is not used for caching data.
For data caching, Drupal 8 automatically uses APCu without requiring third-party modules, if the PHP extension is enabled. See Several cache bins now use APCu caching by default, which states:

> In order to improve cache performance, Drupal 8 now has:
>
> * A cache.backend.apcu service that site administrators can assign as the backend of a cache bin via `$settings['cache']` in settings.php for sites running on a single server, with a PHP installation that has APCu enabled, and that do not use Drush or other command line scripts.
> * A cache.backend.chainedfast service that combines APCu availability detection, APCu front caching, and cross-server/cross-process consistency management via chaining to a secondary backend (either the database or whatever is configured for `$settings['cache']['default'])`.
> * A default\_backend service tag (the value of which can be set to a backend service name, such as cache.backend.chainedfast) that module developers can assign to cache bin services to identify bins that are good candidates for specialized cache backends.
> * The above tag assigned to the cache.bootstrap, cache.config, and cache.discovery bin services.
>
> **This means that by default (on a site with nothing set for `$settings['cache']` in settings.php), the bootstrap, config, and discovery cache bins automatically benefit from APCu caching if APCu is available**, and this is compatible with Drush usage (e.g., Drush can be used to clear caches and the web process receives that cache clear) and multi-server deployments.

So, if you are using APCu as data cache on Drupal 7 (which require installing a third-party module), keep using it; when you will port the site to Drupal 8, you will not need anymore a third-party module, to use APCu to cache data. That is why the APC - Alternative PHP Cache module doesn't have a Drupal 8 version.

The module you are linking just allows Drupal to report status information about the cache and reset the cache; it is not a module you need to use *Zend OpCache* with Drupal.

# Answer
> 1 votes
Its more related to php versions than drupal itself, Drupal tries to gain benefits of new php features opcache that has been added to php itself starting from version 5.5.

> PHP in version 5.5 comes with a caching engine built-in – OpCache – which stores precompiled script bytecode in the memory.

APC does the same plus gives you the ability to store user data for previous php versions.

> APC cache won’t work with the newest PHP versions. It doesn’t support PHP 5.5 at all

Read that article for more information understanding opcache

---
Tags: caching
---


title: add to cart - multiple products at once

text:
# Question
Title: add to cart - multiple products at once
On my commerce site, I would like to use exact functionality like both ubercart cart links or ubercart kits have - to add multiple different products to cart at once (one click on button or link, no quantity).
Requirement is: products inside cart should behave as single products, with quantity enabled. I do not need discounts.

modules I tried:

* commerce product bundle - adds all products as one product, you can only change quantity
* commerce bundle - separate products but quantity fields disabled.

Rules links look promising but I am not so sure how it would work with many kits. Do anybody have a solution for this? Thank you.

User case: Create various product kits (as content types) with add to cart button. After adding to cart, products behave like normal simple products. (Ubercart has this funtctionality - while creating a product kit, you can check wether you want the products to behave in cart like a kit(a bundle) or as a separate products.)

# Answer
> 3 votes
I am working on the very same requirement - different products from a single (product kit) content type, single add to cart button, and products after adding to cart behave normally.

In this process, I use Commerce Product Kit module. It provides a field formatter for *product reference* field or an *entity reference* field pointing to commerce products.
The instructions on use of the module are given on the project page. Try it out and report any issues that you could find :)

P.S: I am the author and maintainer of the module.

# Answer
> 3 votes
Commerce Add to Cart Extras

> This module provides alternative ways of adding products to cart.
>
> The initial version provides a views field handler ("Commerce Product: Quantity input field") that relies on the Views Form API (a part of Views 3 since RC1) to output a quantity textfield that turns the view into an add to cart form. The default quantity can be configured, and only products with a quantity larger than 0 are added to the cart.

# Answer
> 1 votes
You can do that by creating a rule, which you then trigger by rules link, or a view VBO block, like (copied from here https://www.drupal.org/node/1468392#comment-10270105):

> **The Rules Part:**
>
> 1. create a new rules component. Make it an Action set.
> 2. First, add a name. EG "VBO Add To Cart". Below, you'll see a table with three rows - you only need to fill in the top one. Choose Commerce product from the dropdown (under Entity), and then fill in the other 2 with something memorable like 'Commerce Product' for the label. The machine name needs to be something like commerce\_product. Click continue.
> 3. On the next page, choose 'add action'. Choose the type of action: Add product to cart.
> 4. On the next page you need to add the user and the sku. In the user field, start by writing 'site'. This will trigger the dropdown, and you can choose site:current-user. Then for the SKU - first click 'switch to data selection'. You can then click in the field, and select the entity you named earlier (not site). Then you can select sku. Now change the quantity if you need to, then click save.
>
> **The Views Part (The easy part)**
>
> For this you need VBO installed. Make a view displaying a table of commerce products. You can add the name and the price fields. Next add the VBO field. From the actions list, you should see your newly created rule action. Select it, and if you want, choose to skip the confirmation. Under the bulk options, I also changed it to display as single buttons, as I only have this one action that can be performed. Now save the view. (If you want the tickbox on the left of your table, just rearrange the fields.
>
> Now place your view where you want it (eg a block on a page, or a page, or inserted into a panel) and view it. You should be able to select multiple products with the checkboxes, and then add them to the cart with one click.

Or do it programmatically, like

```
<?php
    global $user;
    $line_item = commerce_product_line_item_new(commerce_product_load($YOUR_PRODUCT_ID));
    commerce_cart_product_add($user->uid, $line_item);
    $line_item = commerce_product_line_item_new(commerce_product_load($OTHER_PRODUCT_ID));
    commerce_cart_product_add($user->uid, $line_item);
?>

```

in a custom (Ajax) callback.

---
Tags: 7, commerce
---


title: Drush cache clear corrupting database?

text:
# Question
Title: Drush cache clear corrupting database?
I just moved to a new computer: Windows 10 with XAMPP. As far as I know I set everything up the same as it was on my old Windows 7 computer. But now, for some reason, much of the time when I run `drush cc all` or run update.php, the database gets corrupted. Most frequently, some cache tables' \*.idb files (tablespaces) are deleted from my mysql directory, which makes those tables appear as "in use" in phpMyAdmin and prevents them from being edited or emptied. They are always cache tables and never tables that actually get modified by my update hooks. Restoring the database is the only way to fix it then. This is a mature site that I've been working on for a long time, and have never seen this until the new computer. What's happening here?

A sample error message when using update.php, caused by a missing \*.idb file:

```
PDOException: SQLSTATE[HY000]: General error: 1812 Tablespace is missing
for table '(null)': DELETE FROM {cache_field} WHERE
(cid = :db_condition_placeholder_0) ; Array (
[:db_condition_placeholder_0] => field:message_type:6 )
in cache_clear_all() (line 168 of
C:\<path>\includes\cache.inc).

```

My most recent `drush cc all` error message, which Google has never even heard of, was:

```
exception 'PDOException' with message 'SQLSTATE[HY000]: General      [error]
error: 1030 Got error -1 "Internal error < 0 (Not system error)" from
storage engine InnoDB'

```

# Answer
In general Drush can't corrupt your database, as it's a software which just sends the SQL queries.

However this error can be related to newer version of MySQL, as of 5.5.7, InnoDB always uses the fast truncation technique (which is equivalent to `DROP TABLE` and `CREATE TABLE`). So it no longer performs a row-by-row delete for tables with parent-child foreign key relationships, therefore `TRUNCATE TABLE` returns an error for such tables.

See: 2.11.1.1 Changes Affecting Upgrades to 5.5

This already has been reported in #2229013 for Drupal core.

So you should either:

* consider using different data structures:

+ non-InnoDB,
    + use redis/memcached for your cache management (so this won't happen),
* try clearing your caches in different way, e.g.

```
echo "SHOW TABLES LIKE 'cache%'" | drush sqlc --extra=--skip-column-names | xargs -L1 -I% echo "DELETE FROM %;" | drush sqlc --extra=-v

```
* upgrade your Drupal to 8 and see if the same happens (`drush cr`),
* use different database (maybe will work in MariaDB?),
* downgrade your MySQL to \<5.5.7,
* patch the Drupal core by replacing `TRUNCATE` with `DELETE` statement,

You may also consider the condition like `if ($mysqlversion > 5.57 AND $cache_table_type = 'innodb') { // DELETE } else { // TRUNCATE }`.
* or wait until the fix is provided for Drupal core (#2229013).
> 2 votes

---
Tags: drush, caching, database
---


# Question
Title: Git local repo in combination with Acquia Cloud Dev repo adding contributed modules with Drush
I try to add contributed modules to my local repo following this article.

```
curl https://ftp.drupal.org/files/projects/admin_toolbar-8.x-1.14.tar.gz | tar fz

```

Its not placing the `.tar.gz` file in my local repo?

What I'm doing wrong? After (when it's placed) I want to extract the folder and commit the module. Is this best practice adding contributed modules to my local repo or do i have to use Drush, and if so how do I have to use it in combination with my Git/Drupal workflow?

**Update:**

1. I used Drush `drush dl admin_toolbar` to add the module.
2. I committed the module and pushed it to my Acquia Cloud Dev environment
3. Now from Acquia Dev Desktop `SSH to this server` I want to use `drush en admin_toolbar`. But then I get this message:

*Command pm-enable needs a higher bootstrap level to run - you will \[error\] need to invoke drush from a more functional Drupal environment to run this command. The drush command 'en admin\_toolbar' could not be executed. \[error\]*

* Can't I use Drush to enable modules on Acquia Cloud Dev environment?
* Is this the preferred, most fast/handiest workflow, or is there a better workflow to use (when you use a locally cloned repo in combination with Acquia Cloud?

# Answer
The right command is:

```
curl https://ftp.drupal.org/files/projects/admin_toolbar-8.x-1.14.tar.gz | tar xz

```

`f` process a file, but you want to process the standard input (provided by curl). So remove the f and add the `x` option to uncompress file.

Anyway I think is better to use Drush. Drush can handle dependencies (it can download dependant modules when you enable a module) and is easier to use:

```
drush dl admin_toolbar

```
> 1 votes

---
Tags: 8, drush, version-control, acquia-dev-desktop, acquia-cloud
---


# Question
Title: How do I redirect the unsubscribe link in a newsletter to a particular node?
I am using the Simplenews module for sending newsletters, and the Mandrill service for sending emails. When I send a test newsletter to the test user, the unsubscribe link should be redirected to particular node, for example to `node/2`.

How can I achieve this?

# Answer
> 0 votes
Use the Rules module and use the Rules (System) Event "Drupal is initializing" (= init). And add an extra condition related to the URL of your unsubscribe link. Add to that a Rules Action to perform a redirect to your `node/2`.

Here is a rule that should be close to what you'd need (assuming the path of your unsubscribe link is `Some/Unsubscribe/Path`):

```
{ "rules_redirect_unsubscribe_link" : {
    "LABEL" : "Redirect unsubscribe link",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "Some\/Unsubscribe\/Path",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Redirecting URL [site:current-page:url] ...",
          "type" : "warning"
        }
      },
      { "redirect" : { "url" : "node\/2" } }
    ]
  }
}

```

The above rule does not (yet) take into account to only apply the Rules Action for your "test user" (as in your question) only. But for anybody a bit familiar with the Rules module, that is a straight forward Rules Condition to add ...

And the above rule also uses a Regular Expression in its Rules Condition that could be simplified to a simplified version of it (not using such expression). However, if you have various unsubscribe links that all have a similar pattern, you only have to massage that expression in the above Rules Condition to have all such links fit in the same expression.

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function (available if the Rules UI submodule is enabled). Then further edit/refine to make it fit in your own environment (e.g the "Redirecting URL ..." message to be shown).

---
Tags: 7, redirection, emails
---


# Question
Title: One account, one email, two different usernames
I am trying to create a social website that each member can create two different profiles with two different usernames, one public and one private. The member should be able to toggle between profiles the same way you do with facebook when you toggle between your main profile and a different page you own. The member is able to post new nodes as his/her private username or public username by simple toggling between the two. I have been researching many modules such as profile2 and subuser. The problem with subuser is that you can switch between your main account and the subuser easily but you can't switch between your subuser and the main user except if you logout first. Also, with the subuser, you are required to add another email address for each subuser. It would better if there is only one email address access to both accounts. What is the best solution?

# Answer
Due to drupal architecture you should go with a custom solution that create a second account for the user when he register by adding a global known prefix for unique fields that would be used when switching the user account.

Say user registered with mail **someuser@somedomain.com** you will make another account using that mail **someuser.{global\_key}@somedomain.com** having **{global\_key}** set in code you will use it for logging the user when he needs to switch accounts.

**Scenario:**

* user registered
* in custom module implement **hook\_user\_register()** and create another account for the user by using the **{global\_key}**
* if user needs to switch account do login by adding the prefix **{global\_key}** to username (you could add to password or let password be the same) let switch account be a **hook\_menu** implementation reading the

> global $user object and create a new account using **{global\_key}**

-user forget password send the reset password link with a query parameter identifies the account will be reset by implementing **hook\_mail\_alter**

Hope that helps!
> 1 votes

# Answer
Not having a contributed module providing such feature you are asking here, I believe that the best solution is to design a custom module.

You want to register with a single email address, and post as more users (alias). So, at the very basic, you will have:

* A new content type **user\_alias**, referenced to the user entity, protected by the Node Access module
* a field named **Post as** in the main content type entity (in your FB-like scenario, **Page**), referenced to the **user\_alias** content type
* node hooks handling for rendering the **submitted by**, replace username with the **Past as** as **user\_alias**

Hope will help.
> 1 votes

# Answer
Have you looked into the masquerade module? We use it for cases that a user needs to use multiple accounts. It lets you assign other user accounts a specific user.
> 0 votes

---
Tags: users
---


# Question
Title: Creating a periodic report in Drupal 7 or 8
I have the following use case: users have to report quarterly on their project used an unified form. For example, project 1 is implemented by organization X with contact person John and has to deliver 10 pcs. of A and 15 pcs of B; project 2 is implemented by organization Y with contact person Mary and has to deliver 20 pcs. of A and 3 pcs. of C.

I want to have a report for John and Mary to fill every three months, containing the name of project and submitting person, reference period, item and how many was delivered during the reporting period, as well as accumulated delivery from the project start. Further, I would like to retrieve summary reports on how many items of A. B and C were delivered so far by projects X and Y, and export the information to calculate further stats (i.e. % delivered by project and item, etc.).

The Q2 report for John and Mary should be pre-populated with the information on delivery for Q1 so far, contain fields to add the new performance and sum the new totals for their respective projects. Similarly, in Q3 the reports for both should contain the delivery for Q1+Q2 on their respective projects.

For most of the functionality described, it would be sufficient to use Webform for the reports and Views for accumulating the results; however, I have not found a way to add in a new webform instance representing the Q2 report the data from the Q1 report on the same project.

Could anyone suggest a solution, ideally without programming?

# Answer
Below is a possible approach that may help to address the "reporting" part of your question (not how to pre-populate the webforms, which should really be a separate question I think). It's using "State" names (like Florida, Illinois, etc.) instead of "John, Mary, etc" and "Cities" instead of "A, B, etc". With "City attributes" instead of "pcs".

If I was to implement this in a Drupal site, I'd use either of these "displays":

* **Option 1 - Master detail with nested blocks**

Have a look at this example, which shows 1 "block" for each "State", and within each "block" it shows the "Cities" (and one of its attributes) in that "State".
* **Option 2 - Report that filters based on some lookup**

Have a look at this example, which shows only the data about a specific "State", together with all the "Cities" (and one of its attributes) in that "State". To switch to another state, select the desired state from the Parameter form near the top ("IL" is used as the default in this example).

If you wonder "**How did you do that?!?!**" ... then this is the answer: that's really a piece of cake using the Forena module. And (***without programming***" (unless you would want that instead ...), only using WYSIWYG editing features to either select the data (to build the SQLs) or to create the report that fits your needs to display those data. It also supports creating charts from these data.

Checkout the Community Documentation for details, and/or the documentation that comes with the module. The above 2 examples are actually delivered with the module (out-of-the-forena-box), though you probably don't notice that it is even not a typical "Drupal database". It could be such database instead (about data contained in your Webforms), but in this case it's an SQLite (sample) database (it could also have been Oracle, MS SQL, Postgress or any PDO compliant database).

**Disclosure**: I'm a co-maintainer of Forena.
> 0 votes

---
Tags: views, webforms, log-messages
---


# Question
Title: Use data from one textfield to populate other textfields in drupal 7 form
I am new to drupal. I have a drupal form having fields Customer Name, Address and Phone. Is it possible to populate Name and Address Field automatically from database when the phone number is entered?

I am using Drupal 7.

Please help me and treat me as a beginner. Thank you...

# Answer
> 0 votes
Computed Field

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. T**hese computed fields are populated with values that you define via PHP code**. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

OR

You can do it by using `hook_form_alter` then define `copy_field_value.js` create behavior:

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

      // Repeat this for all fields as needed
      $('#source', context).on('blur', function () {
        // above you can use change instead of blur if element is not changed by another js
        if (!$('#destination').val() || 0 === $('#destination').val().length) {
          $('#destination').val($(this).val());
          // wrap line above in "if no value" like I did, or other condition you like
        }
      });
      // end of "repeat this"
    }
  };
})(jQuery);

```

---
Tags: forms, ajax
---


# Question
Title: Where can I alter the path of the anchor around a views items title?
I have a view with several items and they link to their respective nodes. However I also have an external URL field which if populated needs to replace the path around the title of the views item.

I've been looking for a hook that builds this title path and associates it with the title but so far have not had any luck.

I thought `hook_views_pre_render()` might have it but the title is just a string.

# Answer
> @No Sssweat interesting proposal. Yes, if an external path field is populated we link this node to that path in the view. – dibs

For example: I created a field called **external url**

In you view add field **path** then **external url** and then **title**

They need to be in this specific order for it to work

Then for path:

For external url:

For Title:
> 1 votes

# Answer
The best way to achieve this would be through a view mode (e.g. teaser) and a preprocess function.

Here's what you would need to do:

1. Change view display from fields to nodes.
2. Set the node view mode to be teaser. If you are already using teasers for something else, I suggest creating a new view mode for this. You can do this through your custom module, Entity view modes or Display Suite modules.
3. In `hook_preprocess_node()` you can make all conditions you need, and instead of showing the node URL, use the external link.

This will not only be easy to use, but very self explanatory later on.

For more information, see answers to this question.
> 0 votes

---
Tags: 7, views, hooks
---


# Question
Title: How to use a relative path for a theme's favicon
I'm trying to ship a favicon with my custom Drupal 8 theme, but I can't figure out how to specify its location relative to my theme's installation location.

Following this answer I've created a `config/install/MY_THEME.settings.yml` file containing

```
favicon:
  use_default: false
  path: '/themes/MY_THEME/static/favicon.png'

```

(I'm keeping all my theme's static files in a `static` subdirectory of my theme directory)

This works, but contains a hard-coded reference to the installation location of my theme. Hence, if a user decides to install the theme in `themes/contrib` or `themes/custom` instead of in `themes` the favicon won't be found.

Therefore I would like to specify a path relative to my theme's root directory or relative to the `MY_THEME.settings.yml` file. However, it seems that Drupal uses the server root (`/`) as a base when I specify a relative path, so `static/favicon.ico` ends up as `/static/favicon.ico` which obviously doesn't work.

# Answer
another idea for a workaround would be to overwrite the href property on runtime with hook\_page\_attachments\_alter, somethng like this:

```
function MYTHEME_page_attachments_alter(array &$page) {
     foreach($page['#attached']['html_head_link'] as $k => $v) {
          if (array_key_exists('rel', $v[0]) && $v[0]['rel'] == 'shortcut icon') {
                  $page['#attached']['html_head_link'][$k][0]['href'] = drupal_get_path('theme', 'MYTHEME') . 'static/favicon.png';
          }
     }
}

```

or use the default favicon path (MY\_THEME/favicon.ico), it will be taken, see this source:

```
// Generate the path to the favicon.
      if ($cache[$theme]->get('features.favicon')) {
        $favicon_path = $cache[$theme]->get('favicon.path');
        if ($cache[$theme]->get('favicon.use_default')) {
          if (file_exists($favicon = $theme_object->getPath() . '/favicon.ico')) {
            $cache[$theme]->set('favicon.url', file_url_transform_relative(file_create_url($favicon)));
          }
          else {
            $cache[$theme]->set('favicon.url', file_url_transform_relative(file_create_url('core/misc/favicon.ico')));
          }
        }
        elseif ($favicon_path) {
          $cache[$theme]->set('favicon.url', file_url_transform_relative(file_create_url($favicon_path)));
        }
        else {
          $cache[$theme]->set('features.favicon', FALSE);
        }
      }

```
> 1 votes

---
Tags: 8
---


# Question
Title: How to change a field value to 500 products (commerce module) at the same time?
I have about 500 product in my site powered by the commerce module. I need stock capabilities so installed the commerce\_stock module. So far so good.

This module add a **stock field** and a checkbox to check **Disable stock for this product** in the product itself.

Thing is that **stock field** is set to 0,00 by default, then all the product are shown as **Out of stock**.

The solution is as simple as to mark the checkbox to check **Disable stock for this product** for all products. But I have 500 products, then this will be a waste of time...

Is there any way to do this programmatically? Any other idea to get this done?

I thing of doing this directly in the database with a sql query, but not sure if this is a good idea?

# Answer
> 8 votes
Well I can come out of two ways of doing this. One of them is Using the commerce API which is really good you just have to get all your 500 products with the following method:

```
 $query=new EntityFieldQuery;

    $query= $query->entityCondition('entity_type','commerce_product')->execute();

    foreach($query as $entity){
       $entity->commerce_stock[LANGUAGE_NONE][0]['value'] = 1;
       commerce_product_save($new_product);
    }

```

Or you can also do it on the database updating the value of the table field\_data\_commerce\_stock:

```
update field_data_commerce_stock set commerce_stock_value=ANY_NUMBER;

```

# Answer
> 2 votes
```
$wrapper =        entity_metadata_wrapper('commerce_product',commerce_product_load($product_id));
$wrapper->commerce_stock->set("set the value");
$wrapper->save();

```

# Answer
> 1 votes
I don't know exactly the module you mentioned. But check the schema. You should find a field attached with your Content type, and maybe you can execute a query thought Devel and PHP Execute block (`db_query(...)`).

In the content type fields configuration, if you set a default value, maybe it will set for all products the same value.

Or another solution is to install Views Bulk Operations module and you will be able to change on field for all nodes that you are looking for, but for that the module should be coded to support it.

# Answer
> 1 votes
You can do it with views bulk operation. Edit the product page view. To the view's fields add "Bulk Operations". Under "Selected Bulk Operations" check "Modify entity values".Save. Return to the product's page, select the products you want to modify, and on the Bulk Operations list choose "Modify entity values" click Apply. You can check off Stock under "Fields" and it will give you a field to enter the stock quantity you want and confirm.

---
Tags: commerce
---


# Question
Title: What's the most efficient way to get D8 to notice changes to .yml files?
I'm taking my first steps with Drupal 8, starting with a custom theme. As a result I'm making incremental changes and testing them.

I've found that in order to be able to tweak CSS you have to turn off aggregation. The normal: *change css, `drush cc css-js`, reload page* workflow doesn't work unless aggregation is disabled.

But I'm also having difficulty with Drupal not picking up changes to the yaml files, e.g. add css to the THEME.libraries.yml file - no `drush cc ...` command has any effect. The only thing I've found to work is `drush cr` (or `drupal cache:rebuild`) which adds about 20-30s delay in my workflow.

Is there a quicker workflow for development?

# Answer
> 2 votes
In your development.services.yml file turn twig cache off and debug true. This will assist in theming, twig files are also cached.

Secondly, I think the command you want for yml changes is drush cr. However if they are install yml files, (I believe) they'd only register when a theme is enabled/uninstalled like modules are. So if that's the case you'd need to do that. I've also needed to use cr with libraries.yml changes.

Third, what VM are you using? I can run drush cr and it only takes ~5 seconds on the DrupalVM stack.

# Answer
> 2 votes
Configuration Development does several helpful things for Configuration Management. Among them, the one you need is:

> Automated import of configuration files into the active storage. At the beginning of every request the changed files are saved the way as if it were dumped in the core config module provided "Single import" form.

This means that instead of reading your YAML configuration only when you enable your module, Drupal will reload changes on runtime.

---
Tags: 8
---


# Question
Title: Views count grandchildren with specific value
I have a Organic Groups structure of:

Organsiation

-Property

--Claim

I can use views to show all of the properties within an organisation by setting a contextual filters with OG membership: Group ID.

What I want to be able to do is count the number of open claims (a claim where a feild 'status' is set to 'open') within a property. For example:

Is this possible using views? It seems to ask a lot of views as I guess I need a subquery or second query to get the claims of each property.

Each claim references a property in its group audience feild. Each property references an organisation in its group audience feild.

# Answer
EDITED

The end result of this will be a view using the organisation NID showing **property** with the number of **claims**.

**ie. on an organisation's node, this would be the block.**

```
Property 1 -  18 (open claims)

Property 2 -  13 (open claims)

```

**Step 1: Grandchildren.**

1. Add your regular group ID contextual filter.
2. Add the relationship, `OG membership: Group Node from OG membership`.
3. Add it to your contextual filter as its relationship. This gives grandchildren.
4. **Filter out Property content type.**
5. Add property entity reference as a field.

You now have a all properties with all claims.

**Step 2: Counting**

1. Try Views Aggregation in Advanced. It will probably cause an OG error.
2. Instead, install Views Merge Rows. https://www.drupal.org/project/views\_merge\_rows
3. It will add a new option under Advanced in your view.
4. For title, `Count merged unique values`.
5. For property entity ref field, `Use values as a filter`.

Now you should have something similar to my example above.

**Step 3: Filtering to OPEN**

1. Add a relationship for that field. I just tried it with a taxonomy field but a Boolean should be similar.
2. Add a filter, eg. `(term from field_hello) Taxonomy term: Term ID (= 90210)`

Adapt the filter to what you need or use the general idea to create your own solution.
> 1 votes

---
Tags: views, organic-groups
---


# Question
Title: How to add validation to Drupal commerce checkout submit?
We have a requirement where user can do multiple registration for an event (i.e. for own and for other users). We want to restrict the user to do only N number of registration or less, where number N may vary from user to user specified on user profile. We are using 'Entity Registration' and 'Commerce Registration' module to do registration.

# Answer
> 1 votes
Drupal Commerce's checkout form uses button level validate and submit handlers as opposed to form level handlers. This means instead of just adding a handler to the $form\['#validate'\] or $form\['submit'\] array, you need to add it to the correct checkout button itself.

In your case, you'll add a handler to $form\['buttons'\]\['continue'\]\['#validate'\] via a form alter hook. Note that even if you prevent the form from advancing to the next page, though, that the checkout form is a special kind of form that validates and submits each fieldset independently of the form itself.

I'm not entirely sure how the registration module you're using interacts with the checkout form. However, it's possible what you may *actually* want is to alter the validate callback for a particular checkout pane via hook\_commerce\_checkout\_pane\_info\_alter() to supply an alternate validate handler that checks your additional registration requirements and prevents that pane from submitting (which would also prevent the form from proceeding to the next page.

---
Tags: commerce
---


# Question
Title: Find the parent node type of the commerce product being added to the cart
I have a product variation "Apparel", and a corresponding content type provided by kickstart "Apparel".

I have added a new content type "Product kit", which has an entity reference field pointing to "Commerce product" entity and "Apparel" is one of them. A single product kit node, can contain products of different types : "Apparel", "Luggage", "Cups", etc.

Using the newly created Commerce Product Kit module I have an option to add all the products stored in the entity reference field in a "product kit" node to cart.

I need to find a way to check if a product has been added from the "Product display" node or "Product kit" node. Is there a way to do this? I checked into `hook_commerce_cart_product_add`, but it doesn't help me identifying the source node type of the product. Any pointers would be appreciated.

# Answer
Generally speaking, the line item for each product in the cart has a data array with a *context* sub-array that includes information identifying the context from which the product was added to the cart. In the case of a product added from a node's Add to Cart form, this array would point to the specific node ID and even name the reference field responsible for generating the form.

If I were you, I'd use the Devel module's dpm() function to inspect the contents of the line item's data array. Drilling down through the context array you should discover how to get the information you're needing. Just make sure to use a !empty() check before assuming a particular key in the array exists!
> 2 votes

---
Tags: commerce
---


# Question
Title: Ckeditor Stripping all attributes, when re-editing content
Ckeditor is stripping out all attributes from the source code.

This is the case I'm going through: When I add html code to the source of the Ckeditor, and then want to preview the changes by selecting source again, I find that no styling was taken. When I go back to check the source all styling attributes are removed and some HTML tags.

I found a way to save the content, without stripping by directly saving after pasting the html code in the source. But if I try to re-edit the content it strips all styling attributes and some html tags.

I am using Full HTML Text format, and did try previous versions of the ckeditor module. Also tried to modify the `config.js` file by adding "`config.allowedContent = true`;" as referred by the following post

```
<nav class="footer-wrapper"><section class="col-md-3">
<h3 class="block-title h5">
  About
</h3>
<ul class="list-unstyled"><li>
    <a href="/bio" title="">Biography</a>
  </li>
  <li>
    <a href="/timeline" title="Plans and Billing">Timeline</a>
  </li>
  <li>
    <a href="/quotes" target="_blank">Quotations</a>
  </li>
  <li>
    <a href="/philo" target="_blank" title="">Philosophy</a>
  </li>
</ul></section>

```

CKeditor Stripped HTMl:

```
<p>About</p>
<ul>
    <li><a href="/bio" title="">Biography</a></li>
    <li><a href="/timeline" title="Plans and Billing">Timeline</a></li>
    <li><a href="/quotes" target="_blank">Quotations</a></li>
    <li><a href="/philo" target="_blank" title="">Philosophy</a></li>
</ul>
<p>Intellectual Legacy</p>

```

Any way to resolve the following?

# Answer
> 2 votes
You shouldn't really hack the `config.js` file. You can pass any custom configuration values through the admin:

1. Go to `/admin/config/content/ckeditor`.
2. Click on the "Edit" link next to the profile you are working with.
3. Expand the "Advanced options" fieldset.
4. Enter the following code in the "Custom JavaScript configuration":

```
// Instruct CKEditor to disable the filter. You can also limit this to specific tags.
config.allowedContent = true;
// Allow p, div, li and ul tags to have any attributes attached to them.
config.extraAllowedContent = 'p(*)[*]{*};div(*)[*]{*};li(*)[*]{*};ul(*)[*]{*}';

```

See docs for `CKEDITOR.config.allowedContent` and `CKEDITOR.config.extraAllowedContent`. If you are insterested in having this in every Drupal installation, check out my Drupal 7 installation profile.
The file in question is here.

Hope this helps.

---
Tags: wysiwyg
---


title: Setting product SKU

text:
# Question
Title: Setting product SKU
I'm trying to change 600 products so that the node SKU is set to the value of the node's title. I want to use VBO to accomplish this, with the "execute arbitrary PHP script" option. Here is the code I am using:

```
$new_node = node_load($object->nid);
$new_node->model = $object->title;
node_save($new_node);

```

However, this does not work. Does anyone know where I'm going wrong here?

# Answer
> 1 votes
The only way I could get it to work was to do this:

```
$node->model = $sku;
node_save($node);

```

The reason I could not get values was because of revisions. I changed function "uc\_product\_get\_models". Line 1357 changed to:

```
 $models[] = db_query('SELECT model FROM {uc_products} WHERE nid = :nid order by vid desc', array(':nid' => $nid))->fetchField();

```

I know changing core is bad, but:

* It seems to be fixed in the dev version
* I have no idea when the dev version is going to be released again, but when it does, the change will already be there.

---
Tags: ubercart, views
---


# Question
Title: As an admin, how can I view individual user permissions for individual nodes?
I’m attempting to sell individual nodes (video classes) to individual customers on my client’s website. I've learned how to do this via two videos from Commerce Guys website. It uses the following modules:

Content\_Access, ACL, References, Rules, Commerce

Briefly it works like this: Two content types are created - a video class product, a video class. Each video class product has a reference to a video class. Once purchased an individual then has permission granted to view the video class, the one ref’d by the video class product. By default video class content type permissions are turned off. But on the access control tab of the content type there is an option that is checked that reads ‘Enable per content node access control settings’

My question is this: As an admin how can i view an individual user’s permission setting for individual nodes? and then change that permission?

I’m asking because although it works initially, at some point the user’s permissions are being being reset, ie turned off and I’m not sure why.

Any help would be greatly appreciated.

# Answer
> 1 votes
You can use "Devel Node Access". After enabling it, you can add it as a block. It shows you a table with detailed permission for each content.

# Answer
> 0 votes
On the video class nodes page, by way of the access\_control module there is an access control tab. On that page, toward the bottom there is a section labeled ‘USER ACCESS CONTROL LISTS’. From there you can set individual user permissions.

---
Tags: commerce, users
---


# Question
Title: Specify a node type (bundle) in entity reference field
I have a custom entity type which has an entity reference field.

```
   $fields['referenced_article'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Article'))
  ->setDescription(t('The associated article.'))
  ->setSetting('target_type', 'node')
  ->setSetting('handler', 'default')
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE);

```

This field returns now the nodes of all the node types when finding a match. How can I specify a node type? (I only want to show the nodes of type "article")

Do I need to use a specific setting for selecting content only one node type?

# Answer
> 6 votes
Try adding

```
->setSetting('handler_settings', ['target_bundles' => ['article' => 'article']]),

```

Source

---
Tags: 8, entities
---


# Question
Title: node_load() in a form and display it in an attached form markup
How can i show every node title which is related to the taxonomy term in a form field? I work a little bit around and think i'm really close for a solution, but thats a little bit too tricky for me. I get one node title, but if i related 2 nodes to one term, i still get only one with an error message. I think i need to built an extra array, but I didn\`t know how to handle it with the $link\[$data-\>tid\].

```
        $terms = taxonomy_get_tree('1', 0, NULL, TRUE);
        $image_style = 'medium';

        foreach ($terms as $data) {
          if(!empty($data->field_term_image['und'])) {
            $output[$data->tid] = '<img src="'.image_style_url($image_style ,$data->field_term_image['und'][0]['uri']).'" />'. $data->name;
          } else {
            $output[$data->tid] = $data->name;
          };

          $term_nids = taxonomy_select_nodes($data->tid, FALSE);
          $nodes = node_load_multiple($term_nids);

          foreach($nodes as $node){
            $link[$data->tid] = $node->title;
          };
        }

        $form['step_1']['city_default'] = array(
          '#type' => 'radios',
          '#title' => t('Default category'),
          '#options' => $output,
          '#description' => t('The selected category will be shown by default on listing pages.'),
        );

        foreach ($form['step_1']['city_default']['#options'] as $key => $city_text) {
          $form['step_1']['city_default'][$key]['#description'] = $link[$key];
        }

```

Glad about every help.

# Answer
> 0 votes
You could do this with entity references and the views merge rows module.. An entity reference field to the taxonomy term and an entity reference view providing the term and all related nodes.. Here's a quick example I did up on a node add form. I can give more detail tomorrow if it's what you need.

---
Tags: 7, nodes, forms, taxonomy-terms
---


# Question
Title: How to set a coming soon page on drupal?
All request must be redirected to the coming soon page, is there any module can do it or a solution, I'm using the zen base theme.

Thank you for your help :)

# Answer
You can put the site on maintaince mode and can use the message as coming soon.
> 8 votes

# Answer
Another way, mentioned by VM in this support request 5 years ago is:

> \[...\] creating a page-front.tpl.php file for you theme which only gets called on the front page.

And use that tpl for the coming soon period.

I personally used the maintenance mode (see answer by arpitr in this page). But I don't know how to display a block in the maintenance mode. For instance a block with a mailing list subscription form (which is a must in a coming soon page). The front.tpl.php way instead is more customizable, I think. I'll check it out. (*see updates in edit3*)

Edit: I'll check out also mcd module which integrates with simplenews subscription block (this way it's possible to use the maintenance option).

Edit2: Also, with 3rd party service mailchimp one can embed her subscriptio form in the plain html of the maintenance page (*see updates in edit3*). Another way to go and use the maintenance page option.

Edit3: I've tried to insert an iframe (embedding mailchimp subscription form or google subscription form) in the maintenance page message, with no success. So, if one needs to deal with iframe embedding, one has to use the tpl.php option. The good news (for me) is that there is a more specific *maintenance-page.tpl.php* to configure for this.
> 1 votes

# Answer
Have you tried the Maintenance Countdown module? It puts your site in a maintenance mode and provides a nice counter for the time the site will be available again.
> 1 votes

# Answer
Check ComingSoon: A Distro for Collecting Pre-Launch Sign Ups. I think this could help you.

> "*Coming Soon*" is a distribution for creating a launch site for an upcoming project, idea or business. In it's most basic sense, it's a Drupal clone of LaunchRock.com. It provides a simple signup / registration form on the homepage and unique share pages for new users. So that before the site, app or business itself actual launches, you can start to get new members.
> 0 votes

# Answer
you can create a panel with one column and put a block in it with all data you need so you wil have a new page with a unique url then choose this page from configuration - site information in Default 404 (not found) page or put its link to all your incoming page
> -1 votes

---
Tags: 7, theming
---


title: How to send files to Drupal 8 via REST

text:
# Question
Title: How to send files to Drupal 8 via REST
I can create articles via `REST` without problems. But I can not figure out how to submit files.

How do I submit files (images) to Drupal 8 via `REST`?

Update:

```
REST UI - File: /file/{id}

Example image added in article:
/admin/content/files -> /admin/content/files/usage/1

file {id} = 1?

Get file id 1:

curl --request GET --user admin:admin --header 'Accept: application/hal+json' http://d8.local/file/1
A fatal error occurred: No route found for "GET /file/1"

```

Post image (without entity content):

```
curl --request POST --user admin:admin --header 'Content-type: application/hal+json' http://d8.local/entity/file
{"error":"No entity content received."}

```

I can't find out how to create the `entity content`.

# Answer
> 6 votes
* Apply patch to the core: https://www.drupal.org/node/1927648
* Install Rest UI using: `drush dl restui-8.x-1.x`
* Go to /admin/config/services/rest and activate File `/entity/file/{file}`
* Under /admin/people/permissions set all necessary permissions
* Make sure files folder exists and has proper permissions
* Encode image using command tool base64
* POST to **drupal.url/entity/file/**

```
{"_links":
{
  "type":{"href":"http://drupal.url/rest/type/file/file"}
},
  "filename":[{"value":"input.jpg"}],
  "filemime":[{"value":"image/jpeg"}],
  "data":[{"value":"insert-output-from-base64-here"}] }

```

# Answer
> 2 votes
1. Install and enable RestUi and File Entity modules.
2. Goto 'admin/config/services/rest' and enable **File** Resource with post method along with json and hal\_json formats
3. Enable post permissions ***Access POST on File resource*** @admin/people/permissions
4. Post url - http://d8.local/entity/file?\_format=hal\_json
5. Following format of post data (use base64 encoder for image data)

```
{
 "_links": {
   "type": {
     "href": "http://d8.local/rest/type/file/image"
   }
 },
 "filename": [
   {
     "value": "favicon-32x32.png"
   }
 ],
 "filemime": [
   {
     "value": "image/png"
   }
 ],
 "filesize": [
   {
     "value": "488"
   }
 ],
 "type": [
   {
     "target_id": "image"
   }
 ],
 "data": [
   {
     "value": "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAkUExURUxpcSOq4SOq4SOq4SOq4SOq4SOq4SOq4SOq4SOq4SOq4SOq4U0m8UcAAAAMdFJOUwD/EvAm2qhTPMRrkl4CMYAAAAE1SURBVCjPXZG/S8NQEMePR7Ehnb48khC7BEFFnYJD6/aWOLilVBy6WBVc648/oCii1KlFKDrFwV2tqH+edy9Rk7zh8e7Dfe++944oP5dUO59RDQyPqrFK/WqKCzxUwA30oJyymervlVK8PsVBOd85hh6pyflfhwXg024cjguwBqCjhsCsSOAn+k4MBGpUWAB6Tb6W1VxAgv+MfcPgWUBgazjxoYwlQLrsmBa6MhbH3hep2yu6QJuowWL9Yfs1U4QRSbWOjRts0DMCdEbqjl8s1kYkPqmX7YGRfgy4aJe2IB+0wZJI2s7ojEGbWtJejL1aL55h+wGDVWTWix47+cAug6kAycjs+LkkjFzku0h6dC3D01KxCmdOLrt7pyQ0+Z/tRXT/eEr0dvL7y6zkrbhPtYVPrOAHKZQ53IyepQMAAAAASUVORK5CYII="
   }
 ]
}

```
6. Set Authorization ,Content-Type in headers.(Authorization: Basic xxxxxxxx Content-Type: application/hal+json)
7. Use following php curl

```
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "http://d8.local/entity/file?_format=hal_json",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\n  \"_links\": {\n    \"type\": {\n      \"href\": \"http://d8.local/rest/type/file/image\"\n    }\n  },\n  \"filename\": [\n    {\n      \"value\": \"favicon-32x32.png\"\n    }\n  ],\n  \"filemime\": [\n    {\n      \"value\": \"image/png\"\n    }\n  ],\n  \"filesize\": [\n    {\n      \"value\": \"488\"\n    }\n  ],\n  \"type\": [\n    {\n      \"target_id\": \"image\"\n    }\n  ],\n  \"data\": [\n    {\n      \"value\": \"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAkUExURUxpcSOq4SOq4SOq4SOq4SOq4SOq4SOq4SOq4SOq4SOq4SOq4U0m8UcAAAAMdFJOUwD/EvAm2qhTPMRrkl4CMYAAAAE1SURBVCjPXZG/S8NQEMePR7Ehnb48khC7BEFFnYJD6/aWOLilVBy6WBVc648/oCii1KlFKDrFwV2tqH+edy9Rk7zh8e7Dfe++944oP5dUO59RDQyPqrFK/WqKCzxUwA30oJyymervlVK8PsVBOd85hh6pyflfhwXg024cjguwBqCjhsCsSOAn+k4MBGpUWAB6Tb6W1VxAgv+MfcPgWUBgazjxoYwlQLrsmBa6MhbH3hep2yu6QJuowWL9Yfs1U4QRSbWOjRts0DMCdEbqjl8s1kYkPqmX7YGRfgy4aJe2IB+0wZJI2s7ojEGbWtJejL1aL55h+wGDVWTWix47+cAug6kAycjs+LkkjFzku0h6dC3D01KxCmdOLrt7pyQ0+Z/tRXT/eEr0dvL7y6zkrbhPtYVPrOAHKZQ53IyepQMAAAAASUVORK5CYII=\"\n    }\n  ]\n}",
  CURLOPT_HTTPHEADER => array(
    "authorization: Basic " .base64_encode('User:Password'),
    "cache-control: no-cache",
    "content-type: application/hal+json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

```
8. Go and check file here - admin/content/files

# Answer
> 1 votes
You could install the REST UI module to see what endpoints you can use.

> Very basic user interface for Drupal 8's REST module.

As it also let you configure what resources are exposed by what authentication.

Please note the UI currently provide the wrong endpoints:- REST URI paths changed to canonical paths

---
Tags: 8
---


# Question
Title: When exporting a Feature, how can I turn off all page cache related settings?
I’m trying to export a Feature that would be used in a typical development environment. I want to have anything related to page caching turned off. But on the create feature page I’m not seeing where to do this. I would have thought there would be a Strongarm variable that reads Cache pages for anonymous users but there isn’t one. Also looking for the same for ‘Aggregate and compress CSS files’ and ‘Aggregate JavaScript files’.

So to clarify, how can I export the following in a Feature?

Cache pages for anonymous users -\> OFF

Aggregate and compress CSS files -\> OFF

Aggregate JavaScript files -\> OFF

# Answer
> 1 votes
The variables are named:

* cache - *Cache pages for anonymous users*
* preprocess\_css - *Aggregate and compress CSS files.*
* preprocess\_js - *Aggregate JavaScript files.*

---
Tags: features, strongarm
---


title: Connection to AWS MySql server over SSL

text:
# Question
Title: Connection to AWS MySql server over SSL
Running Drupal 7 and trying to enable secure connection between my AWS EC2 and RDS server using SSL.

Php version 5.3.29

I have found some information suggesting the following setup but I'm unsure how to configure this given my own SSL certs and the single certificate bundle I have from amazon?

When I try the below config I get a 500 server error.

Any pointers much appreciated.

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'database name',
      'username' => 'username',
      'password' => 'password',
      'host' => 'AWS RDS Endpoint',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'pdo' => array (
            PDO::MYSQL_ATTR_SSL_KEY => '/path_to_your/client-key.pem',
            PDO::MYSQL_ATTR_SSL_CERT => '/path_to_your/client-cert.pem',
            PDO::MYSQL_ATTR_SSL_CA => '/path_to_your/ca-cert.pem',
                     ),
      ),
  ),
);

```

# Answer
> 6 votes
Figured it out and required SSL via phpmyadmin admin interface for my users.

There are my Drupal database params

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'database name',
      'username' => 'username',
      'password' => 'password',
      'host' => 'AWS RDS Endpoint',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'pdo' => array(
        PDO::MYSQL_ATTR_SSL_CA => '<path to>/rds-combined-ca-bundle.pem',
      ),
  ),
);

```

---
Tags: 7, database, ssl
---


title: How to add a join to hook_query_alter

text:
# Question
Title: How to add a join to hook_query_alter
I want to use `hook_query_TAG_alter()` for search system so I use `mymodule_search_query_search_node_alter(QueryAlterableInterface $query)`.

What I want to essentially do is make sure that when a **calendar\_item**, **node type**, is one of the results, to make sure that it's field `field_date_value2` (this is the field that determines how long a calendar event or calendar item is valid, each calendar event starts at a certain date - `field_date_value` and ends at a particular date - `field_date_value2`) is greater than the current date.

So I imagine it would look something like:

```
function mymodule_search_query_search_node_alter(QueryAlterableInterface &$query) {
    $u_alias = $query->join('field_data_field_date', 'the_date');
    $query->fields('field_data_field_date', 'field_date_value2');
}

```

Now I am not adding a `$query->condition(...);` because this causes issues alone! I just need to know how to get in there and add the field to the query, then add a condition to that field's value!

Anyone able to steer me in the right direction? Please and thank you!

EDIT #1: You got me to where I needed to be! Thank you very much!! I have one more follow up question, if you do not mind.

The system search will find any node that has "Training" in it. This is great, but the nodes that are of type calendar\_item, I want to make sure the aformentioned **TO** field (`field_date_value2`) has a date older than current. I have modified my code above.

```
function mymodule_search_query_search_node_alter(QueryAlterableInterface &$query) {
     $u_alias = $query->join('field_data_field_date', 'fd', 'n.nid = fd.entity_id');
     $query->fields('fd', array('field_date_value2'));
     $query->condition("{fd}.field_date_value2", '2016-02-17T21:30:00', '>=');
}

```

My issue with my code above makes it so that it applies to all results, so I only grab calendar\_items, I still want to grab everything, just if it is a calendar\_item, to do the exclusion. I must need an outer Join?

# Answer
> 1 votes
Your query is a bit different compared to a regular query. A regular query is constructed like this (source):

```
$query = db_select('users', 'u');
$query->join('domain_editor', 'de', 'u.uid = de.uid');
$query->fields('u', array('name'))
  ->condition('u.name', '%' . db_like('john') . '%', 'LIKE')
  ->condition('de.domain_id', 25, '=')
  ->range(0, 20);
$result = $query->execute();

```

You have the base query:

```
$query = db_select('users', 'u');
$query = db_select($table, $alias);

```

Then the join:

```
$query->join('domain_editor', 'de', 'u.uid = de.uid');
$query->join($table, $alias, $condistion);

```

The fields to select:

```
$query->fields('u', array('name'))
$query->fields($table, array $fields)

```

And the conditions:

```
  ->condition('u.name', '%' . db_like('john') . '%', 'LIKE')
  ->condition($field, $value, $operator)

```

In your code it seems you did not take the table aliases into account. So you might want to try something like:

```
function mymodule_search_query_search_node_alter(QueryAlterableInterface &$query) {
    $u_alias = $query->join('field_data_field_date', 'fd', 'search.date = fd.field_date_value'); // No idea what the field is called, assuming 'search.date'.
    $query->fields('fd', array('field_date_value2'));
}

```

(You'll need to figure out what the name is of the field you want to join with, and substitute 'search.date' with that value.)

---
Tags: search, database
---


# Question
Title: Drush archive-dump override sql dump name
Is there a way to use `drush archive-dump` but to pass it somehow the name of sql file it dumps into archive? Current name is too long (full path with dots instead / and # to separate path and site name) and not as useful so I would love to override its name (like I can do with tar.gz name with `--destination` parameter)

# Answer
> 1 votes
Unfortunately, there is no way to stipulate what the sql dump file should be named. See the archive-dump source code for reference.

Wouldn't be too hard to adjust; PRs would be welcome.

---
Tags: drush
---


# Question
Title: How to only access a page through drupal_goto() function?
I have a form setup so that when the user enters the correct serial #, they are redirected to the download page.

I don't want the person accessing the download page directly or sharing with anyone else through the URL, as this will bypass the serial validation.

How can this be done in Drupal?

# Answer
Below is a solution that should work for users who are logged in (using Drupal 7, I assume).

Use the Content Access module to limit access to your download page to only those users who have a role like (say) "DownloadAllowed". Since you want to protect that download page, you'll need "some" access module.

And use the Rules module to implement a rule like so:

**Step 1**: Store your serial number (entered when your form is submitted) in a field which will be used in the next step. Even though you can use any "machine name" for that field, let's assume you call it "`field_serialnr`"

**Step 2**: Use a variation of the Rule included in my answer to "How to specify a Rules condition related to select list values?". Here is what you should tune in that rule:

* Replace the **Rules Event** to something like "After saving new content (of some type that matches your form)".
* Replace the "Value C" in the **Rules Condition** to the value of your serial nr.
* For debugging reasons, start with a Drupal message to be shown (to ensure your rule works correct if the serial nr is ok, and to also verify it works as you want if the serial nr is wrong or missing). After the message shows up as you want it to show, replace the Rules Action with something like "Assign role to user". The role to assign is ... you probably guessed it ... "DownloadAllowed".

With that, those users who entered your serial nr correctly, will ***just-in-time*** get permission to access the download page. Those who didn't will be stopped by the Content Access module ... Which is exactly what you want.

PS: for anonymous users trying to access your download page, you could create another Rule to set a Drupal message indicating that they must be logged in before they can access that download page. For that, just use Rules Event "Drupal is initializing" and a Rules Condition to check if the URL they entered matches the one from your download page.
> 1 votes

---
Tags: forms, users, uri
---


title: website problem

text:
# Question
Title: website problem
I used to go to a website of an organization .www.nameofthewebsite.org. One day that website was not accessible,may be it could be on change.That time i thought something wrong with my browser.So i searched in google and gave a name in the url as www.nameofthewebsite.org/install.php,then it asked as install in english.I choosed english and it installed something,then it went to drupal website asking username and password.Now whoever public goes to the site it goes to drupal.And i fear it has been done by me.After sometime if i go the website it said site offline due to technical problems.I am not the admin.please help me,what happened when i gave install.php in the url?

# Answer
> 0 votes
You installed Drupal on a website you don't own. But in order to do this, the administrators must have taken some steps in advance. On an attempt to load install.php on a working (installed) website you will see:

> Drupal already installed
>
> * To start over, you must empty your existing database.
> * To install to a different database, edit the appropriate settings.php file in the sites folder.
> * To upgrade an existing installation, proceed to the update script.
> * View your existing site.

So the administrators (or a malicious person) must have emptied the database of the existing site first. You had no way to remove the database (under normal circumstances) and you are not the reason the data is missing.

---
Tags: users, uri
---


# Question
Title: How to write Custom Javascript in "drupal commerce" checkout page?
In drupal 7, there is a common page in Templates folder i.e., "page.tpl.php". In this page if we write javascript, it works in all pages. Now I need to write custom javascript for "drupal commerce kickstart" checkout page. For Example, If I want to use onchange event function to "Full name" field. Even though If I just use "alert(document.getElementById('edit-customer-profile-billing-addressbook').value);", it is not working any where of the pages written. I tried javascript code in below pages.

profiles/commerce\_kickstart/themes/commerce\_kickstart\_theme/template.php profiles/commerce\_kickstart/themes/commerce\_kickstart\_theme/templates/ {almost all pages} profiles/commerce\_kickstart/modules/contrib/commerce/modules/checkout/ {almost all related pages}

So please help.. where should I write Javascript code to work in checkout page. Thanks in advance.

# Answer
> 3 votes
As St0ik mentioned, you'll want to use `drupal_add_js` to add the JavaScript to the page. The real question is, where do you want it to go?

If you want it to show up on every checkout page, use the generic checkout form alter:

```
// Show on every page of checkout.
function MYMODULE_form_commerce_checkout_form_alter(&$form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
}

```

If you want it to only show up on certain pages within the checkout, you can use a more specific form alter to only add it to a certain page.

```
// Review before payment only.
function MYMODULE_form_commerce_checkout_form_review_alter(&$form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
}

```

or

```
// First page of checkout.
function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
}

```

You'll use `MYMODULE_form_commerce_checkout_form_PAGE_alter` where `PAGE` is the wanted checkout step.

# Answer
> -1 votes
Best way to write javascript code to create separate js file. you can create js file in your module folder where you want.

after this you have to add this js to page where you want using drupal\_add\_js('path/to/your/file'.'checkout-script.js');

You can create a custom module, implement hook\_init() and check that you are on the checkout pages

```
function mymodule_init() {
  // your checkout steps, might need to update this to fit your needs
  // make sure you have all the checkout steps you need the script
  if(arg(0) == 'checkout' && arg(2) == 'billing') {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/checkout-script.js');
   }
}

```

You can learn more about drupal\_add\_js here https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_add\_js/7

---

Using hook\_init is not ideal on this situation as it will run on every page request.

nvahalik's suggestion is way better.

# Answer
> -2 votes
Use this hook.

```
function hook_commerce_checkout_page_info_alter(&$checkout_pages){
  drupal_add_js('path to ur module',mycustom.js);
}

```

---
Tags: commerce
---


# Question
Title: Drupal to Salesforce - Check if record exists before create
I am using the Salesforce Suite to push Entity Registrations to Salesforce in our commerce workflow. The problem I am experiencing is that there is no checks to first see if the registrant exists before creating a new one. At the moment every registrant is a duplicate.

How can I make it do the following? Seems like it should be pretty straight forward but isn't there...

* Check to see if Registrant exists based on a set of fields (email, first name, last name)
* If so, update that record with information that is different and obtain the SFID
* If not, create and obtain the SFID

This should be available regardless of record type, you should be able to check if something exists based on a series of fields.

If it needs to be done via a hook, I have been looking for documentation on how to use the Salesforce hooks to handle this but I can't find anything, so if you have any examples of how this can be done it would be awesome if you could share!

Looks like some work was done here for D6, https://www.drupal.org/node/507800 but it doesn't look like the changes were applied to the D7 rewrite.

# Answer
I have solved this myself utilizing the hooks provided in the Salesforce Suite module. I wrote details about it in a 2 part blog post.

Customize Syncing Between Drupal Commerce and Salesforce – Part 1
> 0 votes

---
Tags: crm
---


# Question
Title: Is it possible to have an external script run index.php that bootstraps Drupal?
It seems like such a simple question, and I apologize for my Drupal ignorance, but I am unable to get our Drupal contractors to accomplish what *seems* to be a simple request. I need the below script to work without paying for a month of contracting work:

The user *will* be logged in, and of course, there *is* a valid database. If it matters, the site is hosted by "Pantheon", and the script will also call a custom Drupal function to return a recordset.

Is this code not possible? Am I asking something that cannot be done ind Drupal thus the endless stream of complicated files that they keep giving me?

**`root\myscript\index.php`** (to run as *www.mysite.com\myscript\index.php*)

```
<?php
/* Check for Drupal Instance and then bootstrap to get User and Database connection */
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $db_url;
$creds      =  parse_url($db_url);
$db_host    = isset($creds['host'])     ? $creds['host']    : null ;
$db_user    = isset($creds['user'])     ? $creds['user']    : null ;
$db_pass    = isset($creds['pass'])     ? $creds['pass']    : null ;
$db_name    = isset($creds['db_name'])  ? $creds['db_name'] : null ;

$db = mysqli_connect ($db_host, $db_user, $db_pass, $db_name);
if(!$db){
    die('Failed! Could not open a db connection'.mysqli_connect_errno() . mysqli_connect_error());
}elseif(!$user){
    echo 'Failed! Connected to database, but did not get $user - we canNOT proceed';
    echo '<pre>'.print_r($db,true).'</pre>';
    die('Connected to database, but did not get $user')    ;
}else{
    echo "Success! User and DB are set and ready to use - we can proceed";
    echo '<pre>'.print_r($user,true).'</pre>';
    echo '<pre>'.print_r($db,true).'</pre>';
}

```

This (I think) is at least the start of the Drupal function that will return a recordset when the main code above is working.

```
/**
* Implements hook_block_info().
*
*/
function xyz_listofmyitems_block_info() {
    $blocks['xyz_listofmyitems'] = array(
        // The name that will appear in the block list.
        'info' => t('List of available items'),
        // Default setting.
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
    return $blocks;
}

```

# Answer
To answer your question - Yes, it is possible to have an external script to bootstrap Drupal.

If Drupal is installed in the folder `[root]`, and the index.php file that you want to get working is in `[root/myscript]`, you'd first get the working directory and then call bootstrap.inc and bootstrap Drupal.

```
<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/../includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// do your thing
?>

```
> 1 votes

---
Tags: bootstrapping, external-scripts
---


title: Print fields a different node

text:
# Question
Title: Print fields a different node
I have a News page which links to a bunch of news articles and I'm looking to print the header of the News Page on the individual articles.

The field\_get\_items doesn't return anything right now. Any advice would be greatly appreciated!

```
if ($node->type == 'article') {
         $news_header = field_get_items('page', $node, 'group_header'); print_r($news_header);

             //$url = file_create_url($node->field_header_image['und'][0]['uri']);
             //echo '<img src="' . $url . '" width="100%">';
            // }
        }

```

# Answer
> 1 votes
Are you loading the node first? If you are not getting anything returned then it's probably because $node isn't set. Also is the 'News node' a node type of article?

I would start by trying to retrieve the node information first:

```
$node = node_load(arg(1));
var_dump($node);

```

Also I think your field\_get\_items is not working as your entity type is 'page' but you are inside a check for a node type of article try:

```
$news_header = field_get_items('node', $node, 'group_header');

```

---
Tags: theming, nodes
---