# Question
Title: CKeditor not showing. 403 on ckeditor.config.js and ckeditor.styles.js
I have a site with ckeditor 7.x-1.16 installed (not the WYSIWYG module). I have a local dev (XAMPP windows) staging (Linux) and production (Linux).

On the local dev copy and the production copy ckeditor isn't showing on the edit body tag.

In firebug net tab ckeditor.config.js and ckeditor.styles.js are showing as 403 - forbidden.

I have tried replacing my local copy of the ckeditor module and the ckeditor library with the ones from the staging server where ckeditor is working. This does not fix my dev copy.

I have tried upgrading to ckeditor 7.x-1.17. I have tried a new install of 7.x-1.16. I have tried deleting the ckeditor library and downloading a fresh version. I have tried moving the library files to the alternative location within ckeditor. I have tried to increase the permissions in windows of the ckeditor module (I believe windows doesn't have chmod). I have also tried chmod 755 on the module files on the production site. None of these has helped.

ADDITION: I have have made a new local version of the Staging server version (where the problem doesn't occur). The problem is on the fresh local copy, despite it having the same files and db as the staging version.

# Answer
> 0 votes
I worked this out. I found an .htaccess 'deny from all' file in the sites/all/modules directory. It must have accidentally got copied in there from the sites/all/files/private directory. I removed the file and ckeditor shows fine.

---
Tags: wysiwyg
---


# Question
Title: What is the benefit of making sub theme in drupal?
I have created a sub-theme of a theme in Drupal 7. I have done all changes to create this and it is working fine. But I am confused what actually it is for, what are the benefits of making this? I know the differences between base theme and sub-theme but I need more information why we create sub-theme.

# Answer
> 1 votes
Some of the benefits of using sub-theme:

1. You don't need to build your theme from the scratch. You can just use your parent theme styles and its templates. Drupal bootstrap is a best example.
2. If a new version of your parent theme arrives, you can just replace it with your parent theme since no changes were done in that.
3. To override any templates, you can just copy your parent theme template in your sub theme and start modifying.

# Answer
> 1 votes
For instance. You override only files you need to and you have in your sub-theme directory only these files, not all. You can update parent-theme and not overriding your customizations.

---
Tags: theming
---


# Question
Title: How do I filter a view by the node taxonomy you're currently on?
I've built a content type and added taxonomy to it. The user can choose one of the 10 terms from that vocabulary when they are building the content. On the node I want to build a sidebar that lists all the other nodes from this content type but filtered to be only the same taxonomy choice. I assume this is done through views but I can't figure out how to build that contextual filter that looks at the current nodes taxonomy.

# Answer
To visualize what J. Reynolds said above.

Add Contextual Filter - Content: Has taxonomy term ID with following settings

then add contextual filter - Content:Nid (provide default value -\> Content ID from URL) and in "More" section of that filter check "Exclude" checkbox, which will remove the currently viewed node from the list of nodes related by taxonomy term.
> 0 votes

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


# Question
Title: Custom date range format on a node by node basis
I'm working on a way to alter the way a date field, field\_node\_date, is formatted when rendered.

Currently, on the content type I'm working on, the *Long format* is being used (e.g. Monday 18 January 2016 - 22:55) and "Both Start and End dates" are displayed by default (on Display settings for any view mode this node is using). As a result, in the node's template,

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

```

is rendering the field as expected.

I've added a new checkbox field to the content type. When users check that checkbox, I only want the date part of the field to be rendered, ie without the time, e.g.

```
"Monday 18 January 2016"

```

instead of

```
"Monday 18 January 2016 - 16:55"

```

when only a start date is entered, the same for a date range, e.g.

```
"Monday 18 January 2016 to Tuesday 19 January 2016"

```

instead of

```
"Monday 18 January 2016 - 16:54 to Tuesday 19 January 2016 - 19:44"

```

I tried overriding the theme registry to provide my custom theme callbacks for a single date and a date range:

```
function mymodule_theme_registry_alter(&$theme_registry) {
    if (isset($theme_registry['date_display_range'])) {
        $theme_registry['date_display_range']['function'] = 'custom_range_date_display_format';
    }
    if (isset($theme_registry['date_display_single'])) {
        $theme_registry['date_display_single']['function'] = 'custom_single_date_display_format';
    }
}

```

and then copying over date's theme\_date\_display\_range() and theme\_date\_display\_single() functions from date.theme and alter them to return the dates without the time. But there's no way to hook into each separate node withing the scope of this functions and see if the "don't show the time" field is checked so the returned date format would always be the same, either with the time or not, for all my nodes.

Another solution would be to go straight into the node's template and replace

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

```

with something like

```
<?php print format_date(strtotime($date_field_value) ,'custom','whatever format I need for each node'); ?>

```

and create the same HTML structure for a single date or a range of dates. But that doesn't cover other view modes and it's not very clean.

I also tried to find the node hooks that would allow me to alter the date but I now see that no matter what format is selected, the date item always holds the date field's value as it's saved on the database and then only the markup changes. Programmatically altering the markup of the field would probably not be a preferred solution as any change of the format on the UI under display settings (e.g. from long to short etc) would be ignored.

I'd also like to avoid adding a new date format / type to my db

A good solution that would allow me to hook into my nodes, check if that checkbox is checked and then enforce my preferred custom date format every time the node is rendered would be ideal.

I'd appreciate any suggestions, thanks.

# Answer
> 0 votes
You just need to add `template_preprocess_node(&$vars)` to your `template.php` and check the value of checkbox that is controlling the date format

Date object store start date as value key and end date as value2 key. You need to check on that.

```
if($checkbox) //checked
  //display one format
else
  // display another format

```

You can use **php date api** functions to format your date

---
Tags: hooks, datetime, theming
---


# Question
Title: Create custom endpoints by extending the Resource Base class
I created a custom endpoints by extending the core of Drupal. but I can not retrieve JSON data. I do not know what value to put in 'note: serialization\_class

```
/** * Provides a resource to get bundles by entity.
*
* @RestResource(
*   id = "dna_custom_endpoint",
*   label = @Translation("DNA custom endpoint"),
*   serialization_class = ??????,
*   uri_paths = {
*     "canonical" = "/dnarest/{type}"
*   }
* )
*/

```

You know comprehensive guides that explain?

```
public function patch($type = 'type') {
    ???????
}

```

if you use what you said ( serialization\_class = "Drupal\Core\Entity\Entity",) to me this generates fatal error PHP :

```
Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException: The Drupal\Core\Entity\Entity class does not correspond to an entity type. in Drupal\Core\Entity\EntityTypeRepository->getEntityTypeFromClass() (line 103 of /Applications/MAMP/htdocs/dnaphone/core/lib/Drupal/Core/Entity/EntityTypeRepository.php).

```

# Answer
> 0 votes
The serialization class is the input or output of normalization and denormalization, or in other words, the object that you get when you denormalize data or the object that you normalize on the way out. Drupal 8 core provides one example of this \Drupal\rest\Plugin\rest\EntityResource. If the object is an entity you can use core:

```
  serialization_class = "Drupal\Core\Entity\Entity",

```

In order to use your arbitrary non-entity, you would also probably need to implement a Normalizer, but that is possible as well.

If your goal is to create a non-REST API with a custom endpoint that does not correspond to a REST operation (such as login or getProperty), then you should look at the Services module.

---
Tags: 8
---


# Question
Title: How can I react when a commerce product is explicitly created via the UI?
how do we add a submit handler in drupal commerce everytime a product is created.

I tried using the following code.

```
function custommodule_formid_form_alter(&$form, &$form_state, $form_id) {
    $form['#submit'][] = 'custom_submit_function';

    return $form;
}

function custom_submit_function() {
    print "<pre>";
    print_r($form_state);
    print "</pre>";
    die();
}

```

Is this the correct way?

I tested it, and actually managed to get the form submit new handler works, but the problem is after the form is submitted, I wanted to get the submitted data and manipulate it. It is not working out as the form data is all gone.

```
function custommodule_form_alter(&$form, &$form_state, $form_id) {
    $form['#submit'][] = 'custom_submit_function';
}

function custom_submit_function($form, &$form_state) {
  $value = $form_state['values']['field_data'];
}

```

# Answer
> 2 votes
If you're only wanting to respond do products created via the UI, then form submit handlers should work. As noted, this wouldn't work for products created by any other method.

The correct hook you **should** use is `hook_commerce_product_insert()`. This isn't documented, but it should be. Using this hook will ensure that no matter where the product gets added that the hook runs.

```
function MYMODULE_commerce_product_insert($product) {
  ...
}

```

If you're wanting to create 100 new products, you can still loop in this function but you'll just need to differentiate between products that are created and the one that you began looping by some particular method. This could mean, for instance that there is particular SKU format (e.g. all created products end in `-XXX` where XXX is some number and the one created via the UI does not) or some extra field (e.g. `field_parent_product` that is empty on the one created in the UI but isn't on the sub-products). It's then trivial to both skip products that have a non-empty field, but also be able to handle updates or deletes down the road.

# Answer
> 0 votes
If you want to replace the existing submit handler then you need to remove the \[\] this: Something like this

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

```

Also be sure to check the form id of your form and the weight of your module.

# Answer
> 0 votes
Yes, this is correct way. But it will work only if product is created with the help of form. If you want to add some actions every time when product is created even it is created without the help of product form(e.g programmatically) you should use hook\_entity\_insert

**UPD:** You had to say about autogenerated products in your initial post. You may add some property to all products that are created there and check it in hook\_entity\_insert. Example(maybe need some modifications):

```
/**
 * Implements hook_entity_insert().
 */
function mymodule_entity_insert($entity, $type) {
  if ($type == 'product') {
    if (empty($entity->auto_generate)) {
      $new_product = entity_create('product');
      $new_product->auto_generated = TRUE;
      $new_product->save();
    }
  }
}

```

---
Tags: commerce, entities
---


title: Installing Drush on Mac

text:
# Question
Title: Installing Drush on Mac
I am installing Drush on my Mac following the instructions I found on https://linode.com/docs/websites/cms/drush-drupal/.

Everything works perfect, but I got stuck at the end while creating the symbolic link. Please find the error below.

```
Mudasirs-iMac:/ mudasir$ sudo ln -s /usr/local/src/drush/drush /usr/bin/drush

ln: /usr/bin/drush: Operation not permitted

```

# Answer
> 1 votes
You can't write to `/usr/bin` on OSX (since Yosemite).

Add your symlink to `/usr/local/bin` instead, and make sure that's in your path.

```
ln -s /usr/local/src/drush/drush /usr/local/bin/drush

```

---
Tags: drush
---


# Question
Title: How to display the user registration or profile field on the search page?
How can I render/display user profile or registration field on search result page (user search)?

# Answer
Copy the template file `YOUR_SITE/modules/search/search-result.tpl.php` to your theme and modify the code inside with this:

```
<?php
//obtaining the username
$username = explode('(', $title);
$username = trim($username[0]);
//getting the user object
$user = user_load_by_name($username);
?>
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?></a>
  </h3>
  <p>
  <?php
  /*
   * The following lines will print the info
   */
  print $user->field_date_of_birth[LANGUAGE_NONE][0]['value'] . "<br>";
  print $user->field_gender[LANGUAGE_NONE][0]['value'] . "<br>";
  print $user->field_your_industry[LANGUAGE_NONE][0]['value'] . "<br>";
  print $user->field_your_city[LANGUAGE_NONE][0]['value'] . "<br>";
  print $user->field_zip_code[LANGUAGE_NONE][0]['value'] . "<br>";
  print $user->field_countrynew[LANGUAGE_NONE][0]['value'] . "<br>";
  ?>
  </p>
  <?php print render($title_suffix); ?>
  <div class="search-snippet-info">
    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?></p>
    <?php endif; ?>
    <?php if ($info): ?>
      <p class="search-info"><?php print $info; ?></p>
    <?php endif; ?>
  </div>
</li>

```
> 3 votes

---
Tags: 7, theming, users, search
---


title: Child pages in books module

text:
# Question
Title: Child pages in books module
I can only create 8 child pages in a book not beyond that,It seems like the depth of the child pages is set to 8 but i could not find the location where the depth was set.Please help me

# Answer
The book module has this bit of code in it to enable a user to choose which parent a node has:

```
$form = array(
  '#type' => 'select',
  '#title' => t('Parent item'),
  '#default_value' => $book_link['plid'],
  '#description' => t('The parent page in the book. The maximum depth for a book and all child pages is !maxdepth. Some pages in the selected book may not be available as parents if selecting them would exceed this limit.', array('!maxdepth' => MENU_MAX_DEPTH)),
  '#options' => book_toc($book_link['bid'], $book_link['parent_depth_limit'], array($book_link['mlid'])),
  '#attributes' => array('class' => array('book-title-select')),
  '#prefix' => '<div id="edit-book-plid-wrapper">',
  '#suffix' => '</div>',
);

```

Take a look at the description in particular. When you sub in the relevant variables, it reads:

> The maximum depth for a book and all child pages is **9**. Some pages in the selected book may not be available as parents if selecting them would exceed this limit.

Emphasis mine.

So the limit intentional, it (necessarily) matches up with the maximum depth for a menu in the same system.

It would technically be possible to patch core and increase `MENU_MAX_DEPTH` to something larger, but bear in mind that other parts of the system rely on it (for example the number of `p*` columns in the menu links table), so it probably won't be as simple as all that.
> 1 votes

---
Tags: nodes
---


title: Disable payment via custom module

text:
# Question
Title: Disable payment via custom module
is there anyway, we can disable payment of specific payment option via custom module? I Have done some research that payment in drupal commerce is setup via rules, so is there an option we can create custom module and hit the current payment rules and disable it?

and is there a way via custom module, we can get the list of available or activated payment?

some references would be great.

thank you!

# Answer
> 1 votes
**Option 1: Hook Form Alter**

Rules are event-based conditional actions. For "showing" or "hiding" payments, that event it almost always going to be simply showing the form on checkout. So, technically, you could just use hook\_form\_alter() and locate the checkout pane that has the payment details and modify from there.

A video where I walk you through how to do hook\_form\_alter: https://youtu.be/xYMd6WDqxKY?t=1m3s (admittedly, this is for a different use case, but I do show you how to locate the form\_id and customize the form\_alter for whatever situation you're in).

**Option 2: Custom Rules Condition**

Another option would be to create a rule condition that you can add to your payment gateways. I think this would be more in spirit with how Drupal Commerce works.

Over here, I have shown you how to create a custom Rules action and condition: Different vat rate per commerce shipping service

There is also a clear example here: How do I add a new condition in Rules 2?

**How to do option 2**

As I said above, this is how Drupal Commerce is supposed to work. If you create a custom rule condition (perhaps there's a business server that returns a REST true/false for an A/B comparison) then that condition is exposed in the user interface and keeps the logic in code where it can be maintained separate from being implemented.

1. Create the custom rule condition ***in your custom module with your custom logic***
2. Add that condition to your payment method: /admin/commerce/config/payment-methods
3. Know that every time that payment method might appear (both in checkout and on the order editing payment screen) that rule condition will be run

---
Tags: commerce, payment-gateways
---


# Question
Title: Redirect customer to specific order checkout later
I'm using Commerce Quotes sandbox project (https://www.drupal.org/sandbox/xatoo/1860944) to get quote system in commerce. Customer add products to cart and requests a quote instead of checkout. Then store owner can respond to quote (store owner may give discounts to product s unit price) and system sends new quote to customer by email. Then customer can accept or decline the offer.

My problem is that if customer accepts the offer he/she should be able to pay the order in the website. Is there some url I could redirect customer to? I tried following approach with Rules:

* After accepting quote change Order status to "Checkout: Shipping"
* Redirect customer to /checkout/\[order\_id\]/shipping

The problem was that now in checkout product prices were original, not the discounted one that store owner was saved to order. Any idea why is that?

Is there better way to let customer pay the accepted offer?

Big thanks in advance!

# Answer
Sounds to me like the sandbox isn't using pricing rules to set the "new offer."

Here's what I would do (without knowing what the sandbox is doing):

* I would create a custom line item type using commerce\_custom\_product
* I would then add a price field called "price\_override"
* I would then create a pricing rule that overrides the original price of the line item with the "overridden price" if it exists.
* I would then make sure that the sandbox or a custom module sets that line item field when a new offer is made

The above approach has the benefit that the price is actually using pricing rules, but the "custom price" is per-line-item instead of per-order. Now it might be possible, depending on how the sandbox is functioning, to access the "custom pricing" and use it in a pricing rule. But the same approach would still be taken above.

// Edit

You can always just send users to "/checkout" ... but likely they would need to be logged in first to be connected to their order (this would be based on default permissions). So I would use the Drupal system to your advantage, this little link will present anonymous users with a login form, then redirect to checkout (and will simply redirect to checkout if logged in):

/user/login?destination=checkout
> 1 votes

---
Tags: redirection, commerce
---


title: One product, multiple sellers

text:
# Question
Title: One product, multiple sellers
In a multiseller Drupal Commerce Installation, where every Drupal user being a seller, Some products can be the same from all users, for example a book from some publisher which can be sold by many sellers. Like in amazon, if one is searching for a book, it comes up and shows other sellers also of that particular book.

Is there a way in Drupal commerce to achieve the same?

# Answer
Sure! I would recommend you:

1. Create a taxonomy called "global\_sku" ... Amazon calls their psuedo sku "ASIN" ... which is just a number that ties all the "product displays" to one page.
2. Now ... on your product displays, you could create a taxonomy reference to global\_sku's
3. And then add some Views that will bring in related products based on the taxonomy.
> 0 votes

---
Tags: commerce
---


# Question
Title: Insert a list of links to the related products image area in commerce kickstart 2 drupal
How to insert a list of links to the related products image area (leading into a specific place in the product display of that product) in commerce kickstart 2 drupal

E.g. In the product display page where it shows the product images and the details like Title, SKU, Price, Quantity and add to cart image, I have added a jquery tab field under it which includes 3 tabs (Description1, Description2, Description3).

Under that field, I have added a block with the related products (products that belong in the same category). It shows the title of the product and the image.

Under the image I want to place a link for each of the above tabs (Description1, Description2, Description3) which when is clicked it will lead me to the page of the specific product and at the place int it where I can see the beginning of the tab.

For example: When I click in the link description 2 of the product 3 (related product) it should get me to the products 3 product display page and move have the page scrolled down to the position where the tabs of product 3 appear.

# Answer
> 0 votes
Hard to say from your question, but I think what you want is deep linking (clicking a link takes you to a particular tabbed description). If that is the case, then you might need some custom jquery that uses the Drupal core included jQuery BBQ library to modify the url when the tabs are clicked, then modify your tabbing library to interpret parameters in the urls as which tabs you want to be viewed. I'd imagine if your library doesn't support it, it will all require some javascript.

---
Tags: commerce
---


# Question
Title: How to add a button or link to perform an action on a node with node_view?
I wonder how to add a button or link to perform an action of \_create\_node function. I understand on how to do it on the node edit screen, but not the display.

I want a button of create "new item" on the node display. I'm creating a custom module to create the new node, but need a button to call it.

Any suggestions?

# Answer
> 7 votes
You can implement the `hook_node_view()` like the following code:

```
function YOUR_MODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'CONTENT_TYPE_NAME') {
    $form = drupal_get_form('redirect_button_form');
    $node->content['redirect_button'] = $form;
 }
}

function redirect_button_form($form, &$form_submit) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('New Item'),
    );
    return $form;
}

function redirect_button_form_submit($form, &$form_state) {
    //here the path where you need to go
    $path = 'node/add/CONTENT_TYPE_NAME';
    drupal_goto($path);
}

```

# Answer
> 2 votes
For adding any custom link/button on node display, try by adding your code in **tpl file**. For customizing node display add your code in `node.tpl.php`.

For tpl naming conventions and more details, Please refer

1. Theming nodes by content type.
2. Drupal 7 Template (Theme Hook) Suggestions

Hope this will help you.

---
Tags: 7, entities
---


# Question
Title: How to wrap / manipulate element outputs on a form's checkboxes html?
I have the following form that contains a big list of checkboxes. The first checkbox is the parent of the children below it. In my case it is called "Africa" and the ones below it are "Africa-child" checkboxes. I was able to manipulate the classes, but I can't seem to find a way to add a wrapper div around the "Africa-child" elements. I mean I can do it via javascript, but I was wondering if there was a Drupal hook to add in extra html to the *select* options html before it gets outputted.

The code below is it form data used to build the form. The prefix and suffix is wrapping ALL of the checkboxes, but I only want to wrap certain ones.

```
function hotsite_filters() {

  $form['offices'] = array(
    '#type'       =>  'checkboxes',
    '#title'      =>  '',
    '#options'      =>  get_office_options(true, '', 'local_alias ASC', false, true, true, false, true),
    '#default_value'  =>  filter_get_keys('browse-offices'),
    '#prefix'     =>  '<div id="filters-offices"><div class="filter-header">' . variable_get_value('hotsite_filter_offices_header') . '</div>',
    '#suffix'     =>  '</div>',
    '#size'       =>  11,
    '#multiple'     =>  true,
    '#required'     =>  false,
  );

```

# Answer
> 0 votes
You could use your get\_office\_options function and add some html

For example:

```
$alphas = range('A', 'Z');
    foreach($w_question->get('field_option_radio') as $key => $option){
        $options[$option_id] = '<i></i>'.$option_text;
    }

    return $options;

```

---
Tags: 7, forms, theming
---


title: db_select throws PDOException

text:
# Question
Title: db_select throws PDOException
Trying to do a simple query from a table called 'raffles' under the drupal database.

It is not a complex query, Just trying to get all sets from drupal.raffles

```
$query = db_select('raffles');
$query->execute();
$result = $query->fetchAssoc();
dpm($result);

```

The error

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM raffles raffles' at line 1: SELECT FROM {raffles} raffles; Array ( ) in raffle_create_form() (line 8

```

From the error, the query has the table name twice, and is probably what is causing the error. maybe im doing something wrong? There is not much information related to this on the api page.

Any help would be gladly appreciated.

Thanks.

# Answer
You haven't selected any fields:

```
$result = db_select('raffles', 'r')
  ->fields('r', array('foo', 'bar'))
  ->execute()
  ->fetchAll();

```

If you want to select all the fields, then use the following code.

```
$result = db_select('raffles', 'r')
  ->fields('r')
  ->execute()
  ->fetchAll();

```

Incidentally, the second `raffles` is a valid alias and not related to the problem.
> 2 votes

---
Tags: database
---


# Question
Title: How to pass the nid from hook_node_view to the submit function?
I need one button at the end of one content type view form. This button should redirect the user to another page.

I have something like the following code:

```
function mymodule_node_view($node, $view_mode, $langcode) {

    if ($node->type == 'my_type') {
            $form = drupal_get_form('redirect_button_form');
            $node->content['redirect_button'] = $form;
            //$node->nid is the data I need in the submit function
    }
 }

function redirect_button_form($form, &$form_submit) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Redirect button text'),
    );
    return $form;
}

function redirect_button_form_submit($form, &$form_state) {
    $path = 'mypath';
    $options = ****I need the nid here;
    drupal_goto($path,$options );
}

```

How can I pass the nid from the hook\_node\_view to the submit function?

# Answer
See the code with comments inside:

```
function mymodule_node_view($node, $view_mode, $langcode) {

if ($node->type == 'YOUR_NODE_TYPE') {
  //adding the nid to the drupal_get_form()
  $form = drupal_get_form('redirect_button_form', $node->nid);
  $node->content['redirect_button'] = $form;
 }
}

//see the 3th param ($nid)
function redirect_button_form($form, &$form_submit, $nid) {
    //adding a hiddin field with the nid
    $form['hidden-item'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('New Item'),
    );
    return $form;
}

function redirect_button_form_submit($form, &$form_state) {
    $path = 'node/';
    //here your nid
    $options = $form_state['values']['hidden-item'];
    $path .= $options . '/edit';
    drupal_goto($path);

}

```
> 3 votes

# Answer
You don't need to use form here. Just use l() with the button name and the link path.

```
function mymodule_node_view($node, $view_mode, $langcode) {

if ($node->type == 'my_type') {
   $node->content['redirect_button'] = array(
     '#markup' => l('Redirect button', 'yourpath/' . $node->nid);
   );
    }
}

```
> 3 votes

---
Tags: 7, forms
---


title: Payment method to cart page

text:
# Question
Title: Payment method to cart page
I need to move the payment method from the checkout page in drupal commerce and embed it into the cart page. is that even possible? I have been finding some resources and it does not lead me anywhere.

I believe I will need a custom module for this and which hook should I used for presenting a payment option in the cart page and when hitting 'checkout' button it will just go and review everything. so payment is processed in the cart page also.

thank you

# Answer
It's actually very straight forward! If you want to not completely override the /cart url (basically, leaving the /cart in tact, but simply link key user interface elements directly to checkout) then you can skip to step 2...

**Step 1: Overriding the cart view**

You will want to do three things:

1. First, you'll want to "alias" the "/cart" to "/checkout" (see screenshot above) ... this will ensure all system links that go to cart actually just link to "/checkout"
2. Second, you'll want to override the system path "/cart" and have it redirect to an appropriate location. (code below)
3. Finally, you'll need to disable the view "Shopping cart form" (otherwise our hook\_menu\_alter may not work).

*See verified code below (as in I checked to make sure this works).*

```
<?php
function mymodule_menu_alter(&$items) {
  $items['cart']['page callback'] = '_mymodule_redirectcart';
}
function _mymodule_redirectcart() {
  global $user;
  $account = $user;
  $cart = commerce_cart_order_load($account->uid);

  // if user doesn't have a cart, go to <front>
  // else if user's cart is empty
  if ($cart == false || count($cart->commerce_line_items) == 0) {
    drupal_goto('<front>');
  }

  // go to checkout
  drupal_goto('checkout/'.$cart->order_id);
}
?>

```

*Don't forget to disable the shopping cart form*

**Step 2: Making a one page checkout**

I borrowed the step-by-step from an excellent "Express Checkout" blog.

1. From http://www.example.com/admin, click on the Store link, then Configuration, then Checkout settings
2. Drag the Review item out of the Review order section and into the disabled section
3. Drag the Payment item out of the Review order section and up into the Checkout section
4. Click Save Configuration

**Step 3: Modify the title and button**

This step is optional, but useful. Basically, we just use hook\_form\_alter to change the "Continue" button to indicate that payment will be taken and we modify the page title to "Cart" to further our ruse that this is the cart page and not checkout.

```
<?php
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_checkout_form_checkout') {
    drupal_set_title("Cart");
    $form['buttons']['continue']['#value'] = t('Proceed with purchase');
  }
}
?>

```

**Step 4: Your new cart checkout**

This is not really a step, but it is the result of your effort. Now your new "cart" has a checkout/payment pane. Only thing you would be missing from the original cart is the ability to modify your cart (remove products) and that is where this process would fail you.

**Other Thoughts**

If your customers will need to be able to modify the cart (most likely the case), then you will need to link to a clone of the commerce\_cart\_view at a unique url (perhaps /cart-edit?) and then add a link called "Edit Cart Contents" in the footer of your cart contents view to indicate that they can remove items, but they have to click a link to do it.

1. The view you want to clone is called "Shopping cart form" and the clone option can be found at /admin/structure/views
2. Make sure you edit the path in your cloned view to "cart-edit" or some variation.
3. Edit the footer of the "Shopping Cart Summary" view found at /admin/structure/views/view/commerce\_cart\_summary/edit to look like the below:

The reason you can't modify cart items in checkout is that "forms within forms" is not a straightforward thing to implement, but linking to a view to edit your order is pretty simple and everyone wins with a 10 minute change.
> 2 votes

---
Tags: commerce, hooks
---


title: Adding custom layer to openlayers map

text:
# Question
Title: Adding custom layer to openlayers map
I'm working with Openlayers and I would like to add a custom layer to a map with markers from a webservice.

It should works in this way:

* I create a map with Openlayers UI and display it in a page;
* I call an external webservice that returns me X elements with lat/long informations;
* I show these elements in the map as a normal layer, with markers etc.

The questions are:

* Have I to create with Openlayers UI a custom layer and then I've to populate it with js/ajax?
* Or I should create a map without a layer and add this layers js/ajax, and popoulate it with js/ajax?

# Answer
One way to do this is with a views geojson layer. This seems to be the only way that works right now...at least for me.

With static data, you create a views display of type feed (create a view with no page or block and set it to type feed). Then, set the format to geojson. You'll have to set the settings to your geofield, and add your geofield as a field to the view. Then finally, create a layer through the OL UI and set your feed as a source. Hope this helps.
> 1 votes

---
Tags: javascript
---


# Question
Title: How to iterate through an object returned by fetchAll?
Since fetchAssoc was returning only one row, i was forced to use fetchAll.

The problem is fetchAll returns the data as an array of objects. Iterating through them is kind of painful, not impossible but seems like a long way to go for something that should be really simple.

fetchAllAssoc throws an error.

If somebody could show me a neater trick, that would be great.

```
    $result = db_select('raffles', 'r')
  ->fields('r')
  ->execute()
  ->fetchAll();

  dpm($result);

```

# Answer
> 4 votes
```
<?php
// Retrieve all records into an indexed array of stdClass objects.
$info = $result->fetchAll();

// Retrieve all records into an associative array
// keyed by the field in the result specified.
$info = $result->fetchAllAssoc($field)

```

To iterate just use:

```
foreach($info as $key => $object) {
  print $object->property . "<br>";
}

```

**References:**

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

---
Tags: database
---


# Question
Title: How do I show a custom module settings page as tab of another existing settings page?
I am developing a custom module for Drupal 8.0.1 which shows a custom form in *admin/config/people/ban/settings*.

*admin/config/people/ban* is the routes used by the Ban module. *admin/config/people/ban/settings* should be shown as *Settings* tab in that route, while the settings for the Ban module are shown in the *Default* tab.

How can I achieve this in my module?

# Answer
You need a local tasks menu link yml file, see example in node module: node.links.task.yml
> 3 votes

# Answer
For this you need to create a route in the module.routing.yml file

```
route_name:
  path: 'admin/config/people/ban/settings'
  defaults:
    _form: '\Drupal\modulename\Form\FormController'
    -title: Form Title
  requirements:
    _permission: 'your permission string'

```

then you need to create another yml file with the name mymodule.links.menu.yml

add the following code

```
form_config_link:
  title: Configure Form Title
  description: 'Configuration Form description'
  parent: system.admin_config_people
  route_name: route_name //defined above

```

You need to check system module yml file for parent name
> 3 votes

# Answer
The trick is that always need at least *two* local tasks for local tasks to show up. They don't do if there's only one.

So, define a `yourmodule.menu.task.yml` and put two definitions in there. Default, which has the existing ban route for both base\_route and route\_name and yours, which has your route\_name and the same base\_route as the the default task.

What used to be the default task in Drupal 7 is now simply the task that has base\_route == route\_name.
> 0 votes

---
Tags: 8, navigation
---


title: Feeds doesn't import photos

text:
# Question
Title: Feeds doesn't import photos
I imported products with the help of **feeds** via **commerce product processor**. All products data downloaded correctly except the product photo.

It downloaded from csv file, where there is a full direct path to the picture. At settings of acceptability to this field : `photo: URI (field_product_photo:uri)`

Import runs without mistakes, but there is no product photo in a product's description. Which is strange because the file is copied to `sites/default/files/` it's saving the origin name, except saving in `sites/default/files/images` and changing the origin name to **sku** , as it should be by making this products list by hand-labour.

Can you tell me what am I doing wrong?

# Answer
Thans for your reply. We've already solved the problem. It was bug in sql in file\_managed. The total truncate of the table helped.
> 0 votes

---
Tags: commerce, feeds
---


# Question
Title: How can i make my solr search case sensitive?
I am using search api and search api solr module, currently my search is case insensitive with following configration.

```
<fieldType name="text" class="solr.TextField" positionIncrementGap="100">
<analyzer type="query">
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>

```

if i remove `<filter class="solr.LowerCaseFilterFactory"/>` it becomes case sensitive. How can i have both the thing?

# Answer
> 1 votes
Original answer from: https://stackoverflow.com/questions/10205688/how-to-make-field-search-not-case-sensitive-in-solr-using-solrnet

You could use a copyfield that converts the field in question to lowercase.

Similar problem/solution: https://stackoverflow.com/questions/2053214/how-to-create-a-case-insensitive-copy-of-a-string-field-in-solr

---
Tags: views, search
---


title: Can't get variables

text:
# Question
Title: Can't get variables
I'm trying to get variables to use them in my module but I can' get them.

I try `print_r($variables)` and get

```
"Undefined variable: variables in include_once().."

```

The same happens if I try to get $page, $html, $node, etc.

I tried to use `dpm()` and gets a blank content.

Anyone seen anything like this? I don't understand.

# Answer
`$variables` isn't a global variable accessible to any module. Most of the variable names you've mentioned are a part of (or naming convention in) D7's templating engine. For example:

* `$variables` is common parameter name for most of template preprocessing functions (e.g. `template_preprocess_node()`). In the context of the preprocessing function, it contains a keyed array of variables that will be injected into the template (e.g. `$variables['node']` will be `$node` in **node.tpl.php**)
* `$page` is the variable named used in **page.tpl.php** that contains Drupal block region data.

If you're curious what variables are globally accessible to Drupal 7 modules see this page. Any these variables can be accessed by using the `global` keyword followed by the variable name (e.g. `global $user` to access the current user object in a module function).
> 4 votes

---
Tags: 7, debugging
---


# Question
Title: Cannot enable node_view in ctools page_manager permanently
I have a strange problem. If I enable node\_view in page\_manager everything works as expected and the node layout is according to my settings. If I then do a menu cache clear node\_view is not used anymore and my node layout is as without node\_view. If I do a

```
page_manager_get_current_page();         (1)

```

shortly after activating node\_view the array contains the normal values. Looking into the db the variable

```
variable_get('page_manager_node_view_disabled')         (2)

```

returns 0 as it should be. After the menu cache clear the function in (1) returns an empty array whereas the variable in (2) remains 0. Also the node\_view page stays active inside the page\_manager UI. If I deactivate and activate node\_view everything works again until I refresh the menu cache again. So this seems to be an infinite loop for me: Everytime I do a menu cache flush I have to deactivate/activate node\_view.

I don't know how long this problem exists, but I observed changes in my node layout also last year. I am using Drupal commons, so maybe the problem is related to this, since commons throws in a lot of modules and perhaps something overwrites node\_view (panelizer is disabled on the specific nodes).

If I look into the code of the module, there should be a message

```
drupal_set_message(t('Page manager module is unable to enable node/%node because some other module already has overridden with %callback.', array('%callback' => $callback)), 'error');

```

if node\_view is overridden, but there is simply nothing in dblog. I am really stuck here...

Does anyone have an idea what could be wrong or what I could do to find the reason for this behaviour?

# Answer
Found the reason:

I had a module enabled which implemented a menu\_alter which has changed

```
$items['node/%node']['page callback']

```
> 0 votes

---
Tags: panels, chaos-tool-suite, 7
---


title: Adding classes to <a>

text:
# Question
Title: Adding classes to <a>
I am trying to add classes to the `<a>` tag output from menu.html.twig. I can add these classes to the `<li>`, but not the `<a>` tag.

In the twig file I have a loop and I need to add the classes 'link-1', 'link-2' etc to each `<a>` tag:

```
{% for item in items %}
  <li{{ item.attributes.addClass('link-'~loop.index) }}>
    {{ link(item.title, item.url)}}
  </li>
{% endfor %}

```

This outputs the class on the `<li>`:

```
<li class="link-1">

```

How do I set the code below on the `<a>` tag instead?

```
item.attributes.addClass('link-'~loop.index)

```

So the result I am looking for will be:

```
<li><a class="link-1">Link Text</a></li>

```

# Answer
You can try code below:

```
{% for item in items %}
  <li>
    {%
      set attributes = attributes.setAttribute('class', 'link-'~loop.index)
    %}
    {{ link(item.title, item.url, attributes)}}
  </li>
{% endfor %}

```

more detail about attributes in twig and link
> 6 votes

---
Tags: theming, 8
---


# Question
Title: How to render the same field twice but with different name/id attribute?
I have overriden `user-register.tpl.php` and in it I would like to render same checkbox twice (so that I can submit if either of them have been checked and they are the same I just need to display them twice).

**Example:**

```
<div class='field1'>
   print render($form['field_add_option']);
</div>
<div class='field2'>
   print render($form['field_add_option']);
</div>

```

But this gives same field with same id with same name which is to be expected. Is there a way to change name and id of field before rendering?

I have tried to change the name like (before the second one)
`$form['field_add_option']['und']['#name'] = 'test1';`

But the label `for` and `name` of checkbox are still the same.

# Answer
The select element don't have `#name` atribute (Form API Reference). You can implement the `hook_form_alter()` in a custom module.

```
/**
  * Implements hook_form_alter().
 */
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'YOUR_FORM_ID') {
    //here you can make the copy
    $form['field_add_option_copy'] = $form['field_add_option'];
  }
}

```

You can read this: Creating modules - a tutorial: Drupal 7.x
> 3 votes

# Answer
You need to use hook\_form\_alter to add your additional fields to the user register form so it's a proper field. Or alternatively add the field to the user object within /admin/config/people/accounts/fields and tick the box to tell it to appear on the registration form.
> 2 votes

---
Tags: 7, forms, theming
---


# Question
Title: How to add the User:Picture field on the account registration form?
I saw the User:Picture field after setting the User:uid contextual filter for a Views block. Now I am wondering how to show this field on the account registration form? I looked at config/people/accounts/fields but nothing there.

Any help is appreciated.

# Answer
You can use Register with Picture module.

> This module exposes the 'upload picture' element to the registration form. It also gives you the ability to set a picture as required in the module settings.
>
> Drupal 7 Instructions
>
> 1. Install and enable the module
> 2. Navigate to: Configuration -\> Account Settings. (admin/config/people/accounts)
> 3. Check Enable user pictures if it isn't checked already.
> 4. Confirm Enable pictures on registration is checked.
> 5. Use the Registration Picture Field Weight field to adjust the display order of the picture field on the registration form. It can be a negative or positive number.
> 0 votes

---
Tags: entities, users
---


title: AJAX Populated Views Exposed Filter

text:
# Question
Title: AJAX Populated Views Exposed Filter
I'm re-building a travel website and need the trip search form to have the "Arrivals" select populated using AJAX once the departures has been selected to remove any empty search results.

I have followed all the tutorials I could find online, namely: Views AJAX Dynamic Dependent Exposed Filters & AJAX populated filter breaks when Views Dependant Filter module added, applied patch #106 from https://www.drupal.org/node/1183418 and nothing seems to work. I'm also not getting any error messages which makes it harder to debug.

I've attached my custom module code to the bottom of this post.

Any help or ideas are appreciated as I've been stuck on this for over a week now.

```
    function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
    if ($form['#id'] == 'views-exposed-form-trips-page') {

        if($form_state['input']['field_departure_tid'] === 'All')
            $form['field_arrival_tid']['#disabled'] = 1;
        }
}

function _sort_alphabetically($form, $form_state) {
        foreach ($form_state['view']->filter as $field => $filter) {
            if ($filter->options['exposed']  && $filter->options['id'] == 'field_arrival_tid' ) {
                $field_id = $form['#info']["filter-field_arrival_tid"]['value'];
                asort($form[$field_id]['#options']);
            }
        }
        return $form;
}

function _update_arrival_callback($form, $form_state) {
    return $form['field_arrival_tid'];
}

function _get_associative_array_from_view($viewID, $viewDisplayID, $keyFieldID, $valueFieldID, $contextualFilter){
    $associativeArray = array();
    $associativeArray['All'] = t('- Any -');
    $viewResults = views_get_view_result($viewID, $viewDisplayID, $contextualFilter);
    foreach($viewResults as $viewRow) {
        $associativeArray[$viewRow->$keyFieldID] = $viewRow->$valueFieldID;
    }
    return $associativeArray;
}

```

# Answer
> 0 votes
Try to change:

```
if($form_state['input']['field_departure_tid'] === 'All')

```

in

```
if($form_state['input']['field_departure_tid'] == 'All')

```

And inside \_form\_alter function add this string to see the content of field\_departure\_tid

```
var_dump($form_state['input']['field_departure_tid'])

```

because if I don't wrong remember field\_departure\_tid is a number not a string.

---
Tags: ajax, views
---


# Question
Title: Send Email After User has confirmed email address using Rules
I my drupal site, I have checked **Require Email Confirmation** to enable email confirmation. In this case it is sending an email with link to confirm email to set password for account.

Now when user has confirmed email address and set password for account, I want to send email to the user informing of confirmed email.

I have looked Rules Module for this, but there is no any such even present.

Any suggestion how can I implement this using Rules module.

-- Many thanks for your time

# Answer
> 1 votes
I did something like this on a site not long ago, and at the time I couldn't find a solution that would work without some extra code because of the way registration was set up, but for your case you should be able to use a rule to check when the user's access timestamp is first set, reacting to the "after updating an existing user account" event.

So you need to check the account-unchanged:last-access is 0 and the account:last-access is not 0, then fire your rule. I haven't tested that this will work, and you might need to add some extra conditions for your particular circumstances.

# Answer
> 0 votes
I don't know how to solve this issue, but I think Password Token, for sending the User the password in E-Mail might be helpful in your case.

# Answer
> 0 votes
I am suggesting you to to create your custom rule or the other way is to use logic of workflow module.

In custom rule, once a mail has been sent and when user will confirm the email and set a password at that time, set one flag.If flag is set then send mail and then unset that flag. In this way you can acheive.

The another way is to create states in workflow. And make workflow rules configure accordingly.

HOpe this will help.

# Answer
> 0 votes
You can use https://www.drupal.org/project/logintoboggan rules integration

---
Tags: 7, rules, emails
---


# Question
Title: How to change the position of a block in a particular page?
I have a Drupal's default `User Login` block in `Side bar first` region at the last position. Reference page: http://indiansnakes.org/snakes

The proposed home page has been redesigned and the `User Login` block has to be displayed in the `Footer Fourth` region. Reference Page: http://indiansnakes.org/homepage

So, the `User Login` block should appear in footer fourth only for this new homepage but for the rest of the pages in websites it has to continue to stay in the `Side bar first` region. In normal scenarios if it was a custom block, then I can create a clone of the same block and change the visibility per page / set of pages. But `User Login` block is system defined and it does not allow me to clone or duplicate it.

I tried searching if someone has already addressed this issue but it seems like not. Looking forward for thoughts.

Edit: Nearest I could find is this: Change block location on page by page basis?. But the solution there was to create multiple blocks from same view, unfortunately `User Login` is not based out of views for me.

# Answer
> 4 votes
You can place the default `User Login` block in Sidebar first region at the last position. You can exclude this block from being shown in Homepage using 'Visibility settings' which is available in the block edit page.

Then you can use front page template `page--front.tpl.php` and render the block manually by passing the block markup through `hook_preprocess_page()`.

```
function THEME_NAME_preprocess_page(&$vars, $hook) {
  $front_page = drupal_is_front_page();
  if ($front_page) {
    $user_login= block_load('user', 'login');
    $vars['user_login'] = _block_get_renderable_array(_block_render_blocks(array($user_login)));
  }
}

```

Then you should print the `$user_login` variable in the front page template inside the `Footer Fourth` region.

# Answer
> 2 votes
the context module does this (and more): https://www.drupal.org/project/context

it lets you make a context based on page (so front), then you tell it to display a block where you want it.

you can then make a second context based on page (not front) and display it in the other region.

this lets you reuse the block and avoids writing custom php in your template file.

---
Tags: 7, blocks
---


# Question
Title: How to delete sites showing up in backend of Aquia Dev Desktop
Deleted sites still showing up with Aquia Dev Desktop even if I already deleted files and databases.

Any way to clear these?

# Answer
Found the solution, at the bottom left of the window there is a + and - sign, they look like sorting icons,but actually they are to delete. Clicking on minus does it.
> 0 votes

---
Tags: acquia-dev-desktop
---


# Question
Title: Multiple independent Views attachment pagers (load more)
I have a view with two attachments. I want to have a **load more** button to load items for each attachment and the main view separately, I have the **load more** module, but it loads more items for all the views, not for each attachment separately. Any help will be appreciated.

# Answer
> 0 votes
Make sure you have unique pager id's for all your view displays. You will find the option in Views under the paging section of your display.

**EDIT**

As noted below, attachments don't have the option to add a unique ID, this is a known limitation. See for example this discussion on Drupal.org.

It is currently not possible to solve this issue in Views only. If you want different paging options, you can not use attachments. A workaround is to use block displays and place them on the same page as the main view. (Do change the pager ID of the block views only if there are still problems).

---
Tags: views
---


# Question
Title: Probably corrupted database by deleting records from node / node_revision
I did something where everybody said never ever do it: some weeks ago I deleted records from the node- and/or node\_revision tables manually (DELETE FROM TABLE ...), and thought it won't harm. But now I see that it definitely did harm, as my search function doesn't work anymore the way it should be.

Is there something I could repair or very hard to recover?

Many thanks for help.

# Answer
> 1 votes
Oh dear, as you suspect that's not great. The outlook is probably quite bleak I'm afraid, a few vague possibilities:

* If you know exactly what you deleted manually, restore it manually.
* If you're able to restore a backup to another database, and cherry pick the records you deleted from that to be restored manually to the original DB, and depending on what damage those missing records have done in the meantime, that would possibly be an option.
* If restoring the whole database from a backup is an option, do that.
* If you know the IDs of the nodes you deleted, stick some dummy data with the appropriate IDs into the node/node\_revision table, then call `node_delete_multiple` with the IDs so the system deletes them properly (clear the cache first).

The main problem with deleting straight out of the node table is that you leave a lot of orphaned data elsewhere - Drupal has no enforced referential integrity apart from some 'soft' checks in code for certain operations.

The most important thing to take away from this is never touch the database unless you're 100% confident what you're doing is safe. But I reckon you've probably learned that already :)

---
Tags: database
---


# Question
Title: How can I add a sub-array structure in my results? $_POST
I'm building a form. In that form I have a lot of checkboxes. Normally, It's possible to make an array of some checkboxes (with name attribute).

```
<input type="text" name="reservatie[0][1]" />
<input type="text" name="reservatie[0][2]" />
<input type="text" name="reservatie[1][1]" />

```

Normally I would have this result with print\_r($\_POST);

```
Array(
    [reservatie] => Array(
        [0] => Array (
            [1] => value
            [2] => value
            )
        )
        [1] => Array
        (
            [1] => value
        )
    )
)

```

I tried to add the name attribute, but the `$_POST` takes the structure of $form. But how can I add a sub-array structure in my results?

```
foreach($result as $time) {
                    $form['reservatie'][$item->id][$time->id] = array(
                          '#type' => 'checkbox',
                          '#return_value' => 1,
                          '#default_value' => 0,
                          '#prefix' => '<td>',
                          '#suffix' => '</td>',
                          '#attributes' => array('name' => 'reservatie[0]['.$time->id.']')
                    );
                }

```

This is what I get:

```
array(42) {
  ["date"]=>
  string(10) "01/07/2016"
  ["reservatie[1][1]"]=>
  int(0)
  ["reservatie[1][2]"]=>
  int(0)
  ["reservatie[1][3]"]=>
  int(0)
  ["reservatie[1][4]"]=>
  int(0)
  ["reservatie[1][5]"]=>
  int(0)
  ["reservatie[1][6]"]=>
  int(0)
  ["reservatie[1][7]"]=>
  int(0)
  ["reservatie[1][8]"]=>
  int(0)
  ["reservatie[1][9]"]=>
  int(0)
  ["reservatie[2][1]"]=>
  int(0)
...
)

```

# Answer
> 0 votes
I managed to solve my own problem. It was a problem with the #tree. I have to set #tree in the parents to true..

So if you want an array with the following structure:

```
array {
    ["parent"]=>
     array(4) {
        [1]=>
        array(9) {
          [1]=>
          int(1)
          [2]=>
          int(0)
          [3]=>
          int(0)
          [4]=>
          int(0)
          [5]=>
          int(0)
          [6]=>
          int(0)
          [7]=>
          int(0)
          [8]=>
          int(0)
          [9]=>
          int(0)
        }
    }
}

```

I had to configure #tree for the parents (2 here), and not only for the children

```
['parent']['#tree'] = true
['parent'][1]['#tree'] = true

```

I figured it out after trying and reading https://www.drupal.org/node/48643 (Archived, but it worked for me ;) )

---
Tags: 7, forms
---


# Question
Title: How to have multiple columns for a single field in view
I created a content type with image field which accepts unlimited values. Now, I have 25 images uploaded to the field. I created a page view. I selected the image field. For the view settings, I selected **Grid** format \> **Number of column**: 2.

When I go to views page, I expected to see 2 columns on the page views but I did not. How can I make sure I can see only 2 columns of images in the views page when I set number of columns equal 2 in **Grid** setting?

# Answer
> 1 votes
When you configure field in **Views** there is an option **Display all values in the same row** under **Multiple field settings** uncheck that option. By doing this each image will display in separate column.

---
Tags: views
---


# Question
Title: How can I set per file access controls by role to files on a node
I'm migrating a publications database from an old CMS to drupal 7 using the **migrate** module. One of the requirements is that some publications (nodes of content type document) will be available to the public (anonymous users and everyone else) and some will be staff only (administrators, staff, and probably some higher level roles created for content editing). Each publication can have an arbitrary number of associated files, each of which can also be publicly available or internal only (Same set of role based control).

How could I set this up? So far my two possible solutions have been:

1. creating a different content type called files and using inline entity form to to associate thre file nodes with the publications. This will allow me to ad a field for whether the file node is publicly available or not
2. Using the **media** module. Unfortunately it appears that the **Migrate Extras** module that has media support doesn't support Media 7.2.x (As far as I can tell it is designed for 7.1.x). I have tried installing Media 1.x but I have so far been unsuccessful at getting migrate to recognize the extra field as a destination field for migrate to write to.

# Answer
The first thing to understand when you want to shield files from unauthorized access in Drupal is the difference between the Public and Private stream wrapper. By default files are uploaded in Drupal in a public directory and no matter what you do with access control on entities the files will be publicly available directly via the url to the file. So first make sure you setup Drupal to be able to serve files through Drupal via the Private file system (stream wrapper), instead of directly through the web server (public). Take a look at "/admin/config/media/file-system". You can read more about this on Drupal.org.

In any case you will need an extra access control module (and/or custom code). If you don't use Media and only use the Private files stream wrapper you will be able to shield files per role using the Content Access module.

If you want Media not only for access but also for the other nice features it brings think about this: it will not solve your file access issue out of the box. And the Content Access can't help you anymore because it really only works for nodes and not for File entities. Because Media depends on File Entity (separate module since version 2.x) you are no longer required to create node types for documents that need to be fieldable, this is nice. But currently there are no good contributed modules I know of that add granular access control to file entities. So you will need custom code to manage access. I could help you out in this case, but I guess it should be a separate question.

**Edit:**

I extracted a custom sample module from a project of mine which adds role based permissions to File Entities (untested), see: https://github.com/dmsmidt/drupal\_file\_entity\_access
> 1 votes

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


# Question
Title: How to fix rules which unable to evaluate action?
I have created two rules to act on some events related to commerce products.

**The first** is to act on reference node delete event, to remove the product upon node delete.

**the second** is to delete the node upon expiration event using node\_expire

When running the cron to make expired event to be happen no actions executed except if I disabled the first rule

I have tried rules **components** and **rule sets** as that two rules have conditions and actions in common But nothing changed.

**Edit**: I did some debugging and found that warning and error messages

> **\[warning\]**
>
> WD rules: Unable to load commerce\_product with id "102"
> WD rules: Unable to evaluate action entity\_fetch.
> WD rules: Unable to get variable entity\_fetched, it is not defined.
>
> **\[error\]**
>
> WD rules: Unable to evaluate action entity\_delete.

# Answer
> 1 votes
The error:

> WD rules: Unable to get variable X, it is not defined.

means that Rules can't load the variable X.

If you're using contributed modules, please check if your rules are in the right order and the configuration is right, otherwise check the module issue queue for possible bug issues.

If you're using custom modules, please make sure that these rule variables are passed in the correct way.

For example if you've the following sample rule in `hook_rules_action_info`:

```
'foo_rule' => array(
  'label' => t('Foo rule'),
  'provides' => array(
    'object_to_send' => array(
      'type' => 'data',
      'label' => t('Data Object to pass'),
    ),
  ),
),

```

The `object_to_send` needs to provide the matching array key, e.g.:

```
return array( 'object_to_send' => $object);

```

So the next rule in sequence will "see" that variable, so you can use it.

# Answer
> 0 votes
In your rule, scroll to the bottom, click "Settings" and give the first rule a higher weight than the second.

---
Tags: 7, commerce, rules
---


# Question
Title: Altered line item price not showing in shopping_cart block
I am using two rules. The first one works like that:

1. IF product-A1 is added to the cart (through the add to cart form) THEN also add product-A2 to the cart.

The second rule does
2. IF product-A2 is in cart together with product-A1 THEN set the price of product-A2 to zero.

The events I use for the second rule are:

```
Commerce Line item is viewed
Calculating the sell price of a product

```

When I click on the add to cart button with my cart empty, then both products are added to the cart as per the first rule. Also, the price of product-A2 displays as zero in the page I am returned (the product listing page from where I clicked the add to cart button), as per the second rule. However, the shopping\_cart block (and generally any shopping cart block) displays product-A2 with its original price. If I then refresh the page, or move to another page, eg the shopping cart form, the price becomes zero in those blocks as well.

In the above screenshot, both the shopping\_cart block (provided by the kickstart\_commerce\_product\_ui module) and the Shopping cart block (provided by the commerce/cart submodule) are set to display at the User Bar Second region of the default kickstart theme.

The product I added manually to the cart was "234234 - Download" (which displays as 234234 (PDF) in the cart block). The 234234 (HTML) product was added automatically as per the first rule above. As you can see, the price of the latter displays as zero in the product listing, yet in the shopping cart blocks it displays as 34.00€.

Here are the exports for the two rules: First rule:

```
{ "rules_add_html_variation_to_cart_if_pdf_version_is_added" : {
    "LABEL" : "Add Online view to cart too if Download is added",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "3",
    "OWNER" : "rules",
    "TAGS" : [ "Cart", "Online Giveaway" ],
    "REQUIRES" : [ "commerce_order", "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "IF" : [
      { "commerce_order_contains_product_type" : {
          "commerce_order" : [ "commerce_order" ],
          "product_type" : { "value" : { "book_product" : "book_product" } },
          "operator" : "\u003E=",
          "value" : "1"
        }
      },
      { "list_count_is" : {
          "list" : [ "commerce-line-item:order:commerce-line-items" ],
          "value" : [ "commerce-line-item:order:commerce-order-quantity" ]
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "current_line_item" : "Current line item" },
          "DO" : [
            { "component_rules_add_html_variation_to_cart" : { "line_item" : [ "current-line-item" ] } }
          ]
        }
      }
    ]
  }
}

```

Second rule:

```
{ "rules_set_hmtl_variation_price_to_zero_if_pdf_variation_also_in_" : {
    "LABEL" : "Set Online view variation price to zero if pdf variation also in cart",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Cart", "Online Giveaway" ],
    "REQUIRES" : [ "commerce_discount", "rules", "entity", "commerce_product_reference" ],
    "ON" : {
      "commerce_line_item_view" : [],
      "commerce_product_calculate_sell_price" : []
    },
    "IF" : [
      { "commerce_product_has_type" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "type" : "book_product"
        }
      },
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:commerce-product" ],
          "field" : "field_book_product_type"
        }
      },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-product:field-book-product-type" ],
          "value" : "HTML"
        }
      },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:commerce-product:field-product-node:0" ],
          "field" : "field_product"
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [
              "commerce-line-item:commerce-product:field-product-node:0:field-product"
            ]
          },
          "ITEM" : { "current_product_variation" : "Current product_variation" },
          "DO" : [
            { "component_rules_check_if_pdf_version_also_in_cart" : {
                "USING" : {
                  "order" : [ "commerce-line-item:order" ],
                  "pdf_product" : [ "current-product-variation" ]
                },
                "PROVIDE" : { "bool_pdf_included" : { "bool_pdf_included" : "Pdf is included" } }
              }
            },
            { "component_rules_set_html_variation_price_to_zero" : {
                "bool_proceed" : [ "bool-pdf-included" ],
                "online_view_html_item" : [ "commerce-line-item" ]
              }
            }
          ]
        }
      },
      { "data_set" : {
          "data" : [ "commerce-line-item:order:commerce-order-total:amount" ],
          "value" : [ "commerce-line-item:order:commerce-order-total:amount" ]
        }
      }
    ]
  }
}

```

And the "component\_rules\_set\_html\_variation\_price\_to\_zero":

```
{ "rules_set_html_variation_price_to_zero" : {
    "LABEL" : "(Bool) =\u003E {set_Line-Item_price_to_zero}",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "TAGS" : [ "Online Giveaway" ],
    "REQUIRES" : [ "rules", "commerce_line_item" ],
    "USES VARIABLES" : {
      "bool_proceed" : { "label" : "Proceed", "type" : "boolean" },
      "online_view_html_item" : { "label" : "Online view line item", "type" : "commerce_line_item" }
    },
    "IF" : [ { "data_is" : { "data" : [ "bool-proceed" ], "value" : "1" } } ],
    "DO" : [
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "online-view-html-item" ],
          "amount" : "0",
          "component_name" : "base_price",
          "round_mode" : "0"
        }
      }
    ]
  }
}

```

Am I doing sth wrong? Is there a workaround to this? I originally posted this in drupal.org.

EDIT:

I did a clean install of drupal commerce and imported my rules. The only thing that I had to change to make them work on the clean kickstart installation was to add a select field named field\_law\_product\_type (with options "HTML" and "PDF") to an existing product type (I chose Bags & Cases) and change the two rules to check for this product type instead. I also disabled the *commerce\_add\_to\_cart\_confirmation* module that comes with kickstart. I also added an action to the second rule to display some system message for debugging.

Now, this is really weird. I did some testing and I added the "Download|PDF" variation to the cart through the product's page. After clicking the add to cart button, the product page was reloaded (and as per the 1st rule, the "Online|HTML" variation was added to the cart as well). The cart block showed the two added products, again with the wrong price for the HTML variation. However, the system message used for debugging did not show! Meaning that the rule did not run at all. The events I used to try and trigger the rule were:

```
Calculating the sell price of a product

Commerce Line item is viewed

```

Shouldn't at least the first one ("Calculating the sell price of a product") fire while building the cart block in any of the two views provided by kickstart? If I refresh the page it sure does, since the HTML variation is shown with a zero price!

# Answer
> 1 votes
What's your rule component for checking if the PDF has been added to the cart? Are you sure that the data is getting set properly? You can use the Display a system message to ensure that the data values are getting set.

Rules is a bit picky when it comes to passing data between the various components. If you take a look at my answer here: Exclude Items from Flat Rate Shipping Calculation you'll see that I'm actually not using the dual purpose variables, but instead setting new values.

Also, this is unnecessary as it will get reset during the next order refresh anyway:

```
  { "data_set" : {
      "data" : [ "commerce-line-item:order:commerce-order-total:amount" ],
      "value" : [ "commerce-line-item:order:commerce-order-total:amount" ]
    }
  }

```

---
Tags: commerce
---


# Question
Title: Execute Javascript when the registration form is completed
I am running Facebook advertising campaign for my site. The below code needs to be executed when registration is completed. How can I achieve this?

```
<script>
// Track when a registration form is completed (ex. complete subscription, sign up for a service)
fbq('track', 'CompleteRegistration');
</script>

```

# Answer
You need to add callback for the form submission. Something like this

```
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#form_id'] == 'your_form_id') {
    $form['#submit'][] = 'custom_callback';
  }
}

function custom_callback() {
  drupal_set_message('This is my custom message');
}

```

Now, after the form submission, the `custom_callback` will also be executed.

If the code is Javascript and the form submission is via Ajax, you may have a look at the Ajax framework and Ajax framework commands topics in the API documentation. How to execute custom javascript code after an ajax succes (using the Drupal Ajax framework) ? is another useful page/
> 1 votes

# Answer
You can redirect user on specific page after registration and this js-code should be inserted on this page.
> 0 votes

---
Tags: users, social-network
---


# Question
Title: Delete all nodes of a user using flags and rules
I want to delete all nodes for a user whoes any one node has been flagged as spam.

**For example:**

If user has created 3 nodes of same/different content types, then If admin flag any one content as **spam**, then all the 3 nodes should get deleted and the user should get blocked.

I am able to block the user and delete the flagged node but not the other 2 nodes. I want to delete all nodes associated to that user.

Please help.

# Answer
> 2 votes
I did in this way without writing a single line of code.

1) **Add action**: Fetch entity by property: Choose *Entity type* as '**Node**', *Property* as '**Author**' and *Data selector* as '**flagged-node:author**'. Choose variable label ('**spam nodes**' in my case) and variable name ('**spam\_nodes**' in my case) as you wish.

2) **Add Loop**: Select *Data selector* as '**spam-nodes**' (this will show as per your variable label in step 1). Set variable label('**spam node**' in my case) and variable name('**spam\_item**' in my case) as you wish.

3) Now click on '**Add action**' link under '**Operations**' column against the *loop* you have added in step 2. Select '**Delete Entity**' and set the *Data selector* as '**spam-item**' (this will show as per your variable label in step 2).

---
Tags: 7, rules, flags, advertising
---


# Question
Title: How to add Organic Groups after Site has been created
My site allows people from a certain class to upload their pictures on the website. It has various content types and views made but and I would like to install the Organic Groups module to allow multiple classes from my school to upload images. Can I do that now or do I need to re-create the site from scratch?

# Answer
> 1 votes
It should not be necessary to re-create the whole site from scratch. After installing Organic Groups, you can mark an existing content type as "Group Content" if you want the nodes of that type to belong to a group:

* Go to `admin/structure/types`.
* Click on the "Edit" link next to the type you want to modify.
* In the `Organic groups` tab, check the `Group content` checkbox. It will create a `Groups audience` field in your content type.

After that, you will need to assign each node to the appropriate group, in the `Groups audience` field.

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


# Question
Title: JS script in theme is ignored for anonymous users
It just discovered that my script.js in my theme is ignored for anonymous users. But only on certain pages. When logged in everything works on all pages. When logged out things only work in some content nodes. For example I have a navigation menu outside of the system menu. It's an exposed block from a view, that I use as a navigation menu to mirror the taxonomy (the taxonomy module does not work for me). I use the theme's script.js to collaps and expand menu items as appropriate. But this is ignored when logged out on most pages (but as I said it works when visiting some content nodes). What is this?

I also discovered that flexslider doesn't wok when logged out. But it works in content nodes... I must be missing something.

I have tried adding:

```
drupal_add_library('system', 'jquery', 'ui.sortable', 'ui', 'drupal.collapse');

```

... in my template.php (in template\_process\_page, and I also tried to add it in template\_preprocess\_html). In the Firebug "Net" tab I can see that my script,js is loaded together with jquery and a whole bunch of js files. So if everything is loaded, why is it ignored on certain pages when logged out? Any ideas?

Edited... I also have tried to add break points in my script.js file and it is clear that the script is ignored all together on certain pages.

# Answer
Worked it out! I post an answer myself in case anyone else has the same issue. Hopes it helps somebody.

I had to add the jquery.cookie library in my template.php

```
drupal_add_library('system','jquery.cookie');

```

And it seems you were right to add only one library at a time, Namari, it didn't work until I tried that. Thanks!
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: Ajax form in preprocess_node never triggers
In a `preprocess_node` hook, I try to insert a Drupal node\_form form in my page. I do it with this function:

```
function my_module_get_edit_form($selection) {
  drupal_add_library('system', 'drupal.ajax');
  drupal_add_library('system', 'drupal.form');
  $form = drupal_get_form('selection_node_form', $selection);

  //here some code to disable (#access = FALSE) unwanted fields and options

  $form['actions']['submit'] = array(
    '#type' => 'button',
    '#value' => 'Update',
    '#limit_validation_errors' => array(),
    '#ajax' => array(
      'callback' => 'smll_selection_ajax_callback',
      'wrapper' => 'selection_form'
    ),
  );

  return drupal_render($form);
}

```

The form is rendered properly but when I click my submit button, it always submits the form and forwards me to the node's page, no ajax call.

I tried adding #ajax array onto a select field in the same form (`$form['field_application_type']['und']['#ajax']`) but nothing is triggered when I change the select's value. No HTTP request, no Javascript error, nothing.

I tried using `drupal_build_form` with a manufactured `$form_state`.

I tried creating my form in an another function and calling it with `drupal_build_form`.

I tried setting `#ajax_processed` to `TRUE`.

The HTML id `selection_form` exists but, anyway, I never come to the moment the callback function is called.

# Answer
> 0 votes
You don't use the correct function for that;

```
function MYMODULE_form_alter(&$form, &form_state, $form_id) {
  if($form_id == 'selection_node_form' //and same condition you call your function){
    //do your changes here
  }
}

```

Or use `drupal_retrieve_form` then you can override the form.
The drupal\_get\_form call the function drupal\_build\_form which build the form, you can't override it that way.

---
Tags: 7, forms, ajax
---


# Question
Title: How can I use Migrate Extras to get custom media fields to migrate?
I'm a bit at the end of my rope in trying to get file fields to show up as possible destinations for my Media module migration. I have Media 7.1.x installed because as best I can tell, that must be the version that Migrate Extras was supporting. I'm trying to import files into the Other file type, so I have the following:

```
$this->destination = new MigrateDestinationMedia('other');
$this->map = new MigrateSQLMap($this->machineName,
      array(
        'id' => array(
          'type'        => 'int',
          'length'      => 11,
          'not null'    => TRUE,
          'description' => 'File ID',
          'alias'       => 'f',
        ),
      ),
      MigrateDestinationMedia::getKeySchema()
    );

```

Unfortunately I cannot get the field I added to the Other file type to show up as an available destination field in Migrate UI. Any help on what I'm doing wrong here, or even a code snippet where someone has successfully done a media migration (for files, not youtube or anything fancy like that), would be greatly appreciated!

**Update:** I'm most of the way there, but my fields still aren't coming in. Here is the array I created:

I create a $row-\>fields\_array that looks like:

```
[fields_array] => Array
    (
        [0] => Array
            (
                [field_doc_public] => 1
                [field_testing_testing_testing] => UE2_3009.pdf
            )

        [1] => Array
            (
                [field_doc_public] => 0
                [field_testing_testing_testing] => UE2_3009.doc
            )

    )

```

I really only need the field\_doc\_public field to be filled in, but I added field\_testing\_testing\_testing to test as you might guess from the name. The field machine names are `field_doc_public` and `field_testing_testing_testing`.

The code in the actual migration looks like:

```
    $this->addFieldMapping('field_doc_pub_files', 'file_source_file');
    $this->addFieldMapping('field_doc_pub_files:file_class')
        ->defaultValue('MigrateEntityFileUri');
    $this->addFieldMapping('field_doc_pub_files:fields', 'fields_array')
        ->description(t('Populate the fields.'));
    $this->addFieldMapping('field_doc_pub_files:destination_dir')
        ->defaultValue('private://pub_docs');
    $this->addFieldMapping('field_doc_pub_files:destination_file', 'file_dest_filename');
    $this->addFieldMapping('field_doc_pub_files:file_replace')
        ->defaultValue(MigrateFileBase::FILE_EXISTS_REUSE);
    $this->addFieldMapping('field_doc_pub_files:preserve_files')
        ->defaultValue(FALSE);
    $this->addFieldMapping('field_doc_pub_files:display', file_public);

```

Any help on that last little push over the finish line would be greatly appreciated. (Note: no destination for the fields shows up in Migrate UI either)

# Answer
The following will allow you to use Migrate to import files as File Entities (used for Media 2.x) and populate the File Entity fields when importing Nodes (MigrateDestinationNode). No Migrate Extras needed.

Add the following to your custom migrate module's .info file:

```
files[] = includes/MigrateEntityFileUri.inc

```

Download/save the following code in an "includes" subfolder of your migrate module. (Strip the .php extension) https://gist.github.com/dmsmidt/6f0f498a9dbaea8602fb

Then in your Migration class you can use 'MigrateEntityFileUri' as file\_class.

Example code:

```
$this->addFieldMapping('field_media', 'your_file_uri_source_array');
$this->addFieldMapping('field_media:file_class')
  ->defaultValue('MigrateEntityFileUri');
$this->addFieldMapping('field_media:fields', 'fields_array')
  ->description(t('Populate the fields.'));
$this->addFieldMapping('field_media:destination_dir')
  ->defaultValue('public://your_file_sub_dir');
$this->addFieldMapping('field_media:file_replace')
  ->defaultValue(MigrateFileBase::FILE_EXISTS_REUSE);
$this->addFieldMapping('field_media:preserve_files')
  ->defaultValue(TRUE);

```

Note the sources: 'your\_file\_uri\_source\_array' and 'fields\_array'. You may need to do some processing in prepareRow() depending on your source to get your data organized like this (pseudocode):

```
public function prepareRow($row) {
    $row->fields_array = array(
      array(
        'field_one' => 'value_field_file_one',
        'field_two' => 'value_field_file_one'
      ),
      array(
        'field_one' => 'value_field_file_two',
        'field_two' => 'value_field_file_two'
      ),
    );
    $row->your_file_uri_source_array = array('file_one_uri', 'file_two_uri');
  }

```
> 2 votes

---
Tags: migrations, media
---


# Question
Title: Toolbar to insert HTML tags while editing content
This very site features a neat toolbar just over the textareas in forms, where clicking on "B", for instance, will spawn `**strong text**`, abstracting away the need to know Markdown.

Is there a way to do the exact same thing with, for instance, filtered HTML, or another text format based on HTML, on my Drupal site? I find that WYSIWYG editors tend to bloat the actual code and I want my users to get used to seeing HTML tags, but for the moment they can't be bothered with typing the markup in themselves.

# Answer
> 1 votes
After asking on `#drupal` on `irc.freenode.org`, I was looking for the BUEditor module that does just that, specifically looking at its native support for HTML tags:

Screenshot (using BBCode)

# Answer
> 0 votes
It looks like it may be using "Markdown" filters.

https://www.drupal.org/project/markdown

More info:

http://cms.about.com/od/drupal-modules/a/Write-Faster-In-Drupal-With-The-Markdown-Module.htm

---
Tags: input-formats
---


# Question
Title: Is there a theme equivalent of hook_install()?
I want my theme to control certain block settings, like which elements of the system branding block are enabled. To me it makes sense for that to be code in the theme, not a module, because at the moment the only way I've found to access the config programmatically involves using the theme name.

```
/** @var Drupal\Core\Config\Config $config */
$config = \Drupal::service('config.factory')->getEditable('block.block.my_theme_branding');
$config->set('settings.use_site_logo', false);
$config->save();

```

Since this is a one off config change, I think it should only happen when the theme is installed/activated. It there a theme function/hook that behaves like `hook_install` does for modules?

# Answer
> 3 votes
You may provide configuration via YAML files as part of a module, profile or theme install by adding them to the `config/install` directory inside the respective project. So, for example, a file `block.block.my_theme_branding.yml` would install the branding block into the specified region. This would then contain the setting to disable the site slogan by default. Take a look at block.block.bartik\_branding.yml in the standard profile as a starting point.

If the specific block is provided by another module, then it should probably be placed in the `config/optional` directory.

# Answer
> 0 votes
That was a missing feature; however, after a conversation in IRC that is a feature that we want to implemented. Its currently been working at Add (back) hook\_install for themes.

The solution from @mradcliffe have a lot limitation, because you cant override a anything unless you are a profile.

---
Tags: 8
---


# Question
Title: Managed file input is removing input values of appended input fields by ajax
I have a form with checkboxes that are calling ajax callback on checked. This ajax callback is appending another inputs:

```
$form['expertise']['op-cat-'.$op_cat['id']]['op-'.$op['id']]['checked'] = array(
    '#type' => 'checkbox',
    '#title' => $op['name'],
    '#default_value' => isset($usr['user_scope']['tid'][$op['id']]) ? 1 : 0,
    '#ajax' => array(
        'callback' => 'activit_full_profile_expertise_ajax',
        'wrapper' => 'expertise-div',
    )
);

```

Ajax callback:

```
function activit_full_profile_expertise_ajax($form, &$state) {

    $commands = array();
    $commands[] = ajax_command_html('#expertise-div', render($form['expertise']));
    $commands[] = array('command' => 'reinitializeTooltipster');
    return array('#type' => 'ajax', '#commands' => $commands);

}

```

In form is also an another managed file input:

```
$form['image'] = array(
    '#type' => 'managed_file',
    '#title' => t('Profilová fotografia <span>(nepovinné)</span>'),
    '#default_value' => isset($usr['picture']->fid) ? $usr['picture']->fid : 0,
    '#upload_validators' => array('file_validate_extensions' => array('gif png jpg jpeg')),
    '#upload_location' => 'public://user_images/'
);

```

Everything works fine if image field is not used after checkbox. If checkbox is used before image upload, it brings another input fields, but they are not present in `$state['values']` in form validate & submit function (only original checkbox is present). They are not present in validate & submit function called by ajax of this image upload input, therefore they are not present in final validate & submit functions on form submit.

I have another custom ajax callbacks in form, but the appended input values are allways present. Is this a Drupal bug or am I missing something?

# Answer
I'm not sure if this is a good solution, but now I'm taking values from `$state['input']` instead of `$state['values']`.
> 0 votes

---
Tags: ajax, forms, files
---


# Question
Title: The correct way to include jquery in a module's form
I'm trying to use jquery in a form of mine that is rendered via the form api.

How i'm getting jquery to work now is like so

```
$form['raf_raffle_name'] = array(
    '#type' => "textfield",
    "#prefix" => "<h5>Raffle information</h5><hr>",
    "#title" => "Raffle Name:",
    "#required" => TRUE,
    "#attached" => array(
        'js' => array(
            "$path/jquery.js", "$path/test1.js"
        ),
    )
);

```

well it works, but i'm not sure if its the right way. Is there a better way? I'm inclined to ask after i saw the 'library' attribute which is supposed to load up certain javascript plugins.

# Answer
> 2 votes
You should not have to manually include jQuery:

"When JavaScript is added to a page through Drupal, jQuery is automatically added to the page."

-- https://www.drupal.org/node/171213

---
Tags: 7, forms, javascript
---


# Question
Title: How do I create or modify a custom filter?
I'm following the docs here to create a custom filter.

The first sentence says:

> Go to Custom Filters (/admin/settings/customfilter) (6.x & 7.x)

However, that link just redirects me to the overall admin menu page (looks the same as if I go to /admin). What am I doing wrong?

# Answer
> 1 votes
Did you install the Custom Filters module? (https://www.drupal.org/project/customfilter)

Works fine for me after I install the module.

# Answer
> 0 votes
The correct path for Drupal 7 (there isn't any difference between version 7.x-1 or 7.x-2 of the module) is admin/config/content/customfilter; that is what the module uses as path for its setting pages, in `hook_menu()`.

```
  $access = array('administer customfilter');
  $items = array();

  $items['admin/config/content/customfilter'] = array(
    'title' => 'Custom filters',
    'description' => 'Allow the users to define custom filters.',
    'page callback' => 'customfilter_settings',
    'access arguments' => $access,
  );

  $items['admin/config/content/customfilter/list'] = array(
    'title' => 'Filters',
    'access arguments' => $access,
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -1,
  );

  $items['admin/config/content/customfilter/add'] = array(
    'title' => 'Add filter',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('customfilter_filter_add'),
    'access arguments' => $access,
    'type' => MENU_LOCAL_TASK,
  );

```

---
Tags: 7, input-formats
---


# Question
Title: Uploading image to a node via Angular to Drupal 8 using REST
I have figured out how to upload files from Angular to Drupal 8

```
......
submitCommunity: function(params) {
  var package = {
    "_links":{"type":{"href":"http://dang.dev:8888/rest/type/file/file"}},
    "filename":[{"value":Math.round((Math.random()*1000)).toString() + '.jpg'}],
    "filemime":[{"value":"image/jpeg"}],
    "data":[{"value":params.bannerImage}] //params.bannerImage = B64 encoded string of the image
  };
  $http.post('http://dang.dev:8888/entity/file', package, config).then(function(response) {
    var fileId = response.headers().id; // the file ID of the newly created file entity.
  });
},
......

```

My question is, what if I have a content type that has an image field in it? Specifically, my content type is of type `community` and contains a field called `field_banner_image`. Below is what I have now, however, it produces `422 Unprocessable entity` with a response of:

`{"error":"Unprocessable Entity: validation failed. field_banner_image: This value should not be null."}`

`field_banner_image` is required hence the error, but I have no idea what `field_banner_image` expects me to send it.

```
.....
submitCommunity: function(params) {
  var package = {
    "_links":{"type":{"href":"http://dang.dev:8888/rest/type/file/file"}},
    "filename":[{"value":Math.round((Math.random()*1000)).toString() + '.jpg'}],
    "filemime":[{"value":"image/jpeg"}],
    "data":[{"value":params.bannerImage}] //params.bannerImage = B64 encoded string of the image
  };
  $http.post('http://dang.dev:8888/entity/file', package, config).then(function(response) {
    var fileId = response.headers().id;
    package = {
      _links: {'type':{'href':'http://dang.dev:8888/rest/type/node/community'}},
      type: [{'target_id': 'community'}],
      title: [{'value': params.title}],
      body: [{'value': params.body}],
      field_banner_image:[{'value': fileId}]
    }
    return $http.post('http://dang.dev:8888/entity/node?_format=hal_json', package, config);
  });
},
.....

```

I've tried `field_banner_image:[{'fid': fileId}]` and some other combos of key values, but I think I am attacking this wrong. Documentation on this is kind of sparse right now and a lot of it is old D8 beta stuff. Any Ideas?

# Answer
> 3 votes
ImageItem and FileItem are represented as entity references. The ImageItem has the following schema: `target_id`, `alt`, `title`, `width`, and `height`.

Only the `target_id` column is a required property, which can be seen through ImageItem::propertyDefinitions \> FileItem::propertyDefinitions \> FieldReferenceItem::propertyDefinitions parent method.

The field should be represented similar to the `type` property, which also is an entity reference.

# Answer
> 1 votes
Aha, I figured it out! I ended up finding the answer within views. One of my views was exporting the data as Fields. I switched it back to entity (default display when using rest) and I noticed `field_banner_image` had a list of fields associated with it. Specifically:

```
"field_banner_image":[{
  "target_id":"72",
  "alt":"",
  "title":"",
  "width":"1740",
  "height":"860",
  "url":"http:\/\/dang.dev:8888\/drupal\/sites\/default\/files\/2016-01\/4-ThePiedmont_1740x860_72.jpg"
}]

```

Passing the `target_id` was the ticket!

---
Tags: 8, javascript
---


# Question
Title: Conditional patterns with automatic nodetitles
I\`m using automatic nodetitles module to hide and autogenerate the title of one of my content types. My question is:

Is it possible to use conditional rules to define which pattern to be used when certain conditions is met? I need the pattern to be X if a certain field in the node is present, another if not.

Thanks,

# Answer
> 1 votes
That module also provides the ability to use PHP to construct the pattern. Look for the check box at the bottom.

Please refer to the module's help file for more info on combining PHP and tokens for the pattern.

---
Tags: nodes, entities
---