# Question
Title: Unable to interact with a CKEditor_link hook
**TL;DR;**

My `function MYMODULE_ckeditor_link_TYPE_revert()` is never called.

**Context**

I developed a custom module MMS which works pretty fine regarding its own task, but I've trouble when interacting with the CKEditor\_link module.

The problem is that node titles are internally multilingual, including all needed translations of the real title, so they're looking like `[multi][en]The title[fr]Le titre[/multi]`.
The module is responsible to make the final display to be only `The title` when current language is `en`, `Le titre` when it's `fr`, and so on.

This works fine everywhere else, through different strategies.
Regarding CKEditor\_link, I've to do the same when it looks for nodes, first to create autocomplete list of titles, then to revert to a title from a path.

**What's working fine**

Looking at the `ckeditor_link.api.php` contents, I first found the `hook_ckeditor_link_autocomplete_alter()` template from which I could successfully generate the expected autocomplete list using this:

```
function mms_ckeditor_link_autocomplete_alter(&$results, $string) {
  if ($results) {
    foreach ($results as $key => $value) {
      $results[$key] = ...extract real title from $value...
    }
  }
}

```

**The issue**

Regarding the revert process, `ckeditor_link.api.php` doesn't cite an equivalent `hook_ckeditor_link_revert_alter()`, so the above strategy can't be used.
At the opposite it shows `hook_ckeditor_link_TYPE_revert()`, so I imagined I could work like this:

```
function mms_ckeditor_link_node_revert($path, &$langcode) {
  fb($path, 'Hook revert');##
  $result = ckeditor_link_ckeditor_link_node_revert($path, $langcode);
  if ($result) {
    $result = ...extract real title from $value...
  }
  return $result;
}

```

But this hook is never called, as I could check using the `fb()` included above.

I looked for information about that and notably found these issues:

Although they seem to address my exact problem, I can't figure out what's turning wrong.

---

**EDIT: precisions, based on received comments.**

As evoked by @Mantas Karanauskas I'd been already puzzled by this:

> these hooks can only be implemented by the module that "owns" the types

and I was (and I remain) not really sure of anything about what it actually means.

But we must notice that the `MYMODULE__ckeditor_link_autocomplete_alter()` hook works fine, while it uses the same `node` type: so I tend to think that this type, in the context of my module, is well considered as "owned", whatever it means.

Now based on the @Raf suggestion about `ckeditor_link_get_types()` I just noticed that the CKEditor\_link module calls it the same way both in the *autocomplete* and *revert* processes: one more time this makes me tend to think that type is not the problem, since it's well recognized in the *autocomplete* process.

In the other hand, another point puzzles me from the beginning.
From what I could understand of the general Drupal rules about `added module` hooks interacting with pre-existing `original module` hooks I notably retain that there are two distinct situations, which need two different strategies to be preliminary enforced by the `original module`:

1. For `added module` to be able to **alter `original module` hook results** after it worked, `original module` must have placed a `drupal_alter()` in its own process.
2. For `added module` to be able to **execute its own hook in place of the `original module` one**, `original module` must have placed a `module_invoke_all()` in its own process.

Among the templates showed in `ckeditor_link.api.php`, we find `hook_ckeditor_link_autocomplete_alter()`, which relates to #1 above, and `hook_ckeditor_link_TYPE_revert()` which relates to #2.

Now we can notice that in CKEditor\_link module:

* the *autocomplete* process includes a `drupal_alter()` call (relates to #1 and works fine)
* but despite what is suggested by `ckeditor_link.api.php`, the *revert* process doesn't include any `module_invoke_all()` call (should relate to #2 and doesn't work)

Strictly following the above reasoning would make conclude that the `ckeditor_link.api.php` templates are not reliable and that there is no solution for my issue.
But I hope I'm wrong and a solution exists...

# Answer
> 0 votes
My first guess is that TYPE is wrong, and the hook isn't called because of that. It's a vague term, anywasys. I checked the code and found that ckeditor\_link\_get\_types() gets the types. You may want to add a dpm or such in there, so you know for sure which options the module looks for internally.

**Edit** As discussed in the comments, recapping it here, you may want to patch the CKEditor\_link module. From what you explained in your edit, this seems to be a technical flaw in the module itself. Play around in the module to see if any of the options you found, work, make a patch of it, and contribute it to the original module.

---
Tags: 7, hooks
---


# Question
Title: Is it possible to display a field value as part of Views title?
I'm building a block in Views where different brands show off their respective products, now I'm wondering if it's possible to pass a field value to the title.

I know that `%1` results in displaying the title

I've tried searching for a solution, but fail to find one as I'm not that familiar with the terminologies of Drupal (as in I don't really know what specifics to search for). This might be super simple, but I can't seem to find the answer and if possible it could become pretty useful in the future.

# Answer
Changing a View's title is a theming issue. Have a look at Views: how to programmatically change Views title?. The accepted answer is almost what you need. Add the function to your theme's `template.php` file (or your custom module if you don't have a custom theme yet).

The rest is simply coding. Store the field that you need as a variable `$my_field` and adapt the code from the referenced answer as follows:

```
function MY_THEME_views_pre_render(&$view) {
  if ($view->name == 'YOUR_VIEW_NAME') {
    \\ Store your field: $my_field = ...
    $view->build_info['title'] = "YOUR TITLE" . $my_field;
  }
}

```

You can use the Devel module to inspect `$view` in order to easily find the correct code for `$my_field`.
> 1 votes

---
Tags: views, entities
---


# Question
Title: Function to get all the user permissions
Is there a Drupal 7 function that lists all the user permissions defined from enabled modules?

What I need for a module I am implementing is getting all the permissions and adding to each one a checkbox list.

Is it possible to make the value of the checkbox the same shown in the "permission" column of the "role\_permission" table?

# Answer
There isn't a Drupal function for that. You just need to invoke the `hook_permission()` implementations done from the enabled modules to get the permissions they implement.

```
$permissions = module_invoke_all('permission');

foreach ($permissions as $permission => $perm_item) {
  // $permission is the string used in the database.
  // $perm_item['title'] is the string normally used in the UI.
}

```
> 0 votes

# Answer
There is a Drupal function for that, `user_permission_get_modules()`, which returns an associative array, whose keys are the permissions and values are the modules that define those permissions.

If you only need the permissions without the module names, you can use `array_keys`:

```
$permissions = user_permission_get_modules();
$permissions = array_keys($permissions);

```
> 3 votes

# Answer
In a custom module add this code (Devel module needs to be enabled) use the following code.

*Alternatively, paste this code into Development-\>Execute PHP Code (you'll need to TEMPORARILY grant the user the the Devel:Access Developer Information and Devel:Execute PHP Code permissions and remove after testing):*

This will output using the dpm() function all the current users' roles and all their permissions (all, granted and denied) in the format ModuleName:PermissionName -\> True/False

```
global $user;
dpm($user->roles, 'user roles');

$permissions = user_permission_get_modules();
foreach ($permissions as $key=>$value) {
  $has_perm = user_access($key);
  $perms["$value:$key"] = $has_perm;
  if ($has_perm) {
    $perms_true["$value:$key"] = $has_perm;
  } else {
    $perms_false["$value:$key"] = $has_perm;
  }
}
dpm($perms, 'all user permissions');
dpm($perms_true, 'granted user permissions');
dpm($perms_false, 'denied user permissions');

```
> 1 votes

---
Tags: users
---


# Question
Title: How to make Drupal treat the parameter passed in url as different pages?
I have used successfully implemented a HelloWorld Example module. I have modified module to query mysql database and output based on url parameters. For Example, visiting the following relative paths

* `/hello/rakesh` will output Detailed Profile of Rakesh.
* `/hello/shawn` will output Detailed Profile of Shawn.

I used the parameter passed in url to show a detailed profile of the person. I want Drupal to treat them as different pages. What changes should I do?

# Answer
> 0 votes
Make a menu item (hook\_menu() in your example module) with hello/%user as path. In the path callback, you process the parameter so the right profile is shown.

---
Tags: 8, uri
---


# Question
Title: Can you use basic FAPI without drupal_build_form?
is there any way to use simple FAPI (such as dropdown selection box) without processing it with drupal\_build\_form?

The thing is, I have a page with a custom table view and a drop-down selection widget that limits the view. The only thing that I need the selection widget to do is to redirect me to '...the\_page/id\_of\_selected\_item' (or 'the\_page?gid=id\_of\_selected\_item). And it seems to me that using full form support for such a simple task (which a basic redirect surely is) is a bit of a overkill...

I know I can render the selection widget easily without the form support but then neither AJAX nor simple submit button (that would send the data trough PHP POST) works.

BTW: Is there any way to do simple PHP forms in Drupal?

# Answer
> 0 votes
From https://api.drupal.org/api/drupal/includes%21form.inc/function/drupal\_get\_form/7.x :

> This function should be used instead of drupal\_build\_form() when $form\_state is not needed (i.e., when initially rendering the form) and is often used as a menu callback.

It still does a drupal\_build\_form under the hood, though, but at least you don't have to do it. Mind you, it may or may not work in your specific case, depending on where / how you create and call your form.

---
Tags: forms
---


# Question
Title: How to configure the Answers module to organize questions by product subpages?
I want to use a question and answer system for different subpages. I have many products and on each product page should be a question and answer system. The "Answers" module is good, but I can only configure it for general use. Users can see all questions and answers there.

I want to configure it so that they can only see questions and answers to the specific product (subpage), like these relative paths:

* /category/product1/question1
* /category/product1/question2
* /category/product2/question1

How can I configure the Answers module to get this result?

# Answer
> 1 votes
I'm assuming you're using the most recent 7.x.-4.x version of the Answers module. The new demo site uses a further enhanced version of the most recent dev release. For example the views have been enhanced and will be pushed to D.O shortly. These views are available already in Views Export format via files attached to comment #5 in issue #2783513).

Here is a screenprint of the (new) view to show all the questions:

Note the **Topics** column in the above views result: it's just a term reference field, added as an extra field to the "*Question*" content type (which comes with the module). With that in mind, you could use a similar approach:

* **Step 1**: Add a similar (mandatory) field, I'd recommend an Entity reference field. So that when a question is created the question author indicates which product your question is about.
* **Step 2**: Enhance the view to add a filter related to the product.
* **Step 3**: Adapt the path of your enhanced view that matches your requirements.

**Note**: regarding the "...*so that they can only see*..."-part of your question it may be sufficient to just filter the view as described above. But if you actually want to restrict access to any of the questions, you can use the access method/module of your choice to limit access to the Question nodes. Red flag: be aware of the "Disable Query Rewriting" discussion (and tune that views setting if needed).

Disclosure: I'm a co-maintainer of this module.

---
Tags: 7
---


# Question
Title: Field validation error on nodereference field during D6 to D7 migration
I'm migrating a D6 site to D7.

There are several content types that have cck noderefenrce fields that use referenced views for content types that can be referenced.

When I run the migration, I get a field validation error:

> Field validation error for field: field name: this post can't be referenced.

In the CLI, I've used `--user=1` to see if it was a permissions problem, but no luck.

Has anyone experienced this? Any hints or suggestions?

# Answer
> 0 votes
It doesn't look like there's support for migrating nodereference fields in D2D migrate. You'll need to write a custom migrate class. In general, I haven't had much luck with the D2D GUI; it's only useful for super-simple migrations.

Writing a custom migration class (especially if you're using `migrate_d2d`) is really quite easy to do and a worthy exercise. Take a look at the `migrate_d2d_example` code. The nice thing is that migrate keeps track of the mapping between the old NIDs and the new so that you need only write one line of code in your constructor to ensure the reference field has the right value.

See: Migrate D6 node reference to D7 entityreference

---
Tags: entities, migrations, nodes
---


# Question
Title: How to add a description to the node title field in form
In my Drupal 8 project I tried to find a way to add a description to the title field of a node form by hook\_form\_alter. Following code(s) did not lead to success:

```
$form['title']['widget'][0]['#description'] =  \Drupal\Core\Field\FieldFilteredMarkup::create('hallo');
$form['title']['widget']['#description'] =  \Drupal\Core\Field\FieldFilteredMarkup::create('hallo');
$form['title']['#description'] =  \Drupal\Core\Field\FieldFilteredMarkup::create('hallo');

```

What is the correct place to define a description for the node title field?

# Answer
After several trial and errors this is the code working:

```
$form['title']['widget'][0]['value']['#description'] =  \Drupal\Core\Field\FieldFilteredMarkup::create('hallo');

```
> 3 votes

---
Tags: 8, forms
---


# Question
Title: How to use Rules send an email with a list of nodes that fill certain conditions?
I would like to send an email everyday that has a list of nodes that are filtered by certain conditions. I think the Rules module would be a good place to start.

**Real Example:**

* Content Type named "Issue".
* Field inside Issue that connects a user as Responsible Party for the issue.
* Field inside Issue that defines it as either "Active" or "Resolved".
* Email a list to the responsible party of their Issues that have a "Active" status.

If this can be done with Rules, what event do you have it react to? I would guess the core functionality of it would be put in a component that rescheduled itself every 24 hours. Then the action of the component would be "Send Mail". How would it grab the list of nodes that fulfill the conditions?

# Answer
> 3 votes
When you want to run a rule periodically, use the event **Cron maintenance tasks are performed**.

This will trigger your rule whenever cron runs.

See the cron documentation on drupal.org for more information on cron and its configuration.

Because this action doesn't specifically involve nodes, the next problem is loading the nodes you want to act on.

How you do that depends on which nodes you want to load the nodes. Examples are (there are likely also other ways):

* The **Load a list of entity objects from a VBO View** action that is provided by the Views Bulk Operations module. This was you can set up a view that lists the nodes you want to target and load the nodes from that list.
* The **Fetch entity by property** action. This could be used to fetch all content of a given content type.

When you have a list of entities you can loop add a loop to your actions to loop through the list and perform actions on each entity.

If you need to check perform conditions as you are looping through (like checking the value of a field on the entities) you can use the Conditional Rules module to add if blocks.

# Answer
> 1 votes
The previous answer (from rooby) is great, except that there is 1 thing I think that it is missing: the original question is about "***every day***": if cron runs multiple times a day (like every hour?), then you get multiple eMails. That's why I think the Rules Event **Cron maintenance tasks are performed** is not the most appropriate event. Instead I would use the "Rules Once per Day" module for that. Here is how it works (as per the comment in issue 2495775, from the module owner):

* You specify a **trigger hour** on the administration settings page for this module.
* The Rule trigger will then **run when cron tasks are first run after the start of that hour**. The actual run time will depend on your cron task timings.

So this is another way to understand/Read this:

* The "Event" will only be triggered when a cron job is run.
* And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

With that, you should be able to adapt your "*rule that sends an email*" to run ... ***once a day***.

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


title: Drush equivalent setup on Windows?

text:
# Question
Title: Drush equivalent setup on Windows?
One of my clients insists on using WAMP for hosting Drupal 7. I've always been using Ubuntu for development, but now I have to work with WAMP. I do much Drush administration with `sql-dump` and modifying Drupal from the command line. I tried Drush on windows, but it is PITA to use.

What are some ways to use Drush as close as possible to the Linux versions? For some reasons, some Drush commands don't properly work on Windows. I usually use `drush sql-dump > backup.sql`, but in Windows there is no equivalent to that.

# Answer
There are four possibilities:

1. Using Git Bash for Drush. Off the top of my head, this won't work for SQL commands, though
2. If you're using Windows 10, you may want to install the anniversary edition update. It gives a Linux bash shell. It also has its limits (no kernel modules), but those limits shouldn't impede Drush use
3. CYGWIN. It may take some fiddling, but may do the trick too
4. Try and persuade your client to use Vagrant, then run Ubuntu in there
> 1 votes

---
Tags: 7, drush
---


title: Why isn't the default template used?

text:
# Question
Title: Why isn't the default template used?
I set Mime Mail as the sitewide default mailing system and overrode `mimemail-message.tpl.php`. My custom template is used correctly for e-mails like account activation, but when I send an HTML e-mail with Rules, the template isn't loaded: I simply get an unstyled HTML text.

Did I forget something (e.g. a configuration for Rules)?

# Answer
> 4 votes
Is your administration theme the active theme when the Rule fires? This documentation page about using a custom mail template with Mime Mail might be referencing the issue:

> If you use sub-themes or multiple themes, especially if you use a different administration theme than your default theme, you might end up with a different theme to what you expect.

In the Mail System module configuration settings (admin/config/system/mailsystem), try changing the **Theme to render the emails** from Current to the Default theme or to the theme where your overridden `mimemail-message.tpl.php` lives.

---
Tags: 7, rules, mimemail
---


title: How do I make translatable views?

text:
# Question
Title: How do I make translatable views?
I want to have the front page view with my own title, but if I add it, it is shown for all the languages.

Is it possible to have a different title for each enabled language?

# Answer
> 2 votes
Enable the module "Configuration Translation" and then you get a tab "Translate view":

```
/admin/structure/views/view/[view]/translate

```

where you can add translations and edit the translated view.

The title is in:

**Displays -\> Master Display Settings -\> \[View\] Default Display Options -\> Display title**

---
Tags: views, 8, i18n-l10n
---


title: Change the display name of order total

text:
# Question
Title: Change the display name of order total
the following code to replace the displayed name of the subtotal.

How to change the display name of order total ?

```
// Rename subtotal.
function seven_subtheme_back_office_commerce_price_component_type_info_alter(&$component_types) {
  $component_types['base_price']['display_title'] = t('Sous-total hors remises');
}

```

the following code does not work, it must be poorly written :

```
// Rename subtotal.
function seven_subtheme_back_office_commerce_price_component_type_info_alter(&$component_types) {
  $component_types['base_price']['display_title'] = t('Sous-total hors remises');
  $components['commerce_price_formatted_amount']['title'] = t('ORDERrrrr TOTAL');
}

```

# Answer
For changing order total, this line

```
// Replace ORDER TOTAL text as per your requirement.
$components['commerce_price_formatted_amount']['title'] = t('ORDER TOTAL');

```

should be added inside your above mentioned function. Check if it works.
> 1 votes

---
Tags: commerce
---


# Question
Title: How do I change my navbar from "left to right" to "right to left"?
I built an English language web site, and now I'm working on the Arabic version.

How do I change the navigation bar to be displayed *right to left*?
I'm using the Bootstrap theme 3.3.5.

# Answer
**Note:** Following answer is for D7, but the concept is same for D8 also I think, if you want to do using CSS, Just you need to apply the same logic where to apply CSS `float: left;` and `float: right;`.

This you can do with CSS.

If there is just a menu with list of items, you can do easily with `float: right` at appropriate place.

But, **bootstrap's default** `nav-bar` contains `Logo` `Site name` `primary-menu` and `Secondary-menu`, Hence css will be some complicated.

Now, I have used the following set (**LTR** Default),

>

And after looking their HTML I have applied following CSS,

```
.navbar {
    .navbar-header {float: right;
        a.logo { float: right !important;}
    }
    .navbar-collapse{
        nav {

            ul.menu.navbar-nav {float: right;
                li {
                    float: right;
                }
            }
            ul.menu.navbar-nav.secondary {float: left !important;
                li {
                    float: right;
                }
            }

        }
    }
}

```

After applying the CSS, It has arranged in such a way.

>

If you slightly practice, you can by yourself come to know how it works, it is easy.
> 3 votes

---
Tags: i18n-l10n
---


# Question
Title: Installed a feature, getting warnings on cache clear and view content not loading
The Feature included a menu link, main menu, 2 views, and a custom content type. Now I am getting a warning on cache clearing on my local and dev site. Never saw it before when clearing cache, and one of the views is not loading the content items.

They do load for admin. I have tried setting the view permission to none, to role anonymous, removed sorting by published content, and returning `NODE_ACCESS_ALLOW` in the module's `hook_node_access()`.

The full drush warning is

```
class_exists() expects parameter 1 to be string, array given handlers.inc:34

```

and the watchdog output that corresponds seems to be

```
Warning: strnatcmp() expects parameter 2 to be string, array given in token_asort_tokens() (line 575 of /home/example/public_html/sites/all/modules/token/token.module).

```

I'm at a loss for how all these components interact, or if they are even related.

Edit: module.info file

```
name = Example
description = Example description
core = 7.x
package = Features
version = 7.x-1.0
dependencies[] = course
dependencies[] = menu
dependencies[] = references
dependencies[] = text
dependencies[] = views
features[ctools][] = views:views_default:3.0
features[features_api][] = api:2
features[field_base][] = field_example_key
features[field_base][] = field_example_passcode
features[field_instance][] = node-example-body
features[field_instance][] = node-example-field_example_key
features[field_instance][] = node-example-field_example_passcode
features[menu_custom][] = main-menu
features[node][] = example
features[views_view][] = example_sessions
features[views_view][] = examples
features_exclude[dependencies][ctools] = ctools
features_exclude[dependencies][features] = features
features_exclude[menu_links][main-menu_examples:examples] = main-menu_examples:examples

```

# Answer
> 0 votes
I was able to get the view to display data by Disabling SQL rewriting in the view.

In the view under Advanced \> Other \> Query Settings: Settings \> check Disable SQL rewriting.

---
Tags: 7, views, features
---


title: search_form_alter NOT BLOCK

text:
# Question
Title: search_form_alter NOT BLOCK
I was looking the insertion point to change some stuff in the search form. I manage to change the search block, but I can't find a way to do the same with the form I see in site.com/search/node I was 100% sure the hook should be function SearchformMod\_search\_form\_alter(&$form, &$form\_state, $form\_id) { } But it seems like I'm wrong. If I try to use Theme developer I don't get any .tpl suggestion either. Any Idea ?

# Answer
The hook you want is hook\_form\_FORM\_ID\_alter():

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_search_form_alter(&$form, &$form_state, $form_id) {
  // Code here
}

```

Alternatively you could use hook\_form\_alter():

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    // Code here
  }
}

```
> 1 votes

# Answer
The suggestion `MYMODULE_form_search_form_alter()` did not work for me. Drupal would not even call it. I ended up using:

```
function MYMODULE_form_search_block_form_alter(&$form, &$form_state, $form_id) {
  // Code here
}
```
> 0 votes

---
Tags: search, forms
---


# Question
Title: Error after upgrading ecommerce kickstart is breaking my start
I'm working on someone else's project that hasn't updated its "Commerce Kickstart" (commerce\_kickstart) module in a long time. After I upgrade it using Drush, the site breaks and I'm left with the message when I navigate to the (development) website:

Fatal error: Call to undefined function commerce\_info\_fields() in C:\xampp\htdocs\amherstcopy\sites\all\modules\commerce\_price\_table\commerce\_price\_table.module on line 560

I googled around for the answer, but had no luck. Anyone know how to fix this? Thanks.

# Answer
The only reason commerce\_info\_fields() should have gone AWOL is if the commerce.module file was removed from your server or the module was somehow disabled during your update process. Check those two things: if it's missing, put it back. If it got disabled, try to re-enable it. No clue what about a drush based update would have caused the issue, but I also am unfamiliar with how drush updates distributions. For reference, we document how to update here:

https://drupalcommerce.org/commerce-kickstart-2/install
> 0 votes

---
Tags: commerce, drush
---


# Question
Title: How do I alter the text of the input field in the search form?
I need to alter the text of the search input field. In my quest to do this, I have `dpm()` the content of `$form` on a call to `hook_form_search_box_form_alter()`. The output is the following.

```
Array
(
    [search_block_form] => Array
        (
            [#type] => textfield
            [#title] => Search
            [#title_display] => invisible
            [#size] => 15
            [#default_value] =>
            [#attributes] => Array
                (
                    [title] => Enter the terms you wish to search for.
                )

        )

    [actions] => Array
        (
            [#type] => actions
            [submit] => Array
                (
                    [#type] => submit
                    [#value] => Search
                )

        )

    [#submit] => Array
        (
            [0] => search_box_form_submit
        )

    [#form_id] => search_block_form
    [#type] => form
    [#build_id] => form-Y0XlzH4YO-EqVHxg5wnRf-PrnecuUSGdo5LTCPcLgLU
    [form_build_id] => Array
        (
            [#type] => hidden
            [#value] => form-Y0XlzH4YO-EqVHxg5wnRf-PrnecuUSGdo5LTCPcLgLU
            [#id] => form-Y0XlzH4YO-EqVHxg5wnRf-PrnecuUSGdo5LTCPcLgLU
            [#name] => form_build_id
            [#parents] => Array
                (
                    [0] => form_build_id
                )

        )

    [form_id] => Array
        (
            [#type] => hidden
            [#value] => search_block_form
            [#id] => edit-search-block-form
            [#parents] => Array
                (
                    [0] => form_id
                )

        )

    [#id] => search-block-form
    [#method] => post
    [#action] => /
    [#theme_wrappers] => Array
        (
            [0] => form
        )

    [#tree] =>
    [#parents] => Array
        (
        )

    [#validate] => Array
        (
        )

    [#theme] => Array
        (
            [0] => search_block_form
            [1] => search_box
        )

)

```

Is `$form['search_block_form']['#title'] = '';` the right thing to do here?

# Answer
@NoSssweat has provided a link, it is the answer if you want to alter a placeholder.

But reading your question I am getting other indications also.

### FOR D7:

**Case-1:** If I read the sentence from your question *"I need to alter the text of the search input field"* I think you are talking about the `placeholder`, Now what is placeholder- you can see in following image the word "Search the site" in the text-area is called place-holder.

**Case-2:** But if I read your last sentence, *"Is $form\['search\_block\_form'\]\['#title'\] = ''; the right thing to do here?"* then it talks about other things, this is corrosponds to Text appear when you hover on the input text-area(*"Enter the terms you wish to search for"*) as shown in following image.

I will explain both of that, The best tutorial for this is available here: How to Customize the Block Search Form.

**Case-1**
Paste the following code in your theme's `template.php` file, change the `YourThemeName` with your actual theme-name, save & clear the cache.

```
function YourThemeName_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['search_block_form']['#attributes']['placeholder'] = t('Search the site');
}

```

**Case-2**

```
function YourThemeName_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['search_block_form']['#attributes']['title'] = t('Place a new sentence');
}

```

**Case-3:** If you want title on the block, you can just go to block configuration and put the title whatever you want, it will appear as a title of the Block.

### FOR D8:

as @NoSssweat pointed out in the following comment, how to do in D8. Hence, I am just repeating that comment here as it is needed.
```
function YourThemeNAme_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['keys']['#attributes']['placeholder'] = t('The new placeholder');
}

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to programmatically add a filter that requires a relationship to a view
I have a view filtering out a specific node by nid, and it was working until I added a relationship. I want to filter based on the nid of the target of the relationship, not the base table nid. Here is my code, pre-relationship:

```
$options = array(
  'operator' => '!=',
  'value' => array('value' => $nid),
);
$view->add_item ($display_name, 'filter', 'node', 'nid', $options);

```

I tried replacing `nid` with the view relationship base field alias, but that didn't seem to be recognized at all. How do I indicate to Views that this filter should work via the relationship?

# Answer
I figured this out by a stroke of luck after posting this. Here is what I did:

```
// Get a list of all relationships on the view display
$relationships = $view->get_items('relationship', $display_name);
// In case there are no relationships, set this to null by default.
$last_relationship = null;
if (!empty($relationships)) {
  // @todo: is the last relationship always the one whose ID goes with the returned entities?
  $last_relationship = array_pop($relationships);
}
// Filter out the (un)desired item.
$options = array(
  'operator' => '!=',
  'value' => array('value' => $id),
);
if ($last_relationship) {
  $options['relationship'] = $last_relationship['id'];
}
$view->add_item($display_name, 'filter', $view->base_table, $view->base_field, $options);

```
> 2 votes

---
Tags: views
---


title: How to hide or show Field's Label?

text:
# Question
Title: How to hide or show Field's Label?
Is there any programming method to hide or show each Field's Label of custom content type in twig template files, regardless of fields `manage display` setting?

# Answer
> 5 votes
Heres a little twig filter module that does just that: https://www.drupal.org/project/twig\_field\_value. If you study the code you can see how the filter works and deduce how it works programatically.

# Answer
> 6 votes
Override the template for that specific field and don't print the label.

**field--field-thing.html.twig**

```
{% if multiple %}
  <div{{ attributes }}>
    {% for item in items %}
      <div{{ item.attributes }}>{{ item.content }}</div>
    {% endfor %}
  </div>
{% else %}
  {% for item in items %}
    <div{{ attributes }}>{{ item.content }}</div>
  {% endfor %}
{% endif %}

```

Alternatively, you can preprocess the field and remove the label/change the display, but personally I would do it in the templates so later on the label could easily be added back in.

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


# Question
Title: how can i see recurring payment details on my website?
Currently i am using ubercart for recurring payment everything is working fine i can see status of mine recurring payment on paypal account

But how can i see recurring payment details on my website i have searched so many times on google but not got any relative article.

When i go to **/admin/store/orders/39/recurring** that page always shows blank details .

# Answer
> 0 votes
I'm able to see my memberships at `/admin/store/orders/recurring` (this is Drupal 6). From there I can edit the recurring fees and search based on a number of different properties.

---
Tags: ubercart
---


# Question
Title: Creating view using Index results in "plugin does not exist"
I was having some problems with Search API after adding my second index (using DB not Solr). The index I was trying to create was supposed to just be the body and title of a content type. I was able to build the index just fine, but when trying to attach it to a view (My Test View) I'm getting a funky message directly above the Preview section on the view page.

> The "views\_page:my\_test\_view\__page\_1" plugin does not exist.

I am utterly confused by this. I uninstalled Search API and reinstalled, but the only change is this now happens to both views using a search index. I am able to successfully create non-search index views, but that's the only evidence I have this is even Search API's problem. Can someone please direct me on how to start debugging this?

This is Drupal 8.

# Answer
> 1 votes
I now believe this is some type of caching issue, though I'm not sure why. Originally I thought uninstalling a particular module fixed the issue, but the "plugin does not exist" error appeared the next day when creating a new view. Clearing the cache seems to clear the error, which is a good enough workaround for now until I have more time to dedicate to this.

# Answer
> 0 votes
It is weird try to add on your view configuration file in the context section the following lines:

```
  contexts:
    - 'languages:language_content'
    - 'languages:language_interface'
    - url.query_args
    - user.permissions

```

It seems like when you export the configuration the last two lines are missing.

---
Tags: views, 8, search
---


# Question
Title: show a form in a popup when a button is pressed
I am creating a registration form it has multiple stages. I am able to redirect to another page with the help of a link. How can i get the form as a popup with a button.

```
 $form['adding_disease']=array(
   '#markup'=> '<a href ="nojs">'.t('disease_list').'</a>',
 );

```

Here this snippet is written in a form with many other fields. this link is in the middle of the form.

# Answer
Another solution is to use Ctools Automodal module. This approach is less complicated to @Web-Beest answer.

Here is the example on how to use it.

```
function mymodule_menu() {
  $items['mymodule/form'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form'),
    'access arguments' => array('administer mymodule'),
    'modal' => TRUE,
  );
}

```

The most important line in the above code is `'modal' => TRUE,`.
> 1 votes

# Answer
You can use a CTools Modal window for this.

First you need to add a path to your hook\_menu() which will call the modal function.

```
$items['your_path'] = array(
  'title' => 'Do modal popup',
  'page callback' => 'module_form_modal',
  'type' => MENU_NORMAL_ITEM,
);

```

Then you can create the function which will do the magic. The 'ctools\_modal\_form\_wrapper' will wrap the form so it can be loaded in the modal.

```
function module_form_modal() {
  ctools_include('modal');
  ctools_include('ajax');

  $form_state = array(
    'ajax' => TRUE,
    'title' => '',
    'build_info' => array('args' => array()),
  );
  $commands = ctools_modal_form_wrapper('YOUR_FORM_NAME', $form_state);
  if (!empty($form_state['ajax_commands'])) {
    $commands = $form_state['ajax_commands'];
  }
  print ajax_render($commands);
}

```

Then you need to add a ctools button in your form so it knows to use the modal.

```
$link = ctools_modal_text_button($text, 'your_path', $alt, $class);

```
> 0 votes

# Answer
this worked for me.

```
$form['adding_disease']=array(
'#markup'=>'<a  href="path/nojs" class=" ctools-use-modal" >'.t('click here').'</a>'
);

```

and don't forget to include the below three lines in the callback, before calling the form.

```
ctools_include('modal');
ctools_modal_add_js();
ctools_include('ajax');

```
> 0 votes

---
Tags: forms, ajax, chaos-tool-suite
---


# Question
Title: Why is the replacement not happening when using the Search and Replace Scanner module?
I am using Search and Replace Scanner module to perform replacement of links in my website. When I run this module, It says replacement successful and 250 fields are replaced. My site includes English and Dutch as well.But when I see in the database its not at all reflecting, No changes in the links. I referred this but no success. Give some other suggestions to achieve this.

I tried Drush Search & replace, it works awesome, but I dont want to replace all the links, only body content links should get replace. This filtering option is not there in `Drush Search and Replace`.

Any suggestions?

# Answer
Your scenario sounds similar to what is described in issue # 2616640.

Have a look at Comment nr 6 in it for an explanation for what may be causing it, i.e.:

> It looks like the module assumes that the field content to replace is set to the same language as the node.

Probably your best bet is to try the patch attached to Comment nr 18.
> 0 votes

---
Tags: 7, database, drush, search
---


# Question
Title: Colorbox inline style="display:none" doesn't disappear
I am using colorbox module. I have an inline modal that works o.k, this is the code:

```
<a class="colorbox-inline" href="?width=310&height=460&inline=true#paste-data-to-lp">view content</a>

<div class="colorbox-inline" id="paste-data-to-lp" style="display: none;">
  <pre>
    <input name="name" type="name" />
    <input name="phone" type="phone" />
    <input name="email" type="email" />
  </pre>
</div>

```

This code is an a view header.

When I click the link the modal pops but it is empty. I've noticed that the `style="display: none;"` in the div does not disappear.

What can cause this?

Any help will be great.

# Answer
> -1 votes
O.k... I changed the code to this and it works...

```
<a class="colorbox-inline" href="?width=500&height=500&inline=true#id-of-content">Link to click</a>

    <div style="display: none;">
    <div id="id-of-content">
     <pre>
        <input name="name" type="name" />
        <input name="phone" type="phone" />
        <input name="email" type="email" />
      </pre>
    </div>
    </div>

```

---
Tags: javascript
---


# Question
Title: How do I migrate from the Taxonomy Access Control module to the Group module?
We have a Drupal 6 site, and we are making use of the Taxonomy Access Control module for access control. We evaluated the migration steps, and even if that module could be ported to Drupal 8, we could use a different approach.

We are evaluating the Group module as an alternative to content access control, but there are no automatic path to migrate from. What would the preferred migration path be?

# Answer
My recommendation: go for such replacement. In doing so, you could use the approach detailed in How to bulk assign content to a group. This community documentation page explains how you can use the Rules module together with the VBO module to bulk-assigning existing content to groups.

Here is the Rules Component included in that page (in Rules export format):

```
{ "rules_assign_a_node_to_a_group" : {
    "LABEL" : "Assign a node to a group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ACCESS_EXPOSED" : "1",
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "group" : { "label" : "Group", "type" : "group" }
    },
    "ACTION SET" : [ { "data_set" : { "data" : [ "node:group" ], "value" : [ "group" ] } } ]
  }
}

```

Refer to the community page mentioned above for more details.

PS: the above rule assumes your migration target is D7 (there is no stable Rules release for D8 yet ...). But by using the Group module you're in very good shape also to later on upgrade to D8 also, since this module supports both releases.
> 1 votes

---
Tags: migrations, taxonomy-terms
---


# Question
Title: Is there ever justification for adding HTML before passing content to a twig template?
There seem to be many people trying to pass HTML markup into a twig template and having trouble doing it. It sounds like the best solution is to use something like:

```
$variables['test'] = ['#markup' => '<strong>some markup</strong>'];

```

But, when would this be preferable (or necessary) over adding the markup in the twig template instead?

# Answer
It's not possible to put all html markup in templates. Often for example in case of an error you need to generate some extra markup.

If it is a string constant like in your example this is no problem.

If you have variables, don't concatenate in markup.

Use `Drupal\Component\Render\FormattableMarkup` instead:

```
$variables['error']['#markup'] = new FormattableMarkup('<strong>Error @message at line @line</strong>', [
  '@message' => $message,
  '@line' => $line,
]);

```

Most times you need to make this translatable and this is why `t()` is still one of the most used functions in drupal:

```
$variables['error']['#markup'] = t('<strong>Error @message at line @line</strong>', [
  '@message' => $message,
  '@line' => $line,
]);

```

If you are in a class use `$this->t()`.

To summarize, the answer to the question is yes, there is justification for adding html in php. This is, if you need to react dynamically on things happening in your code. Then instantiate a new FormattableMarkup object. If you need translation, you can simply use t().
> 3 votes

# Answer
The other answer is the most likely/frequent scenario, the only other scenarios I am able to think of are:

1) It's a preference thing, the person does not want to add more markup to template.html.twig so it looks cleaner.

2) `'<strong>some markup</strong>'` is actually a variable which you cannot predict the markup of.

```
$variables['test'] = ['#markup' => $foo];

```

Maybe `$foo` has a value from a WYSIWYG enabled field.
> 1 votes

---
Tags: theming, 8
---


title: hook_menu() with enabled languages

text:
# Question
Title: hook_menu() with enabled languages
I'm trying to implement hook\_menu() in my module. The problem is, it doesn't add the menu item for English while it does for Turkish. I'm guessing it has something to do with title arguments, but I can't be sure. Below is my code:

```
function suweb_agi_menu() {
  global $language;
  $lang = $language->language;
  $items = [];
  $items['agi'] = [
    'title' => ($lang == 'tr')?'AGİ (Aile Geçim İndirimi)':'AGİ (Family Status Declaration)',
    'page callback' => 'drupal_get_form',
    'page arguments' => ['suweb_agi_form'],
    'access arguments' => ['access content'],
    'menu_name' => 'menu-sol-menu'
  ];
  return $items;
}

```

What am I doing wrong?

# Answer
> 1 votes
The following code does what you seem to need (screenshots attached). The following modules need to be activated:

* i18n\_menu (part of the i18n)

Further configuration:

* I added a new language (tr) and set language detection to "Determine the language from the URL (Path prefix or domain)."
* I added a new menu with machine name (menu-sol-menu) and set the translation mode to "Translate and Localize". Also added the new menu as a block to the header region of the theme.
* Added the following code in a custom module and activated it.

```
function agi_menu() {
  $items = [];
  $items['agi'] = [
    'title' => 'AGI (Family Status Declaration)',
    'page callback' => 'drupal_get_form',
    'page arguments' => ['node_form'],
    'access arguments' => ['access content'],
    'menu_name' => 'menu-sol-menu'
  ];
  return $items;
}

```

I visited the menu admin page and saw that a new menu item was added:

I checked the language option for that new menu item, it was set to neutral.

I visited the home page of my drupal instance and checked that the menu item appears, for both english (default language) and turkish, using the URL to define the current language.

Finally, I looked in the translate interface for the title of the menu item.

Conclusion: The provided code with the described configuration works as expected by the OP.

Good luck!

N.B.: Especially for the 'title' and 'title callback' properties, the documentation is very clear about how to use them in a multilingual setting

> "title": Required. The untranslated title of the menu item. "title callback": Function to generate the title; defaults to t(). If you require only the raw string to be output, set this to FALSE.

# Answer
> 1 votes
The code you are using doesn't work simply because `hook_menu()` is not called all the times. Drupal caches the result of the implementations of `hook_menu()` and call them when the cache is invalidated, for example, when after a module has been enabled/installed, or disabled/uninstalled. Changing language doesn't invalidate the cache Drupal uses for `hook_menu()`, so your code would keep using the title in the same language until a module is non installed, for example.

The code you are using is also useless. Just use the following one, and the title would be shown in the same language used for the page, if there is a translation for that language.

```
function suweb_agi_menu() {
  global $language;
  $lang = $language->language;
  $items = [];
  $items['agi'] = [
    'title' => 'AGİ (Family Status Declaration)',
    'page callback' => 'drupal_get_form',
    'page arguments' => ['suweb_agi_form'],
    'access arguments' => ['access content'],
    'menu_name' => 'menu-sol-menu'
  ];
  return $items;
}

```

You can always provide a translation for your menu title on admin/config/regional/translate/translate. (It requires the Locale module.)

---
Tags: 7, routes
---


# Question
Title: Grouping content by taxonomy, multiple taxonomies by node
**Note:** The solution should not change the main Views properties, mainly that it is a View of content nodes.

I have a content type (books) which are under a taxonomy (Category). I have created a View to show the titles. By using "Grouping field" with the category (see picture #1), I can get the title of the category and order by that.

However, when I have books which are classified under several Categories (in this example, the book about Chess is under Sports and Science), I get a mixture of taxonomies in the Grouping field displayed, and the book does not appear in the other categories. I would like it to appear under Sports and under Sciende, and get rid of this "third" combined taxonomy "Science, Sports". (see picture #2).

**Image 1**

**Image 2**

# Answer
> 5 votes
You have many solutions available.

**Solution 1:**

Enable "Use aggregation" option with the default settings, it should be enough.

**Solution 2:**

You can create a view of terms and add a "Relationships" with "Taxonomy term: Content using Category". As fields you have to add the content fields (with the new relation) and the term name (used for the grouping).

This is an example of the view assuming the content type is "article", the category field is called "field\_category" and the vocabulary is "category":

```
$view = new view();
$view->name = 'nestedexample';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'nestedexample';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'nestedexample';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'name',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Taxonomy term: Content using Category */
$handler->display->display_options['relationships']['reverse_field_category_node']['id'] = 'reverse_field_category_node';
$handler->display->display_options['relationships']['reverse_field_category_node']['table'] = 'taxonomy_term_data';
$handler->display->display_options['relationships']['reverse_field_category_node']['field'] = 'reverse_field_category_node';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'reverse_field_category_node';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name_1']['id'] = 'name_1';
$handler->display->display_options['fields']['name_1']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name_1']['field'] = 'name';
/* Sort criterion: Content: Title */
$handler->display->display_options['sorts']['title']['id'] = 'title';
$handler->display->display_options['sorts']['title']['table'] = 'node';
$handler->display->display_options['sorts']['title']['field'] = 'title';
$handler->display->display_options['sorts']['title']['relationship'] = 'reverse_field_category_node';
/* Sort criterion: Taxonomy term: Name */
$handler->display->display_options['sorts']['name']['id'] = 'name';
$handler->display->display_options['sorts']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['sorts']['name']['field'] = 'name';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'category' => 'category',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'nestedexample';

```

**Solution 3:** Another solution is adding a relationshipt with the taxonomy terms "Content: Taxonomy terms on node" and use the taxonomy term from the relationship as group by field. I hope this will help you.

# Answer
> 1 votes
Since the base table of view should not be changed, the required grouping can be achieved by disabling the Multiple field settings value.

* For the taxonomy reference field, disable "display all values in same row"

Now when grouped by taxonomy term, it should list the items in expected order

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


# Question
Title: How update user info using its UID in a custom module?
We have a webform and when submitting this form we would like to update user info in the database regarding values of submitted Webform.

I already managed to get the submitted values from the webform in my custom module. But I don't know how to update the user info in the database because all user info are in separated tables.

*I can run a few update queries for each value but it's not a logical way for me!*

Any other suggestions?

# Answer
You can equally use either `user_save()` or `field_attach_update()`.

```
// Load the user's account.
global $user;
$account = user_load($user->uid);
$edit = $account->field_my_custom_field[LANGUAGE_NONE][0][value] = $new_value;
user_save($account, $edit);
// field_attach_update
$account->field_my_custom_field[LANGUAGE_NONE][0][value] = $new_value;
field_attach_update('user', $account);

```

The difference between using one function or the other is that `user_save()` will update all the user fields whereas `field_attach_update()` will update only the specified field.
> 1 votes

---
Tags: users, database
---


# Question
Title: Webform: how to display warning message, when clicking upload, and no file is chosen?
I have a webform, in which I have file upload.

However, when user chooses no file, he is still able to click upload and nothing happens. I would like to have there similar message like when he chooses file with extension which is not allowed. How can I achieve this?

# Answer
> 0 votes
You could use the client side validaiton module install it then configure it for webforms , you could also use the module's hooks to customise error messages or create custom error handling functions client side validation

---
Tags: webforms
---


# Question
Title: How to change field cardinality per form either programatically or by rule?
I've a multipage form (where each page is determined by field group) where on the first page user type number of people in text field and on the second one I would like to show X number of field collection instances based on the given number. So if user selects 5 people, I expect to see 5 field collection placeholders to fill for the user and no more *Add another item* buttons (especially when field cardinality is set to Unlimited).

Is there any solution which can achieve setting up cardinality per form state by a rule or from the code?

# Answer
> 6 votes
There are the following hooks which allow to alter the widget form such as `hook_field_widget_form_alter` and `hook_field_widget_WIDGET_TYPE_form_alter`, but they only apply to widget form element.

As for workaround, it's possible to set the field to Unlimited and use `hook_form_alter` to remove add\_more element manually like:

```
$form[$field_name][LANGUAGE_NONE][0]['remove_button']['#access'] = FALSE;
$form[$field_name][LANGUAGE_NONE]['add_more']['#access'] = FALSE;

```

or overriding/removing `#theme`:

```
unset($form['field_foo'][LANGUAGE_NONE][0]['#theme']);

```

for certain conditions.

---

Using Rules, it's possible to use Rules Forms Support module which can deal with form elements, so you can change the `items_count`. Here is sample rule dealing with a multi value field in Entityform:

```
/**
 * Implements hook_action_info().
 */
function mymodule_entityform_rules_rules_action_info() {
  return array(
    'foo_entityform_rules_set_cardinality_value' => array(
      'label' => t('Change items count of a multi value field'),
      'group' => t('Rules Forms'),
      'parameter' => array(
        'form' => array('type' => 'form', 'label' => t('Form')),
        'form_state' => array('type' => 'form_state', 'label' => t('Form State')),
        'element' => array('type' => 'form_element', 'label' => t('Target Element')),
        'value' => array('type' => 'form_element', 'label' => t('Value from Element')),
      ),
      'base' => 'foo_entityform_rules_set_cardinality_value',
      'callbacks' => array(
        'access' => 'rules_forms_integration_access',
        'form_alter' => 'rules_forms_element_form_alter',
      ),
    ),
  );
}

/**
 * Implementation of rule callback.
 */
function mymodule_entityform_rules_set_cardinality_value($form, $form_state, $element, $value) {
  module_load_include("module", "rules_forms", 'rules_forms');
  $val_elem = &_rules_forms_get_element($form, $value);
  if (!isset($form_state['field'])) {
    return;
  }

  $element = substr($element, strpos($element, ':') + 1);
  $path = explode(':', $element);
  if (count($path) == 1) {
    $path[] = LANGUAGE_NONE;
  }

  $field_state = &drupal_array_get_nested_value($form_state['field'], $path);
  if (!$field_state) {
    return;
  }

  $limit = !empty($val_elem['#value']) ? $val_elem['#value'] : (!empty($val_elem['#default_value']) ? $val_elem['#default_value'] : NULL);
  $field_state['items_count'] = $limit;
  $field_state['field']['cardinality'] = $limit; // Won't work for field_multiple_value_form().
}

```

This works when field is set to Unlimited, however *Add another* and *Remove* buttons still needs to be removed from `form_alter` as shown below:

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

    // Check cardinality.
    // If items_count for a field has reach its cardinality limit,
    // then remove Add more and Remove buttons.
    foreach ($form as $key => $item) {
      if (is_array($item) && !empty($item['#type']) && !empty($item['#language']) && $item['#type'] == 'container') {
        $field = &$form[$key];
        $langcode = $field['#language'] ?: LANGUAGE_NONE;
        $field_state = field_form_get_state($field[$langcode]['#field_parents'], $field[$langcode]['#field_name'], $langcode, $form_state);
        if ($field_state['items_count'] == $field_state['field']['cardinality']) {
          $field[$langcode]['add_more']['#access'] = FALSE;
          foreach (array_column($field[$langcode], 'remove_button') as $key2 => $rm_item) {
            $field[$langcode][$key2]['remove_button']['#access'] = FALSE;
          }
        }
      }
    } // end: foreach
  }
}

```

---

It's also worth to try some patches from Allow cardinality to be restricted (overridden and reduced) in the field instance settings or Add hook alter to override field\_multiple\_value\_form().

There is also Field instance cardinality module which allows the cardinality of specific instances of fields to be overridden.

Some other proposed workaround from here by @donquixote (without actually hacking Drupal core) could include:

* a new widget type with `FIELD_BEHAVIOR_CUSTOM` with widget settings to change a cardinality limit, the name of another ("decorated") field widget type and other settings for the decorated field widget type,
* add a number field in the instance settings form and use `hook_field_widget_properties_alter` to replace `$instance['widget']['module']` (keep original in `$instance['widget']['_module']`) and replace `override $instance['widget']['type']` with own `FIELD_BEHAVIOR_CUSTOM` and save the original in `$instance['widget']['_type']`, so you can do the same decorator trick in `hook_field_widget_form` as above.

---

### Modules

Related modules:

# Answer
> 0 votes
Another approach suggested by @BDuell in his post:

```
  // In your hook_form_FORM_ID_alter() function...

  // Our field and the number of values that we need to have in it...
  $field_name = 'field_machine_name';
  $items_count = count($array_of_values);

  // If we have an array of values that need to be prepopulated...
  if (!empty($array_of_values) && $form_state['field'][$field_name][LANGUAGE_NONE]['items_count']!=$items_count) {
    $form_state['field'][$field_name][LANGUAGE_NONE]['items_count'] = $items_count;
    $form_theme = $form[$field_name][LANGUAGE_NONE]['#theme'];
    $items = &$form_state['field'][$field_name][LANGUAGE_NONE];
    // Generate required number of fields collection
    if ($items_count > 1 and $items['items_count'] != $items_count) {
      $items['items_count'] = $items_count;
      $items['field']['cardinality'] = $items_count;
      $form[$field_name][LANGUAGE_NONE] = field_multiple_value_form($items['field'], $items['instance'], LANGUAGE_NONE, array(), $form, $form_state);
      // Reset theme function, as field_multiple_value_form hijacks it
      $form[$field_name][LANGUAGE_NONE]['#theme'] = $form_theme;
    }

    // Tell our form that we need to rebuild once we are done...
    $rebuild_p = TRUE;
  }

  // ANY OTHER FORM ALTER STUFF

  // If we need to rebuild, notify the form...
  if ($rebuild_p) $form['#after_build'][] = 'MYMODULE_after_build';

```

then in custom module you can define `hook_after_build` like:

```
/**
 * Rebuild the form if necessary...
 */
function MYMODULE_after_build($form, &$form_state) {
  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);
}

```

---
Tags: 7, entities, rules
---


# Question
Title: How do I access the data of a field using PHP?
I'm trying to print out different links to an e-mail based on the values selected in the in the multi-select field. I've used devel to make sure that the field is actually storing the values and it is, but it always goes to the default case in my switch. I am trying to access the information from a node.

```
    print("I am in the php tag");
    $field_lab = field_get_items('node', $node, 'field_lab_s_requested');
    for($i = 0; $i < 4; $i++){
       print("I am in the for loop" + "Count:" + ($i+1));
        $lab = $field_lab['und']['value'][$i];
        switch ($lab) {
            case "127":
                print("link");
                break;
            case "129":
                print("link");
                break;
            case "130":
                print("link");
                break;
            case "132":
                print("link");
                break;
            case "117":
                print("link");
                break;
            case "112":
                print("link");
                break;
            case "113":
                print("link");
                break;
            case "116":
                print("link");
                break;
            case "118":
                print("link");
                break;
            case "121":
                print("link");
                break;
            case "122":
                print("link");
                break;
            case "119":
                print("link");
                break;
            case "123":
                print("link");
                break;
            case "124":
                print("link");
                break;
            case "140":
                print("link");
                break;
            case "143":
                print("link");
                break;
            case "146":
                print("link");
                break;
            case "148":
                print("link");
                break;

            default:
                print("Hit the default case");
                break;
}

```

}

# Answer
Language negotiation is handled for you by `field_get_items`, and the delta is above the field column in the array hierarchy (it goes `$field[LANGUAGE][DELTA][COLUMN_NAME]`).

So using `und` isn't necessary, and you need to change how you're accessing each field item.

Code similar to this should work:

```
$field_lab = field_get_items('node', $node, 'field_lab_s_requested');
foreach ($field_lab as $field_item) {
  switch ($field_item['value']) {
    case "127":

      break;
    // ...
  }
}

```
> 0 votes

---
Tags: nodes, entities
---


title: The answers are being cut off

text:
# Question
Title: The answers are being cut off
I'm using the FAQ module on my Drupal website; I noticed that, on one of the questions, the answer has been completely cut off.

I've tried changing input format (e.g. full HTML instead of WYSIWYG), but I'm still having the same problem.

Is there any problem with the module, or am I doing something wrong?

# Answer
I figured out the answer to this problem

I went to admin/structure/types/manage/faq/display/teaser and noticed that the format said 'Trimmed'. I changed that to 'default' and the answer is no longer cut off.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to update user profile after submitting a webform?
We have a webform and our clients can register for an event using this webform, some of fields are preloaded in the form like *"firstname"* or *"lastname"*, but i like to update the user info in the user's table in case if the user change his/her info in the event registration webform.

I like to know also how can I update user info using single query because when I look at Drupal database, every single info is in different table like *'field\_data\_field\_first\_name'* !

*I'm not really experienced in Drupal development, so thx for ur help.*

# Answer
Resolved with this :

```
function module_name_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id == "form_id")
    {
        $form['#submit'][] = 'module_name_additional_insert';
    }
}

function module_name_additional_insert($form, &$form_state)
{
    $data = $form['submitted'];

    global $user;
    $account = user_load($user -> uid);

    $account -> field_name[LANGUAGE_NONE][0][value] = $data['variable_name']['#value'];

    field_attach_update('user', $account);
}

```
> 0 votes

# Answer
You can use the 'Rules' module to trigger an event when your webform is submitted. Using rules pull out the fields, compare them and update the Profile information if they have changed.

Webform integration: - http://drupal.org/node/474644

Hope this helps.
> 0 votes

---
Tags: users, webforms, updating
---


# Question
Title: How can we find the id of the parent form in preprocess_HOOK() or HOOK_alter() theme functions?
I'm working with an entity-creation form that needs some extensive theming. So far this has required me to alter template suggestions and create (twig) template variables for fieldsets. I've used `template_preprocess_fieldset()` and `hook_theme_suggestions_fieldset_alter()` to do this.

The suggestions and variables I'm creating are specific to one entity type, so I'd like to use the form id or the entity type to limit the action of the functions above, but the variables available within the scope of the functions don't include information outside the scope of the fieldsets themselves--in other words, *I can't find out what form the fieldsets belong to*.

Is there a way, in the context of a theme's preprocess\_HOOK or HOOK\_alter functions, to get information about the parent form?

---

I'd neglected to mention that I'd unsuccessfully tried @Berdir's two-part solution:

1. Set some value in `hook_form_alter()`
2. Access that value in `hook_template_suggestions_fieldset_alter()`

Going back at @Berdir's suggestion, I cracked it (thanks!) In Drupal 8, this combination works for my specific issue (and should work for other implementations of \`hook\_theme\_suggestions\_HOOK\_alter() as well):

```
/**
 * Implements hook_form_alter().
 */
function themename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case 'some_specific_form_id':
      foreach ($form as $key => $value) {
        if (strpos($key, 'field_') === 0) {
          $form[$key]['widget']['#parent_form_id'] = $form_id;
        }
      }
      break;
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function u2d8_theme_suggestions_fieldset_alter(array &$suggestions, array $variables) {
  // Key the use of this suggestion to the front page.
  if ($variables['element']['#parent_form_id'] === 'some_specific_form_id') {
    $suggestions[] = 'fieldset__some_specific_form';
  }
}

```

# Answer
> 3 votes
Not directly, but you can do it in two steps. In a form alter, set whatever information you need on the element where you later need it.

I'd suggest do use some sort of prefix, like `#project_form_id = ABC`

That should then be available in the preprocess/suggestions hooks.

# Answer
> 0 votes
You can use `[hook_field_widget_WIDGET_TYPE_form_alter][1]` if you want to alter an widget on a certain form\_id. One arguments passed through this hook is $form\_state and $context , I think you can find form\_id using them.

---
Tags: entities, 8
---


# Question
Title: Corresponding entity references: two way sync
I have two content types containing a reference to each other. When I update the reference on the node of the first content type, I want the reference on the node of the second content type to be automatically updated. Is this possible?

I used the CNR module in Drupal 7, but that's no longer supported.

# Answer
On the CNR module page, it has introduced the replacement....

> New development is done in the http://drupal.org/project/cer module. This expands the corresponding node reference functionality to enitities. Please focus all attention on getting a stable release of cer as soon as possible.

It can do the exactly same thing as CNR...
> 1 votes

---
Tags: 8
---


# Question
Title: Access denied PDO Exception - other users are getting it but not me
I've set up a new Drupal 7 site (which is still in a vanilla post-install state with no custom code, no themes, no content). This particular site runs on a remote DB, with users (my team colleagues) downloading the Drupal code from a VCS to run on their local machines. Everyone is getting the following error while trying to access the site - **except me.** I can log into the site just fine.

```
PDOException: SQLSTATE[HY000] [1045] Access denied for user
'root'@'localhost' (using password: YES) in lock_may_be_available()
(line 167 of /private/var/www/drupal_media_7/includes/lock.inc).

```

What could be different about my local setup, given that we should all be running the same code and accessing the same database with the same credentials? (since the credentials are all in the code).

How might I start debugging this?

# Answer
Have them check sites/default/settings.php and see if the credentials for your database user (assuming 'root') are correct.

If it is, they should also be checking to see if:

1. The user 'root' has access to the local database and
2. Root has that same password as an sql user
> 2 votes

---
Tags: database, debugging
---


# Question
Title: jdrupal entity_index success function not called
I have an ionic 1 app with jdrupal. In a controller i query a remote api with this code:

```
// If logged in:
console.log('Hello ' + Drupal.user.name);

// Get the Contacts list.
var query = '';
var options = {
   'service': 'rest/basic',
   'resource': 'contact'
};

console.log('before entity_index');

entity_index('contact', query, options, {
   success: function (result) {
      console.log(result);
   }
});

```

the success function is never called. With Drupal.settings.debug = true; i can see the result is returned from the server. Status is 200, response contain my array of objects, but no success function call.

If someone has an idea?

thx, david

# Answer
According to its source code, `success` should be part of the `options`

```
options.success = function(result) {
    console.log(result);
}
entity_index('contact', query, options);

```
> 0 votes

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


title: Custom Ajax Route, I want to cache it

text:
# Question
Title: Custom Ajax Route, I want to cache it
I'm making an Ajax call to a route that performs an entityQuery. I know that when a node is added, it will change the results of that entityQuery, but until then, I want the route to return cached data so it doesn't have to perform the full query every time. What is the fastest way to do this?

Is there a way to put a cache tag on the route itself, that I can invalidate on node creation?

Should I do a $cache = \Drupal::cache()-\>get($cid) kind of thing in the route itself?

Thank you for reading.

# Answer
> 4 votes
What kind of ajax exactly? I guess it returns JSON?

Drupal's standard ajax API currently always does POST requests, those are not cached. So make sure you are doing a GET request.

Render caching is also only available for render arrays/HTML.

Your response would be cached if you return an object that returns CacheableResponseInterface but only by the (anoymous) internal page cache.

To have caching for all users, you likely need to implement your own logic to cache the response object as you suggested. By default, the node\_list cache tag can be used to have it invalidated automatically whenever any node is created or saved. You can define your own cache tag (any string works) that you invalidate yourself only when certain conditions are true (for example, a new node of a specific type, matching your entity query).

---
Tags: 8
---


# Question
Title: Entity Background 'parallax image' positioning 'top' value issue when DOM is manipulated by other modules
I am having an issue where the calculated value for the 'top' property that applied to the parallax-slider image is excessively large and pushing the image outside of the viewport.

```
<div class="parallax-mirror" style="visibility: visible; z-index: -100; position: fixed; top: 397px; left: 0px; overflow: hidden; transform: translate3d(0px, 0px, 0px); height: 400px; width: 1209px;">
    <img class="parallax-slider" src="/sites/default/files/paragraphs/e_background/ct_1920_0.jpg" style="transform: translate3d(0px, 0px, 0px); position: absolute; top: 34946px; left: 0px; height: 755px; width: 1209px; max-width: none;">
</div>

```

In my case as you can see the 'top' property is **34946px** which is 5X the height of my page content (6502px). After some testing I (believe) I have narrowed it down to a result of other modules manipulating the DOM and giving a miscalculation.

I am using the Responsive Menu module as well as the Adminimal Theme and Menu modules which both manipulate the DOM and create various wrapping and spacing elements. Disabling these modules give me slightly different results (however still and issue) This seems like it must be a jQuery firing order issue and these other DOM changes are interfering with the parallax.js calculations?

To confirm I have tested the following:

* I have tested with versions 1.3.1 and the most recent 1.4.2 of the parallax.js library with the same result
* it is not a background colour issue :-p
* Disabling the Responsive Menu module and viewing as an anonymous user the parallax image is still being miscalculated but the number is about 15K pixels less than my initial test.

Can anyone else confirm having issues with these or similar DOM altering modules?

Also How can I alter the module firing weight?

# Answer
For anyone coming across this issue, the real problem was not having a value in the 'speed' field.
> 0 votes

---
Tags: 7, javascript
---


title: hook_node_view selectively responding

text:
# Question
Title: hook_node_view selectively responding
I have inherited a complex site with multiple node type.

My current task is to prevent some nodes from loading based on some preset conditions. To accomplish that I used **hook\_node\_view** in the following function:

```
function accessibility_node_view($node, $view_mode, $langcode){
    drupal_set_message('Node View Responding');
}

```

That's just a simple test but I find that code responds on some nodes types but not on others.

Does anyone know a reason why that would be happening, please?

# Answer
After a long and confusing time experimenting with a lot of various hooks, I finally found **hook\_node\_access**.

I'm not sure if I had tried it previously but it seems to do the trick.

I used the following code to test when any node of any type is being viewed at which point I test for the presence of an particular taxonomy and value to determine if I want certain roles to view and read the page:

```
function mymodule_node_access($node, $op, $account){
    if($op == 'view'){
        if( isset($node->field_accessibility['und'][0]) ){
            ....
        }
    }
}

```

I hope that helps @longboardnode
> 0 votes

---
Tags: 7, nodes, hooks
---


# Question
Title: How to show Total with taxes at admin/commerce/orders when order status is Review (using Commerce)?
I need to show Total with taxes at **admin/commerce/orders** using Commerce. Here the orders are shown without taxes, how can get to show the total including taxes? I didn't see anything like a **Total with taxes** in the view fields.

**UPDATE 2** I need that the system show the taxes when the order status is **Review** It seems to me that the taxes are added when the status is **Completed.** or **Pending**. See my first capture.

**Update 1**: I also see that the taxes are not shown in admin/commerce/orders/XX nor in admin/commerce/orders/XX/edit. How am I supposed to see the taxes for the order?? This can't be right.

Capture with PENDING status

# Answer
> 2 votes
You can use the Commerce price by components module.

> Extension to Drupal commerce that provides a price formatter to enable/disable price components such as discounts or taxes when displaying prices. This gives the admin absolute control over which components should be displayed and which shouldn't. It also provides two Views handlers to display/hide price components in cart totals and order totals. Additionally it has basic rules support that gives to the commerce administrators the ability to do conditions using price components such as discounts or taxes and react accordingly.

Install the module and change the commerce total field of the view with this one.

# Answer
> 1 votes
**To add the display to a custom block or page design:**

1. Go to "Home » Administration » Store » Configuration » Order settings » Manage display"
2. Click on the link at the bottom that says "Custom Display Settings"
3. Enable any custom display mode by clicking the check box beside it. If you have Display Suite, you could also make a new view node. If you go that route, you'll have to make the view mode first, and click the check box beside "Commerce Order" to make sure it's connected to the right part of Drupal.
4. After you've clicked a check box, click Save.
5. A button will appear near the tabs at the top of the "Manage Display" screen, and it will be named after whatever display node you created. If this is the first one you activated, there will also be a "Default" button.
6. Click that button to display the view mode you want.
7. Drag any unwanted display fields below "Hidden" to take them out of your custom display.
8. Click "Save" to finalize the display.
9. Click in the menu beside "Order Total" and pick "Price by components."
10. A configure button will appear beside the menu. Click that button to expand the list of available components.
11. Click the check box beside whatever fields you want to display.
12. Click "Save."

**To add the display of sales tax to a view:**

1. Construct or edit a view and click "Add" beside the list of fields.
2. Click the check box beside "Order Total."
3. In the field configuration dialog, select "Price by components."
4. Click the check box beside whatever fields you want to display.

# Answer
> 0 votes
Edit the view on the admin/commerce/orders page.

Edit the total field and set the formatter to raw amount then exclude field from display.

Next add the tax field to the view and set it to be excluded and to show raw amount.

Then add a php views field that is provided by Views PHP. Now you can use the replacement keys in the php code and you can do something roughly to the follow.

```
return commerce_currency_format([tax] + [total], 'USD');

```

Give this php field the label of Title and you should be all set.

# Answer
> 0 votes
There are two places where commerce adds taxes, based on the type of taxation system (vat vs. sales). I think you have activated the 'tax included in this price', but didn't disable the rules that add taxes to the price afterwards. Once you will do that, the tax will be displayed with my price as soon as an item is added to the cart.

---
Tags: commerce
---


title: how to make drupal use mysqlnd_ms

text:
# Question
Title: how to make drupal use mysqlnd_ms
I have installed mysqlnd\_ms plugin , created the mysqlnd\_ms.json with following configuration.

```
{
  "myapp": {
    "master": {
      "master_1": {
        "host": "mysql://drupal@1x4.xx6.x.1x9",
        "port":  3306,
        "user": "drupal",
        "password": "password",
        "db": "site2"
      }
    },
    "slave": {
      "slave_0": {
        "host": "mysql://drupal@1xx.1x1.xx9.2x1",
        "port":  3306,
        "user": "drupal",
        "password": "password",
        "db": "site1"
      }
    }
  }
}

```

its still not splitting the queries! how will drupal work withmynsqlnd. Do i have make edits in setting.php

# Answer
That extension's operations are transparent to the application, you only need to configure the host that the DB connection is setup with.

From a Drupal point of view, you just need to update the "host" entry for the relevant database in settings.php to match the name of your mysqlnd\_ms application. From the looks of your config file that's `myapp`, so your database connection might look like this:

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'foo',
  'username' => 'bar',
  'password' => 'baz',
  'host' => 'myapp',
  'prefix' => '',
);

```

If that doesn't work, check that the extension is installed, configured, and enabled.
> 0 votes

---
Tags: database
---


title: Ajax calls not properly queued

text:
# Question
Title: Ajax calls not properly queued
I ran into this issue on my own plugin and then decided to download the Drupal Example Modules to discover the same issue was happening to me in the 'ajax\_example' section.

Ajax calls don't seem to queue, and the last message sent to the server overrides the last.

This is the code I am using. (It can also be found in ajax\_example.module.)

```
function ajax_example_autotextfields($form, &$form_state) {
  $form['ask_first_name'] = array(
    '#type' => 'checkbox',
    '#title' => t('Ask me my first name'),
    '#ajax' => array(
      'callback' => 'ajax_example_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
    ),
  );
  $form['ask_last_name'] = array(
    '#type' => 'checkbox',
    '#title' => t('Ask me my last name'),
    '#ajax' => array(
      'callback' => 'ajax_example_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
    ),
  );
  $form['textfields'] = array(
    '#title' => t("Generated text fields for first and last name"),
    '#prefix' => '<div id="textfields">',
    '#suffix' => '</div>',
    '#type' => 'fieldset',
    '#description' => t('This is where we put automatically generated textfields'),
  );

  // Since checkboxes return TRUE or FALSE, we have to check that
  // $form_state has been filled as well as what it contains.
  if (!empty($form_state['values']['ask_first_name']) && $form_state['values']['ask_first_name']) {
    $form['textfields']['first_name'] = array(
      '#type' => 'textfield',
      '#title' => t('First Name'),
    );
  }
  if (!empty($form_state['values']['ask_last_name']) && $form_state['values']['ask_last_name']) {
    $form['textfields']['last_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Last Name'),
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Click Me'),
  );

  return $form;
}

function ajax_example_autotextfields_callback($form, $form_state) {
  return $form['textfields'];
}

```

This is the screenshot of the page.

>

After selecting 'first name', 'second name' before 'first name' has time to finish loading.

>

The 'first name' field is never loaded.

How can I fix this?

# Answer
> 0 votes
Drupal doesn't queue AJAX requests, no. If it's causing a problem, you might want to implement some JS to disable the form while a request takes place.

Alternatively, as it doesn't appear your fields are required, you could use `#states` instead. They don't require an AJAX call, but (depending on your ultimate requirements of course) will give you the same effect as your current code.

---
Tags: 7, ajax
---


# Question
Title: How do I add CSS files only to the front page?
I am trying to add a CSS file to the front page. I have seen Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme; I just need to know the HOOK machine name for the front page.

```
function THEMENAME_preprocess_HOOK(&$variables) {
  $variables['#attached']['library'][] = 'CSSPATH';
}

```

What name should I use for the preprocess function, in order to make Drupal calls it only for the front page?

# Answer
You can find exactly what you want under the topic **Adding Libraries to Specific Pages** at this tutorial Drupal 8 Theming Fundamentals, Part 1

To give you a real example, I am going to explain with the Bartik theme, so you can change easily.

I have created a css file `cssfile.css` under the path `css/cssfile.css`. Now this CSS file I want to use on only front page.

* **Step 1: Add the library to the theme:** Add the following code in the `bartik.libraries.yml`

```
css-filling:
  css:
    theme:
      css/cssfile.css: {}

```

*Note: Here I have given the name `css-filling` to this library but you can give any other name. We will use this name in path*
* **Step 2:** Setting the code in `bartik.theme` so above perticular library(ultimately css) will only be added to front-page,

```
function bartik_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    $variables['#attached']['library'][] = 'bartik/css-filling';
  }
}

```

*Note: Now in the above code the important thing is path, `bartik` part comes form the `themename` and `css-filling` comes from the step-1.*

This code I have tested in my test site and it is working on front-page only.
> 11 votes

# Answer
You can attach libraries in templates, for example `html.html.twig` is an ideal place to attach libraries conditional on the path. You can either use template suggestions, e.g. `html--front.html.twig` or a twig expression.

The other answers revolve around preprocess, which is fine, however preprocess is an abstraction and makes theming development more opaque, i.e. it buries important information in a PHP function, rather than being obvious and clear in the template.

I'm not saying preprocess is bad, only that it depends largely on how you want to work and how opaque/abstract you want to theme.

To attach a library only for the front page in `html.html.twig` we can use the `not` operator and the `root_path` variable as a condition:

```
{{ not root_path ? attach_library('my_theme/my_library') }}

```

If you create the template suggestion `html--front.html.twig` you can attach the library unconditionally:

```
{{ attach_library('my_theme/my_library') }}

```
> 8 votes

# Answer
Make sure you have created the css you want as a library in `libraries.yml` first. Then you need to use `hook_preprocess_page()` like so:

```
/**
 * Implements hook_preprocess_HOOK() for page templates.
 */
function THEMENAME_preprocess_page(&$variables) {
  // Add page preprocess functions here.
  if ($variables['is_front'] == TRUE) {
    // Attach your css
    // - replace "theme_name" with the name of your theme
    // - replace "library_name" with the name of what you called
    //   this particular css library in libraries.yml
    $variables['#attached']['library'][] = 'theme_name/library_name'
  }
}

```

You might be better creating a `page--front.html.twig` file and attaching it there instead via your `libraries.yml` file. This is the preferred approach in Drupal 8.
> 2 votes

---
Tags: 8, theming
---


title: How do I silence PHP errors?

text:
# Question
Title: How do I silence PHP errors?
Is there a way to silence all PHP errors, warnings and notices in Drupal? They are usefull on the devel site but they are a big security risk, and make the site look bad on live.

I know on Drupal 6 the page at admin/settings/error-reporting can stop Drupal from writing errors to the screen, but where can I find this in Drupal 7? It seems it is missing.

# Answer
The path changes, as in Drupal 7 the same page you would before see at admin/settings/error-reporting is now at admin/config/development/logging.
> 29 votes

# Answer
As suggested, in `Administration » Configuration » Development` (at `/admin/config/development/logging`) you can find the setting to disable **displaying** of error messages, but it won't disable error/notices completely.

It's because Drupal 7 enforces E\_ALL, so they're still written to syslog and you can see them in *Recent logs* affecting your website performance.

To disable the notices completely, you'll have to add the following line into your `settings.php` or `php.ini` file:

```
ini_set('error_reporting', E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);

```

> Show all errors, except for notices and coding standards warnings.

To silence all PHP errors, which is not recommended, you may try to addin your settings file:

```
error_reporting(0); // Disable all errors.

```

See: `error_reporting()`

---

Responsible Drupal 7 core code for `E_ALL` logging (file: `includes/bootstrap.inc`):

```
// Enforce E_ALL, but allow users to set levels not part of E_ALL.
error_reporting(E_ALL | error_reporting());

```

---

See also:
> 20 votes

# Answer
One thing no one has mentioned that may be helpful for people to know is that Drupal 7 ignores all local system error reporting levels. So you can't use .htaccess or even php.ini to set php error reporting levels in Drupal.

There is a patch proposed for this in D8, but currently in D7 you're restricted to the 3 error masks –all, none, or errors & warnings– that are set on the admin page kiamlaluno indicated.
> 4 votes

# Answer
Settings are always in **admin/config/development/logging** :)
> 3 votes

# Answer
Not sure why the Drush method is so undocumented, but I have in my build script:

```
drush vset error_level 0

```

... which saves error messages to the log but doesn't show them on screen.
> 2 votes

# Answer
You may need to add quotes to the solution kenorb posted above:

```
ini_set('error_reporting', 'E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR');

```
> 1 votes

# Answer
There is a module for that:

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

From the project page:

So you can

* have a sitebuilder role (or even a special debugger role) see errors and notices
* have others not see errors and notices.
> 0 votes

---
Tags: 7
---


title: Auto Load next Post like qz.com

text:
# Question
Title: Auto Load next Post like qz.com
How the functionality of auto loading the next post when you reach the end of a content is reached. This functionality is seen in Quartz which is built on Wordpress. Most probably they are using the Auto Load Next Post plugin.

Is there any module or a way by which this can be replicated in Drupal (Drupal 8 if possible)?

# Answer
> 1 votes
If you want to go a site builder approach, one solution here is Views Infinite Scroll.

> Views infinite scroll allows you to load and display pages of any view inline, using AJAX (this has been called infinite scrolling, load more, autopaging, endless pages and more). The pager can be triggered with the press of a button or automatically as the user scrolls to the bottom of the view's content.

The caveat with this approach is you'd need to rely on a Views page configured with an *Infinite Scroll* pager set with the **Automatically Load Content** option. In other words, a static URL showing paged full content. That's pretty close to the functionality, but not perfect replication.

---
Tags: nodes, 8, ajax
---


# Question
Title: How do I change date format in the submitted line using only template.php without node.tpl.php?
Using Drupal 8, I can change the date format, and adapt it to the country.

How can I do the same in a Drupal 7 site, where I do not want to create a node.tpl.php file in my theme since I need fast work?

# Answer
You can use `template_preprocess_node` to alter `submitted` variable. Here is the sample code.

```
function awesome_preprocess_node(&$variables) {
  $node = $variables['node'];
  $date = format_date($node->created, 'custom', 'm-d-Y - H:i');
  $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $date));
}

```

The most important line there is `$date = format_date($node->created, 'custom', 'm-d-Y - H:i');`. Change the format (`m-d-Y - H:i`) to any format you want.

See this page about PHP date format.
> 4 votes

---
Tags: 7, theming
---


# Question
Title: In Drupal 8 how can I print the page title within a paragraph.html.twig
Is there a way to print the page title within a paragraph.html.twig?

In Drupal 7 your could just do a drupal\_get\_title(); in an tpl.php and use it as a variable.

That function is depreciated and from what I read about TWIG not in the spirit of themeing in Drupal 8 now.

What is the Drupal 8 way to do this?

# Answer
> 7 votes
An alternative strategy to setting cache context is to use a placeholder. This is a more complex approach but you will never have issues with the database cache table filling up - as 4k4 points out this can be a real problem.

All of this code goes in themename.theme.

First we must define a callback function that returns the page title to the placeholder:

```
function _MyTheme_paragraphs_title_placeholder($page_title) {
  // Must go here, if you attempt to pass in $page_title from preprocess it will
  // be cached!
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

  $title_array = array(
    '#theme' => 'page_title',
    '#title' => $page_title,
  );

  return $title_array;
}

```

Next we create the placeholder in preprocess, we will print a variable in the template, so we must populate it with the placeholder:

```
function MyTheme_preprocess_paragraph(&$variables) {
  // Note: the first item in the #lazy_builder array is our callback.
  $placeholder_title = array(
    '#lazy_builder' => ['_MyTheme_paragraphs_title_placeholder', ['page_title']],
    '#create_placeholder' => TRUE,
  );

  $variables['title'] = $placeholder_title;
}

```

Finally create copy the paragraphs template and use the title variable:

```
<div{{ attributes.addClass(classes) }}>
  {{ title }}
  {{ content }}
</div>

```

This is how I have implemented the breadcrumb title feature in Adaptivetheme (D8 version), to avoid cache context url as I noticed the database entries, I think it's a great method and I'd love more feedback if I have done something wrong - I'm a themer of course, not a hardcore dev :)

# Answer
> 5 votes
You can borrow the code from preprocess breadcrumb:

```
function mytheme_preprocess_paragraph(&$variables)
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $variables['title'] = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

  $variables['#cache']['contexts'][] = 'url';
}

```

Twig:

```
{{ title }}

```

You need to set a cache context. Normally a paragraph is cached until the cache tag is invalidated by a change in the database. It will appear with the title it was first generated with on all following pages. If you use a context on the url, you get a new cached version of the paragraph for every new path. This will fill up your cache table. So you should try to target only that paragraphs where you need the title.

Or think about another solution, because if you have a big site with many pages this may not be a good idea at all.

---
Tags: theming, 8
---