# Question
Title: How close the admin overlay on submit for a drupal form shown within the admin overlay
I'm currently showing a drupal form via the admin overlay. I'm using jQuery to perform the processing of the form.

The problem I have is how do I close the overlay on submit? right now the only way to close the overlay is by pressing the X at the top right (well based on the default theme), which is just a .

Now I'm presuming that I could somehow change the form to add the "overlay-close" to the submit button, but I'm not sure how to do this.

Is there a way to add a class to a button on a form in drupal?

Cheers,

James

# Answer
> 0 votes
I don't have experience with the admin overlay, but from what you are writing, I understand that you want to add the class "overlay-close" to an element (admin overlay?) when submit button is pressed. You can adapt the following code for that:

```
$('#form_id').submit(function(){
  // Add "overlay-close" class to the proper element
  $('#element').addClass('overlay-close');
});

```

# Answer
> 0 votes
Old question but I googled to this question a couple of times before figuring out an answer. Rather than adding a class to the button you could use the hook\_form\_FORM\_ID\_alter() to add a callback function when the user clicks the submit button, and then in that callback function tell the overlay to close with the overlay\_close\_dialog function. This worked for me:

```
**
* Implementation of hook_form_FORM_ID_alter()
* *
**/
function mymodule_form_FORM_ID_alter(&$form, &$form_state) {
  $form['#submit'][] = 'mymodule_callback';
}

//callback after saving form to close overlay
function mymodule_callback(&$form, &$form_state) {
  // Form API will re-render the current page and pass the redirect information to the overlay JavaScript
  overlay_close_dialog($url, $url_settings);
  // stay on the same page after all submit callbacks have been processed.
  $form_state['redirect'] = FALSE;
}

```

See https://api.acquia.com/api/drupal/modules!overlay!overlay.module/function/overlay\_form\_submit/7 for more on overlay\_close\_dialog options

# Answer
> 0 votes
The simplest way is to put this code in your submit handler:

```
if (module_exists('overlay') && overlay_get_mode() == 'child') {
  overlay_close_dialog();
  $form_state['redirect'] = FALSE;
}

```

---
Tags: 7, forms, modal-dialogs
---


# Question
Title: Cannot use fields as product attributes if they are within a field collection
I am building a commerce marketplace, and have several field that I am reusing on multiple product types. It's getting tedious adding them over and over, so I'd like to include them in a field collection.

The issue is that fields within a field collection cannot be marked as (and I'm paraphrasing) "should be used as a product attribute." I'm assuming this is because the fields do not know that they will be used on a commerce product, so the option isn't available.

Does anybody know of a way to implement this functionality? I'm open to coding, I just don't know what I'd work on.

# Answer
> 0 votes
I wasn't able to answer the questions above, but I was able to solve my problem using Field Tools, which let's you clone fields to and from any bundles, as well as apply mass edits to all instances of a single field.

# Answer
> 0 votes
By default Drupal Commerce supports list type fields (list, term reference - list, etc.) as Product attributes, not sure but may be because pre-defined list of values.

It would be difficult to get the field collection as your product attribute, because attributes make the product Unique and using the field collection won't give you much feasibility to use every field value to differentiate between product. Instead you can re-use fields in every product type and get it working easily.

If you still would like to give field collection module a try, you can check Drupal Commerce module in detail for attributes implementation or refer Commerce Attributes Date module which allows date field to be used as Product Attributes (Drupal Commerce doesn't support Date type field as attribute by default).

---
Tags: commerce, entities
---


title: What should I enter as server URL?

text:
# Question
Title: What should I enter as server URL?
I have a Drupal site on Amazon server. On the amazon server, I have created an Elasticsearch server. I want to connect my Drupal instance with that server so I can use the search server for performing the search operation on the site.

I added and configured the Elasticsearch connector module which, in order to connect to the search server, needs I create a cluster which would help in connecting both the instances.

While adding a cluster to the Drupal instance, it asks me about the server URL. I am not sure on what I should write as server URL. What should I add in that form field?

# Answer
Just enter the Endpoint of your AWS Elastic-search Cluster.

Use port : "80".

the Complete url will be something like:

XXX-XXX-XXX-XXXXXX.ap-southeast-1.es.amazonaws.com:80

First check are you able to access the Elastic-search , Try to telnet on the server:

telnet XXX-XXX-XXX-XXXXXX.ap-southeast-1.es.amazonaws.com 80

If it's not accessible make it available for your IP by changing the access policy .
> 2 votes

---
Tags: 7
---


title: How to use replacement pattern in css?

text:
# Question
Title: How to use replacement pattern in css?
Is it possible to use tokens such as \[view\_node\] in css ? I want to display links only for a particular content type.

Thanks !

# Answer
> 1 votes
**Assuming your view uses `Show: fields`.**

Add `type` as a field, check mark the hide from view box.

Click on your field, in REWRITE RESULTS, checkmark rewrite outlput of field

In there, put `<div class="all-links [type]">[field_name]</div>`

Then in CSS

```
.all-links { display: none; }
.all-links.article { display: block !important; }

```

---

Another solution, is to use Views Conditional

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views.

Then just do a simple condition if `type` is x, then `[field_name]`

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


title: Commerce - Alter quanitity widget

text:
# Question
Title: Commerce - Alter quanitity widget
I'm new to commerce and I have a question. I'm building a website for a butcher, and he wants products to be sold per 100gr. I have the price in kilo and I allow decimal values for quantity.

The quantity field widget is a text box by default. I did some googling and found some things but i'm unable to get it work. I assume I need the commerce\_cart\_add\_to\_cart\_form() function :)

I want to have a drop down with pre-defined values per 100 gram for example.

---

100 gram - 1 euro 200 gram - 2 euro 300 gram - 3 euro ....

## 1000 gram - 10 euro

Add to cart button

Any idea's? Or is there an easyer solution for this?

Thanks in advance

# Answer
> 1 votes
Assuming that you allow decimal in the quantity field, you can use the hook\_form\_alter() hook. It is one of the most used drupal hooks.

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  // add to cart form
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {

    // Replace the text quantity field with a select list.
    if (isset($form['quantity']) && ($form['quantity']['#type'] == 'textfield')) {

      $product = commerce_product_load($form['product_id']['#value']);
      $price = commerce_product_calculate_sell_price($product);

      $select = array(
        '0.1' => '100grams '.commerce_currency_format(1*$price['amount'], $price['currency_code'], $product),
        '0.2' => '200grams '.commerce_currency_format(2*$price['amount'], $price['currency_code'], $product),
        '0.3' => '300grams '.commerce_currency_format(3*$price['amount'], $price['currency_code'], $product),
        '0.4' => '400grams '.commerce_currency_format(4*$price['amount'], $price['currency_code'], $product),
      );

      $form['quantity']['#type'] = 'select';
      $form['quantity']['#options'] = $select;
      $form['quantity']['#size'] = 1;
    }
  }
}

```

---
Tags: commerce, navigation
---


# Question
Title: Why is unchanged and new value always the same in my Rules condition?
I have a boolean field called verified defined in profile2. When this field changes from not ticked to ticked I would like to send out an email to the user. Easy I thought with rules

Starting using "After updating an existing profile" then comparing the fields `profile2-unchanged:user:profile-directory-information:field-verified` and `profile2:user:profile-directory-information:field-verified` (bascially saying equal and then negating the condition)

```
   "IF" : [
      { "user_has_role" : {
          "account" : [ "profile2:user" ],
          "roles" : { "value" : { "12" : "12" } }
        }
      },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3", "28" : "28" } },
          "operation" : "OR"
        }
      },
      { "NOT data_is" : {
          "data" : [ "profile2-unchanged:user:profile-directory-information:field-verified" ],
          "value" : [ "profile2:user:profile-directory-information:field-verified" ]
        }
      }
    ],

```

However they are always the same value and the rule never fires. However when I take out the condition and send myself an email with the two values. One is true the other one is false.

also tried this in the condition:

```
  { "data_is" : {
      "data" : [ "profile2-unchanged:user:profile-directory-information:field-verified" ],
      "value" : 0
    }
  },
  { "data_is" : {
      "data" : [ "profile2:user:profile-directory-information:field-verified" ],
      "value" : 1
    }
  }

```

which is also not working. Tried to move it in before saving a profile, and also in various save user events. Always the same result. So why are the values different in Actions then they are in conditions?

Am I missing something here?

# Answer
# Rule refinements

### Entity has field

Make sure to add a Rules condition `Entity has field` (related to your additional `profile2:user:profile-directory-information:field-verified`-field in your Rules condition). And make sure to add that `Entity has field` condition BEFORE the condition you already have.

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

### Add ":value" to your fields

Adapt your rule by adding `:value` to both of your fields, so that they look like so:

* `profile2-unchanged:user:profile-directory-information:field-verified:value`
* `profile2:user:profile-directory-information:field-verified:value`

# Rules debugging

If none of the above helps, then move on to Rules **debugging**, as explained in my answer to "How can I display the value of a variable inside a condition?".

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of your `profile2:user:profile-directory-information:field-verified`).
> 0 votes

---
Tags: 7, users, rules
---


# Question
Title: Imported site doesn't displays CSS styles
I imported a site from pantheon to my localhost to work on it. The site pulls up just fine, however, it has no CSS styles at all. Its plain HTML through and through. Also i'm getting 30+ of these type of errors:

```
Warning: file_put_contents(temporary://fil739F.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (line 1940 of C:\wamp\vhosts\cbirc\includes\file.inc).
The file could not be created.

```

How do I get the styling added back to the site?

# Answer
> 4 votes
Make sure you've properly configured **Temporary Directory** inside **Admin =\> Configuration =\> Media =\> File System**, and check if "Public File System" and "Temporary Directory" have valid permissions to them. Once confirmed, clear site cache.

If not required you can also disable CSS Compression by navigating to "Admin =\> Configuration =\> Performance". So they will be accessed directly for there original location.

# Answer
> 0 votes
Set the temporary file directory in File System. Then Go to either Performance clear cache or use drush cc within your site folder on command line

---
Tags: 7, theming
---


title: Drupal PHP Coding Standards

text:
# Question
Title: Drupal PHP Coding Standards
I have declared two items in my hook menu.

```
//Calls a function that enables inputting/updating data of a particular template.
$items['user/%user/myid_inputting'] = array(
    'title' => 'MyID Inputting',
    'description' => 'Inputting data for a particular data',
    'page callback' => 'myid_inputting',
    'page arguments' => array(1),
    'access arguments' => array('perform_regular_task'),
    'file' => 'includes/myid_inputting.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -20,
);

//Calls a function that enables ID printing
$items['user/%user/myid_printing'] = array(
    'title' => 'MyID Printing',
    'page callback' => 'myid_printing',
    'page arguments' => array(1),
    'access arguments' => array('perform_regular_task'),
    'file' => 'includes/myid_printing.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -19,
);

```

I had used two separate files for the two items. Is that best practice in Drupal? I just notice some functions that I used are redundant when separating the code between the two. What are advantages and disadvantages of doing so?

# Answer
If the code in `myid_inputting()` and `myid_printing()` is different and large, you might want to keep these callbacks separate. I generally avoid having too many lines in one file, so whenever it's possible to logically organize the code of your module into files, it's better to do so.

Regarding the code that is redundant: I always have a separate file with helper functions where I store functions that need to be shared. Include this file at the top of the `.module` file, and you're all set. You can see an example in my D7 module boilerplate on Github.

Here's how you would include the helpers file (this would go at the top of the `.module` file):

```
// Load the helper functions.
require_once dirname(__FILE__) . '/YOUR_MODULE.helpers.inc';

```

Back to your case - leave different code in separate files, make helper functions for the rest and move it to `YOUR_MODULE.helpers.inc`. This works great for very large modules as well, and is self explanatory when more people are working with you on a project.

Hope this helps.
> 1 votes

---
Tags: 7, routes
---


title: Add image to taxonomy terms menu item

text:
# Question
Title: Add image to taxonomy terms menu item
My menu block is using the module: taxonomy menu terms to construct the main menu as a block to display in frontend.

I want to add image to each menu item, anyone know what is the simplest way to do that? or other module can do the same things?

# Answer
Have you tried Menu Icons? It is useful. If you want to add some custom image to every term, add the field into your entity and upload default image. But I think, this module works better.
> 0 votes

---
Tags: taxonomy-terms
---


title: Error when printing URI in drupal Views

text:
# Question
Title: Error when printing URI in drupal Views
I tried to print the Image field URI and the image field in the views-field.tpl and i got this error. Notice: Undefined index: field\_photo in include() (line 6 of timeline.tpl.php). Notice: Trying to get property of non-object in include() (line 6 of timeline.tpl.php).

Here is my code

```
<li class="row no-margin">
    <div class="timeline-badge <?php print $fields['field_event']->content ?>" data-toggle="tooltip" data-placement="top" title="<?php print $fields['field_event']->content ?>"><?php print $fields['field_icon']->content ?></div>
    <div class="timeline-panel">
        <div class="timeline-mins"><?php print $fields['field_minute']->content ?></div>
        <div class="timeline-comment"><?php print $fields['field_comment']->content ?></div>
        <?php if($fields['field_photo']->content){  ?>
        <div class="timeline-photo">
        <a id="tml-photo" href="<?php  print $fields['uri']->content; ?>" title="<?php print $fields['field_comment']->content ?>">
        <?php print $fields['field_photo']->content ?>
        </a>    </div>
        <?php } ?>
    </div>
</li>

```

# Answer
> 0 votes
If you just want to check if it has a value, you can add a check if it exists, so on row 6:

```
<?php if (isset($fields['fields_photo']->content) && $fields['fields_photo']->content) { ?>

```

Otherwise do a `<?php dpm($fields); ?>` to see what is actually available to use for your theme.

It couldn't be that you have set it to "Exclude from display"?

# Answer
> 0 votes
For line 6, try:

```
<?php if(!empty($fields['field_photo']->content)){  ?>

```

or

```
<?php if($fields['field_photo']->content != NULL){  ?>

```

The above two codes checks if the field is not empty, which means it exists.

---
Tags: views, theming
---


# Question
Title: How can I extend Commerce Discount to apply discount on custom price field?
I have products with 2 prices, the Commerce default one `commerce_price`, and a custom field `field_price_with_flight`. In some cases, depending on the node display term value of a taxonomy, I need to calculate and display the discount prices onto the custom price instead of default Commerce price.

If it can be achieved with rules, I'd appreciate a detailed answer because I'm not very comfortable with the use of rules, especially commerce ones.

How could I achieve that ?

## EDIT :

I need to make it possible through discount module UI. I'll try to expose why with the business model below.

The site sells travels. **Anytime, depending on sales, the owner decides to create new discounts**, with parameters such as:

* Limited time
* A different discount value usually fixed amount but could be % sometimes
* Applied on a selection of travels, choosed across discount UI whether per product or per category, with the help of Commerce Discount Product Category

The flexibility of Commerce Discount does the job most of the time. I could setup rules for one case, but this is just impossible to teach the site owner and sellers how to setup discount rules for each new one.

Now whenever you create a discount like that, The module creates a dedicated rule. Basic one exported below.

The challenge is that by default it will apply on `commerce_price`. I need to extend Discount module so that :

* Or it detects the travel type has a field\_price\_with\_flight value
* Or we tell the module it is that case with a checkbox in the discount form for instance

and applies then the discount to `field_price_with_flight`.

Or, last, if possible, create a global rule that will overwrite each discount rule whenever necessary?

**Basic rule created by discount**

```
{ "commerce_discount_rule_discount_discount_example" : {
    "LABEL" : "Discount example",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-1",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Discount", "R\u00e9duction par produit" ],
    "REQUIRES" : [
      "commerce_discount",
      "commerce_discount_date",
      "commerce_product_reference"
    ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "commerce_discount_compatibility_check" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "commerce_discount" : "discount_discount_example"
        }
      },
      { "commerce_discount_date_condition" : { "commerce_discount" : "discount_discount_example" } },
      { "commerce_product_contains_products" : { "sku" : "VE1201#2556#09-05-2016" } }
    ],
    "DO" : [
      { "commerce_discount_fixed_amount" : {
          "entity" : [ "commerce_line_item" ],
          "commerce_discount" : "discount_discount_example"
        }
      }
    ]
  }
}

```

# Answer
All you need is Rules :)

You can start with next steps:

1. Visit Product pricing rules page: /admin/commerce/config/product-pricing
2. Click + Add a pricing rule
3. Enter Name. E.g. "Custom discount calculation"
4. Click "Save"

After that you can program logic of "some cases, depending on the node display term value of a taxonomy" via rules. If you provide more details I can explain steps more precise.

From this point you should only add conditions and actions. There is a good module rules\_conditional which allows you to add conditions in any place of your rule.

**Some hints on Rules:**

When you want to do some actions and check with field values, you have to check if the field exists first (that's a tricky part of rules).

E.g. if you want to check the value of the field\_price\_with\_flight, you have to add 2 conditions before:

1. Entity has field: Entity `commerce-line-item`, Field: `commerce_product`
2. Entity has field: Entity `commerce-line-item:commerce-product`, Field: `field_price_with_flight`.

After these 2 actions you can do things with the field.

P.S. An alternative way for checking fields is to check the bundle of the entity.

If you need to do some price calculations you can use actions:

* Data \> Add variavle
* Data \> Calculate a value

Once you have finished your calculations, you can apply your price. Check the \`Commerce line item' actions for unit price. You can multiply, divide, set unit price.

That is basically it. In this case you do not need the discount module.

**Advanced**

If you need some very custom calculations you can code a custom action for price calculation. There is a lot of examples if you try to search it. E.g. How To Create A Custom Rules Action

**Useful links, videos:**
> 4 votes

# Answer
You can use Rules. The rule should be something like Event: Calculate product sell price Conditions: On which conditions this rule should be evaluated Actions: Actions that should be done aka ( set commerce price to custom price ) etc.

For more advanced usage you can also use rules\_conditional module.
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: Why does Drupal store the uploaded files for a content node even if the content is not created?
In Drupal 7, I try to create a News, which is a custom content type, with an Image file. I upload the file (not by pressing Ajax button, but just selecting the file), and leave all the other fields (some mandatory) empty. I press Send, and I get the red errors. Even if I close the browser, the image will have been uploaded to the folder ( `sites/default/files/news/images` ). Even after deleting cache and running cron.php, the orphane image will be still there. Isn't it a bug of Drupal, which would have to delete those images with no associated content? The file is not reused in other content types.

# Answer
> 0 votes
I have discovered that the files are physically stored, and also in the database, there is an entry in the table `file_managed` with the field **status** with the following indication and value : 0

```
A field indicating the status of the file. Two status are defined in core:
temporary (0) and permanent (1).
Temporary files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed during a cron run.

```

I have manually changed the timestamp of the uplodaded file, run the cron, and the file dissapears. Obviously there must be a confident time, because if not, files in contents still being update could have the risk of being deleted. My fault for not thinking of this last point.

---
Tags: 7, media
---


title: Help combining 2 views?

text:
# Question
Title: Help combining 2 views?
I have a content type with two fields: **Exterior Images** and **Interior Images**

Both of these fields are Unlimited Values - so the user can upload as many images as they want to exterior and interior. Screenshots: http://prntscr.com/a9m8o5 http://prntscr.com/a9m8uc

Now I'm trying to create a view that grabs all exterior and interior images uploaded and displays them.

The only way I can find to have each image displayed as its own individual field and row is to perform a UNION betwen something like SELECT exterior UNION SELECT interior etc. etc. but I just can't seem to figure out the rest.

I've tried creating two views and combining them like this:

```
function pgallery_views_pre_execute(view &$view){

    if ($view->name == 'photo_gallery'&& $view->current_display == 'page_1') {
        // View 1 contains Interior Images
        $view1 = views_get_view('photo_gallery');
        $view1->build('block_1');
        $query1 = $view1->build_info['query'];

        // View 2 contains Exterior Images
        $view2 = views_get_view('photo_gallery');
        $view2->build('block_2');
        $query2 = $view2->build_info['query'];

        $query1->union($query2);

        $view->build_info['query'] = $query1;

    }

}

```

but it won't render whatever is in $query2 - it just repeats $query1 values. So I get the correct number of "rows" from the result but it repeats the data for some reason. Please help!

# Answer
> 0 votes
Views Field View module does that. Create a new view and add both needed views as fields.

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.

# Answer
> 0 votes
You should be able to add both fields in views and in the settings for the field, there are options for multiple values. So views go through each node and outputs each image.

---
Tags: views
---


# Question
Title: Cannot create users as administrator. Users can register by themselves but I can't add users (site exported directly from Drupal Gardens)
I have a weird problem with my user registration in 2 of my sites. When I go to the "Add User" link under "People" menu, I fill in the information of the user and press the "Sign Up" button. The page refreshes, there is no error message or a confirmation message that the user has been added and the user is not added. I have checked the error messages in the "Reports" section and no entry is created there either.

When I turn on the user registration from "Configuration - Account Settings" a user can create a new account and I can edit the account as admin but I still can't create new user accounts.

Some extra information:

The site that I created is a direct export from Drupal Gardens. I did not mess with any code. It's pretty clean, direct export.

Any ideas on how to troubleshoot this and find out what is causing this strange issue?

Edit: for the time being I use the workaround to manually register through the regular user registration form and then disable the manual user registration and edit the users as admin but I'd prefer the normal functionality for obvious reasons.

# Answer
I had the same problem. However, once I disabled three Drupal Gardens custom modules, I was able to add users. The modules are:

* Gardens Features
* Gardens Feedback
* Gardens Required Features
> 2 votes

# Answer
Are you sure you copied the .htaccess file when you migrated your site ? Page submits leading nowhere are often caused by improper .htaccess configuration.
> 0 votes

# Answer
I encountered the same problem but the solution above cant solve it. let me take you through the steps.

The problem occured when i was moving my drupal files from my localhost to server, this problem may arise when you didnt copy all your enabled modules when moving to the server.

**kindly check all your modules in `sites/all/modules` both on local machine and live server.**
It might help you
Thanks.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Call Drupal behaviour when AJAX form is submitted?
I have a form with an AJAX callback. I need to run some JavaScript when the form is submitted. Ive got this working by following the tutorial below:

http://www.jaypan.com/tutorial/calling-function-after-ajax-event-drupal-7

However I already have a JavaScript file in the module and I would prefer to put my code in there. This file is loaded on page load so I think I would need to listen for an event and run when this was detected. Can I use the AJAX callback to trigger an event thats within a Drupal behaviour?

```
function after_ajax_form($form, &$form_state)
{
    // First we create a form element with AJAX enabled
    $form['ajax_example'] = array
    (
        '#type' => 'select',
        '#title' => t('Change me'),
        // Note that I am setting the value and the display of the elements to be the same, for convenience sake in our callback function
        '#options' => array(t('Select something') => t('Select something'), t('Something selected') => t('Something selected')),
        '#prefix' => '<div id="after_ajax_element_wrapper">',
        '#suffix' => '</div>',
        '#ajax' => array
        (
            'callback' => 'after_ajax_ajax_callback',
            'event' => 'change',
        ),
    );

    // Next we add our JavaScript file, named after_ajax.js. This file
    // lives in the /js folder inside our module:
    $form['#attached']['js'] = array
    (
        array
        (
            'type'  => 'file',
            'data' => drupal_get_path('module', 'after_ajax') . '/js/after_ajax.js',
        ),
    );
    return $form;
}

function after_ajax_ajax_callback($form, &$form_state)
{
    // First, we initialize our $commands array. This array will
    // contain each of the commands we want to fire for our
    // #AJAX callback:
    $commands = array();

    // Next, we create our insert function that will insert our updated content
    // back into the page. To do this, we use the system provided
    // ajax_command_html() function. We pass this function two values:
    // 1) Our AJAX wrapper (that we defined as the #prefix and #suffix of our form element)
    // 2) The rendered HTML that needs to be inserted into the wrapper in the page.
    $commands[] = ajax_command_html('#after_ajax_element_wrapper', render($form['ajax_example']));

    // Next, we will use the system provided ajax_command_alert() function as an example to show it's
    // working:
    $commands[] = ajax_command_alert(t('ajax_command_alert() is working'));

    // Next we will include a custom function that we will call ourselves in our JavaScript file:
    $commands[] = array
    (
        // The command will be used in our JavaScript file (see next section)
        'command' => 'afterAjaxCallbackExample',
        // We pass the value that the user selected in the select element to our
        // JavaScript function:
        'selectedValue' => $form_state['values']['ajax_example'],
    );

    // And finally, we will return all of our commands to the system to be executed:
    return array('#type' => 'ajax', '#commands' => $commands);
}

(function($, Drupal)
{
    // Our function name is prototyped as part of the Drupal.ajax namespace, adding to the commands:
    Drupal.ajax.prototype.commands.afterAjaxCallbackExample = function(ajax, response, status)
    {
        // The value we passed in our Ajax callback function will be available inside the
        // response object. Since we defined it as selectedValue in our callback, it will be
        // available in response.selectedValue. Usually we would not use an alert() function
        // as we could use ajax_command_alert() to do it without having to define a custom
        // ajax command, but for the purpose of demonstration, we will use an alert() function
        // here:
        alert(response.selectedValue);
    };
}(jQuery, Drupal));

```

# Answer
AJAX callbacks only return an array of commands, and those commands are then executed by Drupal. It is the method I prefer when dealing with AJAX in Drupal.

Behaviors are attached to every page. If you really want to call the behavior, detached from a Drupal AJAX response, then your behavior needs to react when the form is submitted by attaching to that event without using AJAX event on the submit button of the form. See this answer: https://drupal.stackexchange.com/a/87600/57.

With an AJAX command, you can ensure that your command only executes if the form is validated without messing around with a lot of Javascript - though it depends on what you are doing. If you are showing a modal or some notification to the user about submitting the form, you may want to opt for the command so that you aren't running JS if the form did not really submit (i.e. not validated).

In your case, if you are using AJAX submission, then the submit event won't bubble up to the document. You can use ajax\_command\_invoke however to call a method. I recently had to do this on an AJAX'd form to push data to Google. Here is an example:

```
$commands[] = ajax_command_invoke(NULL, 'onFormSubmitSuccess');
return array('#type' => 'ajax', '#commands' => $commands);

```

Javascript file:

```
(function($) {
  $.fn.onFormSubmitSuccess = function(data) {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      'event' : 'formSubmitted',
    });
  };
})(jQuery);

```

https://api.drupal.org/api/drupal/includes!ajax.inc/function/ajax\_command\_invoke/7
> 3 votes

---
Tags: ajax
---


# Question
Title: Assigning OG group title to OG group image title field
Every member of my site can create groups (OG.) Each group requires a title, an image, and a mission statement. The image Title field is enabled because in some parts of the site, the group images are displayed as thumbnails without the group titles.

However, most users don't bother to fill in the image title field so there is no indication of the group's title or purpose.

The idea here is to have the title of the group show automatically when the mouse cursor hovers above the group image after the group is created.

Any idea on how to accomplish this feast?

# Answer
> 1 votes
Your event should be after saving new content of type: your group content type. Then add a condition, entity has field: node \> your image field. You should then be able add a condition to check if that field is empty.

Your action would then be to set a data value on the image using the node title.

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


# Question
Title: Load login / register block in custom template
I've created my own homepage template \[`page--front.html.twig`\] and want to add the drupal default login and register form. I was looking for something like

```
{% include 'themes/bootstrap/templates/block--system-login.html.twig' %}

```

But it looks like none of these kind of blocks exist.

If I go to `user/login` and take a look into the source code (with devel enabled) I also do not see any block hint:

```
<div class="region region-content">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--flowers-content.html.twig
   * block--system-main-block.html.twig
   x block--system.html.twig
   * block.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/block--system.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form' -->
<!-- BEGIN OUTPUT from 'core/modules/system/templates/form.html.twig' -->
<form class="user-login-form" data-drupal-selector="user-login-form" action="/user/login" method="post" id="user-login-form" accept-charset="UTF-8">

```

How can I add the login and register form in my (homepage)-Template? I did not find any useful information related to Drupal 8.

Any help is much appreciated. Thanks!

# Answer
The `user/login` **page** is different from the the user login **block**. To add the user login form to an arbitrary page, then you would need to add the user login **block** to a region you want, and configure it to display only on the front page. This can be done using the Block administration page (documentation).
> 3 votes

---
Tags: 8, blocks
---


title: No Settings for SMTP module

text:
# Question
Title: No Settings for SMTP module
I installed SMTP module for Drupal 7. I enabled it and press Settings button to go to Settings menu. But there is no Setting menu there... How to reach it?

# Answer
The SMTP module configuration page is at `admin/config/system/smtp`.

Make sure that you have the permission change the SMTP configuration.
> 0 votes

# Answer
It was error in Views page - conflicting path. To find it I checked report page. After fixing this problem, Settings menu for SMTP module appeared.
> 0 votes

# Answer
Step 1: Download SMTP module and enable it.

Step 2: Go to Admin \> Configuration \> System \> SMTP authentication support and set the following values:

* Turn this module on or off: On.
* SMTP server settings:
    + smtp server: smtp.gmail.com
    + smtp backup server: leave blank.
    + smtp port: 465
    + use encrypted protocol: select "use SSL"
* SMTP authentication:
    + Enter a valid Gmail email address and password.
* Email options:
    + Set the same email address that you used at SMTP Authentication.
* Send test email: set an email to receive a sample email and to test whether the module is working.
* Enable debugging: yes.

Step 2a(Optional): Allow Less Secure Apps Access which is here: http://www.google.com/settings/security/lesssecureapps

Step 3: Click on Save and go to your inbox to check. If there is an testing email then it is fine.

Note: Your email address provided in your smpt setting MUST be the same like in your site information.
> 0 votes

---
Tags: 7
---


# Question
Title: How do I change the text of the "View" and "Edit" links on the user account page?
I'm looking for a way to change the text being displayed in the links on the user account page.

More specifically, I'm trying to change the text "View" and "Edit" to "View Profile" and "Edit Profile". Ideally, I would prefer a solution that allows me to do this in my `.theme` file via a **preprocessor** or a **hook** function.

# Answer
> 7 votes
As I know you can't do it in your theme, but it is possible to do in your module.

```
/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $route_name) {
  // Change title for user profile's tabs.
  foreach ($data['tabs'] as &$tabs) {
    foreach ($tabs as &$tab) {
      $route_name = $tab['#link']['url']->getRouteName();
      if ($route_name == 'entity.user.canonical') {
        $tab['#link']['title'] = t('View profile');
      }
      elseif ($route_name == 'entity.user.edit_form') {
        $tab['#link']['title'] = t('Edit profile');
      }
    }
  }
}

```

# Answer
> 0 votes
There is also a module that could be exactly what you need : Tab Tamer.

---
Tags: 8, users, theming
---


title: drupal 7 webform custom views query

text:
# Question
Title: drupal 7 webform custom views query
I have a custom hook\_views which queries db for a webform submission. the query looks like this

```
$query = db_select('webform_submitted_data','n');
    $query->leftJoin('webform_component', 'wc', 'wc.cid = n.cid');
    $query->fields('n', array('sid','data','cid'));
    $query->fields('wc', array('form_key','cid'))
    ->condition('n.nid',25)

```

Which translates to mysql:

```
select n.sid,n.cid,n.data,wc.form_key,wc.cid from webform_submitted_data n left join webform_component wc on wc.cid = n.cid where n.nid = 25

```

Now i have made a new field called status whose value can be 1 or 0, i want to show only those form submission whose status values are 1, I tried the following query in phpmyadmin but it gives out only 1 row output where the form\_key value = status and data =1, where as the earlier query gave all the form\_key, and data values for form id 25.

```
select n.sid,n.cid,n.data,wc.form_key,wc.cid from webform_submitted_data n left join webform_component wc on wc.cid = n.cid where n.nid = 25 and wc.form_key="status" and n.data =1

```

Is their any way by which i can add a views filter like condition here to show only data where status = 1

# Answer
> 1 votes
Webform's schema makes it fairly painful, but this should fetch all of the submitted data for any submission where the field with key status has a value of 1:

```
$nid = 25;
$form_key = 'status';
$data = '1';

$query = db_select('webform_submitted_data','n');
$query->leftJoin('webform_component', 'wc', 'wc.cid = n.cid AND wc.nid=n.nid');
$query->innerJoin('webform_component', 'wc_filter', "wc_filter.nid=n.nid AND wc_filter.form_key=:form_key", array(':form_key' => $form_key));
$query->innerJoin('webform_submitted_data', 'n_filter', 'wc_filter.cid = n_filter.cid AND n.sid=n_filter.sid AND n_filter.data=:data', array(':data' => $data));

$query->fields('n', array('sid','data','cid'));
$query->fields('wc', array('form_key','cid'))
  ->condition('n.nid', $nid);

```

There may be performance implications doing this if you have more than a few records...

You could simplify a bit by looking up ahead of time the `cid` of the data component, or just hardcoding it.

---
Tags: views, webforms
---


title: Load a variable displayed in devel

text:
# Question
Title: Load a variable displayed in devel
I'm using devel to find specific fields I'd like to be able to access in a template I have for a user profile page (user-profile.tpl.php)

The field values are present in devel just fine however I'm not sure what to do with the path it gives me.

I see the info I need, (created = 1349810890) and I see a path that devel has given me $...-\>created but I'm not sure what to replace $... with to get access to that field.

I've attempted the following

```
$node->created;
$page->created;
$user->created;
$node['created'];
$content->created;
$variables->created;
$variables->node->created;

```

And several others with no luck

# Answer
> 0 votes
Are you operating on the user account object?

If so, it *should* be:

```
$variables['account']['user']->created;

```

Which would be used at the template\_preprocess function level. From the actual template itself, unless you have intimate knowledge of what was passed to $variables, you will sit there and guess all day long and not get far. Even I am guessing. The only way to know exactly what you have to work with is by using a real debugger.

The best option is implementing a debugger like xdebug so you can get a better idea of whats going on.

It will **save a lot of time** if you leverage it over devel. You can then set a breakpoint in your template\_preprocess function in template.php, inspect all the variables being passed to that appropriate template, and print or modify as you need.

---
Tags: theming, entities
---


title: css errors main menu

text:
# Question
Title: css errors main menu
I have this error with my css, what drush commands I can use to fix this? is it a permissions fix? please guide me step by step

# Answer
> 0 votes
You provide very little information ... Which version of Drupal? (It's Drupal 7 based on the paths.) Which theme have you just enabled causing this problem? It worked before you switched theme, right?

My best guess: You have installed a theme that is a subtheme of Bootstrap without installing the Bootstrap theme itself.

---
Tags: drush, theming
---


# Question
Title: How do I enable CORS on Service endpoint?
I tried to call a Drupal service endpoint, exposed by the Services module, using ionic which is built on Cordova. I ran 'ionic serve', so it wasn't serving from the file system but had an actual localhost and port url. I then installed the CORS module and I'm a bit confused by what I need to include. My endpoint is http://example.com/api/v1/ It is a REST based server and I only enabled JSON.
I want to get data from the site to load into a mobile app - such as an Android - a hybrid app (meaning coded in HTML/JS and packaged with ionic).

The documentation is a bit confusing to me. It reads

> "A list of paths and corresponding domains to enable for CORS. Multiple entries should be separated by a comma. Enter one value per line separated by a pipe, in this order:"
>
> Internal path
>
> Access-Control-Allow-Origin. Use to echo back the Origin header.
>
> Access-Control-Allow-Methods
>
> Access-Control-Allow-Headers
>
> Access-Control-Allow-Credentials
>
> Examples:
>
> \*|http://example.com
>
> api|http://example.com:8080 http://example.com
>
> api/\*|\<mirror\>,https://example.com
>
> api/\*|\<mirror\>|POST|Content-Type,Authorization|true

Do I include `Access-Control-Allow-Origin|api/*|http://example.com`, or is the domain supposed to represent the domain that can call my service?

Maybe I just need Internal Path and not anything else. None of the examples uses `Access-Control-All-*`. I don't plan to do more than GET requests at this time.

# Answer
> 2 votes
If your endpoint is "your.host/api/v1/" this minimal CORS module configuration should work for anonymous GET requests:

```
api/v1/*|<mirror>

```

# Answer
> 2 votes
I had to enable headers on my ubuntu server: `sudo a2enmod headers`

Also, for the CORS settings I used: `*|http://myappURL-that-gets-data-from-drupal`

# Answer
> 1 votes
I advice you to use oauth2 server which provides an oauth2 server used to authenticate rest requests so your endpoint would process requests that have authorization header.

Implement the Client credentials to support the apps (mobile apps/angular clients) with keys used to get access token so that no other app will take any information from your endpoint except having those keys.

by that way you authenticate the source of the request so you are in no need for other modules.

---
Tags: 7, services
---


# Question
Title: Create a template for a custom page in Drupal 7?
Is there a simple way to create a custom template in a theme for a custom page in Drupal 7.

I've tried all of the normal conventions:

page-custom\_page\_name.tpl.php page-custom--page--name.tpl.php etc.

None seem to be working. Help would be much appreciated!

# Answer
> 11 votes
Drupal automatically provides path based overrides; so if the path to your custom page is, say, 'custom/page/path' you can create a template file called 'page--custom--page--path.tpl.php\`, which will only be used for that page.

Remember to clear Drupal's caches each time you add a new template file or the theme registry won't pick it up.

# Answer
> 0 votes
Using the alias or 'custom/page/path' as suggested didn't work for me.

According to the Drupal documentation:

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

The internal/path is not the alias it's the node's ID.

> ...the Drupal path is not any of its aliases: there is one and only one Drupal path for a page. For the examples "http:// www.example.com/node/1/edit" and "http:// www.example.com/mysitename?q=node/1/edit", the Drupal path is node/1/edit, and its components are "node", 1, and "edit".

So in my case a basic page would be custom themed by page--node--1234.tpl.php where 1234 is the node id.

---
Tags: theming, 7
---


# Question
Title: how to find out if a custom filter handler is in use when in hook_views_query_alter()
Drupal 7. I have a custom filter handler which needs to amend the views query. As the filter can be added to any view I can't simply check for view name in the hook\_views\_query\_alter()

I know the filtername exists somewhere in the $views parameter to hook\_views\_query\_alter() within its arrays of array of objects I have yet to find an efficient way of checking if the filter is in use.

anyone come up with a solution to similar?

# Answer
Found a way, you can check for the filtername in the view object e.g. if (isset($view-\>filter\['myfiltername'\])) {
> 0 votes

---
Tags: views
---


# Question
Title: dupal form: how to assign specific id to radio button using form api
I wanted to change id of radio button. But i dont know which attribute shall i use to do that.

```
$form['entry.497535900'] = array(
'#type' => 'radios',
'#title' => t('Category'),
'#options' => array('P' =>'Product','S' => 'Services','O' =>'Others'),

```

);

# Answer
If you need to assign IDs to each radio option, then you can use custom theme function, to theme your radios. See example:

```
$form['entry.497535900'] = array(
  '#type' => 'radios',
  '#title' => t('Category'),
  '#options' => array('P' =>'Product','S' => 'Services','O' =>'Others'),
  '#theme' => 'mymodule_custom_radios',
);

```

The #theme parameter specifies function, which overrides the default radios styling function. You will need to define this function in hook\_theme() and create the content of the function, where you can specify, how radios should be rendered.

```
/**
 * Implements hook_theme.
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_custom_radios' => array(
      'arguments' => array('element' => NULL),
    ),
  );
}

```

Then create the content of this function.

```
function theme_mymodule_custom_radios($element) {
  // You can access all radios options like this - $element['#options'];

  $output = '';
  // ... create html output according to your needs
  return $output;
}

```
> 2 votes

# Answer
```
'#attributes' => array(
    'id' => 'your-id',
 ),

```

You need use "#attributes".
> 1 votes

---
Tags: views, forms, theming
---


# Question
Title: "Drush cannot find your database connection details"
I'm having an issue that is baffling to me as a new user and I'm hoping someone here can answer me how to fix the error. I'm trying to clone an existing drupal installation into a place on my mac with the commands

```
echo "Pushing private files"
/usr/local/bin/drush core-rsync @hpc.dev:%private @hpc.local:%private
echo "Pushing webroot files"
/usr/local/bin/drush -y core-rsync @hpc.dev @hpc.local
echo "Pushing database"
/usr/local/bin/drush -y sql-sync --no-cache @hpc.dev @hpc.local
echo "Clearing Drupal cache"
/usr/local/bin/drush -y @hpc.local cc all

```

This works fine until with the sql-sync piece, where I get the error:

```
... stuff stuff stuff
Command dispatch complete                                                             [notice]
Copying dump file from Source to Destination.                                      [ok]
Starting to import dump file onto Destination database.                            [ok]
/usr/bin/php /usr/local/drush-master/drush.php --php=/usr/bin/php  --backend=2        [notice]
--verbose --yes --strict=0 --root=/Users/cook47/Sites/drupal-test/html
--uri='http://localhost/~cook47/drupal-test'  sql-query
--file=/tmp/hpc-drupal-dev_20160302_005939.sql.gz --file-delete 2>&1
exception 'Drush\Sql\SqlException' with message 'Unable to find a matching SQL     [error]
Class. Drush cannot find your database connection details.' in
/usr/local/drush-master/commands/sql/sql.drush.inc:591
Stack trace:
#0 /usr/local/drush-master/commands/sql/sql.drush.inc(419):
drush_sql_get_class(NULL)
#1 [internal function]: drush_sql_query()
#2 /usr/local/drush-master/includes/command.inc(366):
call_user_func_array('drush_sql_query', Array)
#3 /usr/local/drush-master/includes/command.inc(217): _drush_invoke_hooks(Array,
Array)
#4 [internal function]: drush_command()
#5 /usr/local/drush-master/includes/command.inc(185):
call_user_func_array('drush_command', Array)
#6 /usr/local/drush-master/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#7 /usr/local/drush-master/includes/preflight.inc(66):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#8 /usr/local/drush-master/drush.php(12): drush_main()
#9 {main}

```

Something appears to be awry with my database on the localhost or perhaps with my alias.

Here is my alias for localhost:

```
$aliases['local'] = array (
  'root' => '/Users/cook47/Sites/drupal-test/html', //CHANGEME
  'uri' => 'http://localhost/~cook47/drupal-test', //CHANGEME
  //'remote-host' => "localhost",
  //'remote-user' => 'cook47',
  'path-aliases' => array (
    '%drush' => '/usr/local/bin/drush', //CHANGEME
    '%site' => 'sites/default/',
    '%files' => 'sites/default/files',
    '%private' => '../private',
    '%dump' => '/export/www/hpc-drupal-dev.llnl.gov/drush-dump.sql',//CHANGEME
  ),
  'target-command-specific' => array(
    'sql-sync' => array(//CHANGEME
      'enable' => array('devel'),
      'disable' => array(
      ),
    ),
  ),
  'command-specific' => array(
    'rsync' => array(
      'mode' => 'vrlzOk',
      'exclude-conf' => 1,
    ),
  ),
  'databases' => array (
    'default' => array (
      'default' => array (
        'database' => 'hpc-drupal-dev', //CHANGEME
        'username' => 'hpc-drupal-dev', //CHANGEME
        'password' => 'xxxxxx', //CHANGEME
        'host' => 'localhost',
        'port' => '',
        'driver' => 'mysql',
        'prefix' => '',
      ),
    ),
  ),
);

```

# Answer
Drush no longer allows you to define a 'database' record in your site alias file for use with sql-sync. This used to work in earlier versions, but is no longer supported. Make sure that the source and target sites both have valid settings.php files that include the database information.

To test:

```
drush @hpc.dev sql-conf

```

If your database connection is correct, it will be displayed. Using sql-conf on each site can help isolate which one is having a problem with its connection info.
> 2 votes

---
Tags: drush
---


# Question
Title: How to reference existing term if it exists or create new one if not exist via Inline Entity Form module?
I have a content type **book** and it has a taxonomy term reference field: `author`.

I want to enter **name** and **surname** separately for each author on **node add/edit** page. Name and surname **together** will be the taxonomy term.

If I enter John for the name and Smith for the surname the taxonomy term will be John Smith.

I'm doing this by using the Inline Entity Form module with the Automatic Entity Label module.

The problem here is: the Inline Entity Form has **two** options while entering the term:

1. `Add new term`
2. `Add existing term`.

If you don't know if the term **exists or not** it become useless.

## What I need is only one option and if the entered `[name + surname]` **exist** then **select** it as author automatically and if that **not exist** **create** a new term.

How can I do this?

*(Similar structure **can be created** with some different methods such as References Dialog module, Entity Connect module etc but the main problem exist there too.)*

---

**Note**: This question is not a duplicate of "How to create a name-surname structure for taxonomy terms?" ... even though they use the same image. In this question the main point is "how to combine creating new term and choosing existing one options", in the other question "how to create a name-surname structure on node form" is asked.

# Answer
This solution is a bit "out there" so I'll just describe the logic.

1. Three taxonomy fields. One for first name, one for last name (so there's autocomplete), one for full name generated by rules.
2. On node save, join the first+last as tokens and fetch term by property name. This will give a list containing one or no terms.
3. Two rules components that receive the list.
4. No. 1: condition, list is empty. Actions. Create term and send it back to the rule.
5. No. 2: condition, list is not empty. Actions. Send back the fetched term.
6. In the main rule, set data value on node, returned terms.

It's "out there" but that's because there are two fields for one term.
> 2 votes

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


title: Inserting data to external DataBase

text:
# Question
Title: Inserting data to external DataBase
i'm trying to insert data to a different data base that i created. I've read a lot in the forum, the support documents and other pages but i haven been able to figure it out the problem, can someone give me a hand? point me to a right direction?

first i modified the settings.php like this:

```
<?php
/** ORIGINAL DATA BASE CONNECTION
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'dbname',
      'username' => 'dbuser',
      'password' => 'dbpsw',
      'host' => 'dbhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);
*/

/** DOUBLE DATA BASE CONNECTION  */
$databases = array();
$databases['default']['default'] = array(
   'database' => 'dbname',
      'username' => 'dbuser',
      'password' => 'dbpsw',
      'host' => 'dbhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
);
$databases['civilproconstru']['default'] = array(
   'database' => 'name',
      'username' => 'username',
      'password' => 'password',
      'host' => 'datahost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
);
?>

```

And then in the module i'm creating i'm using this code: (i'm pasting the full module code, the insert is at the end, just in case the error is in the back)

```
<?php
/** START CONFIG MODULE
 * Implements hook_permission().
 */
function project_creator_permission() {
  return array(
    'access project_creator content' => array(
      'title' => t('Access content for the project_creator module'),
    )
  );
}

 /**
 * Agrega a lista de estructura hook_block_info().
 */
function project_creator_block_info() {
  $blocks['project_creator'] = array(
    // The name that will appear in the block list.
    'info' => t('Project Creator'),
    // Default setting.
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

/**
 * Agrega menu en toolbar para "role" contratante hook_menu().
 */
function project_creator_menu() {
  $items['admin/crear_proyecto'] = array(
    'title' => 'Crear Proyecto',
    'description' => 'Crear Proyecto',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('project_creator_insert'),
    'access callback' => 'project_creator_access',
  );

  return $items;
}

function project_creator_access() {
 global $user;
 if (in_array('contratante', array_values($user->roles))){
     return TRUE;
 }
}
 /**
 * END CONFIG MODULE.
 */

/** START PROJECT CREATOR FORM */

function project_creator_insert($form, &$form_state){

    $form['p_name'] = array(
    '#type' => 'textfield',
    '#title' => 'p_name',
    '#size' => 15
    );

    $form['save'] = array(
    '#type' => 'submit',
    '#value' => 'save',
    '#submit' => array('project_creator_insert')
    );
    return $form;

db_set_active('civilproconstru'); /* OPEN DATA BASE*/
db_insert('project_info')
->fields(array(
'p_name' => $form_state['values']['p_name'],
))->execute();
drupal_set_message("succesfully saved");
db_set_active(); /*CLOSE DATA BASE*/

}
?>

```

At the end, it shows me the form but when i click save button it seems to be inserting the data but when i check the database it still empty. It doesnt give me any kind of errors on execution. Thank u for the help...

# Answer
You don't have any submit callback. You should do any process with the submitted data in a submit callback like that:

```
function project_creator_insert_submit($form, &$form_state) {
  db_set_active('civilproconstru'); /* OPEN DATA BASE*/
  db_insert('project_info')
    ->fields(array(
      'p_name' => $form_state['values']['p_name'],
    ))->execute();
  drupal_set_message("succesfully saved");
  db_set_active(); /*CLOSE DATA BASE*/
}

```
> 2 votes

# Answer
Ok! i finally got it! this is the code that worked for me:

`function project_creator_permission() {
 return array(
 'access project_creator content' => array(
 'title' => t('Access content for the project_creator module'),
 )
 );
}
function project_creator_block_info() {
 $blocks['project_creator'] = array(
 // The name that will appear in the block list.
 'info' => t('Project Creator'),
 // Default setting.
 'cache' => DRUPAL_CACHE_PER_ROLE,
 );
 return $blocks;
}
function project_creator_menu() {
 $items['admin/crear_proyecto'] = array(
 'title' => 'Crear Proyecto',
 'description' => 'Crear Proyecto',
 'page callback' => 'drupal_get_form',
 'page arguments' => array('project_creator_form'),
 'access callback' => 'project_creator_access',
 );
 return $items;
}
function project_creator_access() {
 global $user;
 if (in_array('contratante', array_values($user->roles))){
 return TRUE;
 }
}
function project_creator_insert($form, &$form_state) {
 $form['p_name'] = array(
 '#type' => 'textfield',
 '#title' => t('p_name'),
 '#required' => TRUE,
 '#description' => "Introduzca el nombre del proyecto.",
 );
 $form['submit'] = array(
 '#type' => 'submit',
 '#value' => 'Submit',
 );
 return $form;
}
function project_creator_insert_submit($form, &$form_state) {
 /*OPEN DATA BASE*/
 db_set_active('secondDataBase');
 db_insert('test')
 ->fields(array(
 'p_name' => $form_state['values']['p_name'],
 ))->execute();
 drupal_set_message(t('The form has been submitted.'));
db_set_active();
/*CLOSE DATA BASE*/
}
?>`
> 1 votes

# Answer
In the code you are giving submit callback but not writing insert code inside that function. You should write insert code in a function like this:

```
function project_creator_insert($form, &$form_state) {
      db_set_active('civilproconstru');
      db_insert('project_info')
         ->fields(array(
         'p_name' => $form_state['values']['p_name'],
          ))->execute();

      drupal_set_message("succesfully saved");`
      db_set_active();`
}

```
> -2 votes

---
Tags: forms, database, hooks
---


title: Dynamic base url with angularjs

text:
# Question
Title: Dynamic base url with angularjs
I have create 2 angular app into drupal 7 like

```
"example.com"
"example.com/app1"
"example.com/app2"

```

example.com is my main site. So, when I set html5 pushstate enable for removing hash in angular apps, I got nobase error from angularjs. Coz,

```
<base href="">

```

require for enable angularjs html5 pushstate.

My question is, since i have multiple angualr app in this drupal site, how can i dynamically add conditional base url for "/app1" and "app2" ?

anybody can help me? Waiting for response. Thanx.

# Answer
Add base element to your sites theme template file:

```
YOUR_THEME_NAME_preprocess_html(&$variables, $hook) {
    $url = 'default';// default url
    if($application1) {// your condition for app1
      $url = 'app1';
    } elseif($application2) {// your condition for app2
    $url = 'app2';
    }
    $data = array(
      '#tag' => 'base',
      '#attributes' => array(
      'href' => $url,
      ),
    );
    drupal_add_html_head($data, 'base_href');
}

```

Put it into your template.php

Ref: https://stackoverflow.com/a/35725528/3770000
> 1 votes

---
Tags: uri, javascript
---


# Question
Title: how to import csv file using feed import module
I am using feed import module . But i do not know how to import the csv file. can anyone explain how to import the csv file using this feed import module

# Answer
Feeds module allow you to import data with csv file.You can follow the following steps to import your csv content and convert them to individual nodes.

* After installing the Feeds module , open the feeds admin panel. `Admin menu -> Structure -> Feeds Importers`
* There you will see Add Importer link.Click on that.
* Provide a name and description for the importer.Name can be anything that represent your cause of creating a feed importer.

* Then Click on the basic settings link.In the section `Attach to content type` select the content type in which you want to feed the data.Then `Periodic import`, here choose `As often as possible` or depending upon your need.

\- Click on `fetcher change` and select the `File Upload` option as we are uploading our csv file.

\- Then Click on `Parser` and select `CSV parser` since we are parsing a csv file.

* Leave `Processor` as such .
* Click on `Node processor`.In the `Bundle` dropdown,select the content type you want to import the feeds data to. ( If you have not created a content type, you will be require to create one that matches with the csv content). Leave other option as such.

* Click on the `mapping` Link now.This is the most important of all steps .It maps your csv columns with the content type field that you have created for importing the data.Carefully type the name of csv columns on teh left section and then selct the respective field name from the drop down in the right section.

Example Mapping settings

`Always save at every stage`
> 1 votes

# Answer
**Run the import:**

* Navigate to Structure -\> Feeds Importer, and click on the "import" link.
* Click on the Bulk File Upload link.
* Upload your CSV file into your sites/default/files folder.
* Upload your import-upload folder, containing all the files to be imported into your Drupal root.
* Enter your CSV file's name in the File text field, with a the word "public://" prepended. So the entry should be something like "public://bulk\_import.csv".
* Click on the Import Button.

More Details
> 0 votes

---
Tags: importing-exporting
---


# Question
Title: How to change default query plugin for views?
By default Views uses 'views\_plugin\_query\_default' plugin. How can I alter something so that Views could use another class for building queries?

I found one good example how to write Views query plugins: building views query plugins

But this example is for custom tables. But I need to have my own query builder for ordinary node, terms and users tables.

# Answer
Firstly you will need to have defined your query plugin to Views using `hook_views_plugins()`:

```
function MYMODULE_views_plugins() {
  return array(
    'query' => array(
      'myplugin' => array(
        'title' => 'My custom plugin',
        'handler' => 'MyCustomQueryClass',
      ),
    ),
  );
}

```

Then, you should be able to override the query class used for any of the built-in tables using `hook_views_data_alter()` and setting the `query class` key in the table base property:

```
function MYMODULE_views_data_alter(&$data) {
    $data['node']['table']['base']['query class'] = 'myplugin';
}

```
> 0 votes

---
Tags: views
---


# Question
Title: How do I replace a module with a dev version through the UI?
I copy the reference to the dev release for a module and paste it into the "Install module" form, but Drupal complains that the module is already installed. Is there a good way of doing this through the UI or drush or do I just have to uninstall and reinstall?

# Answer
> 3 votes
I just found that I can run `drush dl <module_name>-8.x-1.x-dev` and confirm that I was to override the old module.

---
Tags: drush
---


# Question
Title: How do I output a list of PDF files set up via a custom content type
I set up a custom content type 'yam' where I upload a PDF file. Each file has a language of either "English" or "Spanish", along with a title, like "Winter 2016".

I've been playing with Views, but I cannot get it to output the equivalent of :

```
<a href="URL">Title</a>

```

I can only get a list of Titles or a list of file names URLs like:

`<a href="URL">Filename</a>`

.

# Answer
> 0 votes
Change the **Formatter** to be *URL to file*

Rewrite the field as attached image using the title to display link to file with the title as link text

---
Tags: views
---


# Question
Title: How to implement node access control with a simple field used during node creation?
I have multiple roles on the site. I have used Role reference field in Nodes to choose which Role should see Nodes. Then I have set Views to show content based on roles and Role reference field in Node.

Now I'm facing issue with Search. Search shows all content and users in different roles can see all the content.

I was looking for solution to set access per node, but Content access and Nodeaccess modules only allow access to be set **after** node is created. And in these case user need to set access to two fields: Role reference field AND Content access/Nodeaccess tab. Not good. I do not want to create own content type for each role.

Is there a way to use Role reference field to set access control to node?

I did install both Content access and Nodeaccess modules and tried to use the Rules module to achieve this, but seems that neither of the modules support Rules.

Any help/tips appreciated.

# Answer
> 2 votes
You can get this to work using a combination of the Rules module and the Content Access module, whereas the Rules module will automatically (behind the scenes) trigger the logic that's needed. The logic itself is entirely hidden for the user (author).

Here are some more details to get it to work:

1. Start from a rule that is similar to the example I included in my answer to "How to specify a Rules condition related to select list values?".
2. This sample rule uses a field named `field_optionlist`, with 3 possible values A,B,C. In your case you should use the fieldname of your ***Role reference*** field, and you should tune the possible values for that field also. Some more tips to get you going:

* Make sure to tune the fieldname of this field (so that it matches the name you already have) BEFORE importing the rule sample in item '1.' above (if not the import of the rule will fail).
    * Adapt the Rules condition related to "value = `C`" to the values that fit your case, and the message included in the Rules Action.
3. QA-test the intermediate result after completing step '2.': you should have an appropriate Drupal message show up when a node is created with.
4. Use the integration of the Content Access module with the Rules module to create a Rules Action that updates the access of the node, similar to the Rules Action I included in my sample rule included in my answer to the question "How to revoke edit access to the node's author after publishing a node?". The actual settings to use for the content access module should match with your settings of course.

# Answer
> 1 votes
Instead of using those modules, you could just have a taxonomy field and use Rules "Content is viewed" and check for taxonomy and current user role. For Views, have separate views per role.

---
Tags: 7, nodes, users
---


title: Newbie-question: how to use hooks

text:
# Question
Title: Newbie-question: how to use hooks
Ok, this is a newbie-question i'm afraid to ask for some time .. how to use Drupal Hooks? Yes, i know where to look for the code, but then? Put it in the template-folder, a block, a custom module?

When i google for a tutorial, the most results are for Drupal 6 / before 2010.

# Answer
Drupal Hooks are a call back mechanism, you name your function modulename\_Hook like mymodule\_form\_alter(). Based on the name of the function, it is called in the proper phase of the Drupal execution. This is an entry point from Drupal into your module.

Using Drupal Hooks doesn't change that much from version to version, the hooks that are available do change from version to version. The old tutorials are still good. The best way to learn how to use hooks is to examine existing contributed modules, or that's what worked for me. Hooks you really need to learn, or that you should start with are the FORM API hooks hook\_form\_alter, hook\_form, hook\_form\_validate (https://api.drupal.org/api/drupal/includes!form.inc/function/drupal\_form\_submit/7), ..., hook\_menu is generally needed if you're adding a page to the website.

If you can get a copy of "Pro Drupal Development" or "Pro Drupal 7 Development" (http://www.drupalbook.com/ or http://www.amazon.com/Drupal-Development-Experts-Voice-Source/dp/1430228385) it might help as well. Go with the pdf downloads. There are also 2 or 3 day classes you can take, or you can get training at your local Drupal Camp or Drupal convention.
> 0 votes

---
Tags: hooks
---


# Question
Title: How can I add the sku code in [commerce-order:commerce-email-order-items]
While the shortcode \[commerce-order:commerce-email-order-items\] is used to send several commerce emails, it does not includes SKU code. How can I add sku code or edit the output of \[commerce-order:commerce-email-order-items\]

# Answer
Some tokens are generated by code others by views. This token is generated by code

So edit commerce\_email.module and around line 420 you will see commerce\_email\_order\_items function here you can add the sku.

**Take in mind that this is not an ideal solution** See hook\_tokens\_alter
> 0 votes

# Answer
The best way:

* Go to: `admin/structure/views/view/commerce_cart_summary/edit/`
* Under `Fields` you should change: Commerce Belegzeile: Product Erscheint in: commerce\_line\_item:product, commerce\_line\_item:product\_discount.
* Set the same settings from: `admin/structure/views/view/commerce_cart_form/edit/`
* Delete the line for the `Title`.

Now you can change the output over the product-variation-types-sites under Basket: admin/commerce/config/product-variation-types/

Now you have a very good looking and adjustable order confirmation email.
> 0 votes

---
Tags: commerce
---


# Question
Title: Copy content from Word and use paragraph style names as classes
Is it possible to copy content from a Microsoft Word document into Drupal and use the name of paragraph styles used in word as class names in the HTML?

I am using:

* Drupal 7.34
* CKEditor 7.x-1.15+1-dev

If I drag-and-drop content from Word into CKEditor the paragraph styles are used as class names which is good, but unwanted XML comes over from Word too. Example:

```
<h3><span lang="EN-AU">Prefixes<o:p></o:p></span></h3>

<p class="NormalBeforeBullet"><span lang="EN-AU">A paragraph here with the normal paragraph style to test that class comes along:<o:p></o:p></span></p>

<p class="Bullet" style="margin-left:0cm;text-indent:0cm;mso-list:l0 level1 lfo1"><!--[if !supportLists]--><span lang="EN-AU"><span style="mso-list:Ignore">•<span style="font:7.0pt "Times New Roman"">       </span></span></span><!--[endif]--><span lang="EN-AU">These are my own bullets<o:p></o:p></span></p>

<p class="Bullet" style="margin-left:0cm;text-indent:0cm;mso-list:l0 level1 lfo1"><!--[if !supportLists]--><span lang="EN-AU"><span style="mso-list:Ignore">•<span style="font:7.0pt "Times New Roman"">       </span></span></span><!--[endif]--><span lang="EN-AU">To test if the HTML<o:p></o:p></span></p>

<p><!--[if gte mso 9]><xml>
 <o:DocumentProperties>
  <o:Version>15.0</o:Version>
 </o:DocumentProperties>
</xml>.... a lot more xml code follows....

```

If I copy and paste the same content from Word into CKEditor, I get better HTML but no class attributes. Example:

```
<h3>Prefixes</h3>

<p>A paragraph here with the normal paragraph style to test that class comes along:</p>

<ul>
    <li>These are my own bullets</li>
    <li>To test if the HTML</li>
    <li>Is created correctly</li>
</ul>

```

CKEditor config options I've tried include

* Disabling Advanced Content Filter with `config.allowedContent = true;`
* Adding allowed content filter with `config.extraAllowedContent = 'p(mso*,Normal)';`
* Disabling additional paste filter with `config.pasteFilter = null;`

None of these options have resulted in clean HTML with paragraph styles as class names.

# Answer
> 1 votes
CKEditor Editor will not work the same way as Word so when you copy and paste some document to CKEditor. CKEditor will change the setting based on it own setting

---
Tags: wysiwyg
---


# Question
Title: How can i Use drupal 8 CMI between two different sites?
I think, normally the CMI works between cloned sites, not different sites. Is there any way to do that with CMI ? or still we hardly depends the features module ?

# Answer
> 1 votes
I'm afraid you are right, configuration management is for different instances of a same site. According to the Drupal 8 CMI documentation,

> The Configuration Manager module in Drupal 8 provides a user interface for importing and exporting configuration changes **between a Drupal installation in different environments**, such as Development, Staging and Production, so you can make and verify your changes with a comfortable distance from your live environment.

The same idea appears in this article,

> Perhaps the most important concept to understand is that the configuration system is designed to optimize the process of moving configuration between instances of the same site. **It is not intended to allow exporting the configuration from one site to another**. In order to move configuration data, the site and import files must have matching values for UUID in the system.site configuration item. In other words, additional environments should initially be set up as clones of the site. We did not, for instance, hope to facilitate exporting configuration from whitehouse.gov and importing it into harvard.edu.

---
Tags: 8, features, configuration
---


title: .gitignore file setup for Acquia Cloud

text:
# Question
Title: .gitignore file setup for Acquia Cloud
I want to add `.gitignore` file to my local repo. My local repo is a clone from my **Drupal 8** distro from Acquia Cloud.

What are best practices for my `.gitignore` file for Acquia Cloud hosted sites? I followed this tutorial.

* For example: do i have to ignore `settings.php` and not `settings*.php`? Regarding this quote from the tutorial:

> Drupal 8 You can modify .gitignore so that it ignores settings.php (not settings\*.php). Then, you can update the standard settings.php with the Drupal 8 local settings file checker:

* Where is `settings.local.php` for, mentioned in the Quote above from the article?

Currently my `.gitignore` file looks like this:

```
# This file contains default .gitignore rules. To use it, copy it to .gitignore,
# and it will cause files like your settings.php and user-uploaded files to be
# excluded from Git version control. This is a common strategy to avoid
# accidentally including private information in public repositories and patch
# files.
#
# Because .gitignore can be specific to your site, this file has a different
# name; updating Drupal core will not override your custom .gitignore file.

# Ignore core and vendor when managing dependencies with Composer.
# core
# vendor

# Ignore configuration files that may contain sensitive information.
sites/*/settings*.php
sites/*/services*.yml

# Ignore paths that contain user-generated content.
sites/*/files
sites/*/private
sites/*/files-private

cache/
files/

# Ignore SimpleTest multi-site environment.
sites/simpletest

# If you prefer to store your .gitignore file in the sites/ folder, comment
# or delete the previous settings and uncomment the following ones, instead.

# Ignore configuration files that may contain sensitive information.
# */settings*.php

# Ignore paths that contain user-generated content.
# */files
# */private

# Ignore SimpleTest multi-site environment.
# simpletest

# Ignore default text files
/CHANGELOG.txt
/COPYRIGHT.txt
/INSTALL*.txt
/LICENSE.txt
/MAINTAINERS.txt
/UPGRADE.txt
/README.txt
sites/all/README.txt
sites/all/modules/README.txt
sites/all/themes/README.txt

# ------------------------------------------------------------------------------
# SublimeText files
# ------------------------------------------------------------------------------

# Workspace settings.
*.sublime-workspace

# Project settings.
*.sublime-project

# ------------------------------------------------------------------------------
# OSX
# ------------------------------------------------------------------------------

# Common OSX files.
.AppleDouble
.DS_Store
.LSOverride

# Thumbnails.
._*

# Files that might appear in the root of a volume.
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns

# Directories potentially created on remote AFP share.
.apdisk
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items

# ------------------------------------------------------------------------------
# Windows
# ------------------------------------------------------------------------------

# Windows image file caches.
ehthumbs.db
Thumbs.db

# Folder config file.
Desktop.ini

# Recycle Bin used on file shares.
$RECYCLE.BIN/

# Windows Installer files.
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts.
*.lnk

# ------------------------------------------------------------------------------
# Linux
# ------------------------------------------------------------------------------

# Tilde files.
*~

# KDE directory preferences.
.directory

# Linux trash folder which might appear on any partition or disk.
.Trash-*

```

What do i have to change to make it perfect?

# Answer
Acquia Cloud provides you with a default `.gitignore` in your repository (as described here):

```
docroot/files
docroot/sites/*/files
docroot/sites/*/private
acquia-files

```

It usually is enough for the vast majority. You're however free to add anything you don't wish to keep under version control. There's no perfect setup and it really depends on what you'd like to achieve. I strongly suggest keeping `settings.php` under version control because it holds critical configuration for your site.
> 4 votes

---
Tags: 8, version-control, acquia-cloud
---


# Question
Title: Git Workflow Acquia Cloud and Acquia Dev desktop
I use *Acquia Cloud* and installed Drupal 8 and cloned this (origin) locally using *Acquia Dev desktop.*

1. To use *Dev Desktop* I think I'm able to develop the Front-end design faster, instead of committing the changes every time and push them to Acquia Cloud to see them in the browser. Am I right?
2. And will my client also be able to commit his code from his local branch to the Acquia Cloud repo?

# Answer
> 2 votes
1. Working on the frontend isn't tied to using Acquia Dev Desktop or not. It's a personal preference to work locally by cloning a remote site and work on theming/frontend and commit changes periodically to the remote repo when you're happy with the changes you see in your browser. Some customers prefer working directly on the Acquia Cloud dev environment with Livedev. Really, it's what you think is best for you.
2. Git is a decentralized version control system. It means both you and your client can checkout the Acquia Cloud repo and hold a live copy of the repo. You and your client can then commit/push code either to the default branch (`master`) or with a feature branch. This is by no means specific to Acquia Cloud. This is how git works. What matters is you `git pull` always before committing / pushing code, so that you can retrieve the changes your client has made on the current working branch (e.g. `master`). With a feature branch, it'll require you merge it back to e.g. `master` when it's ready. See https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell for details.

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


# Question
Title: Webform is currently not enabled on any content types
I have installed the "Webform" module with no problem, but when I create a new webform, I don't have the possibility to add a new field. I have checked the section `config/content/webform`. I get this message "**Webform is currently not enabled on any content types**". Since I am new to Drupal, I don't know what to do,can somebody help me please?

# Answer
Just make sure you have enabled WEBFORM in the Drupal menu modules
> 0 votes

# Answer
Well, the answer lies in the question.

"Do you have Webform enabled for any 'content types'?"

You can check this by navigating to the 'content type' overview page: `admin/structure/types`

Then click any of the available 'content types' and check if Webfrom is enabled.

This functionality is located under the Webform Tab, i.e. Enable webform functionality.
> 0 votes

---
Tags: webforms
---


# Question
Title: Getting all nodes that have a specific term id using EntityFieldQuery
I have been using the following line to get all the nodes with a term id

```
taxonomy_select_nodes($tid);

```

But now I want to sort the output by weight (field\_audio\_weight - field I created). How can I achieve the same output using `EntityFieldQuery` ?

# Answer
> 1 votes
Something like:

```
$query = new EntityFieldQuery()
  ->entityCondition('entity_type', 'node')
  ->fieldCondition('field_taxonomy_reference', 'tid', TERM_ID)
  ->fieldOrderBy('field_audio_weight', 'value', 'DESC');

$results = $query->execute();

```

Check these articles for more information:

https://www.phase2technology.com/blog/entityfieldquery-let-drupal-do-the-heavy-lifting-pt-1/

https://www.phase2technology.com/blog/entityfieldquery-let-drupal-do-the-heavy-lifting-pt-2/

---
Tags: 7, database
---


# Question
Title: Get last accessed timestamp value of a user in Drupal 8
Im trying to display the last accessed field when a user logs in. For this I tried using User::getLastLoginTime() . But this returns a fatal error saying

**PHP Fatal error: Call to undefined method Drupal\customize\_block\Plugin\Block\ContractDetails::get() in /var/www/html/core/modules/user/src/Entity/User.php on line 265**

Here is my block ,in my custom module:

```
/**
 * Provides a 'Customized contract' Block
 *
 * @Block(
 *   id = "customer_info",
 *   label = @Translation("Customer and contract info"),
 *   module = "user",
 *   context = {
 *     "current_user" = @ContextDefinition("entity:user", label = @Translation("Current User"))
 *   }
 * )
namespace Drupal\customize_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;

class ContractInfo extends BlockBase {
 public function build() {
 $output='';
 global $base_url;
 $current_user = $this->getContext('current_user');
 $output.='<div>' . $current_user -> contextData . '</div>';

     return array(
      '#markup' => $output,
      '#cache' => array(
     'contexts' => array('url'),
      ),
    );
  }
}

```

Am I calling this method correct way?

# Answer
`getLastLoginTime` is not a static method so you would not be able to call it statically like that. You need to get the current user object from a couple of different ways:

### 1. Use the Drupal::currentUser.

This is easy, but not recommended to tightly-couple your block.

### 2. Inject the `current_user` service into your Block by implementing ContainerFactoryPluginInterface.

The disadvantage is that this also has a dependency on the container, but can be mocked.

### 3. Use the Context system because blocks extend ContextAwarePluginBase.

This is the recommended option in my opinion because there is already a current user context (as well as node contexts) for blocks.

```
 * @Block(
 *   ...
 *   context = {
 *     "current_user" = @ContextDefinition("type" = "entity:user", "label" => @Translation("Current User")
 *   }
 * )

```

Then `$current_user = $this->getContext('current_user')` will get the current user.

Unfortunately there is not a handbook page about using contexts so documentation is relegated to guessing things based on the change record, which itself was no longer accurate at the time of writing this answer.

Interestingly some IDEs (*cough* PhpStorm 10 *cough*) choke on the above annotation syntax because.

### Finally...

You should look at the documentation for render arrays and the changes to make markup safe.
> 1 votes

---
Tags: 8, users
---


# Question
Title: How do I attached language specific css in Drupal 8?
As the question states - how do I include a stylesheet based on a language? It has nothing to do with right to left reading, but for different colours etc.

# Answer
You may want to use the "lang" attributes to style the language.

Here is the example:

```
<!DOCTYPE html>
<html>
<head>
<style>
p:lang(it) {
    background: yellow;
}
</style>
</head>
<body>

<p>I live in Italy.</p>
<p lang="it">Ciao bella!</p>

<p><b>Note:</b> For :lang to work in IE8, a DOCTYPE must be declared.</p>

</body>
</html>

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: On AJAX-Enabled Views the "Add to Cart" button does not work properly
On **AJAX** enabled Views with exposed filters or pagers the "**Add to Cart**" button and "**add to wishlist**" does not work properly.

After an **AJAX call**, the add-to-cart form action changes to **views/ajax**, so if i press the button, only a **JSON** output will be displayed.

# Answer
Yes, it is. This module will be usefull for you:Commerce Ajax Cart
> 0 votes

---
Tags: views, ajax
---


# Question
Title: How to add suffix and preffix for radios field in drupal?
This is my code. And is it right way to add suffix and preffix to a radios?

```
    $form['option_' . $question_count_flag] = array(
      '#type' => 'radios',
      '#options' => $qt_options,
      '#prefix' => '',
      '#suffix' => '',
    );

```

Here $qtn\_options is an array.

# Answer
Yes, your code is correct. When you add a prefix/suffix, the whole field will come before/after your markup.

You can use the prefix/suffix attributes to wrap the whole field in a container; here's an example:

```
$form['option_' . $question_count_flag] = array(
  '#type' => 'radios',
  '#options' => $qt_options,
  '#prefix' => '<div id="radio-wrapper">',
  '#suffix' => '</div>',
);

```

The output you would get is:

```
<div id="radio-wrapper">
  // Regular form item markup with your radio options will go here.
</div>

```
> 1 votes

---
Tags: theming
---


title: Print login page url in node.tpl.php

text:
# Question
Title: Print login page url in node.tpl.php
It seems nevertheless rather simple, but I do not find the solution.

How to print in node.tpl.php the url of the login page?

The url has to serve for a link:

```
<a href="<?php print ... ?>"><span>Login</span></a>

```

# Answer
Use this if you just want the URL:

```
<?php print url('user/login'); ?>

```

If you want to print a link:

```
<?php print l(t('Login'), 'user/login'); ?>

```

And in your case it would be:

```
<?php print l('<span>' . t('Login') . '</span>', 'user/login', array('html' => TRUE)); ?>

```
> 1 votes

---
Tags: 7, theming, uri
---


# Question
Title: How to render / preprocess list of entity reference nodes?
I hove a content type that editors can 'attach' related nodes to.

When I 'theme' / 'style' nodes of this content type through `view mode` everything is basically fine: the related nodes are rendered as teasers and I can style them as I like.

Now I need to wrap the list of related nodes in an extra class e.g. 'related-nodes' according to the output of another field. For example the editor chooses 'round corners' from a list field, then the css class "rounded" should be added to the wrapper of the list of related nodes should.

I am aware I can remove the entity reference field from the display settings and preprocess it through `template.php`. But then ***how*** do I preprocess the list in `template.php`? So far I just don't know how to actually access / handle it.

In `devel` tab I do get the array of related items. I could of course loop through that array and re-build node by node thruogh `node_load` – but since I only want to wrap that loop re-rendering each node feels wrong. Any suggestions?

# Answer
> 0 votes
As per @Clive comment, Fences module may be able to help with that.

A quite straightforward option would be to implement `hook_node_view()` in a custom module and add a `#prefix` and `#suffix` to the field element (prefix of `<div class="foo">`, suffix of `</div>`)

---
Tags: theming, nodes
---


# Question
Title: How authenticated users can choose favorite products and show them in their profile?
in my drupal project, I want to have many products specification. I want authenticated users can choose their favorite product and they can set price for favorite product. these favorite products can show in their user's profile. and in any product page, all users can see all of the prices that set by authenticated users.

In Drupal 7 which approach / technique should I use?

# Answer
> 0 votes
This really seems like a perfect fit for the Flag module. Excerpt from its project page (bold markup added here):

> ... Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
>
> **Flags may be** per-user, meaning that each user can mark an item individually, or **global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.**
>
> In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.

Refer to Flag's Community documentation for (way) more details.

And to show this in their user's profile, could be implemented via an appropriate view (using Views), in the format of a block display, whereas you adapt the block visibility settings to only show such block for an URL that corresponds with the user's profile.

---
Tags: 7, users
---


# Question
Title: How do customize the HTML output around a specific field using field.tpl
I in the middle of creating a content type with multiple fields. All the fields need to have all the extra markup removed, except for a specific 3 and I would like these to actually be wrapped in `<h3>` tags.

I've copied the `field.tpl` file into my theme and renamed to be used just for this specific content type, which is working fine with this code:

```
  <?php if (!$label_hidden): ?>
  <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?> </div>
  <?php endif; ?>

  <?php foreach ($items as $delta => $item): ?>
  <?php print render($item); ?>    <?php endforeach; ?>

```

My trouble is that I have no idea the syntax I need to target a specific field. So I'm im guessing once I figure out how to target the specific field, I can just use:

```
  <?php foreach (something here to find the right field): ?>
  <h2><?php print render($item); ?></h2    <?php endforeach; ?>

```

What would that be if my field name was `field_sizing_title`?

I found the Field Wrappers Module, but it seem like overkill and I really like to learn more about how to work with the `field.tpl` file

# Answer
> 2 votes
You need identify the field machine name. For example if you have a field called `Name` and have a machine name `field_name` the field tpl name should be `field--field-name.tpl.php`.

See this thread as well as it provides a comprehensive guide on how to override field template using `hook_theme` and `preprocess` function.

One of the most handy helper I used is `$conf['theme_debug'] = TRUE;` in `settings.php`. It will show a template suggestion in HTML source.

# Answer
> 1 votes
To find the right field, you should use `template_process_HOOK` to load it first and expose into your template file as variable.

Here is example using with Entityforms:

```
/**
 * Implements template_process_HOOK().
 */
function mymodule_preprocess_myfieldhook(&$variables) {
  $entity = $variables['form']['#entity'];
  $field_name = $variables['form']['#field_name'];
  $variables['info'] = field_info_field($field_name);
  $variables['instance'] = field_info_instance($entity->entityType(), $field_name, $entity->type);
}

```

Then you should have in your TPL file two extra variables: `$info` and `$instance` where you can access some field settings.

---
Tags: 7, entities
---