# Question
Title: How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?
What I try to achieve with Rules:

After saving a new comment, this comment has to be sent only to those users who've checked a corresponding boolean box on their profile page.

Any suggestions?

# Answer
Assuming your question is about D7, there are basically 2 ways (options) to answer your question, as further detailed below.

# Option 1: Use Rules and Views Bulk Operations

You could create a view (using the Views module) of those users that you want to send an eMail to.

After you succeeded in creating such view, you can ***process the results of a VBO enabled view via Rules***, using a rule that looks like so:

* Rules Event: After saving a new comment.
* Rules Actions:
    + Load the VBO list of the users in your View.
    + Add a loop to perform a Rules Action "Send an eMail", for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

# Option 2: Use Rules and Views Rules

### a) About this module

The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

> ... provides two types of elements in Rules, configured with a "Rules" view display:
>
> * **Views loop**: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.
> * **Collect view result rows (action)**: This action collects each variable in all view result rows into list variables for use in Rules.
>
> ***Tip***: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

### b) Create a view of display type 'Rules'

After you enable the Views Rules module, you can use Views to create a view of those users that you want to send an eMail to. Add of view of display type ***`Rules`*** (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

You probably want to use one or more of the variables similar to those that are shown in this screenprint:

### c) Create a rule using the view of display type 'Rules'

Create a rule that looks like so:

* Rules Event: After saving a new comment.
* Rules Actions:
    + Use the link that says `Add view loop` to add a Views loop, and select the "Rules" display created in the previous step.
    + Configure the parameters and variable names.
    + For each user contained in your Views loop, perform a Rules Action "Send an eMail", using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed). If you created the *Rules row variables* as suggested in the previous step, your actual eMail can use tokens such as `[usermail:value]`, `[username:value]`, etc.
> 2 votes

---
Tags: users, rules, emails
---


# Question
Title: how to remove all slashes from all path aliases
After I import data to my site, the url aliases have `/` at the end, when I visit that Url alias I faced with `page not found`, I tried to edit one of them manually and when I removed the slash from end I could see that node correctly, my question is how can I remove all slashes `/` from all aliases ?

# Answer
> 0 votes
one solution is using `Views Bulk Operation`, create a view and with using `run arbitrary Php option` in VBO try to remove all `/` from aliases,

something like ( I didn't test this )

```
  $entity->path['alias'] = rtrim($entity->path['alias'] ,'/');

```

and another and faster solution is using MYSQL TRIM in order to update in database go to phpadmin my admin ( or mysql command line ) and run below command

```
 UPDATE `url_alias` SET `alias`= TRIM(TRAILING '/' FROM `alias` )

```

---
Tags: 7, path-aliases
---


# Question
Title: How to add another entity type to Search API multiple types index?
I created a multiple types index using Search API. Now I would like to add another entity type to it, but it's not possible. Is there any solution? I really would like to avoid recreating the index.

# Answer
> 0 votes
Not a proper answer, more like a workaround:

1. Load index.
2. Delete it.
3. Mark it as new.
4. Change the datasource settings.
5. Save it again.

Source: https://www.drupal.org/node/2632880#comment-11208443

---
Tags: 7, search
---


# Question
Title: How do I make my service dependent on another module existing?
I want to provide a service in my module, but only if another module (say the core File module) is enabled. I don't want to require this module, it should be optional.

Something like this:

```
services:
  helper.file:
    class: Drupal\helper\File
    arguments: ['@entity_type.manager']
    requirements: ['file']

```

Is there a way to do this without needing to declare it as a dynamic service? If not, is there an example on how to declare a dynamic service, because https://www.drupal.org/node/2026959 is woefully lacking:

> Finally, it is also possible to define the register() method to register services dynamically, however this should be very rare.

# Answer
> 5 votes
Yep, you need a ServiceProvider that only registers the service if the module exists in the container.modules parameter

See https://github.com/md-systems/file\_entity/blob/8.x-2.x/src/FileEntityServiceProvider.php#L25 for an example

# Answer
> 1 votes
Drupal core itself uses `register()`, in one of its modules. See `LanguageServiceProvider::register()`.

```
  // The following services are needed only on multilingual sites.
  if ($this->isMultilingual()) {
    $container->register('language_request_subscriber', 'Drupal\language\EventSubscriber\LanguageRequestSubscriber')
      ->addTag('event_subscriber')
      ->addArgument(new Reference('language_manager'))
      ->addArgument(new Reference('language_negotiator'))
      ->addArgument(new Reference('string_translation'))
      ->addArgument(new Reference('current_user'));

    $container->register('path_processor_language', 'Drupal\language\HttpKernel\PathProcessorLanguage')
      ->addTag('path_processor_inbound', array('priority' => 300))
      ->addTag('path_processor_outbound', array('priority' => 100))
      ->addArgument(new Reference('config.factory'))
      ->addArgument(new Reference('language_manager'))
      ->addArgument(new Reference('language_negotiator'))
      ->addArgument(new Reference('current_user'))
      ->addArgument(new Reference('language.config_subscriber'))
      ->addMethodCall('initConfigSubscriber');
  }

```

The code is quite similar to the code you would use: It checks a condition is verified at run-time, and then adds the necessary services. In this case, the alternative would be having two services that check if the site is multi-lingual and do nothing in the case it is not.

I take the note you quoted as meaning *don't implement the `register()` method if there are other alternative implementations for what you are trying to achieve.* In your case, the alternative would be checking from the service if the other module is installed, which is what the service implemented by the Drupal core module tries to avoid, or making your module dependent from the other module, which is what I would avoid, since (from what I understand) the module is not dependent from the other one, and it would work even without it being installed.

---
Tags: 8
---


# Question
Title: Continually adding fields to a form each time a button is pressed using AJAX
I'm attempting to add fields dynamically to a form using AJAX in a block plugin however no action occurs when clicking on the button that is meant to add a field. The code I'm currently is below

```
   class Standard extends BlockBase {
    public function blockForm($form, FormStateInterface $form_state) {
        $form_state->setCached(FALSE);
        $form['actions'] = array(
            '#type' => 'actions',
        );
        $form['column']['columnNum'] = array(
            '#type'          => 'value',
            '#default_value' => $this->configuration['columns_submit'],
        );

        $form['column_wrapper'] = array(
            '#type'       => 'container',
            '#attributes' => array(
                'id'         => 'column_wrapper',
            ),
        );
        for ($i = 1; $i <= $this->configuration['columns_submit']; $i += 1) {
            $form['column'][$i] = array(
                '#type'           => 'details',
                '#title'          => t('Column '.$i),
                '#open'           => FALSE,
                'group'           => 'Content',
                'body_text'       => array(
                    '#type'          => 'text_format',
                    '#title'         => $this->t('Body'),
                    '#default_value' => $this->configuration['column'][$i]['body_text_submit']['value'],
                ),
                'class'           => array(
                    '#type'          => 'textfield',
                    '#title'         => $this->t('Class'),
                    '#default_value' => $this->configuration['column'][$i]['class_submit'],
                ),

            );
        }
        $form['addcolumn'] = array(
            '#type'     => 'button',
            '#name'     => 'Add Column',
            '#value'    => t('Add column'),
            '#submit'   => array($this, 'addColumnSubmit'),
            '#ajax'     => array(
                'callback' => [$this, 'addColumnCallback'],
                'effect'   => 'fade',
                'wrapper'  => 'column_wrapper',
            ),
        );
        return $form;
    }
    public function addColumnSubmit(array&$form, FormStateInterface $form_state) {
        $this->configuration['columns_submit'] += 1;
        $form_state->setRebuild(TRUE);
    }
    public function addColumnCallback(array&$form, FormStateInterface $form_state) {

        return $form['column'];
    }

```

Nothing occurs when clicking the $form\['addcolumn'\] button. I've based my attempts on examples such as this one https://www.drupal.org/node/2723033. (I understand that is an example of it not working, but based on the comments it seemed like an error that was easily fixed) I'd like to be able to continually add fields each time the button is pressed. Is there something wrong with my code? Is there a proper way to continually add fields when a button is pressed to a form using AJAX?

---

Update: I made another attempt which failed as well.

I used

```
    if (empty($form_state->getValue('columnNum'))) {
        $form_state->setValue('columnNum', 1);
    }
    $columnNum = $form_state->getValue('columnNum');

```

in BlockForm()

and

```
    $numColumns = $form_state->getValue('numColumns');
    $numColumns += 1;
    $form_state->setValue('numColumns', $numColumns);
    $form_state->setRebuild(TRUE);

```

in addColumnSubmit()

# Answer
Assuming all your logic for $form\[‘column’\]\[$i\] is correct, you can try replacing '#attributes'

```
$form['column_wrapper'] = array(
        '#type'       => 'container',
        '#attributes' => array(
            'id'         => 'column_wrapper',
        ),
    );

```

With '#prefix' and '#suffix'

```
$form['column_wrapper'] = array(
        '#type'       => 'container',
        '#prefix' => '<div id="column_wrapper">',
        '#suffix' => '</div>',
    );

```

And then in the callback get the values from the complete form.

```
public function addColumnCallback(array $form, FormStateInterface &$form_state) {
    $form = $form_state->getCompleteForm();
    return $form['column'];
}

```

I had a similar problem, Ajax does rebuild the form, but using “old” values, so after the $form\[‘column’\]\[$i\] is completed and calculated, Ajax then just overrides it with the previous $form\[‘column’\]\[$i\]. If that makes sense.
> 0 votes

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


# Question
Title: Can I use Views query in my custom code or not?
Through views I am getting result perfectly in update preview. But when I use the same query in my custom code, its not working as expected. Do I need to do any modification in code or do I need to do any configuration in views so that I can get a query which should be executed through code also. Any help will be appreciated. For example code is here:

```
SELECT node.nid AS nid,
   node_uc_product_kits.nid AS node_uc_product_kits_nid,
   node_uc_product_kits.language AS node_uc_product_kits_language
 FROM node node
 LEFT JOIN uc_product_kits uc_product_kits ON node.nid = uc_product_kits.product_id
 LEFT JOIN node node_uc_product_kits ON uc_product_kits.nid = node_uc_product_kits.nid
 WHERE (node_uc_product_kits.status = 1) AND (node.nid = 1 )

```

In code:

```
$ord_weight = db_result(db_query("SELECT node.nid AS nid,
   node_uc_product_kits.nid AS node_uc_product_kits_nid,
   node_uc_product_kits.language AS node_uc_product_kits_language
 FROM node node
 LEFT JOIN uc_product_kits uc_product_kits ON node.nid = uc_product_kits.product_id
 LEFT JOIN node node_uc_product_kits ON uc_product_kits.nid = node_uc_product_kits.nid
 WHERE (node_uc_product_kits.status = 1) AND (node.nid = 1 )"));
print_r ($ord_weight->num_rows);

```

# Answer
> 0 votes
Long story shory, if you run the same query that the views module runs, you will get the same result.

If you are getting a different result this means that you

1. Don't run the same query (where do you get the views query from)
2. Don't provide the same dynamic variables if any is used

You should also note that Views has it's own magic variables in views, that only works in views, like `****CURRENT_LANGUAGE****` which maps to the current language.

You should also note that views does a lot of work in the theme layer to output data. Getting the same data from SQL doesn't mean that the actual output will be the same.

---
Tags: 7, database, views
---


# Question
Title: How do I render two links with a pipeline as separator?
How do I render two links with a pipeline as separator? For example, `$edit` and `$action` are links generated using `\Drupal::l()`. Then, I edited them with the following code.

```
if ($edit) {
  $action =  $edit . ' | ' .  $action;
}
else {
 $action = $action;
}

$action  = $action . "<span class = 'loader'></span>";`

```

Instead of links, the page is displaying HTML markup as plain text, but no links.

```
<a href="/en/node/51357/edit?ser=383&rel=49064&env=1&destination=group/39/">Edit</a> | <a href="/archive/" class="archive_deployedRelease" nid="51357">Archive</a><span class = 'loader'></span>

```

Can anyone suggest me how to achieve this?

# Answer
What you see as displayed HTML is escaped by Twig. Only safe markup is not escaped.

`l()` produces safe markup, but if you add something to it, the complete string becomes unsafe.

You can use an inline template to get around this problem.

```
if ($edit) {
  $action = [
    '#type' => 'inline_template',
    '#template' => '{{ edit }} | {{ action }}<span class = 'loader'></span>',
    '#context' => [
      'edit' => $edit,
      'action' => $action,
    ],
  ];
}

```
> 1 votes

---
Tags: navigation
---


# Question
Title: How ajax open a link of node in custom region?
Please help someone who knows how to deal with this. I'm not the first day trying to realize this. But unfortunately nothing sensible on the subject on the Internet is not found.

By default in drupal when you link (example, http://site.domain/node/7) to page content of material is loading on a full page. I need to make so that when you click on link (example, http://site.domain/node/7) first is loading the front page and then over it ajax loading content of material (/node/7) in custom region. How it can be best implemented? I would be grateful for tips. I create regions in theme and them work well.

# Answer
> 0 votes
I don't have much time to write the example code for you at this moment, please try to digest the steps below. Let me know if you find some points which you don't understand.

1. Duplicate a new ajax endpoint (e.g. ajax/node/%node`) for`node/%node`in`hook\_menu\`.
2. Alter the menu item 'node/%node' with custom page callback.
3. In the custom page callback, load front page content.
4. Load a custom JS file in the page callback.
5. In block admin, move a empty block to the desire region.
6. In the custom JS file, use `l_ajax()` to load the content `ajax/node/%node` to the target DIV.

---
Tags: 7, navigation
---


# Question
Title: Warning: array_flip(): Can only flip STRING and INTEGER values!
I have a custom module that hooks into a commerce extension module.

The function splits a payment for a product and splits it to beneficiaries who helped create the product.

I use user\_referance module in a field collection field in the product content type to store the beneficiary users from the system. The drupal system log shows this when running through the function

```
Warning: array_flip(): Can only flip STRING and INTEGER values! in      EntityAPIController->load() (line 219 of /www/opigno/profiles/opigno_lms/modules/contrib/entity/includes/entity.controller.inc).

```

Drupals error back trace function showed the error came from this line

```
  if (!empty($item_id)){
      $split_pay = commerce_funds_object_to_array(entity_load('field_collection_item',
array($item_id)));
  }

```

The function does run through fine but I'd like to squash any bugs that are appearing, the `$item_id` array only contains the `user_ids` of beneficiary users so i don't really understand why a non integer value is being passed

# Answer
> 2 votes
I had a similar issue, you just have to be sure it is an integer and not a string, also you can use entity\_load\_single:

```
if (!empty($item_id)){
$item_id = (int) $item_id;
  $split_pay = commerce_funds_object_to_array(entity_load_single('field_collection_item', $item_id));
}

```

# Answer
> 0 votes
If your `$item_id` is already array as you've mentioned:

> $item\_id = {array}\[2\] 0 = "12" 1 = "14"

then you don't need to wrap it again into array.

Use it directly, like:

```
entity_load('field_collection_item', $item_id);

```

as per @Mołot suggestion, or just make sure it's in the right expected format.

See: `entity_load()` API:

> $ids: An array of entity IDs, or FALSE to load all entities.

---
Tags: 7, commerce, entities
---


# Question
Title: Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet()
I tried a lot to get this warning solved, but end up with nothing. Can anyone look into this warning issue.

```
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 175 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 175 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 388 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 175 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 388 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 175 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 388 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 175 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 388 of /var/www/html/std-build/httpdocs/includes/entity.inc).

```

# Answer
This patch is work for me. Try this out
> 1 votes

# Answer
This is related mostly to the issue in your code or bug in the module which you're using.

Basically you should validate your DrupalEntityControllerInterface implementation, and you should not patch your Drupal core as suggested by @vgoradiya since it's not a bug in Drupal core.

> Consensus seems to be that issues arise with bad data and should be corrected at the offending module level, not by adding a safeguard to DrupalDefaultEntityController that would mask deeper problems. Having an error here is a warning to developers that they are using the D7 APIs incorrectly. - @jessebeach

So the challenge should be to identify which module implements Entity API incorrectly.

See also:

---

If you're developer of the module which causing the issue, please check the followings:

* Make sure your array won't contain NULL values, otherwise use the following trick:

```
$arr = drupal_map_assoc($arr, function($v) { return (string) $v; });

```
* Check the Examples module (entity\_example) for Developers how to implement entities.
* You're loading entities using the right `$ids` structure.
* Use debugger or `debug_backtrace()` to debug the issue.
> 2 votes

---
Tags: 7, entities, database
---


# Question
Title: How to prevent 'drush up' from deleting non native inodes in a sub-theme folder?
I installed the Basic theme, ran `drush up`, updated this theme. Once done, the sub-theme folder I created was deleted.

Is there something to do to prevent Drush from deleting a directory?

# Answer
> 4 votes
If your sub-theme folder is inside the base theme folder, it will get wiped out when there is an update to the base theme, as drush will remove the contents of the theme folder and replace them with the new updated contents of the theme.

The solution is to move the sub-theme folder to be along-side the base theme folder, so it's a sibling, rather than a child.

---
Tags: drush, updating
---


# Question
Title: How to investigate arrayFlip errors in Commerce
I get periodic errors telling me that something expects a parameter to be an array. But the messages are too vague, and don't tell me which piece of code is feeding that information to Drupal. Here's an example:

```
Warning: array_keys() expects parameter 1 to be array, null given in inline_conditions_field_widget_form_validate() (line 353 of /Users/newman/Sites/visionart/sites/all/modules/inline_conditions/inline_conditions.field.inc).
Warning: array_filter() expects parameter 1 to be array, null given in inline_conditions_field_widget_form_validate() (line 353 of /Users/newman/Sites/visionart/sites/all/modules/inline_conditions/inline_conditions.field.inc).
Warning: array_flip() expects parameter 1 to be array, null given in inline_conditions_field_widget_form_validate() (line 353 of /Users/newman/Sites/visionart/sites/all/modules/inline_conditions/inline_conditions.field.inc).
Warning: array_intersect_key(): Argument #1 is not an array in inline_conditions_field_widget_form_validate() (line 353 of /Users/newman/Sites/visionart/sites/all/modules/inline_conditions/inline_conditions.field.inc).

```

Most of these are in connection with array\_flip(). I can see that this one in particular is being flagged but inline\_conditions, bit it's such a core module that it's impossible to find out what's triggering it. How can I do that and how can I fix?

# Answer
> 1 votes
BTW, I think you're mistaken, inline conditions isn't a core module. In fact looks like the latest version is *7.x-1.0-alpha7*. Also, notice that these are warnings, not errors. It's likely that they won't effect a site set up with production error handling.

The way I've dealt with that is through debugging on copy of the site running in a local environment with xdebug. If you haven't set that up yet there are a **bunch of ways** you can do it, here's a few:

* Here's a link for how to do it using Homebrew. That's my reply but read the others there, they've got good info.
* you can sign up for a free account on Acquia and use their dev desktop software. Here's some info on doing that. (Seems like I'm plugging my own posts, but thats what I know.) I've gotten
* There's a similar app from Kalamuna called Kalabox that specifically is set up to work with Pantheon, but I was able to get to work standalone. Let me know if you need help with this, I'll try to get time to put more details up.

*Be ready to be frustrated getting a local environment with debugging up and running, it takes some doing, but it's well worth the effort.*

Once you've got debugging happening, you can put a breakpoint on line line 353 of /sites/all/modules/inline\_conditions/inline\_conditions.field.inc. If you can reproduce the error, then just hit continue until just before you expect the error to occur. (If you can't, you'll have to do this each time it breakpoint is reached.) From the breakpoint, you'll be able to look at the parameters that are referenced on that line and see what's expected to be an array that isn't. My setup using Netbeans allows me to hop to earlier parts of the code by checking the stack. This will allow you to see just where the parameter was originally set.

Sorry this isn't just an easy answer, but getting yourself set up will be worth it in the long run.

# Answer
> 0 votes
This may be related to issues with Commerce discounts (possibly related to AJAX?), if so, make sure you'e using the latest version of Commerce Discount.

Also clear all your caches and re-try. If problem persist, report a bug against the module it-self.

---
Tags: 7, commerce, entities
---


# Question
Title: Linking entities using EntityFieldQuery?
I have several entities (content types) using node references to relate the content together.

I need to write queries which relate two or more nodes together through their node reference fields, then apply conditions based on fields from each of the entities and returning at the very least the nids that meet those conditions.

An example: Engagement attaches to Event via node reference. I need to query for Engagement entities within a certain date range. The date field is defined in the Event CT. So what I want is to link the Engagement 'entity' with the Event 'entity', apply the date range condition to the Event entity, and return the nids of the Engagement entities meeting the condition.

This is one somewhat simple example, and there are other relationships which will require similar queries...

So far it seems I may need to extend the EntityFieldQuery class, but I'm not sure that this will get me what I want.

This effort is going towards converting a site I built in D6 into D7. I wrote a custom query builder to accomplish these queries by just manually building the queries. I'm attempting to convert these queries to use D7's query building architecture.

It may also be possible to write these queries using db\_select and manually linking in the necessary tables (basically what I did for D6).

I'm at a bit of a crossroads. I'm going to need to make this happen. Any help at this point would be quite helpful. Does anyone have any experience with this type of problem or extending the EntityFieldQuery class?

# Answer
Well your approaches sound ok ... an alternative might be the Relation module. You can define a relation such as "event-has-engagement" between any number of entity ids. A "relation" is just given a numerical id typically and then the endpoints go into a table.

The Relation module has already extended the EFQ class to encapsulate querying Relations; eg you can easily query for "Find me all Engagements for Event with some entity id". You can additionally attach drupal Fields to endpoints and query those fields in your EFQ-Relation query object.

I imagine you could loop through your existing database and build the necessary Relation(s) to migrate the data into "Relation" relations.

There are also Views integration with Relation .... but I personally stick with EFQ for alot of stuff.

Just my 2 cents ...

EDIT

there is a patch to allow the use of the migrate module to move Reference fields into Relations.
> 1 votes

# Answer
So each Event node has an entity reference to Engagement, and you wish to find all Engagement where the Event is within a date range?

Have you considered just query for the Event and load all its references to Engagement nodes into an unique array?

For example:

```
$query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->fieldCondition(<date_range_condition>)
  ->execute();

$engagements = array();
foreach ($results['node'] as $nid => $result) {
    $event = node_load($nid);
    $engagement_nid = $event->field_reference[LANGUAGE_NONE][0]['target_id'];
    $engagements[$engagement_nid] = $engagement_nid;
}

```

Not ideal if the sets are really really large, but I find that reasonable sizes are ok, like when you can use range to limit the size. Depending on your use case, I find it nicer to sacrifice a bit of performance and not having to tinker around with classes and keep things as simple as possible, especially when performance loss is negligible.
> 1 votes

---
Tags: 7
---


title: Alter an existing view definition

text:
# Question
Title: Alter an existing view definition
I have an existing view to which I would like to add some contextual filters if my module gets enabled. In D7 this was possible using `hook_views_default_views`, but I can't seem to find the equivalent in D8. Is this possible in D8?

# Answer
> 4 votes
Providing a view by using `hook_views_default_views()` is no longer possible. In D8 views are configuration entities. This means when a module wants to provide a view, it puts a yml file in /config/install.

If you want to change a view in code, load the view, change it and save it.

```
$view = View::load('test_filter_taxonomy_index_tid');
$display =& $view->getDisplay('default');
$display['display_options']['filters']['tid']['type'] = 'textfield';
$view->save();

```

A third alternative is to change the view directly in configuration, for example replace it with the content of a yml file:

```
$config_path = drupal_get_path('module', 'mymodule') . '/config/optional/views.view.myview.yml';
$data = \Symfony\Component\Yaml::parse(file_get_contents($config_path));
\Drupal::configFactory()->getEditable('views.view.myview')->setData($data)->save(TRUE);

```

The last option might be the easiest for your use case. You can configure the view in ui, export it to a yml file and use this file to overwrite the configuration of an existing view in `hook_install()`.

---
Tags: views, 8
---


# Question
Title: Problems creating Drupal Commerce Product Display, list of available products not populating
This is something that has happened to a site I'm maintaining. I can't create product displays for many of my products because the select list of products in the product field isn't populated with many of my products.

I have a content type called "Product Display" with product field of type product reference. When adding products the select list of products is only display 10 of about 100 products.

This only diagnostic information is that two javascript errors are reported

```
Uncaught TypeError: cannot read property 'behaviors' of undefind in jquery-noconflict.slicknav

```

And

```
Failed to load resource: Server responded with a status of 403 (forbidden)

```

This leads me to thing it's a jquery issue, but not sure how to debug this further.

So, how do I get that list of products to contain all of the products in the store?

# Answer
> 1 votes
This is a bug in Drupal Commerce 1.13. I'll be patching it today:

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

---
Tags: commerce
---


# Question
Title: How to make method entity_uri work when $entity_type is taxonomy_vocabulary?
I have a table with entities of type *content*, *taxonomy\_vocabulary* and *terms*. For *content* and *terms*, I can show a link to each detail page by using the method entity\_uri.

But for entities with type *taxonomy\_vocabulary* this does not work, entity\_uri returns null.

What is the best way to get the url for a *taxonomy\_vocabulary* entity?

# Answer
> 1 votes
I hope it is not the best answer, because it requires customized code. But anyway, it is a possible solution and I'll share it.

```
/**
 * Implements hook_entity_info().
 */
function mymodule_entity_info_alter(&$info) {
  if (isset($info['taxonomy_vocabulary'])) {
    $info['taxonomy_vocabulary']['uri callback'] = 'my_module_entity_info_uri_callback';
  }
}

/**
 * Return path for taxonomy_vocabulary entities
 */
function my_module_entity_info_uri_callback($taxonomy) {
  return array(
    'path' => 'admin/structure/taxonomy/' . $taxonomy->machine_name,
  );
}

```

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


title: How to override form error message

text:
# Question
Title: How to override form error message
Let's say I have a simple `form` with some `id` like `myform`. This `form` has `field` called **Mobile number** with `id` `mobile_number`.If a user enter mobile number less than 10, it will prompt `error` like `It must be 10 digits`.

**Form validation snippet:**

```
public function validateForm(array &$form, FormStateInterface $form_state) {

  if (strlen($form_state->getValue('mobile_number')) < 10) {
    $form_state->setErrorByName('mobile_number', $this->t('It must be 10 digits.'));
  }

}

```

On inspect I found something like below **markups**

```
<div class="messages__wrapper layout-container">
      <div class="messages messages--error" aria-label="Error message" role="contentinfo">
      <div role="alert">
              <h2 class="visually-hidden">Error message</h2>
                It must be 10 digits.
            </div>
  </div>

</div>

```

I want to manipulate `markups` in either of two scenarios:

**1) For whole website**

**2) Only for `form` with `id` `myform`.**

How can I achieve that?

I am using `8.1.3`

# Answer
You can use this twig to theme the status message:

**status-messages.html.twig**

```
{#
/**
 * @file
 * Default theme implementation for status messages.
 *
 * Displays status, error, and warning messages, grouped by type.
 *
 * An invisible heading identifies the messages for assistive technology.
 * Sighted users see a colored box. See http://www.w3.org/TR/WCAG-TECHS/H69.html
 * for info.
 *
 * Add an ARIA label to the contentinfo area so that assistive technology
 * user agents will better describe this landmark.
 *
 * Available variables:
 * - message_list: List of messages to be displayed, grouped by type.
 * - status_headings: List of all status types.
 * - display: (optional) May have a value of 'status' or 'error' when only
 *   displaying messages of that specific type.
 * - attributes: HTML attributes for the element, including:
 *   - class: HTML classes.
 *
 * @ingroup themeable
 */
#}
{% for type, messages in message_list %}
  <div role="contentinfo" aria-label="{{ status_headings[type] }}"{{ attributes|without('role', 'aria-label') }}>
    {% if type == 'error' %}
      <div role="alert">
    {% endif %}
      {% if status_headings[type] %}
        <h2 class="visually-hidden">{{ status_headings[type] }}</h2>
      {% endif %}
      {% if messages|length > 1 %}
        <ul>
          {% for message in messages %}
            <li>{{ message }}</li>
          {% endfor %}
        </ul>
      {% else %}
        {{ messages|first }}
      {% endif %}
    {% if type == 'error' %}
      </div>
    {% endif %}
  </div>
{% endfor %}

```

I'm not sure, if you can get the form id in this template. But you can try to narrow down the kind of error message and make the modifications to this twig conditional.
> 1 votes

---
Tags: theming, forms, 8
---


# Question
Title: Define custom view page template with theme_hook_suggestions
I would like to define 'theme\_hook\_suggestions' for a custom views-view.tpl.php file.

To achieve this, I wrote the following code into my template.php file:

```
/**
 * Implements hook_preprocess_views_view().
 */
function MYTHEME_preprocess_views_view(&$variables) {
  // Some logic to decide if the hook_suggestions should set or not
  // ...
  $variables['theme_hook_suggestions'][] = 'foo';
}

```

After that, I created a copy of views-view.tpl.php in the templates folder named foo.tpl.php.

Sadly, my template file is ignored by Drupal and the default views-view.tpl.php file is rendered on the page.

What's the matter? I debugged the theme\_registry and the template path should be correct (points to my theme).

**Update** The target is that I can switch between two template files which are defined in my preprocess function (see above). Because in some cases, my layout markup is significant different as in other cases.

I don't want to use the same template file for both cases; when I do this, the file is full of tousands of `if()` just for adjusting the markup for some cases.

# Answer
Your approach is fine. The only problem is with the name of the hook suggestion and the equivelant tpl.php file.

Since you are preprocessing views\_view the hook suggestion should be named something that starts with views\_view ex: views\_view\__\[anything\]. Note that all the undersores will be replaced with dashes for the filename. So it should be something like views-view--\[anything\].tpl.php

For example:

```
/**
 * Implements hook_preprocess_views_view().
 */
function MYTHEME_preprocess_views_view(&$variables) {
  // Some logic to decide if the hook_suggestions should set or not
  // ...
  $variables['theme_hook_suggestions'][] = 'views_view__foo';
}

```

And the filename will be views-view--foo.tpl.php
> 3 votes

# Answer
You can have multiple templates for views like :

views-view--home-slideshow-mobile.tpl.php if your display is a block, you can write it like this :

views-view--home-slideshow-mobile--block.tpl.php then you have templates for views fields :

views-view-fields--home-slideshow-mobile.tpl.php Templates for views format (like unformatted for example) :

views-view-unformatted--home-slideshow-mobile.tpl.php If you want to alter the template of your block, you can declare a block.tpl.php like :

block--my-block-module--my-block-machinename.tpl.php

You can copy the template and paste them in your theme and rename it to target your specific view. form sites/all/contrib/views/theme/...

See this links really help you out: http://www.wdtutorials.com/how-to-create-custom-template-view-drupal-tutorial-article/7#.VgQw5XU4bK4

https://www.ostraining.com/blog/drupal/views-templates/

Best of Luck :)
> 0 votes

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


# Question
Title: Debugging panels visibility rule with custom access check plugin
I created a ctools access plugin for use with visibility rules in panels. When I click to add the rule, my rule "Site Installation Profile" shows in the list. I click it and click continue and my form for input of the profile name shows. I enter the name and click save only to get an AJAX error message that says the service is unavailable. If I cancel and try to edit the content of the panel, I get an error page. The error page simply says "Error" with no stack trace information. I've put in break points in my access plugin to try to debug with xdebug but it's not catching anywhere where the error is occurring and I'm not sure where to look. Here is the plugin:

```
$plugin = array(
  'title' => t('Site Installation Profile'),
  'description' => t('Installation profile value check'),
  'callback' => 'llnl_form_alterations_site_profile_ctools_access_check',
  'default' => array(
    'profile' => '',
    'negate' => 0,
  ),
  'settings form' => 'llnl_form_alterations_site_profile_ctools_access_settings',
  'summary' => 'llnl_form_alterations_site_profile_ctools_access_summary',
  'all contexts' => TRUE,
);

/**
 * Actual access check.
 */
function llnl_form_alterations_site_profile_ctools_access_check($conf, $context) {
  $profile_ck = $conf['profile'];
  $profile = drupal_get_profile();
  if ($profile == $profile_ck) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
 * Provide a config form.
 */
function llnl_form_alterations_site_profile_ctools_access_settings($form, &$form_state, $conf) {
  $form['settings']['profile'] = array(
    '#type' => 'textfield',
    '#title' => t('Installation Profile'),
    '#default_value' => $conf['profile'],
    '#required' => TRUE,
  );
  return $form;
}

/**
 * Provide a summary description.
 */
function llnl_form_alterations_site_profile_ctools_access_summary($conf, $context) {
  $profile = $conf['profile'];
  return t('Show if "@profile" is site installation profile', $profile);
}

```

# Answer
I found it within a few minutes of posting this question. The issue was in my summary function and my use of placeholder values. Once that was fixed, it was working fine.
> 0 votes

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


# Question
Title: BigPipe messing up JS, is there a BigPipe ready() equivalent function?
I'm experimenting with BigPipe on D8 and it seems that the regular jQuery $(document).ready() function fires before the BigPipe has finished loading all the elements causing quite a few difficulties.

For instance I have buttons with activation trigger element ID's which are loaded into a variable, but the trigger elements don't seem to get loaded by the time JS runs and they aren't present yet,breaking the functionality.

Is there a simpler workaround than rewriting all the JS libraries I'm using, that rely on the ready() function? Maybe something BigPipe specific solution I haven't found yet?

# Answer
You must not ever rely on `document.ready` when you write js for drupal. You should use drupal behaviours; If used properly this will ensure that your code runs both on normal page loads and when data is loaded by AJAX (or BigPipe!)

Also read this interesting post on drupal issue queue JS relying on document.ready event does not work with BigPipe
> 5 votes

---
Tags: 8, javascript
---


title: Dynamic menu items

text:
# Question
Title: Dynamic menu items
The Drupal 8 menu system is much more logical than in previous versions, and breaking the many functions of hook\_menu() into multiple YAML files makes perfect sense and simplifies the creation and management of most Drupal menu items.

However, because the YAML files are static elements, it's not clear to me how I can create a dynamic path and menu item in my module. This was fairly easy in hook\_menu(), and was handled the same way as regular menu items.

In my module, I'd like to allow the admin to set the path, menu title and parent menu item for a form (the form will have several instances, each of which will have its own path and menu item, defined by the site admin).

Really appreciate if anyone can point me at an example, or give a simple run down of how to do this.

# Answer
You can follow two example:

In Providing dynamic routes you can easy use simple code:

```
<?php
/**
 * @file
 * Contains \Drupal\example\Routing\ExampleRoutes.
 */

namespace Drupal\example\Routing;

use Symfony\Component\Routing\Route;

/**
 * Defines dynamic routes.
 */
class ExampleRoutes {

  /**
   * {@inheritdoc}
   */
  public function routes() {
    $routes = array();
    // Declares a single route under the name 'example.content'.
    // Returns an array of Route objects.
    $routes['example.content'] = new Route(
      // Path to attach this route to:
      '/example',
      // Route defaults:
      array(
        '_controller' => '\Drupal\example\Controller\ExampleController::content',
        '_title' => 'Hello'
      ),
      // Route requirements:
      array(
        '_permission'  => 'access content',
      )
    );
    return $routes;
  }

}

```

Just need **array store data and foreach** in function **routes**. You can dynamic router.

After dynamic **router** you can create dynamic menu with **Derivative plugin**. Example class MenuLinkContentDeriver. In function **getDerivativeDefinitions** you need return array have data like this:

```
 $links = array(
      'route_name' => $router_name,//like example.content in define route
      'id' => $menu_link_id,
    );
 $links['title'] = $title;
 $links['description'] = $description;
 $links['parent'] = 'main:';
 $links['enabled'] = 1;

```
> 7 votes

# Answer
While D8 uses the symfony routing system and configures this with yml files and dynamic route callbacks as described by @MrD, menus are now a separate system.

The menu system offers two ways to define menu links. Static in `mymodule.links.menu.yml` and dynamic as content.

To do the latter add an item to a menu by creating a `MenuLinkContent` entity:

```
$item = \Drupal\menu_link_content\Entity\MenuLinkContent::create([
  'link' => ['uri' => 'internal:/<front>'],
  'title' => 'Front Page',
  'menu_name' => 'admin',
]);
$item->save();

```

A more complex example would be how drupal generates the menu link when it saves a node:

https://api.drupal.org/api/drupal/core!modules!menu\_ui!menu\_ui.module/function/\_menu\_ui\_node\_save/8.2.x
> 5 votes

# Answer
To provide an alternative, you could work with a single route with an argument and just create URL Aliases for, similar to how all nodes have a system path at /node/ID but can have whatever visible path/alias that a user wants.

That's how contact forms work for example, every contact form is available ad contact/{contact\_form\_id}, if you don't want that you can create an alias for /foo to point to /contact/foo. Core doesn't actually provide that for contact forms in an integrated way but contact\_storage adds exactly that functionality in the latest version.

The main advantage is that by having a single, static route, changing/creating/deleting a $thing doesn't require you to rebuild the router, which is a relatively slow, locking (no other requests can be served while that happens) process.

And as already mentioned in a comment, menu links could also be created as menu link content entities.

To summarize, you'd basically do what path.module and menu\_ui.module do with nodes.
> 5 votes

---
Tags: 8, routes
---


# Question
Title: How to display field collection items left to right in views grid
I created a content type as follows:

Content Type \> field collection field \> accepts unlimited values.
Field collection field \> text field, Image field. \> Each accepts one value.

Add content \> content type x \> added 5 field collection items. So I have one content with 5 field collection items. Each item has one text field value and one image value.

Views: Created views grid \> number of columns equal to 3. Fields \> added field collection field.

I see all the items in a single column. I would like to display items left to right. How can I do it?

# Answer
> 1 votes
Click on `Content: MyProducts` (within fields).

Then scroll down a bit, until you see `MULTIPLE FIELD SETTINGS`, click on it to expand it and then uncheck the `Display all items in the same row` box.

---
Tags: views
---


title: Change secondary menu id

text:
# Question
Title: Change secondary menu id
How can i change the secondary menu id, by default it has the same id like primary menu. My primary menu id is menu-main-navigation and when i print in twig the secondary menu like {{ page.secondary\_menu }} it prints with same id.

# Answer
> 0 votes
No need to change the id, i am printing the region not the block, just change the block from secondary menu region and will print the new block.

---
Tags: 8, navigation
---


# Question
Title: Programmatically delete field collection items
Is there any way to delete field collection items programmatically in Drupal 8?

I have created a field collection item and attached it to the user entity in the following method.

```
$user_id = \Drupal::currentUser()->getAccount()->id();
$user = User::load($user_id);

$fc = FieldCollectionItem::create(array(
  "field_name" => "field_hobbies",
));

$fc->set('field_name', 'Watch TV');
$fc->setHostEntity($user);

```

It works fine and the field collection item got created successfully. Now I want to delete this field collection item. That means, I want to delete the hobby from the user. Is there any way for doing this?

# Answer
Copied from (and then tested):

https://www.drupal.org/node/2757827#comment-11398243

```
$user = User::load($user_id);
$storage = \Drupal::entityTypeManager()->getStorage('field_collection_item');
$fc_items = [];

foreach ($user->get('field_hobbies') as $item) {
    $fc_items[] = $item->value;
}

if (!empty($fc_items)) {
    $items = $storage->loadMultiple($fc_items);
    $storage->delete(items);
    $user->set('field_hobbies', array());
}

$user->save();

```
> 1 votes

---
Tags: 8, entities
---


# Question
Title: how to save checkboxes values in node programmatically
i want to save checkboxes values in entity reference checkboxes field with node\_save :

```
   $form['wrapperrr']['id_offre'] = array(
        '#title' => t('Liste des Offres'),
        '#type' => 'checkboxes',
        '#options' => $optionsoffres,

    );

```

and into the submit button :

```
$node->field_entity_reference['und'][]['value'] =$form_state['values']['wrapperrr']['id_offre'];

```

# Answer
> 0 votes
i found the solution :

```
  $aaz= array_filter($form_state['values']['wrapperrr']['id_offre']);
 foreach($aaz as $of)
   {

  //  $node->title = $form_state['values']['wrapperrr']['id_offre'][0]['value'];
   $node->field_offre[LANGUAGE_NONE][]['target_id'] = $of;

   }

```

---
Tags: 7, forms, nodes
---


# Question
Title: How to prevent duplicate URL patterns and not have "-#" appended to the URL alias?
We have a situation where we need to prevent the same URL from being generated within the same language.

Current situation (all for en):

1. Create nodeA with a URL alias of "page/node-title"
2. Create nodeB with a URL alias of "page/node-title"
3. Create nodeC with a URL alias of "page/node-title"

Results of current situation

1. nodeA generates "page/node-title"
2. nodeB generates "page/node-title-0"
3. nodeC generates "page/node-title-1"

Expected results:

1. get created as expected
2. user is prompted to modify the url since for the en language, that alias already exists
3. user is prompted to modify the url since for the en language, that alias already exists

That is not the expected results however. When nodeB and nodeC are generated, then the user should be prompted to let them know that the URL alias is a duplicate and thus it must be changed so it is unique. We have reviewed a lot of the documents for URL generation in Drupal but cannot find the correct configuration to prevent duplicate node alias from being generated.

# Answer
> 1 votes
As Clive mentions, Pathauto does not have a configuration to disable uniquification (suffixing "-#").

If you look through the main function that builds paths, `pathauto_create_alias()` you can see that the only way to prevent `pathauto_alias_uniquify($alias, $source, $language)` from running would be to trigger one of the scenarios in which pathauto gives up on alias creation (e.g. empty pattern, updating an existing alias, etc.) which wouldn't help where you need it still generated in some cases.

Your best bet to cover this scenario is to have a custom node validation function execute `pathauto_create_alias()`'s logic with `$op = 'return'` to see what the generated alias *would be* before generation, and throw back errors upon duplicate uniquified paths.

---
Tags: 7, nodes, path-aliases, uri
---


title: Create Linestring Between 2 Points

text:
# Question
Title: Create Linestring Between 2 Points
I have a series of letters, each with a recipient and sender address stored with Addressfield, with spatial data added Geocoder into lat/long and stored in a Geofield. I'm using IPGV&M, Views, and Leaflet to render these points - 1 letter to each row, with 2 points (sender / recipient). This is working fine.

I'd now like to add a linestring between those two points, but am at a loss for how to do that. Can Geofield store linestrings? Can I automatically generate a linestring and store that in a Geofield field based on the geo POINT values of the sender / recipient Geofields?

# Answer
> 0 votes
I ended up using Rules to automatically populate a text field with the linestring data LINESTRING(lat lon, lat lon) after every new entity add or existing entity update, with the condition that both geofields (sender and receiver) were filled. Created another geofield to hold the LINESTRING, geocoded from the text linestring field as WKT. Ran VBO to update all existing nodes. Plots well in IPGV&M and should handle itself automatically from now on.

---
Tags: 7, google-maps
---


# Question
Title: Creating a field that has node values using FAPI
I would like to use the Form API to create a form that uses a textfield that references all the current nodes as an autocomplete. Is there a way to added field using the FAPI that allows a user to type the node's title or ID and the field is validated by whether the node exists.

# Answer
> 1 votes
If it is for a custom module, Drupal makes it quite easy to do an autocomplete field.

See a tutorial here... http://timonweb.com/posts/how-to-create-an-ajax-autocomplete-textfield-in-drupal-7/

You would then do a validation function to determine whether the entity exists, or you would only provide a list of existing entities in the first place.

If you are using the core fields, then try the entity reference module.

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


# Question
Title: How to render mini panel in custom template programatically?
I have a minipanel and I have a custom template. How can I render minipanel in my custom template programatically?

# Answer
Mini Panels are available as blocks. So you'd be rendering it in the same way you render any block programmatically in Drupal 7.

Use

```
$block = module_invoke('panels_mini', 'block_view', 'machine_name_of_mini_panel');
print $block['content'];

```
> 0 votes

---
Tags: panels
---


title: Convert tpl template to twig template

text:
# Question
Title: Convert tpl template to twig template
I have file tpl in drupal 7 like this:

```
<div class="<?php print $classes; ?>" <?php { print $attributes; } ?>>
    <?php
    $content_section = '<div class="'.$container_class.'">';
    foreach($columns as $key => $column) {
      $content_section .= render($column);
    }
    $content_section .='</div>';
    if(isset($customHTML)){
      $customHTML = str_replace('[content]', $content_section, $customHTML);
      print $customHTML;
    }
    else {
      print $content_section;
    }?>
</div>

```

I want convert two twig template. But i have problem with function **render**() and **str\_replace**(). I know in twig have function replace. But don't know how to convert to twig.

# Answer
In Drupal 8 you can use the drupal `|render` twig filter:

```
{{ myvar|render }}

```

Replace might be used as:

```
{% set customHTML = customHTML|replace({'[content]': content_section}) %}

```

having the variables all ready.

To convert your whole template to twig have a look at loops, also.
> 2 votes

# Answer
For render, you can do something like

```
{{ variable|render }}

```

For more information on converting .tpl to twig, kindly check out "Drupal Twig conversion instructions (tpl.php to html.twig)".
> 2 votes

# Answer
Same with @Alex and @Suresh R

```
{{ myvar|render }}

```

you can follow document see more filter in drupal 8. Note if variable customHtml have tag html. You need use filter **raw** to print it.

```
{{ myvar|raw }}

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How can I provide anonymous user to access my REST GET API without providing any auth information?
The Drupal 8 REST UI configuration page asks me to select *Authentication providers* for *GET method*; otherwise, it doesn't allow me to export the REST request.

How can I provide anonymous user to access my REST GET API without providing any auth information?

# Answer
According to the Drupal documentation : https://www.drupal.org/developing/api/8/rest

> Don't forget to grant the corresponding permission! In case of a decoupled site, you typically need to grant the authenticated user role permission to GET content. In case of a web service, you typically need to grant the anonymous users permission to GET/POST content. Grant them at /admin/people/permissions#module-rest, or using Drush: drush role-add-perm anonymous 'restful ', for example: drush role-add-perm anonymous 'restful get entity:node'

basically add the anonymous permission for the GET resource.
> 5 votes

# Answer
You could create your own authentication provider; it could then allow anonymous users access to your resource. It is not that difficult, the only thing I found is that you have to be careful to make sure the authentication provider only applies whe you specifically want it to. Look here for a tutorial:

http://enzolutions.com/articles/2014/12/28/how-to-create-an-authentication-provider-in-drupal-8/
> 4 votes

---
Tags: 8
---


# Question
Title: Changing a block title per theme or page
I have a search view, and I use the exposed form as a block to put the search box on every page. In the block configuration I hide the exposed form block title so that I'll just get the search form with no title.

That works fine, but now on the Admin dashboard, I want to include the same search box. The dashboard shows the block title, which is what I want, except the view title is 'Exposed form: publication\_search-page' which is gross.

If I try to go into the block configuration and change the block title to Publication Search, I override the that is in there now, and the title starts showing up everywhere.

How can I change the block title in the dashboard (or when I'm using the adminimal theme or whatever the admin theme is set to if that is easier) without messing up the configuration to hide it on all the other pages?

# Answer
> 1 votes
### Here is a per theme solution.

In your View, under Advanced, click on `Theme Information`, the following pops up:

Now click on `style output`, and copy the entire code inside in to a new file in your text/code editor.

In my case it is:

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

Change the `<h3><?php print $title; ?></h3>` to `<h3>Your Custom Title</h3>`

Then save the file as **views-view-unformated--\[view-name\]--\[machine-name\].tpl.php**

(In my screenshot, `example` is the name of my view, and machine name is `page`, **basically use last name suggestion**)

Put this template file in your Adminimal theme's template folder and clear the cache to see changes.

---
Tags: 7, views, blocks
---


title: How to theme a form with bootstrap

text:
# Question
Title: How to theme a form with bootstrap
I want to add much HTML to my form elements in order to arrange them on the page, I will be using bootstrap framework to do this.

Which method would be better, to create a twig template file or to use HOOK\_form\_alter?

If the way to do this would be to create a twig template file, then how can I ensure the form html tags with the form method is also rendered to the page? I have attempted to do this but I don't know how to get the actual form to render, just the inputs are there in the html source code.

I know in Drupal 7 that you had to render something called child elements, but when I check for this array in Kint there is no such thing.

# Answer
A good starting point is the bootstrap theme. They have a stable version for drupal 8. (It's the most object oriented theme I've seen so far)

> So I would suggest to make your custom theme, as sub-theme of it.

If you want to do it fully by yourself, you would use hook\_form alter existing forms (if needed) and theme\_hooks/html.twig to add some bootstrap specific classes and change HTML structure. The mentioned theme is a good starting point to look at all the things that need to be changed.
> 1 votes

# Answer
http://www.hbensalem.com/php/drupal-7-and-bootstrap-3-theming-the-login-form/

That gives some code to add to the template.php file for a login form and could be a useful base for you to improve upon.

I'm doing the exact same thing as you are right now.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to translate strings available in JS library?
I'm showing some images on my site where those are displayed using jquery.magnific-popup.min.js library. I'm not able to translate a string in that library. i.e.

> "%curr% of %total%"

It is not searchable even in the translate interface. How can I translate it?

# Answer
See the plugin's translation documentation for a list of strings and their option names.
Pass these strings through Drupal.t() when attaching your popup.
> 1 votes

# Answer
Do not waste your time with the interface translation, you may find strings started with "" in jquery.magnific-popup.min.js file, just locate there with your editor, and change them. Just before make a backup of the javascript file for sure. Then clear your site's cache /admin/config/development/performance and reload your page. Hope it can help, that's worked for me.
> -1 votes

---
Tags: javascript, i18n-l10n
---


# Question
Title: How to use 2 twig template for for one field (or how to add a variable to a template from a template)
Let say I have a node template which is calling twice the same field like the following:

```
...
{# First call #}
{{ content.my_field }}
...
{# Second call #}
{{ content.my_field }}
...

```

I also have a preprocessing function which is adding VAR1 and VAR2 to the 'my\_field' array like the following:

```
function mymod_preprocess_field(&$vars) {
  if (isset($vars['element'])) {
    $fn=$element['#field_name'];
    if ($fn=='my_field'){
      $vars['VAR1'] = 'a value';
      $vars['VAR2'] = 'another value';
    }
  }
}

```

I would like that the first call of 'My\_field' use the default twig template and the 'VAR1' value... As you can imagine, I could do it as this is the normal way Drupal is working. But I didn't success to make use of an alternate twig template for the second call (and also, I would like this second template use 'VAR2')

My first idea was to put the following just before the first call:

`{{ set content.my_field.is_first_call = true }}`

and to use **only** the default template (I mean not 2 templates) with something like

```
{% if is_first_call %}
  ... code to print the first call
{% else %}
  ... code to print the second call
{% endif %}

```

But I couldn't succeed to transmit a value (is\_first\_call) from the node template to the default my\_field template

**Final note**: I have added the 'VAR1/VAR2' story because I have also tested the `{{ content.my_field | without ('a_check_var')}}` filter: the idea was to remove `a_check_var` from the array to use a construct like `{% if a_check_var %}` in the default template. Unfortunately, my preprocess function which is adding 'VAR1/VAR2' runs after the `without` filter

# Answer
**How to add a variable to the field template from the node template?**

What you see in the node template from the field is before the field preprocess is run.

The global preprocess for fields starts like this:

```
function template_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];

  // Creating variables for the template.
  $variables['entity_type'] = $element['#entity_type'];
  $variables['field_name'] = $element['#field_name'];
  $variables['field_type'] = $element['#field_type'];
  $variables['label_display'] = $element['#label_display'];

```

Here can see, how the variables for the field template are built.

**Example:**

To add a variable in node set the variable with a '#' prefix:

```
function mytheme_preprocess_node(&$variables) {
  if (isset($variables['content']['my_field'])) {
    $variables['content']['my_field']['#var1'] = 'a value';
  }
}

```

And then in the field template:

```
function mytheme_preprocess_field(&$variables) {
  if (isset($variables['element']['#var1'])) {
    $variables['var1'] = $variables['element']['#var1'];
  }
}

```

The variable is then available in the field twig:

```
{{ var1 }}

```

To solve your specific problem I would suggest you copy the field in node preprocess and then set for both copies different variables.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Render Teaser Image in search block using Twig
I am trying to render the teaser image in my search block using twig. For my views page for rending the articles i am using this:

```
  <div class="img-container" itemscope="" itemtype="http://schema.org/imageObject" data-internal-url="{{ url }}">
    {% block teaser_img_container %}
        {{ content.field_teaser_media }}
    {% endblock %}
  </div>

```

And it works very nice but on search block it does not display the image, so I am trying other options like

```
<div class="img-container" itemscope="" itemtype="http://schema.org/imageObject" data-internal-url="{{ url }}">
  <picture>

   {% block teaser_img_container %}

<img src="{{ file_url(node.field_teaser_media.entity.uri.value) }}" >
 {% endblock %}

     </picture>
  </div>

```

Which should solve my problem, but i still don't see the image i am getting no errors, if i go in my page source the link to image appears but when i inspect the code from I get

```
<img src="/">

```

The link works, but it does not display my image. Any ideas for fix?

# Answer
You could use the URL Formatter Module

Then go to Manage Display and for your image field and select URL Formatter as your formatter.

then use: `<img src="{{ content.field_teaser_media[0] }}">`
> 1 votes

# Answer
The problem was in my Manage Display i forgot to put my Teaser Default (Display from where i take my default settings for other teaser displays) to the format Rendered Entity.

Thank you for your help.
> 0 votes

---
Tags: theming, 8, media, search
---


# Question
Title: Drupal URL encoding breaks redirects/links
I added a link to my Toolbar Shortcuts list and the path is:

`admin/content?title=&type=slides&author=&status=All&vid=All`

But when you click it, Drupal redirects to:

```
admin/content%3Ftitle%3D%26type%3Dslides%26author%3D%26status%3DAll%26vid%3DAll

```

Which breaks the link and redirects to a wrong page.

How do I prevent Drupal from converting symbols and leave it as it is.

# Answer
Temporal workaround, create views with friendly URLs for pages you need, e.g. now each exposed filtered result has its own views page.

Can't come up with anything else since Drupal 'works this way'.
> 0 votes

# Answer
This is drupal core functionality that converts special correctors to string when using in toolbar shortcut menu.
> 0 votes

---
Tags: 7, uri, navigation
---


# Question
Title: How can I check in Drupal 8 an externally set $_COOKIE?
I would like to check whether a Cookie exists, and if so, get the value. But it looks like Drupal is blind to external cookies that have not been set inside Drupal.

```
$mycookie = \Drupal::request()->cookies->all();

```

Returns an array with only the Drupal cookies, and I can see in my web browser that there are more (some that I am interested in and I can't modify he app that is creating those cookies). I remember there was a similar issue with Symfony 2 and session but I can't find it...

# Answer
For external cookies please try with $\_COOKIE\['cookie\_name'\].

```
if (isset($_COOKIE['cookie_name'])) {
  print($_COOKIE['cookie_name']);
}

```

The code will print out the value of the cookie if present.

For a more specific answer please explain your question.Ty!
> 1 votes

---
Tags: 8
---


title: Programmatically update node via array

text:
# Question
Title: Programmatically update node via array
I'm trying to import some nodes into a new D8 installation. Therefore I wrote a module. Importing nodes is already working perfectly. As you can see in my code snippet, I'm using the $field\_array variable to create the nodes. Now my questione: is it possible to use this variable also for the node update functionality?

Regards

M.

```
 public function ausgabe($import_node,$action,$new_old_uid,$new_old_nid) {
    global $content_type;

    $lang = $this->get_current_language();

    $field_array = [
        'uid' => $new_old_uid["new_uid"],
        'type' => $content_type,
        'langcode' => $lang,
        'status' => $import_node->status,
        'created' => $import_node->created ,
        'changed' => $import_node->changed ,
        'title' => $import_node->title,
        'body' => [
            'summary' => "",
            'value' => (isset($import_node->body) && !empty($import_node->body)) ? $import_node->body : "",
            'format' => 'full_html',
        ],
        'field_teaser' => [
            'value' => (isset($import_node->teaser) && !empty($import_node->teaser)) ? $import_node->teaser : "",
            'format' => 'full_html',
        ],
        'field_onid' => array('value'=>$import_node->nid),
        'field_image' =>  $this->get_set_images($import_node->field_ausgabe_bild),
        'field_files' => $this->get_set_files($import_node->files),
    ];

    if($action == "create") {
        $node = Node::create($field_array);
    } else {
        $node = Node::load($new_old_nid["new_nid"]);

    }
    $node->save();

    \Drupal::service('path.alias_storage')->save("/node/" . $node->id(), '/'.$import_node->path, $lang);
    echo $action.": Node " . $import_node->title . ' ('.$node->id().') <br>';

    $this->pre("",true);

}

```

# Answer
There seems to be no method to update a complete node.

But you can do this on a field basis:

```
foreach ($field_array as $field => $values) {
  $node->set($field, $values);
}

```
> 4 votes

---
Tags: nodes, 8
---


title: Bulk field update?

text:
# Question
Title: Bulk field update?
I added a new (text) field to a Drupal 7 content type that already has many nodes.

How can I fill the field with a default value for all these nodes?

# Answer
You can use `EntityFieldQuery` to retrieve a list of nodes, then update the node's fields with `node_save()`:

```
$lang = LANGUAGE_NONE; // Replace with ISO639-2 code if localizing
$node_type = 'page'; // Machine name of the content type

$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'node')
  ->propertyCondition('type', $node_type)
  ->execute();

if (!empty($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));

  foreach($nodes as $node) {
    // Replace field_foo with the machine name of the field to update.
    // - 0 refers to specific value within the field array, for when the field contains
    //    multiple values. If the field only has one value, it should be 0.
    $node->field_foo[$lang][0]['value'] = 'New Value';
    node_save($node);
  }
}

```

If this is a one-off operation, you can use the Devel module's *Execute PHP* function to run the above: otherwise, you can create a simple custom module.
> 38 votes

# Answer
I would use Views Bulk Operations and use the "Execute Arbitrary PHP Script" to do essentially the items above, but you don't have to do all the extra code, just the little snippet that does what you want (like `$object->field_foo['und'][0]['value'] = 'some_value'`)
> 18 votes

# Answer
If you want only to update field with some value, then the more performant alternative to accepted answer is this:

```
$lang = LANGUAGE_NONE; // Replace with ISO639-2 code if localizing
$node_type = 'page'; // Machine name of the content type

$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'node')
  ->propertyCondition('type', $node_type)
  ->execute();

if (!empty($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));

  foreach($nodes as $node) {
    // Replace field_foo with the machine name of the field to update.
    // - 0 refers to specific within the field array, for when the field contains
    //    multiple values. If the field only has one value, it should be 0.
    $node->field_foo[$lang][0]['value'] = 'New Value';
    field_attach_presave('node', $node);
    field_attach_update('node', $node);
  }
}

```

The difference is in using directly `field_attach_presave` and `field_attach_update` functions, which update correctly only node field and skip the rest of node saving process. This has an impact that no node presave/save hooks will be called, "changed" date will not be updated to current date etc. According your use case it may be better as using whole node\_save() process.
> 10 votes

# Answer
Indeed VBO (Views Bulk Operations) is a good solution. Furthermore, with the latest versions, you will find an option "Modify entity values" that provides a very easy way to update nodes language in one operation.
> 4 votes

# Answer
Install and enable the Views Bulk Operations module and create a view with a page display.

Add =\> Bulk operations: Content (Content) field in view.

Refer

Select the Fields you want to set the default value.

In your case its title. In the image it is tags.

Save the view, and go to the page it created. If you have more than one page of results, you can choose to select all items on the current page, all items on all pages, or you can manually check boxes corresponding to individual nodes. At least one checkbox must be checked to proceed.

Now you set the default value and save it.
> 2 votes

---
Tags: 7, entities
---


title: How to bulk update select list fields?

text:
# Question
Title: How to bulk update select list fields?
I have a content type and it has a **select list field**. There are two options **Yes** or **No** and this field is not a required field.

The website has about 100,000 nodes and I want to **bulk update** all nodes in order to select the "Yes" for each node. Is there any way to do this?

# Answer
You have multiple options:

* You can use code that iterates over all nodes and changes the value of the field (you will need some module to execute the code, for example devel).
* Other option is to use the Views Bulk Operations module, build a view which shows a list of nodes of that type, and add a *views bulk operations* field which has the option to edit a node, and this will allow you to select all the nodes in a view and modify a field with the same value.
> 2 votes

# Answer
# Question refinement

This answer ALSO takes into account the answer to my extra comment like "*What should the updated value become for a node that currently has value **No**? Should it become **Yes** or remain **No**?*". And to which you answered like "*Good question :) For this case, every node should have the **Yes** value. But for other cases we should check the current value first and then change if needed, you're right*".

# Step 1: Create a Rules Component

Have a look at this example of a **Rules Component** (in Rules export format):

```
{ "rules_set_an_initial_value_for_a_text_field" : {
    "LABEL" : "Set an initial value for a text field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "NOT data_is" : { "data" : [ "node:field-optionlist" ], "value" : "A" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-optionlist" ], "value" : "B" } }
    ]
  }
}

```

Some more details to further explain the above above example:

* This Rules Component will be used in "Step 2" below.
* In my case I have a selection list field with machine name `field_optionlist`.
* This field actually has 3 possible values, like so:

+ A (=Advanced).
    + B (=Basic).
    + C (=Custom).
* As an example, I decided to use a Rules Condition "The selected value must NOT be `Advanced`" (assume that's the value I do not want to reset).
* For any other value of that field I want the Rules Action to change the value of that field to `Basic`.

Note that I also added the Rules Condition `Entity has field` to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*". For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

Note that I've not added a Rules condition here about selected content types, that's possibly an extra condition you might want to add also. But if the selection list field is only used for the content types you're interested in, then the `Entity has field` condition should be sufficient already.

If you want, just grab (copy) the exported rule above, change all occurences of the machine name of that field to match the machine name of your field (and adapt the possible values like 'A' and 'B' in my example). After doing so you can simply import this Rules Component in your own environment.

After you imported this Rules Component, navigate to `admin/config/workflow/rules/components` in your own site. Then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says ***`Switch to direct input mode`***. Then you'll be able to enter some ***Node identifier*** and hit the ***`Execute`*** button. Depending on the node id you selected (i.e. if it has that field, and if the Rules Condition is satisfied), your node will be updated accordingly.

After you're confident your Rules Component works perfect for all variations of your nodes, move on to step 2 below.

# Step 2: Let VBO to the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your **about 100.000 nodes** to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: **Execute the Rules Component from Step 1**.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Of course there are multiple variations of the above approach, like processing by component type, narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.

**Attention**: to process 100.000 nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

# Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

Happy VBO-ing while Rules-ing!
> 2 votes

# Answer
You need something along the lines of

```
<?php
$nodes = node_load_multiple(array(), array('type' => 'page'));
foreach($nodes as $node) {
  // Only modify nodes that have something in the body field
    $node->field_select['und'][0]['value'] = 'yes';
    node_save($node);
}

```

Modify as needed. Don't forget to clear the caches afterwards.

Another option is installing the Administrative Views and Views Bulk Operations modules, and pointing to Change Value, as seen in the below screenshot
> 1 votes

# Answer
In such scenario, one could be required to preserve node timestamps or avoid whole `node_save()` process, in this case you would do:

```
$key = 'value'; // Key that holds the field value.
$value = '1'; // Assuming '1' is the value for the option "Yes".
$bundle = 'article'; // Name of the node type.

// Get $bundle node ids.
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', $bundle)
  ->execute();

if (isset($result['node'])) {
  // Load matching nodes.
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);

  foreach ($nodes as $nid => $node) {
    // Update the field(s). Assign whole array since some nodes may
    // come with an empty field.
    $node->field_foobar[LANGUAGE_NONE] = array(array($key => $value));

    // Give other modules the opportunity to act before saving fields.
    field_attach_presave('node', $node);

    // Save field data (modules can also hook here).
    field_attach_update('node', $node);
  }

  // Reset cache for the updated nodes.
  entity_get_controller('node')->resetCache($nids);
}

```
> 1 votes

# Answer
Install and enable the Views Bulk Operations module and create a view with a page display.

Add =\> Bulk operations: Content (Content) field in view.

Refer

Select the Fields you want to set the default value.

Save the view, and go to the page it created. If you have more than one page of results, you can choose to select all items on the current page, all items on all pages, or you can manually check boxes corresponding to individual nodes. At least one checkbox must be checked to proceed.

Now you set the default value and save it.
> 0 votes

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


# Question
Title: How to use Feed importer to import content type in which one of the field is node reference field type?
I have a content type, in which one field has multiple values and they are referred from another content type. How can I upload this content type from a .csv file with the help of feeds importer?

# Answer
> 0 votes
I have used feeds tamper. Multiple values are comma separated in the file that I intended to upload. I have added explode plugin and , delimeter in the feed importer page (tamper).

---
Tags: feeds, nodes
---


# Question
Title: Using Contextual Filters to Filter "Content: Published"
Is there any solution to filter "Content: Published" with Contextual Filters?

# Answer
> 1 votes
Out of the box I don't believe this is available. I have a similar use case however I am also using Workbench Moderation. I'm using the moderation state as the contextual filter and using setting a standard filter of current revision as true. This allows you to target a specific moderation state in your view, published being one of them. It could get irritating if you end up with a lot of moderation states and have to target each of them specifically but my use case requires me to get either just published, or all content regardless of published or not.

---
Tags: 7, views
---


# Question
Title: Concept of services, tags, and arguments
I defined a service using the following code.

```
services:
  redirect.repository:
    class: Drupal\redirect\RedirectRepository
    arguments: ['@entity.manager', '@database', '@config.factory']
    tags:
      - { name: backend_overridable }

```

According to my understanding, `'@entity.manager'` , `'@database'`, and `'@config.factory'` are classes on which *the service* is dependent.

Now, the entity.manager service definition is the following.

```
class: Drupal\Core\Entity\EntityManager
parent: container.trait
tags:
  - { name: plugin_manager_cache_clear }

```

It has a tag associated with it. Maybe this tag manages all entity specific cache.

What is the responsibility of the redirect.repository services?
Does this service help communicating with the database directly?
What if I don't have any entity and I implemented `hook_schema()`? Can I mention my custom database table name instead of @entity.manager?
Where do these tags actually get registered?

# Answer
### 1. Database

`redirect.repository` communicates with the database through its usage of the class represented by the `database` service injected into its initialize method (`__construct`). However the RedirectRepository class does not itself use `PDO` to connect to the database.

The redirect module has chosen not to implement an entity to store its data, and is an example of using Drupal's database abstraction layer (DBAL) from the `database` service.

```
// Load redirects by hash. A direct query is used to improve performance.
$rid = $this->connection
  ->query('SELECT rid FROM {redirect} WHERE hash IN (:hashes[]) ORDER BY LENGTH(redirect_source__query) DESC', [':hashes[]' => $hashes])
  ->fetchField();

```

### 2. Entity Manager

The `entity.manager` service provides a *deprecated* helper class to make it easier to get information about **entities** only. If you do not implement an entity, then you cannot use any of the entity-related services such as `entity.manager` or `entity_type.manager`.

### 3. Dependency Injection Tags

> Dependency Injection Tags are little strings that can be applied to a service to "flag" it to be used in some special way. For example, if you have a service that you would like to register as a listener to one of Symfony's core events, you can flag it with the kernel.event\_listener tag.

Tags are treated specially so that when the service container is "compiled" certain classes may be able to make a second "compiler pass" and act on services that are tagged.

See the Symfony2 documentation for more details about compiler passes: http://symfony.com/doc/current/components/dependency\_injection/compilation.html#components-di-separate-compiler-passes
> 3 votes

# Answer
1.) RedirectRepository is not a Drupal core functionality please specify contrib module name or provide code in order to be able to respond to your question.

2.) The arguments in services mean that the are put as dependency an can be directly injected via the \__constructor method of your service. No you cannot mention no table name here! Only services! You need to define a custom entity and service!

3.) A name to identify groups of services. Tags are used in compiler passes and for collecting cache bins. http://symfony.com/doc/current/components/dependency\_injection/tags.html What do you want to achieve with the tags?
> 0 votes

---
Tags: 8, symfony-services
---


# Question
Title: How to avoid the following errors while adding options for Polls in our site?
We use core drupal's Poll module where admin can add options to the polls by clicking "Add option" & at the same time they can remove the options by clicking "Remove option"

Here's our problem,

On Second Submit of AHAH Form by clicking "Add options" we are getting these warnings:

> warning: array\_shift() \[function.array-shift\]: The argument should be an array in ...
>
> warning: call\_user\_func\_array() \[function.call-user-func-array\]: First argument is expected to be a valid callback....

Can some one suggest the possible changes to be done to avoid these errors.

We are using Authcache module with APC . The environment consists of 3 servers. each running its own apc instance. and the servers are behind a load balancer.

### Module file

```
function custom_apachesolr_search_init() {
  module_load_include('inc', 'node', 'node.pages');
}

function custom_apachesolr_search_menu() {
$items['admin/settings/apachesolr/urlboosting'] = array(
    'title'            => 'Url boosting',
    'page callback'    => 'custom_apachesolr_url_boosting',
    'access arguments' => array('administer search'),
    'weight'           => 2,
    'type'             => MENU_LOCAL_TASK,
    'file'             => 'custom_apachesolr_search.admin.inc',
  );
$items['custom_apachesolr_search/vocabulary/callback'] = array(
   'page callback'    => 'custom_apachesolr_search_vocabulary_callback',
   'access callback'  => TRUE,
   'file'          => 'custom_apachesolr_search.admin.inc',
   'type'              => MENU_CALLBACK,
 );

}
function custom_apachesolr_search_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'custom_apachesolr_search_urlboost_form':
      $form['#cache'] = FALSE;
      ahah_helper_register($form, $form_state);
      break;
  }
}

```

### custom\_apachesolr\_search.admin.inc

```
function custom_apachesolr_search_synonyms_form(&$form_state) {

    $form['apachesolr_search_synonyms_settings']['addonemore'] = array(
      '#type' => 'submit',
      '#size' => 30,
      '#value' => t('Add one more..'),
      '#description' => t("If the amount of boxes above isn't enough, click here to add more choices."),
      '#weight' => 2,
      '#submit' => array(''), // If no javascript action.
      '#ahah' => array(
        'path' => 'custom_apachesolr_search/vocabulary/callback',
        'wrapper' => 'more-textboxes',
        'method' => 'replace',
        'effect' => 'fade',
      ),
    );
    $form['apachesolr_search_synonyms_settings']['removeone'] = array(
      '#type' => 'submit',
      '#size' => 30,
      '#value' => t('Remove one..'),
      '#description' => t("If the amount of boxes above isn't enough, click here to add more choices."),
      '#weight' => 3,
      '#submit' => array(''), // If no javascript action.
      '#ahah' => array(
        'path' => 'custom_apachesolr_search/vocabulary/callback',
        'wrapper' => 'more-textboxes',
        'method' => 'replace',
        'effect' => 'fade',
      ),
    );
}

function custom_apachesolr_search_urlboost_form(&$form_state)
{
  cache_clear_all('form_'. $_POST['form_build_id'], 'cache_form');
  //On form load, take the values from the table in to an array.
  if(!isset($form_state['values']))
  {
    // Check for deleted content that wasn't deleted from the index.
    $result = db_query("SELECT casu.urlid,casu.url,casu.score FROM {custom_apachesolr_search_url_boost} casu");
    $urllist = array();
    $edit_content = array();
    while ($urllist = db_fetch_array($result)) {
      $edit_content[][$urllist['url']] = $urllist['score'].','.$urllist['urlid'];
    }
  }
  /*print "<pre>";
  print_r($edit_content);
  print "</pre>";*/
  drupal_add_css(drupal_get_path('module','custom_apachesolr_search').'/css/custom_apachesolr_search.css');
  try {
    $i=0;
    $num_txtboxes = 1;
    if(count($edit_content)>0)
    {
      $num_txtboxes = count($edit_content);
    }
    $txtcnt = 0;
    if(isset($form_state['values']["url$i"]))
    {
      while(isset($form_state['values']["url$i"]))
      {
        ++$i;
        ++$txtcnt;
      }
      $num_txtboxes = $txtcnt;
      if($form_state['clicked_button']['#id']=="edit-addonemore")
      {
        $num_txtboxes += 1;
      }
      if($form_state['clicked_button']['#id']=="edit-removeone")
      {
        $num_txtboxes -= 1;
      }
    }
    else if($form_state['clicked_button']['#id']=="edit-removeone")
    {
      $num_txtboxes = 0;
    }
    else if($form_state['clicked_button']['#id']=="edit-addonemore")
    {
      $edit_content = array();
      $num_txtboxes = 1;
    }
    $form['#action'] = base_path() .'custom_apachesolr_search/urlboost/callback';
    $form['apachesolr_search_urlboost_settings'] = array(
      '#type' => 'fieldset',
      '#title' => t(''),
      '#prefix' => '<div id="urlboostblk">',
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#suffix' => '</div>',
    );

    // Container for just the textboxes.
    $form['apachesolr_search_urlboost_settings']['more-textboxes'] = array(
      '#prefix' => '<div id="more-textboxes">',
      '#suffix' => '</div>',
      '#type' => 'fieldset',
    );
    $form['apachesolr_search_urlboost_settings']['more-textboxes']['urltitle'] = array(
      '#type' => 'item',
      '#prefix' => '<div class="container-inline"><div id="urltitle">',
      '#description' => t("URL Pattern"),
      '#suffix'  => '</div>',
    );
    $form['apachesolr_search_urlboost_settings']['more-textboxes']['scoretitle'] = array(
      '#type' => 'item',
      '#description' => t("Score"),
      '#suffix' => '</div>',
    );
    $form['apachesolr_search_urlboost_settings']['addonemore'] = array(
      '#type' => 'submit',
      '#size' => 30,
      '#value' => t('Add one more..'),
      '#description' => t("If the amount of boxes above isn't enough, click here to add more choices."),
      '#weight' => 2,
      '#submit' => array(''), // If no javascript action.
      '#ahah' => array(
        'path' => 'custom_apachesolr_search/urlboost/callback',
        'wrapper' => 'more-textboxes',
        'method' => 'replace',
        'effect' => 'fade',
      ),
    );
    $form['apachesolr_search_urlboost_settings']['removeone'] = array(
      '#type' => 'submit',
      '#size' => 30,
      '#value' => t('Remove one..'),
      '#description' => t("If the amount of boxes above isn't enough, click here to add more choices."),
      '#weight' => 3,
      '#submit' => array(''), // If no javascript action.
      '#ahah' => array(
        'path' => 'custom_apachesolr_search/urlboost/callback',
        'wrapper' => 'more-textboxes',
        'method' => 'replace',
        'effect' => 'fade',
      ),
    );
    $weights = drupal_map_assoc(array('21.0', '13.0', '8.0', '5.0', '3.0', '2.0', '1.0', '0.8', '0.5', '0.3', '0.2', '0.1'));
    for ($i=0; $i<$num_txtboxes; $i++) {
      $key = '';
      if(isset($edit_content[$i]))
      {
        $key = key($edit_content[$i]);
        $edit = explode(',',$edit_content[$i][$key]);
      }

      $form['apachesolr_search_urlboost_settings']['more-textboxes']["url$i"] = array(
        '#type' => 'textfield',
        '#prefix' => '<div class="container-inline">',
        '#size' => 54,
        '#description' => t(""),
        '#default_value' => $key,
      );
      $edit[0] = ( strpos($edit[0],'.') == false ) ? $edit[0] = $edit[0].'.0' : $edit[0];
      $form['apachesolr_search_urlboost_settings']['more-textboxes']["score$i"] = array(
        '#type' => 'select',
        '#description' => t(""),
        '#options' => $weights,
        '#suffix' => '</div>',
        '#default_value' => $edit[0],
      );
      $form['apachesolr_search_urlboost_settings']['more-textboxes']["urlid$i"] = array(
        '#type' => 'hidden',
        '#description' => t(""),
        '#value' => $edit[1],
      );

      if (isset($form_state['values']["url$i"])) {
        $form['apachesolr_search_urlboost_settings']['more-textboxes']["url$i"]['#value'] = $form_state['values']["url$i"];
      }
      if (isset($form_state['values']["score$i"])) {
        $form['apachesolr_search_urlboost_settings']['more-textboxes']["score$i"]['#value'] = $form_state['values']["score$i"];
      }
      if (isset($form_state['values']["urlid$i"])) {
        $form['apachesolr_search_urlboost_settings']['more-textboxes']["urlid$i"]['#value'] = $form_state['values']["urlid$i"];
      }
    }

    $form['apachesolr_search_urlboost_settings']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
      '#weight' => 4,
    );

    $form['apachesolr_search_urlboost_settings']['submit_message'] = array(
      '#type' => 'value',
      '#value' => t('The Scores were saved.'),
    );

    $form['apachesolr_search_urlboost_settings']['note'] = array(
      '#type' => 'item',
      '#value' => t('Note:Please enter the url pattern like http://www.dentalproductsreport.com/subscribe.'),
      '#weight' => 6,
    );
    //ahah_helper_register($form, $form_state);
  }
  catch (Exception $e) {
    watchdog('Custom Apachesolr Search', nl2br(check_plain($e->getMessage())), NULL, WATCHDOG_ERROR);
    drupal_set_message(nl2br(check_plain($e->getMessage())), "warning");
  }
  return $form;
}

function custom_apachesolr_search_urlboost_form_submit($form_id, &$form_state)
{
  $content = '';
  drupal_set_message($form_state['values']['submit_message'], 'status');
  $terms = $form_state['values'];
  $i=0;
  if (!empty($terms)) {
    db_query("DELETE FROM {custom_apachesolr_search_url_boost} ");
  }

  foreach($terms as $key => $value)
  {
    if($key == "url$i")
    {
      $urls[] = trim($value);
    }
    if($key == 'score'.$i)
    {
      if($i+1==count($urls))
      {
        $scores[] = trim($value);
      }
    }
    if($key == 'urlid'.$i)
    {
      if($i+1==count($scores))
      {
        $result = db_result(db_query("SELECT casu.urlid FROM {custom_apachesolr_search_url_boost} casu WHERE casu.urlid=%d",$value));
        if($urls[$i]!=''){
          if($result>0)
          {
            db_query("UPDATE {custom_apachesolr_search_url_boost} SET url = '%s', score = %f, changed = %d WHERE urlid = %d", $urls[$i], $scores[$i], time(),$value);
          }
          else
          {
            db_query("INSERT INTO {custom_apachesolr_search_url_boost} (url, score, changed) VALUES  ('%s', %f, %d)", $urls[$i], $scores[$i], time());
          }
        }
        /*else
        {
          db_query("DELETE FROM {custom_apachesolr_search_url_boost} WHERE urlid = %d",$value);
          echo "DELETE FROM {custom_apachesolr_search_url_boost} WHERE urlid =".$value;
        }*/
        $i++;
      }
    }
  }
}

/**
 * Callback for autocheckboxes. Process the form with the number of checkboxes
 * we want to provide.
 */
function custom_apachesolr_search_urlboost_callback() {
  include_once 'modules/node/node.pages.inc';
  $form = custom_apachesolr_search_urlboost_callback_helper();

  $checkboxes = $form['apachesolr_search_urlboost_settings']['more-textboxes'];

  // Remove the wrapper so we don't double it up.
  unset($checkboxes['#prefix'], $checkboxes['#suffix']);

  $output = theme('status_messages');
  $output .= drupal_render($checkboxes);

  // Final rendering callback.
  print drupal_json(array('status' => TRUE, 'data' => $output));
  exit();
}

/**
 * Does the very standard things that must be done in any normal callback.ahah_helper_path
 * Used by each callback in this example module.
 */
function custom_apachesolr_search_urlboost_callback_helper() {
  $form_state = array('storage' => NULL, 'submitted' => FALSE);
  $form_build_id = $_POST['form_build_id'];
  $form = form_get_cache($form_build_id, $form_state);
  $args = (array) $form['#parameters'];
  $form_id = array_shift($args);
  $form_state['post'] = $form['#post'] = $_POST;
  $form['#programmed'] = $form['#redirect'] = FALSE;
  drupal_process_form($form_id, $form, $form_state);
  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
  return $form;
}

```

# Answer
> 0 votes
> warning: call\_user\_func\_array() \[function.call-user-func-array\]: First argument is expected to be a valid callback

The warning above basically means you've defined callback function, but it doesn't exist.

For example you should have the functions associated with these page callbacks:

* `'page callback' => 'custom_apachesolr_url_boosting',`
* `'page callback' => 'custom_apachesolr_search_vocabulary_callback',`

but based on your provided information, these callbacks does not exist.

So make sure these functions does exist and file which have them defined is included. The function name should be named exactly as you have defined in `page callback` parameter in `hook_menu`.

---
Tags: 7, forms, caching, search
---