title: Drupal 7 Multilingual Site Search

text:
# Question
Title: Drupal 7 Multilingual Site Search
I have a drupal multilingual site (English and Arabic) . Arabic page site search gives me an extra value "English" in search result. I am using default drupal site search.

What it actually means? How can i remove this?

# Answer
That is because of language switcher enabled. Go the particular content type page, edit and in publishing options CHECK the check box Hide content translation links.
> 1 votes

---
Tags: 7, hooks, search, i18n-l10n
---


# Question
Title: Programmatically add custom meta description via metatag module
I'm trying to add a custom meta tag description for a custom module using the metatag module.

I tried this without success:

```
function mycustommodule_metatag_metatags_view_alter(&$output, $instance) {
  if ($instance == 'mycustom:entity') {
    $output['description']['#attached']['drupal_add_html_head'][0] = array(
      array(
        '#tag' => 'meta',
        '#name' => 'desription',
        '#value' => $my_custom_description,
      ),
      'description',
    );
  }
}

```

# Answer
> 2 votes
Instead of directly altering the metatag, you might want to look into creating a custom token: As described in this article

This will give you more freedom and flexibility. Then you can just use that custom token in the backend of metatags and configure it for content types that you like.

`/admin/config/search/metatags`

If you however, still prefer to use the hook in the op, don't forget that those are cached, you will need to clear all caches before it might appear.

---
Tags: 7, meta-tags
---


# Question
Title: How to write a drupal cron job to fetch data from a link
How can I write drupal cron job that fetches data from a link and update the database ..? Im new to drupal so unable to understand the working of cron after searching alot. Any help will be appreciated ..

# Answer
Create a simple Drupal 7 module, there are a lot of examples for this (i.e. here). Then hook into cron with a `function mymodulename_cron()` and inside the mymodule\_cron function fetch your json data.

Your mymodulename\_cron() will be executed each time, the drupal cron is run. This can be done from outside or from the admin/reports page. Look at /admin/reports/status for info about this.
> 1 votes

---
Tags: cron
---


title: How to customize the edit link in Views

text:
# Question
Title: How to customize the edit link in Views
I have added an edit link before the title in my View by adding the field `Content: Edit link` on top in the fields list, excluding it from display and not adding any text in the field `"Text to display"`. I also rewrote the output of my title field like so: `[edit_node] [title]`.

That gives me a link with the text "Edit" just before the title (in spite of leaving the text field empty as explained above). But I would like to change that text into a symbol. I have tried a number of things including CSS, but I am stuck on this thing.

Can anyone help?

# Answer
Simply rewrite the results of `Content: Edit link` and add image with HTML.

```
<img scr=".....">

```

For Example:
> 2 votes

---
Tags: 7, views
---


# Question
Title: Custom entities created time is always the same
I have a custom content entity type. When I create an instance, the first one got the right created time stamp. But starting with the second one, they all have the same created time stamp: as the first one have!

Why is this happening?

Base field definition:

```
$fields['created'] = BaseFieldDefinition::create('created')
  ->setLabel(t('Created'))
  ->setDescription(t('The time that the entity was created.'))
  ->setReadOnly(TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

Setter / getter methods:

```
  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

```

# Answer
I had my php code cached before adding the `setCreatedTime`method to my custom entity. After clearing the cache everything was fine!

So in general: add the `setCreatedTime` method to your custom entity to make your created timestamp work.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Make an exposed node reference filter to show only nodes created by current user
I am having a little problem I cannot figure out how to solve.

I have a 3 content types:

* campaign
* post
* publication

Post contains a node reference to campaign. Publication contains a node reference to post. I am making a view that lists all publication and I would like to give user an option to filter them by campaign.

However when I am making an exposed filter that allows a user to select a campaign to filter and it works just fine, but I am not able to figure out how to limit exposed filter options to campaign nodes created only by current user?

I know how to do this through code, but I'd like to figure out if this is possible to do via UI.

# Answer
> 1 votes
Either it's a bug by the references module or works as designed.

You can accomplish your goal using the Entity Reference and Views Reference Filter modules.

In Views, add relationship of Referenced Entity.

Click the `+Add` button and add an entity reference view.

Add relationship of Referenced Entity (this is probably already done as it clones your current view) and make field title have a relationship. Remove all other unnecessary fields, if you have them, and just leave the title (make sure you select *for This entity reference (override)*, so it doesn't affect your page view).

In settings, checkmark ☑ content title.

Now go back to your page view and add your entity reference field as a filter.

---
Tags: 7, views, nodes
---


title: How can I get a list of content types?

text:
# Question
Title: How can I get a list of content types?
Is there any way to get a list of some of many content types?

I am not asking to list nodes of content type(s).

# Answer
> 4 votes
**List of content types**

In code you can have the list of all node content types, using the node\_type\_get\_names() method :

```
foreach (node_type_get_names() as $name => $type) {
     // Do something
}

```

After, you'll have to sort them if you do not want to use them all.

**Template override**

It is not a good practice *to hack* any files of the Drupal installation.

But you can easily override any template files provided by the core or a module, directly in your theme folder.

Have a look at this subject : Drupal 7 Template (Theme Hook) Suggestions.

To have a custom content type template, just take the default "node.tpl.php" file, and copy it in your template theme folder, with a name like "node--\[type-machine-name\].tpl.php" (you'll have to replace the "\_" in the type\_name by "-").

**Custom node add form**

And finally I already saw some website using a override node form page using page manager module. But I cannot say how they've done it.

---
Tags: nodes, 7
---


title: How to filter content by date in Views?

text:
# Question
Title: How to filter content by date in Views?
There is one date field = "Display-date" and my content is displaying as:

2016 | abc

2016 | def

2015 | pqr

2014 | wer

I'm applying a filter in view:

```
content:display-date

```

and set `its value = 2016` so that only 2016 year content will get visible. (as shown in below screenshot) I chose time zone = UTC.

This is giving me NULL results.

**How can I get only 2016 year result to get rendered?**

# Answer
You need to use CCYY-MM-DD format

So use **is between** `2016-01-01` and `2017-01-01` which will print all 2016 nodes, don't worry, it will not print any 1st day of 2017 nodes. (tested it)

Use a group filter so you can change the name, if you expose the filter that is.
> 1 votes

---
Tags: views, 8
---


# Question
Title: Execute cron job automatically after a specific interval of time in windows
I've created a custom module in drupal and implemented `hook_cron`. My hook is working perfectly, when I click on run cron button from admin interface.

How can I automatically execute my hook after a specific time interval is passed, without clicking on the *Run cron* button from the administrative interface?

# Answer
Drupal supports two types of cron jobs:

## Poormanscron

This is the default Drupal 7 cron, where at the end of a page request after a certain amount of time, hook\_cron is called. This is controlled by the `Run cron every ...` setting at `admin/config/system/cron`.

This means that if cron is configured to run every 3 hours, the first user to visit the page after 3 hours will trigger cron. This also means on a low-traffic site that it can many more hours before cron is actually called.

## Scheduled cron

This is a much more reliable method which does not involve the user. The principle is that the cron page is called from an external source (usually crontab on the server) at a set interval. As long as the server is up, it will run guaranteed every 3 hours.

In order to enable this, make sure to disable Poormanscron at `admin/config/system/cron` (set it to run never). And create a cron job (General and Linux manual).

In case of a Windows environemt, one can use Windows' built in scheduled tasks. Please refer to this manual page.

UPDATE Be aware that the manual is a little outdated, since Drupal 7 the cron script is protected by a token (to prevent DDoS). So where you see to call `http://www.example.com/cron.php`, add your site specific token. This can be found on your site's status page and looks like this: `http://www.example.com/cron.php?cron_key=xxxxxxxxxx`.
> 1 votes

# Answer
Create a Drupal 7 Module. Then add this following function.

```
function my_sample_module_cron() {
    $sample_module_rule =  60 * 60; //Second * Minute [You can d0 60 * 60 * 2 for running cron in every two hours
    $date = date("Y-m-d H:i:s", time());
    if ((time() - variable_get('sample_module_rule ', 0)) > $sample_module_rule ) {
        variable_set('sample_module_rule ', time());
        sample_function();
    }
}

```

Now visit **admin/config/system/cron** in Administrator Login.

From **Run cron every** option select the time gap for each cron run. In there you will find option from "One Hour" to "1 Week".

If you need smaller timegap install **Ultimate Cron** Module - https://www.drupal.org/project/ultimate\_cron . Where you will be able to setup Advance Cron settings.
> 0 votes

---
Tags: hooks, cron
---


# Question
Title: How to set specific Meta Tag values while creating Article Content.?
I am using Meta tags(Module: Metatag) on my Article content type page. I want to set specific Meta Tag values depending on Article type I select for example by default check some check box for robots.

Does this possible in Drupal 7. If yes please give sample code for doing the same.

# Answer
You don't need any code for that, that Metatag module has that functionality built into it

These 2 listed features could apply to your use case specifically:

> * Per entity and per entity bundle to control default meta tags for all items of a certain type, e.g. all nodes of a certain content type.
> * Ability to override meta tags on each entity object, e.g. to override meta tags on an individual node.
> 2 votes

---
Tags: 7, meta-tags
---


# Question
Title: How do I unpromoted existing node when new node is promoted to front page (Programatically)?
In Drupal 8 I want only one node at a time to be promoted to front page. If user promoted new node the existed should un-promoted automatically.

Can we implement this with events in Drupal 8?

# Answer
> 3 votes
The settings for `FrontPage` is provided by default in Drupal 8. Because the `Frontpage` in Drupal 8 is a View, so it opens all kind of setting feasibility.

Hence if you go at `Admin/structures/views` you will find a view named `FrontPage`.

Hence, you **just need to change the Pager setting. Change `item 10` to `item 1`**.

And in sort criteria It is already `Content: Author on (desc)`, so it will automatically will show new item first. So as you publish new item it will replaced and you have set `item 1` in pager, so only 1 item will be shown on front page which is latest one.

>

---
Tags: 8, event-subscribers
---


# Question
Title: How do I remove classless divs around my paragraphs?
Using `stable` as a base theme, I'm building a theme that will provide styles for paragraph items.

The default output (without any templates affecting this area) seems weird to me, though. Take a look at this simplified version (stripped of `data-`-classes):

```
<div>
    <div>
        <div class="paragraph">
            <!-- paragraph content -->
        </div>
    </div>
    <div>
        <div class="paragraph">
            <!-- paragraph content -->
        </div>
    </div>
</div>

```

As you can see, the wrapping element around all paragraphs, as well as the element wrapping each paragraph lack any classes and are therefore quite useless. Furthermore, for the indivudual paragraph, *another* div inside them *has* a class that would actually be useful, but it's too far down the document hierarchy to be actually useful in styling.

Attempting to remedy this by myself by modifying `paragraph.html.twig`, I can get to the div currently holding the `.paragraph` class, but nothing above that.

I assume all has it's purpose, but I also think this is a weird default behavior, as there is no apparent need for two nested divs for each individual paragraph in any normal use case. Am I missing something?

# Answer
In the theme stable the field twig has two div's, one overall and one for each item. This would match what you have provided as html markup.

So this should work, copy `field.html.twig` from stable to `field--entity-reference-revisions.html.twig` in your theme and remove the div's from there.

That the div's are useless is not correct for all circumstances, because there may be different configurations or modules, which use the attributes of the div's. So if you remove them, you might loose some of that functionality.
> 3 votes

---
Tags: theming, 8
---


# Question
Title: Unable to retrieve node content with drupalgap
I've set up drupalgap on my website, followed all the instructions and got the Hello World example up and running via Ripple. I've also been able to adapt that example to put a new logo and different menus on the front page. However, when I try and view node content it just hangs, with "SyntaxError: Unexpected end of input" being reported via the console. I've not written any code of my own to do this, I'm just trying to access nodes via the top-left menu provided in the tutorial example.

I've made sure the node entity type is enabled in the services. I can view user entities (and if I disable these then I get a 404 so enabling nodes doesn't appear to be the issue.

So I've taken it back to basics and if I navigate to example.com/user/1/json I get the page I expect and likewise for example.com/node/1/json. However when I use example.com/?q=drupalgap/node/1.json I get a blank screen, whereas for example.com/?q=drupalgap/user/1.json I get the JSON output for that user. So I am concluding that for some reason nodes are not being output via drupalgap (returning null instead?) whereas users are.

Any clues?

David

# Answer
Ok, so with thanks to the advice about it being another module interfering with the retrieval of JSON data, I've identified the culprit through a process of elimination.

When I disable the "Node Registration" module the problem goes away and I can view node content through the mobile app.

Of course, that gives me another problem with how to get the functionality Node Registration was giving me, but I'll save that one for now...
> 0 votes

---
Tags: javascript
---


# Question
Title: AJAX error: node form + list field with multiple options + image field
I'm trying to add an AJAX callback to a list field with multiple selection enabled. This works properly on its own, but if I add an image field, the form will throw errors when 2 or more fields are selected.

Here's my setup:

1. Blank installation of Drupal 7 + image + list modules.
2. Create a "Sample" (machine name: `sample`) content type.
3. Add an image field ("Image").
4. Add a list field with possibility to select unlimited values ("List").
5. Enable the custom module below.
6. Try creating a new node and select 2 options in the "List" field. This will throw the following AJAX validation error:
*"An illegal choice has been detected. Please contact the site administrator."*

Code:

```
//
// File: sample.module
//
function sample_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'sample_node_form':
      $form['#id'] = $form_id;
      $form['field_list'][LANGUAGE_NONE]['#ajax'] = array(
        'method' => 'replaceWith',
        'wrapper' => $form_id,
        'callback' => 'sample_form_alter_ajax',
      );
      break;
  }
}
function sample_form_alter_ajax($form, $form_state) {
  // Of course, my logic will be added here.
  return $form;
}

//
// File: sample.info
//
name = Sample
description = Sample
package = Sample
core = 7.x
version = 7.x-1.0

```

Am I doing something wrong or is this a bug in `image.module`?
Is there anything I need to change in the way I set up my AJAX callback?

Thanks!

## Update 1

The problem can be further narrowed to any file upload field. Here's a sample module that can be used standalone to replicate the issue. No need for creating content types.

`sample.module` file content:

```
function sample_menu() {
  $items['sample'] = array(
    'title' => 'Sample page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('sample_page_form'),
    'access callback' => TRUE,
  );

  return $items;
}

function sample_page_form($form, &$form_state) {
  $form['#id'] = 'sample-page-form';
  $form['list'] = array(
    '#type' => 'select',
    '#title' => t('Select something'),
    '#options' => array(
      'option1' => t('Option 1'),
      'option2' => t('Option 2'),
      'option3' => t('Option 3'),
    ),
    '#multiple' => TRUE,
    '#ajax' => array(
      'method' => 'replaceWith',
      'wrapper' => $form['#id'],
      'callback' => 'sample_page_form_ajax',
    ),
  );
  $form['image'] = array(
    '#type' => 'file',
    '#title' => t('Test fileupload field'),
  );

  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit the form',
  );

  return $form;
}

function sample_page_form_ajax($form, $form_state) {
  return $form;
}

```

## Update 2

This seems to work properly if the field type is changed to `checkboxes` instead. Not a real solution though, just a workaround.

# Answer
After additional testing, this seems to be a bug in Drupal core that affects only the `select` form elements.

Workaround is to change the field type to checkboxes. Everything else can stay the same. Values are then passed properly and everything works OK even with multiple file upload fields added to the same form.

Also the validation and submit handlers work as expected in this case.

I created a ticket for Drupal core here.
> 0 votes

---
Tags: 7, forms, media
---


# Question
Title: How to rebuild a cached page when it expires?
I'm using views caching after reading this great Q&A and getting good results. I have to keep the expiration short because I'm showing the "last comment" in the view and those changes often.

I'm thinking about using views content cache to expire the cache every time a comment is added. Or cache actions to do it with rules.

What I would like to do is rebuild the cache immediately after it expires? I read that boost module offers that but I need a solution for authenticated visitors (already use Varnish for anonymous).

The cache graceful module seems to offer that but only has 20 installs (plus requires a couple of other modules).

Are there any other solutions that allow expiring a cache and "warming" it up right away?

# Answer
If you know what functions need to run in order to warm a cache, checkout httprl. httprl\_queue\_background\_callback() is the function to look into using. Simple example of calling watchdog in the background http://drupalcode.org/project/httprl.git/blob/24a88acd2180191d0b54696e577f14615e37302d:/README.txt#l268

In terms of graceful varnish cache clears this has a good example: https://www.varnish-cache.org/trac/wiki/VCLExampleGrace Example of it in use: http://groups.drupal.org/node/63203
> 4 votes

# Answer
Boost for Drupal 7 works admirably well and, thanks to its new Crawler submodule and the Cache Expiration module, you can conditionally expire and proactively re-cache any selection of your pages. With a setup like this you do not need modules such as Views Content Cache because you can achieve the same behaviour with the above concoction, and not just for views (Cache Expiration integrates with Rules, so possibilities are really endless). There is a full recipe to get this working at this page.
> 2 votes

# Answer
There is a rather new Module which is called https://www.drupal.org/project/recacher It works together with https://www.drupal.org/project/expire and https://www.drupal.org/project/httprl\_spider

Instead of re-crawling everything it only re-caches the nodes that have been exipred bei the expires Module.

In my landscape it should work like that: On Node Change / Create -\> Expire -\> Purge from Nginx -\> re-Cache with httprl\_spider.

That way the cache will be fresh in most cases.
> 1 votes

# Answer
I think that your best option is Edge Side Includes. Take a look at the Edge Side Includes integration module. Here is a quote about it (from the module's project page):

> ESI - or Edge Side Includes - is a high performance caching solution for Authenticated users but can be helpful for Anonymous users as well.
>
> Typically, pages which are personalised for authenticated users (even minor personalisations, such as a block which says "Logged in as manarth") will prevent reverse-proxies (which can easily perform 100 times faster than Drupal) from caching the page, because messages intended for one user could then be seen by another.
>
> ESI is a W3C standard to address this issue. The personalised content is replaced with an ESI tag - `<esi:include src="http://example.com/esi/block/xxxxxx" />` \- which is identical for every user; the page can then be cached. Edge devices such as Varnish fetch the ESI URL, and merge its contents with the cached page (and the contents of that ESI URL may also be cached).
>
> This technique can easily improve performance by 10x, 100x, maybe even more.
> 0 votes

# Answer
You should consider using cache actions module in conjunction with a custom module that can reuse the code from cache warmer module.

Cache warming can be done by pinging the changed/desired urls as various users(One user per rule). You would need to make some cURL calls along with the user credentials. Cache Warmer module has the code for how this calls should be made.

So using Caching Actions module you can say when the cache for a particular page should be broken and in the subsequent action in the you could call the function from your custom module for cache-warming that particular url or set of urls.
> 0 votes

---
Tags: 7, caching
---


title: Drupal get form returns string "array"

text:
# Question
Title: Drupal get form returns string "array"
I have module, that should build form. However it is not showing form.

There is my code:

```
function weblabs_form() {
    $form = array();

$form['name']=array(
    '#type'=>'textfield',
    '#title'=>t('Enter your name'),
    '#description'=>t('Your first name goes here')
);
$form['last_name']=array(
    '#type'=>'textfield',
    '#title'=>t('Enter your Last name'),
    '#description'=>t('Your Last name goes here')
);

$form['email']=array(
    '#type'=>'textfield',
    '#title'=>t('Enter your email'),
    '#description'=>t('Your email goes here')
);

$form['country']=array(
    '#type'=>'select',

       '#title'=>t('Select your country'),
        '#options'=>array('USA','UK','France','Japan')
    );

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

    return $form;
}

function weblabs_form_submit($form, &$form_state){
    echo("<h1>TEST</h1>");
    drupal_set_message("TEST");
}

function weblabs_menu() {
    $items['calculator'] = array(
        'title' => 'Kalkulačka WebLabs',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('weblabs_form'),
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
        );
    return $items;
}`

```

# Answer
To print the HTML code corresponding to your form you need to render it:

```
$form = drupal_get_form('weblabs_form');
print drupal_render($form);

```
> 2 votes

# Answer
Maybe the name (id) of your form is not the most appropriate : weblabs\_form reference the hook\_form hook, with is used to add custom form elements to be displayed in the node editing form.

Consider changing its name (and the submit method associate) with something less ambivalent (example: calculator\_page and calculator\_page\_submit).

The drupal\_get\_form method returns a Form API array for a given form ID. You must use the drupal\_render() method to render it properly... See https://www.drupal.org/node/224333#unrendered.

After, the MENU\_CALLBACK option do not generate a menu, but you must be able to access your form on /calculator on your drupal website. The drupal\_render method is directly call from the template (normally).
> 0 votes

# Answer
In addition, if you want to have a form page. You should use `drupal_get_form` as the page call function and the form builder name as the arguments

```
function mymodule_menu() {
  $items['path/to/form'] = array(
    'title' => 'Weblabs Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('weblabs_form'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Pass data from a hook to (be used in another hook)
So in a hook `hook_commerce_cart_order_refresh()` I make some calculations that I would later like to use in a different hook `hook_form_alter`, how can I pass these data/object and use later on?

In that first hook, I have a `EntityMetadataWrapper` but it seems I can only give it data that actually is persisted, and mine should only exist for the request.

Again, I could use `$_SESSION` but that storage is used for persistent storage through multiple requests. And I'm not looking for that.

Any suggestions?

# Answer
You can't, there's no mechanism to pass data from one arbitrary function to another (which is what two separate hooks essentially are). You'll have to make the data available another way.

Drupal uses a pattern like this all over the place:

```
function MYMODULE_get_data() {
  $data = &drupal_static(__FUNCTION__, NULL);

  if (!$data) {
    $data = some_function_to_build_data();
  }

  return $data;
}

function MYMODULE_commerce_cart_order_refresh(...) {
  // Get the data, populating it if it doesn't already exist.
  $data = MYMODULE_get_data();
}

function MYMODULE_form_alter(...) {
  // Retrieve the data.
  $data = MYMODULE_get_data();
}

```

That's a contrived example, it'll make more sense when you plug your own requirements into it.
> 2 votes

---
Tags: commerce, hooks
---


# Question
Title: How to attach css classes to the <h1> title attributes if node_is_page() dynamically?
To preprocess the **node title field** is obviously not the easiest. It has its place in the **node.tpl.php** and in the **page.tpl.php** by default and it has its own status in Drupal core, which makes it not fieldable as simply as other fields and entities in a given content type bundle.

That's why there are many discussions going on at drupal.org and some little helper modules are also around already, to make the title field more flexible in different scenarios like field translation, label design, field order and much more. So if this is your problem you will easely find a little module helping you.

But what if you don't want to touch the behaviour of the title field as designed in core but only **want to preprocess the title to change the markup dynamically?** Suddently google keeps silent. Unlike others I agree with some core contributors who explain wisely why the title field has its reasonable difficulties and why the decision to make it simply a "field like others" is not THAT easy to make. So for some reasion I need a solution in template.php

This is how the page.tpl.php looks like in my case:

```
// page.tpl.php

<?php print render($title_prefix); ?>
    <?php if ($title): ?>
        <?php if ($page): ?>
            <!-- This is where we want to get in with template.php -->
            <h1 <?php print $title_attributes; ?>>
                <?php print $title; ?>
            </h1>
        <?php endif; ?>
    <?php endif; ?>
<?php print render($title_suffix); ?>

```

And this the place where we obvisously should try to make it happen:

```
// template.php

function YOURTHEME_process_page(&$variables) {
    if ($variables['view_mode'] == 'full' &&
        node_is_page($variables['node'])) {
            // do something with $variables['title']['attributes'][];
    }
}

```

But to be honest, I am a little bit lost here, since I only want to change the rendering of `<h1>` to `<h1 class="my_css_class">`. Does anybody has an idea of how to achieve this?

The attributes class seems not to exist this way, because I get an Unknown index warning and the class gets not attached. Or maybe I have to point to $title another way? Maybe something like $node-\>title ? I know how to wrap the title with a new container, or how to change the suffix/prefix. But here would really appreciate your thoughts. Thank you very much ...

# Answer
Okay, as commented under the question, I've tried out another idea: a little bit dirty since this is far away from the way it is supposed to be, but hiding '$title' in page.tpl.php and removing the IF NOT PAGE condition from the standart node.tpl.php (like in Bartik) makes it possible to access the title-attributes array, since node.tpl.php seems to know title-attributes, but page.tpl.php not...

But in this case I have to reimplement the programmatically *"node is page OR node list switch"* toggling of h1 and h2 again, since if-page $title in page.tpl.php did this before:

After removing the complete if-title-title part (in Bartik it looks like this, near the $content) from page.tpl.php,

```
<?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <h1 class="title" id="page-title">
      <?php print $title; ?>
    </h1>
  <?php endif; ?>
<?php print render($title_suffix); ?>

```

... I have added (exchanged) this in the node.tpl.php:

```
//node.tpl.php

// usually we have something like the following here
/*
<?php if (!$page): ?>
   <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?></a>
   </h2>
<?php endif; ?>
*/

// but we exchange it with this ...

<?php print render($title_prefix); ?>

  <?php if ($page): ?>
    <h1<?php print $title_attributes; ?>>
       <a href="<?php print $node_url; ?>">
          <?php print $title; ?>
       </a>
    </h1>
  <?php endif; ?>

  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>">
         <?php print $title; ?>
      </a>
    </h2>
  <?php endif; ?>

<?php print render($title_suffix); ?>

```

Now I do have my title inside of my wanted scope, where I can theme it programmatically inside the main content container. Thanks to Clive for his support on my question, and special thanks to Digidog from drupal.org, who gave me the final hint per mail.
> 2 votes

# Answer
This is how I add classes to titles from page.tpl.php:

In page.tpl.php:

```
<?php if ($title): ?><h1 <?php print $title_attributes; ?> id="page-titles"><?php print $title; ?></h1><?php endif; ?>

```

Note that `$title` prints the title itself. Note that `$title_attributes` prints out `class=''` where included classes are found in `$title_attributes_array['class'][]`.

You can add classes the following way. In template.php:

```
/**
 * Implements template_preprocess_page().
 */
function hook_preprocess_page(&$vars) {

  $vars['title_attributes_array']['class'][] = 'element-invisible';

}

```

Note that the hook\_preprocess\_page function should be \[your\_theme\_name\]\_preprocess\_page.

What's interesting is that `$title_attributes` does not exist in the available variables. Drupal does some magic to allow `$title_attributes` to print as `class='class1 class2'` based on what `$title_attributes_array` contains.
> 2 votes

# Answer
If you are okay with using jQuery, then you can achieve this using the addClass method.:

```
 function YOURTHEME_process_page(&$variables) {

   if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {

       drupal_add_js('
       jQuery(document).ready(function(){
            $('jQery SELECTOR OF H1').addClass('my_css_class');
        });

    ', 'inline');

}

```

}
> 1 votes

# Answer
This is how I made it work:

`template.php`

```
/**
 * Implements template_preprocess_page.
 */
function my_theme_preprocess_page(&$vars) {
  $node = isset($vars['node']) ? $vars['node'] : '';
  // Set class name for the page's title.
  $vars['class_name'] = node_is_page($node) && $node->type == 'node_type' ? ' title-class-name' : '';
}

```

`page.tpl.php`

```
<?php if ($title): ?>
  <h1 id="page-title" class="title<?php print $class_name; ?>"><?php print $title; ?></h1>
<?php endif; ?>

```

Alternatively you may use the Display Suite module which, of course, exceeds the limits of just adding a class to a title.
> 1 votes

---
Tags: 7, theming
---


title: User-Access return value issue

text:
# Question
Title: User-Access return value issue
I'm executing the following code in hook\_init:

```
function my_module_init(){
    global $user;

    $apprenticeship = user_access('prevent publishing apprenticeship job', $user);
    drupal_set_message("CHECKING permission[prevent publishing apprenticeship job]: " . $apprenticeship);
    $content = user_access('access content', $user);
    drupal_set_message("CHECKING permission[access content]: " . $content);
}

```

I am logged in as USER#1 and the *prevent publishing apprenticeship job* permission is **NOT** set for user#1.

However, each time my code executes `user_access('prevent publishing apprenticeship job', $user)` returns 1 i:e true.

As I said, that permission is not set for for the administrator role.

Can anyone help and point out what I'm missing or doing wrong?

PS:

The `access content` also returns 1 but that is set for the administrator role.

# Answer
The user #1 is special, in Drupal. It will always have all permissions, even the ones not explicitly set for the administrator role.

See `user_access()` source code.

```
  // User #1 has all privileges:
  if ($account->uid == 1) {
    return TRUE;
  }

```
> 2 votes

---
Tags: 7, users
---


title: Displaying values on hook_form

text:
# Question
Title: Displaying values on hook_form
I'm displaying a form on admin url :`admin/settings/custom`. In the page argument I pass `array('custom_admin_form'),` to the menu item. In the form function I'm writing form elements to display folder and file names present in the public folder. I get those values through the code below:

```
$dir_path = variable_get('file_public_path', conf_path(). '/files') ;
$fileslist = glob($dir_path . "*.*");
$dirs = glob($dir_path . '/*' , GLOB_ONLYDIR);
foreach($dirs as $directs){
     $names = explode('/', $directs);
     $fnames[] = end($names);
}

```

How can I display the results in the form function? I tried it using `print`, `echo`, `drupal_render` but nothing is working. I've also used `#markup` element, but it was displaying `array()`, not the values of array.

# Answer
You can try something like this:

```
 $form['sample'] = array(
     '#type' => 'item',
     '#markup' => print_r($sample_values, TRUE),
 );

```

or simply just

```
print_r($sample_values);

```

or install `Devel` module and use `dsm` function.

```
dsm($sample_values);

```

UPDATE:

Try this:

```
$form['sample'] = array(
    '#type' => 'item',
    '#markup' => print_array_values($sample_values),
);

```

Then declare the function below:

```
function print_array_values($sample_values){
    $content = '';
    foreach($sample_values as $val){
            $content .= '<div>' . $val . '</div>';
    }

    return $content;
}

```
> 2 votes

# Answer
I would suggest `dpm` or `dsm` or `kpr`, which is very common among Drupal developer for printing variables to debug in Drupal 7. But you need to enable Devel module in your site first as @AlyssaGono suggested.

If you want to use something not depends on other module, you can use `var_dump()`.

Example:

```
var_dump($variable);
drupal_exit();

```
> 1 votes

---
Tags: 7, forms, files
---


# Question
Title: Does Boost work together with Google analytics?
This may be a stupid question, but can the Google Analytic module still track users and count page visits etc. if I use Boost module to speed my site up?

Is there anything I should be aware of? Are there any settings I must do in `robots.txt` for example? (Other than the line `Disallow: /boost_stats.php` which should be entered according to the instructions).

# Answer
I am not a Boost expert, but I know Google Analytics. Google Analytics is client-side JavaScript, so as long as your pages render the Analytics code along with everything else in the HTML, you should be fine. Boost should have nothing to do with it.
> 2 votes

---
Tags: 7, google-analytics, caching
---


title: No working link to network files

text:
# Question
Title: No working link to network files
For an intranet solution I would like to add a bunch of rather static links in Drupal to network files which change from time to time and are maintained by people not using Drupal.

To achieve this I used the link functionality of CKeditor: Protocol URL file:///s:\Gloss.xls target popup window

When I throw `file:///s:\Gloss.xls` into any browsers address field it works perfectly (tried in IE, chrome and firefox) but from a Drupal node clicking on the link explained above, the browsers inspection reveals `Not allowed to load local resource: file:///s:\Gloss.xls` in chrome and firefox, only in IE it works.

What do I need to do to get it working in chrome or, at least in firefox?

# Answer
I think the trouble comes from your browser. See the answer from this question : How can I create a link to a local file on a locally-run web page?

> Some browsers, like modern versions of Chrome, will even refuse to cross from the http protocol to the file protocol, so you'd better make sure you open this locally using the file protocol if you want to do this stuff at all.

Maybe another approach is to make a script witch will get the file from the server side and send it to the client in streaming.
> 0 votes

---
Tags: 7, files, navigation
---


title: How to get bundle in form alter?

text:
# Question
Title: How to get bundle in form alter?
I want bundle in `hook_form_alter`. In Drupal7 we can get all these in hook\_form\_alter.

I tried like this in D7:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $bundle_type = $form['#bundle'];
}

```

Here I am getting bundle in D7. Whereas in D8 I am not getting any bundle like article/page/tags etc.,

# Answer
> 12 votes
This is the final solution:

```
use Drupal\Core\Entity\ContentEntityForm;

$bundle = FALSE;
$form_object = $form_state->getFormObject();
if ($form_object instanceof ContentEntityForm) {
  $bundle = $form_object->getEntity()->bundle();
}

```

---
Tags: 8, forms
---


title: How to filter content by taxonomy term?

text:
# Question
Title: How to filter content by taxonomy term?
I'm using Drupal 7 and trying to filter my content based on taxonomy, but it looks like I can only filter based on status and type. Is there a setting or module that would offer more options to filter content by?

Thanks!

# Answer
It is easy to expose taxonomy term as filter in views. Unfortunately, in Drupal 7, the content list is not built by views.

Administration Views is a module which can replace it with the views **Administration: Nodes**.

In the views, you can add ***Content: Has taxonomy term*** filter and expose it. But it only support **ONE** vocabulary.

How about having a term filter on more then vocabulary? It is quite tricky, but not impossible.

First, add a relationship ***Content: Taxonomy terms on node***, and check the vocabularies. In example, they are `tags` and `topics`.

Then, now you can add filter ***Taxonomy term: Name***, this filter only appear when you added the taxonomy term as relationship.

In ***Operator***, there are many options, you can pick a suitable one for your case. I chose `Contains` in my example.

> **Note:**
>
> With this method, you will have a ordinary text field rather then autocomplete field. It is the only downside.
> 2 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to have new activity count above any view?
I have seen on your website, when there is a new question posted, the list shows a new activity button with a count above the list. How can I do that in Drupal with any view?

I am interested in showing such a thing with Statuses. There is an option in statuses settings to show a refresh button below the status stream when there is a new activity, but I want to show it above like on stackexchange and with a count.

# Answer
> 1 votes
Have a look at the Menu Badges module to add such notifications to any **menu item** and/or **menu tab** of your choice.

Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)
>
> ### Adding Badges to Menus
>
> Once enabled, go to `Administration > Structure > Menus`, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
>
> ### Adding Badges to Tabs
>
> For adding badges to menu tabs, there is a tab under `Administration > Structure > Menus` called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
>
> ### Badge Types
>
> The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".

### Video tutorials:

---
Tags: views, notifications
---


title: Turning on verbose logging

text:
# Question
Title: Turning on verbose logging
Is the "Verbose logging" in Drupal actually the PHP errors that can be activated in various ways (.htaccess, php.ini, settings.php) to be seen on screen?

Is it `drush ws --full` ?

From the material I've seen I can't say for sure if there is a unique definition for this concept in Drupal.

I would thank an experienced Drupal programmer to give the final word on this.

# Answer
> 4 votes
Navigate to admin/config/development/logging and set "All messages, with backtrace information".

---
Tags: 8, debugging
---


title: Changing Exposed Filter Label in Views

text:
# Question
Title: Changing Exposed Filter Label in Views
I have a view in Drupal 7 site that needs some editing. In particular, there are some exposed filters on that page that require their labels to be changed. How can I do that?

I cannot seem to find where to do that. From my understanding, the filters are innate to the Views module.

# Answer
As @Kevin already suggested.

In the following image, Please, see the red circle. From that input text area you can change the Label. Are you looking something else?
> 2 votes

---
Tags: 7, views
---


# Question
Title: How do I check if the user is watching the front page or the user is logged in?
I like to have the same result in a template if the user is logged-in or is on the front page.

So if the user is not logged-in nor on the front page, it should be the same result as if the user is logged in and not on the front page.

I got

```
<?php if ($logged_in): ?>

Do something

  <?php else: ?>

Do Something Other

<?php endif; ?>

```

How to extend this to force drupal to do the same on front as for the logged in user if the user is not logged in but viewing the front page

In other words how to get if drupal\_is\_ \_on\_front **OR** $logged\_in

elseif

I am a php newbee

thank you for an explanation

# Answer
You would do something like

```
<?php if (user_is_logged_in() || drupal_is_front_page()): ?>
  Do something
<?php endif;?>

```

**Source**:
> 1 votes

# Answer
I think you will want the following:

```
<?php if ($logged_in || $is_front_page): ?>
    Do something
<?php endif;?>

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: User::id() and Node::id() return a string instead of an integer
I wrote a class constructor whose parameter can be an instance of Drupal\user\Entity\User, an integer, or `FALSE`.

```
public function __construct($user = FALSE) {
  if ($user && $user instanceof User) {
    $this->account = $user;
  }

  if ($user && is_int($user)) {
    $this->account = User::load($user);
  }

  if (!$user) {
    $this->account = User::load(Drupal::currentUser()->id());
  }

  $this->setProfileId();
}

```

When I want to use the ID from any kind of entity, the value returned by `$account->id()` is a string, not an integer.

```
function custom_node_access(NodeInterface $node, $op, AccountInterface $account) {
  $profile = new IgbUser($account->id());
}

```

$account is a class instance of `Drupal\Core\Session\AccountInterface`. When I call `$account->id()` or $node-\>id(), the value returned is a string, not an integer as the documentation of that method reports. This means that `is_int($account->id())` returns `FALSE`.

# Answer
The value is in integer (for most content entity types, that is). The variable type however is a string.

That has a simple technical reason, values loaded from the database are always strings, those put into the node object and never explicitly cast to something else. Doing so would be too expensive for what it brings.
> 4 votes

# Answer
As @4k4 mentioned, it can be `int` or `string`. If the value type does matter to your code. Just force convert it to integer.

```
(int) $account->id()

```
> 3 votes

# Answer
For User and Node this is defined in the class Drupal\Core\Entity\EntityInterface:

```
  /**
   * Gets the identifier.
   *
   * @return string|int|null
   *   The entity identifier, or NULL if the object does not yet have an
   *   identifier.
   */
  public function id();

```

And as far as I checked, all subclasses inherit this doc.

The methods to retrieve the id are defined later in the subclasses, so you have to consider both possibilities `string` and `int` in your code, which should be no problem.
> 1 votes

---
Tags: entities, 8
---


# Question
Title: Trigger Authcache Reload on Field Change for Drupal Commerce Products
I activated authcache and the cache system is working well. When i change the price for a product the page is read from the cache. How can i trigger to reload the page from database if one specific field (price field for example) is changed?

Information on my installation:

I have installed Drupal Core 7.37 , Commerce 7.x-1.11. and AuthCache 7.x-2.0-beta5.

# Answer
> 0 votes
Authcache comes with an integration module for the Cache Expiration project. See also the Authcache 2 tuning guide - integrate with Cache Expiration module.

It might get tricky to find all pages where a particular product/price is displayed due to the separation of products and display nodes in commerce. Depending on how frequent prices are changed, you might consider nuking the whole cache, e.g. using a combination of Rules and the Cache Actions module.

---
Tags: commerce, caching
---


# Question
Title: Blocks: Old vs. "Custom" and Config vs. Fields
I have quite a bit to ask in this question, so I apologize in advance. I believe these questions are all related, and I'm trying to grasp some thoughts on the new block system in Drupal 8.

## Background

I am troubleshooting a custom block implemented by a vendor. This block is not listed in the *Custom block library*, but I can add it to the page with the *Place Block* link on the *Block layout* page (note: this makes me think it's an "old-style" block, as in D7 type block). When I place a new block, I am presented with a "Configure block" screen, which I believe shows and stores the values of these fields in config. The custom class extends **BlockBase**, so the form I'm seeing is built/shown/processed with *blockForm()* and *blockSubmit()* in the code.

The problem I am having is that files/images added via these "config" fields (aka a form file upload field, or a wysiwyg editor's IMG button) upload "temporary" files to the file system, which are then later deleted as orphans by a cron run a few hours later. I realize I can turn off that cron job, but I am looking for a BETTER solution. When I go to the files page (*/admin/content/files*), I want to see that my uploads are "used in" at least one place, and have that place show correctly as a link to the block. My belief, is that if this block were built as a custom block type, using fields, that Drupal would by default take care of the association of these images, which really are content.

## Questions

So this brings me to some questions... Am I on the right path here? Should I be using fieldable, custom blocks for this implementation? If the image is a field, and the body is a field, and saved appropriately in the database, then the files page will be able to see this content correctly. This is do-able, correct?

So this brings me to my next question, when should I be using blocks/configuration and when should I be using blocks/fields? This particular example screams "content" at me, and in that case, I think the argument is for fields. Does that sound right? I can think of another example off the top of my head that I'm a little more fuzzy on. We offer a custom block for "Polls" on our website where, when creating a new poll, you choose a reference to a poll, and can optionally set (override) the Title shown in the block. That's 2 settings that a site admin should be able to change. Are these still content, or are they config? To me, it seems like the "poll reference" could go either way... I assume most custom blocks have some combination of "content/fields" AND "config", right? For example, all the "Visibility settings" for a block get saved as config, right?

Any help understanding all of this is much appreciated! Thank you!

# Answer
> 1 votes
What you describe are three different things:

1. If you put code in a class that extends BlockBase, then yes, this is a **block plugin**.
2. If you add a custom block in the block library, then you store content in the database as **block\_content**.
3. If you place a block in the block library then you add a block configuration, this is a config entity with the name **block**.

In a block configuration (3) there can be either a plugin (1) or a block content (2).

You can configure fields in (2), then the storage will be managed by drupal, also for image fields.

If you put form fields in (1) then they are not content, but config. You need submit code to handle this. The result of a file field remains temporary until you decide to save it. And combining config with an uploadable file seems a bit odd, but is possible, see for example the site logo.

Comparing both, I would start with (2) and only use (1) if I need code to make something that (2) does not provide.

**Edit: Answer to the comment**

If you use (2) you probably should be able to solve most of the tasks you describe in the comment in theming (preprocess + twig).

If not, there may be a solution by using (1) + (2). Put the image in block content (to store it properly in the database), but then use this not as a custom block as in (2), but pull the data in your own plugin. For this put a field in blockForm() to configure the block content id and then use in build() the entity api to load the field data of the configured id.

In fact drupal does the same to get the block content entity into a block, it uses also a plugin for this, but you would make your own.

---
Tags: entities, 8, blocks, configuration
---


# Question
Title: Generating pages with multiple views based on url parameter
I wish to generate pages that populate a series of views of different content types based on a parameter in the url.

For example, a user may navigate to:

```
www.mysite.com/{tag}

```

The generated page would find all content tagged with the {tag} parameter and present it as a series of views, for example:

```
Custom page for {TAG}

View 1                 View 2
Item 1 (type A)        Item 1 (type B)
Item 2 (type B)        Item 2 (type B)
etc                    etc

and etc.

```

I wish to style and theme the resulting page considerably. Ideally I would also make it possible for an end user to style the resulting page.

I am a little unsure what the best 'drupal' way to make such a page is.

a) Is it possible to somehow style and manage the taxonomy page for 'tag' to look how I want?

b) Should I programatically generate the pages in a custom module that searches for content based on a taxonomy term (not even sure how this would be done)

c) Should I generate a series of views then pass parameters to them on each specific page?

d) Is there some other, better way to achieve such a page in Drupal 8?

One final question, which solution would perform best in terms of page loads, or would they all be pretty similar?

# Answer
Create 7 different views, one for each content type. Create a block display for each view, and use block layout to put them all on one page.

Use contextual filters for the block view to get an argument from the URL. I believe it's a bit odd to configure: "in the section 'What to do if the URL is not available' select ' Provide default value' and select 'Raw value from URL from the dropdown box. From the 'Path Component' box select the position in the URL that your contextual filter gets its value."

This is a straightforward Drupal approach, should be performant.

Alternatively, you could use Views aggregation to use only 1 view, divided into 7 different groups, and use CSS wizardry to adjust the layout.

Which approach you prefer depends on whether you want to be able to customise each view, and whether you want to use UI rather than CSS to control layout.
> 2 votes

---
Tags: views, 8, taxonomy-terms
---


# Question
Title: How to make autocomplete return nid and name?
My question is about textfield autocomplete. I have this code:

```
function my_module_menu(){
  $items['my_module/textfield_autocomplete'] = array(
    'page callback' => 'my_module_textfield_autocomplete',
    'file' => '.\my_module\my_module.inc',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access example autocomplete'),
  );
  return $items;
}

```

In `my_module.module`:

```
$form['fieldset7-wrapper']['prop'][$i] = array(
          '#type' => 'textfield',
          '#title' => t('Nombre de propietario'),
          // The autocomplete path is provided in hook_menu in ajax_example.module.
          '#autocomplete_path' => 'my_module/textfield_autocomplete'
        );

```

In `my_module.inc`:

```
function inmoges_ofertas_propietario_autocomplete($string) {
  $matches = array();

  // Some fantasy DB table which holds clientes

  foreach ($return as $row) {
    $value = check_plain($row->name).' '.check_plain($row->surname1).' '.check_plain($row->surname2);
    //$value = $row->name.' '.$row->surname1.' '.$row->surname2;
    $matches[$value] = $value;
  }

  // return for JS
  drupal_json_output($matches);
}

```

This works perfect. But I want that json return callback `{nid; name}` instead of `{name,name}`, and also show the name in textfield, but I can save `nid` in my form.

If I change to this my function ajax

```
$matches[$row->nid] = $value;

```

The previous sentence returns `{nid, name}`, but if I choose one value of the list name, in the textfield is shown the `nid` value, not the `name` value.

Any suggestions?

# Answer
> 0 votes
Take a look at the examples module's ajax\_example\_autocomplete.inc file. You'll need to add a validation function that looks up the nid from the node-\>title:

```
  $result = preg_match('/\[([0-9]+)\]$/', $title, $matches);
  if ($result > 0) {
    // If $result is nonzero, we found a match and can use it as the index into
    // $matches.
    $nid = $matches[$result];
    // Verify that it's a valid nid.
    $node = node_load($nid);
    if (empty($node)) {
      form_error($form['node'], t('Sorry, no node with nid %nid can be found', array('%nid' => $nid)));
      return;
    }
  }
  // BUT: Not everybody will have javascript turned on, or they might hit ESC
  // and not use the autocomplete values offered. In that case, we can attempt
  // to come up with a useful value. This is not absolutely necessary, and we
  // *could* just emit a form_error() as below.
  else {
    $nid = db_select('node')
      ->fields('node', array('nid'))
      ->condition('title', db_like($title) . '%', 'LIKE')
      ->range(0, 1)
      ->execute()
      ->fetchField();
  }

```

---
Tags: 7, ajax
---


title: how to set Drupal Auto complete OFF

text:
# Question
Title: how to set Drupal Auto complete OFF
I am new to drupal i want to set auto complete off in my following code

```
$form['plantuser']['username'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#description' => t(''),
    '#required' => true,
    '#maxlength' => 50,
     '#weight' =>1,
  );

```

# Answer
> 6 votes
That code doesn't enable Drupal's autocomplete (it would need the `#autocomplete_path` property to do so), so I guess you mean the browser autocomplete?

The standard way to do that is to set the `autocomplete` attribute on the element which you can do like this:

```
  $form['plantuser']['username'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#description' => t(''),
    '#required' => true,
    '#maxlength' => 50,
    '#weight' =>1,
    '#attributes' => array('autocomplete' => 'off'),
  );

```

Bear in mind `autocomplete` is only valid using the HTML5 doctype; if you're using another doctype you'll need to implement a JS solution to set the attribute instead, e.g.

```
(function($) {
  $(function() {
    $('#input-id').attr('autocomplete', 'off');
  });
})(jQuery);

```

# Answer
> 0 votes
the form does not have autocomplete feature by default.May be when you type in the field the the suggestions are populated from browser cache so you can test it again on other browser or on same brwoser after clearing the cache.

# Answer
> 0 votes
Another way to do this if you are only targeting one element and don't need an array:

```
your_module_form_alter(&$form, &$form_state, $form_id) {

    if ($form['#id'] == 'the_id_of_your_form'){
        $form['the_id_of_your_form']['#attributes']['autocomplete'] = 'off';
    }
}

```

---
Tags: views, 7
---


# Question
Title: Skip checkout process if special field has value
I want to skip the checkout process and node has bin publish for free product, but my module is not working!

Any pointers greatly appreciated

```
<?php
function MYMODULE_node_submit($node, $form, &$form_state) {
  global $user;
  if (in_array('administrator', $user->roles)) {
    if ($node['field_noeagahi']['und']['0']['value'] = 1) {
      $form_state['values']['commerce_node_checkout_skip'] = True;
      $node->status = 1;
    }
  }
  return $form;
}

```

# Answer
You can implement hook\_commerce\_checkout\_router and there check if order has product that has special field value

```
function hook_commerce_checkout_router($order, $checkout_page) {
  /*
if $order has product with special field
drupal_goto('');
  */
}

```
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How can I add Zurb Foundation as a library?
I'm trying to add **Zurb Foundation** framework to my theme library file. However, when I add the following code to my library, I'm not getting any result.

I would be grateful to hear what is the problem with the code and what is the right way to load a library?

This is my theme folder structure (Zurb Foundation folder location):

```
|-Theme Name
|  |-includes
|  |  |-foundation
|  |  |  |-css
|  |  |  |-js

```

Library file:

```
foundation:
  version: 6.x
  css:
    includes/foundation/css/app.css: {}
    includes/foundation/css/foundation.css: {}
    includes/foundation/css/foundation.min.css: {}
  js:
    includes/foundation/js/app.js: {}
    includes/foundation/js/foundation.js: {}
    includes/foundation/js/foundation.min.js: {}
    includes/foundation/js/jquery.js: {}
    includes/foundation/js/what-input.js: {}

```

# Answer
> 5 votes
You created the library, alright, but you need to call the library.

In **\[theme\_name\].info.yml** add the following:

```
libraries:
  - '[theme_name]/foundation'

```

Also you need to modify your **\[theme\_name\].libraries.yml** file and add `dependencies:`

```
foundation:
  version: 6.x
  css:
    base:
      includes/foundation/css/app.css: {}
      includes/foundation/css/foundation.css: {}
      includes/foundation/css/foundation.min.css: {}
  js:
    includes/foundation/js/app.js: {}
    includes/foundation/js/jquery.js: {}
    includes/foundation/js/foundation.js: {}
    includes/foundation/js/foundation.min.js: {}
    includes/foundation/js/what-input.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once

```

As per Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

---
Tags: 8, theming
---


title: Working with a subtheme

text:
# Question
Title: Working with a subtheme
I am customizing my sub-theme and looking to see where to place styling rules. My web inspector is not showing me the specific files where the base theme rules are, it just show that all the rules are in foundation\_subtheme.css. I don't believe that I have any aggregation turned on, what do I need to do to see the specific files that the styling rules are inside of?

For example, how do I fine this rule?

```
.top-bar input, .top-bar select, .top-bar .button, .top-bar #contact-btn, .top-bar .button-ghost, .top-bar button {
    font-size: 0.875rem;
    height: 1.75rem;
    position: relative;
    top: 0.53125rem;
}

```

Even when I add a rule to \_header.scss the web inspector doesn't show me that its there it only shows the main css file.

# Answer
scss isn't parsed by the browser- it needs to be compiled to css... ,Assuming you have already installed ruby and sass, open a terminal window and navigate to your theme's root directory. Then `sass --update` to compile the styles once or `sass --watch` to continue compiling as you work.
> 0 votes

---
Tags: theming
---


# Question
Title: help with custom module form variable_get();
I am working on a module written by another developer; the module shows pray times and I have to add the option for people to select a month and year and show pray times for that month. All is going fine, but I am not sure I understand how the form for this module was set up because when I try to use `variable_get(praytimes_month)`, it never returns anything, even after submitting the form.

Right now, what I have works, but I can't set the default month because the only way for me to get something into my variable is through the cookies.

```
function praytimes_user_settings_form($form, &$form_state) {
      if ((variable_get('praytimes_userselect') == 'no')){

      $form['overview'] = array(
        '#markup' => t('Access denied!'),
        '#prefix' => '<p>',
        '#suffix' => '</p>',
      );

        return $form;
      }

      if(!isset($_COOKIE['Drupal_visitor_praytimes_address']))
      {
        $address = variable_get('praytimes_address');
        $tz = variable_get('praytimes_tz');
        $cmonth = variable_get('prayertimes_month',date("m"));
        $cyear = variable_get('prayertimes_year',date("Y"));
      }
      else {

        $address = $_COOKIE['Drupal_visitor_praytimes_address'];
        $tz = $_COOKIE['Drupal_visitor_praytimes_tz'];
        $cmonth = $_COOKIE['Drupal_visitor_praytimes_month'];
        $cyear = $_COOKIE['Drupal_visitor_praytimes_year'];

      }

      $form['overview'] = array(
        '#markup' => t('This page allows user to configure City and Time Zone'),
        '#prefix' => '<p>',
        '#suffix' => '</p>',
      );

      $form['praytimes_address'] = array(
        '#title' => t('Address'),
        '#description' => t('City, State, Contry or zipcode e.g: Dearborn, MI, USA or 48126'),
        '#type' => 'textfield',
        '#default_value' => $address,
        '#required' => TRUE,
      );

      $form['praytimes_tz'] = array(
        '#title' => t('Time Zone'),
        '#description' => t('Enter the time zone(e.g. Eastern is -5, Central is -6, Mountain is -7 and Pacific is -8).'),
        '#type' => 'textfield',
        '#default_value' => $tz,
        '#required' => TRUE,
      );
        $form['praytimes_month'] = array(
        '#title' => t('Month'),
        '#description' => t('Please enter a month in number form.'),
        '#type' => 'textfield',
        '#default_value' => $cmonth,
      );
        $form['praytimes_year'] = array(
        '#title' => t('Year'),
        '#description' => t('Please enter a Year.'),
        '#type' => 'textfield',
        '#default_value' => $cyear,
      );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save'),
      );

      return $form;
    }

    /**
     * Process a validated Pray Times user setting submission.
     */
    function praytimes_user_settings_form_submit($form, &$form_state) {
      //Rebuild the form.

      $form_state['redirect'] = 'prayertimes/timetable';

      $address = $form_state['values']['praytimes_address'];
      $tz = $form_state['values']['praytimes_tz'];
      $cmonth = $form_state['values']['praytimes_month'];
      $cyear = $form_state['values']['praytimes_year'];
      $coord = getLatLong($address);
      $lat = $coord['lat'];
      $long = $coord['long'];

      user_cookie_save(array(
        'praytimes_month' => $cmonth,
        'praytimes_year' => $cyear,
        'praytimes_address'=> $address,
        'praytimes_tz' => $tz,
        'praytimes_lat' => $lat,
        'praytimes_long' => $long,));

      // Notify user.
      drupal_set_message(t('City and Time Zone settings has been saved.'));
    }

    function praytimes_table (){
        $output = '';

        if(!isset($_COOKIE['Drupal_visitor_praytimes_address'])){
            $address = variable_get('praytimes_address');
            $cmonth = variable_get('prayertimes_month');
            $cyear = variable_get('prayertimes_year');
            $tz = variable_get('praytimes_tz');
            $lat = variable_get('praytimes_lat');
            $long = variable_get('praytimes_long');
          }
          else {
            $cmonth = $_COOKIE['Drupal_visitor_praytimes_month'];
            $cyear = $_COOKIE['Drupal_visitor_praytimes_year'];
            $address = $_COOKIE['Drupal_visitor_praytimes_address'];
            $tz = $_COOKIE['Drupal_visitor_praytimes_tz'];
            $lat = $_COOKIE['Drupal_visitor_praytimes_lat'];
            $long = $_COOKIE['Drupal_visitor_praytimes_long'];
          }

        $dst = variable_get('praytimes_dst');
        $today = mktime(0,0,0,$cmonth,1,$cyear);
        $currentmonth = date('F', $today);
        $currentyear = date('Y', $today);
    //  $tempdate = strtotime($currentmonth.'-1-'.$currentyear);
        $tempdate = $today;
        $oneday = 24*60*60

```

What I want is storing the submitted month/year to $tempdate and, if nothing was submitted, have a default value.

# Answer
> 1 votes
`variable_get('praytimes_month')` doesn't return any value because you aren't saving any value with `variable_set('praytimes_month', $cmonth)` which you should put where there is now the `user_cookie_save()` call.

There is a more important mistake in your code, though: The values saved with `variable_save()` and obtained from `variable_get()` are the same for every user. This means that a user will see as default value the value submitted from the last user who used that form; users will never see the values they entered earlier, if not in case the last user who used that form entered the same values.

That is why the other developer used cookies: Because they at least return the last values entered using the same browser on the same computer.

What I would use to store data is:

* If the users don't have an account on the site, in the session data (`$_SESSION`)
* If the users have an account on the site, in a custom database table containing the user ID, and the data to store

In this way, each user will see as default values the value they entered earlier. In the case of using `$_SESSION`, there is still a chance a user would see what the previous user entered, since the session is opened for the browser used on a computer.

---
Tags: 7, forms
---


# Question
Title: How to allow editing a single node to a single user?
I am building 500 nodes of same type with different info in them. When I am finished, I want to give each user that will register 1 node that is already in the system, and only that user can edit or add data to that particular node.

Any suggestions about how to do so?

# Answer
I would setup all those nodes as a particular content type and author. Then you could give those users a role once they register that allows them to edit their own nodes for said content type. Then you will of course need some custom code that runs at that time to find one of those nodes and change the author to the registered user so that they can edit it. Probably could the last part with Rules but you might need to use custom php to find a node and change the author.
> 1 votes

# Answer
I'd make a module that implements `hook_user_insert()`, and this module would allocate a special node whenever a user was created. I'd then make sure that the permission system never allowed users to create that node type, or edit or delete, or whatever you don't want users to do with their node.

I might also use Entity Reference module, or Node Reference, to attach the node to the user entity.
> 1 votes

# Answer
It may be possible to coming Node Access module with Rules module to create a conditional action where, on registration, a user is assigned to a node. I haven't done this and would suggest reading documentation before going head first at it.
> 0 votes

# Answer
Start with implementing "*give each user that will register 1 node*" (as in your question): simply change the node author to the user you want to give a specific node to.

Combine this with the Rules module by using Rules Event ***System \> Drupal is initializing***, and with a Rules Condition related to the URL for the *edit* operation. The rule you'd need is a variation of the rule I included (in export format) in my answer to the question about How to restrict access to a node via node/12 and allow access via a path like content/sometitle?

These are the changes to that rule to make it work this case also:

* The paths containing `node` should be extended by adding `/edit` at the end.
* Add a (1ste) Rules Condition like "If **NOT** (`Author id` matches the `uid` of the currently logged in user)".
* Add a (2nd) Rules Condition to check if the content type to be edited matches the content type you want to use for this.
* If you also want to continue to allow special roles to edit such nods (eg an administrator), add a (3rd) Rules Condition to check if the currently logged in user does NOT have that role.
* Change the "Message" in the Rules Action to something that fits your case.
* Modify the Rules Action to fit your own requirements, e.g. to issue a redirect to some 'help page' with more details about this.

Should you also want to impose similar validations to 'delete' such nodes (which is not what your question currently says however ...), then create another rule in which you use a similar approach as for 'edit' (as described above), just replace all 'edit' by 'delete'.

# Video tutorials

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

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


title: How can we hit/run the rules using code

text:
# Question
Title: How can we hit/run the rules using code
I have defined a rule in " **Configuration » Workflow » Rules**". I have setup this as following...

**EVENT** : After saving a new account **Conditions** : User has role(s) And role is (Referral Source) enter code here **Actions** Send a HTML mail.

But it's not sending the mail to register user. It's because of the user don't have the role as **Referral Source** at the same time. I am assigning the role using the PHP code and I would like to run the rule on same time. So how can I do that?

# Answer
> 0 votes
Create first rule "**After saving a new user account**" action "**Add user role**" to user and set its priority first(by set its **weight** 0 in **SETTINGS** of rule) and create one another rule for the same and set condition for role is(Reffereal source) and action send a HTML mail, set its priority down (by set its **weight** 1 in **SETTINGS** of rule) will work for you.

---
Tags: 7, rules
---


# Question
Title: If there are so many modules in Drupal, are the hard-coded functions reserved only for contributed modules?
I read somewhere (cannot recall source) that a programmer was capable of doing extremely complex and tailor-suited web pages using Drupal without writing a single line of code (using hooks), just using the GUI of suitable contributed modules. Is this at all possible?

Are the Drupal 7 (and 8) functions thought as a way of extending capability via contributed modules, or is it good practice to tailor-suit your own functionality via hard-code modifications of SQL queries via `hook_views_pre_view`, `hook_views_query_alter`, `hook_views_pre_render`, `theme_preprocess_page` and all of these available functions?

I suspect that most of the time being ready to face a difficult project would need to be spent on trying dozens of different contributed modules, mutual compatibility, flexibility, etc., in order to reduce the custom code you would need.

I am not sure about this commentator being truly honest, but I find difficult not to create my own custom modules and modify queries, template.php, etc., in order to get the desired results, sometimes even by fixing long existing bugs in some contributed modules.

# Answer
> 9 votes
Only using Site Building features (no custom module development yet) should get you *pretty far* (if not *far enough* ...).

# The Relativity Data Model for Drupal

Have a look at the (illuminating) article "Relativity Model for Drupal", for which this is an introduction to it (quoted from this linked page):

> The Relativity Data Model for Drupal is a zero-custom-code, collection of steps, procedures and methods that strive to help site builders, users and site visitors interact with Drupal in a far easier and more efficient way. This is done by:
>
> * Data architecture and data modeling merging as a single step through a documentation procedure.
> * Customized user interfaces that cater to individual workflows throughout permission roles.
> * Multi-level relational data structures that relate to other multi-level relational structures.
> * Mimicking the concept of database joins within Drupal's UI's.
> * Vastly reducing the size of Drupal sites by a small handful of modules that provide greater power, speed and expansion capabilities.

The *small handful of modules* (cfr. the last bullet) is like so (apart from Drupal core):

Note: this same topic is also presented in the video "Revolutionary DRUPAL Data Modeling Concept!! (This will change your Drupal life!)".

# Typical add-on modules

Even though that *small handful of modules* above can get you already extremely far, I often add a subset of other contributed modules to it also, as further detailed below.

### Business logic

Using the Rules and Flag module, it is possible to implement all sorts of business logic (= *rules*), simply using the typical Drupal admin UI for those modules.

### Queries, custom reports and charts

* To perform queries (listings, etc), use the Views module, possibly further extended with modules such as Views Slideshow: Galleria (there are dozens of modules to further enhance views).
* The Forena module can be used as a supplement / alternative (e.g. if you'd need to also create charts or so, or if you have a need to access data in some external database such as MS SQL, Oracle, etc).

Using the Forena integration with the Feeds module it is possible to import data blocks and reports as Drupal nodes or Drupal users. For a tutorial about the available features check out the video about How to import data and reports based on data as Drupal nodes.
* Create charts using the views integration of the Charts module to visualize a lot of data in a way that can be quickly digested.

### Page Layout

Modules like Display Suite and/or Panels can help to enhance the look and feel of it all also.

### Many more modules

* Group (a pretty new alternative to Organic groups, to create arbitrary collections of your content and users and grant access control permissions on them).
* Workflow (to create arbitrary workflows, and assign them to entities).
* IP Geolocation Views & Maps, a mapping engine to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**)
* Or, or ... on and on goes the list.

Disclosure: I'm a (co-)maintainer of Forena and Charts.

---
Tags: 7, views
---


# Question
Title: How to display events in chronological order?
I am new in Drupal and I want to display events in chronological order by start date of the event.

My current setup is that the latest added event is showing.

Here is a screenprint of the View I created so far:

Any suggestions?

# Answer
Your screenprint and your generated SQL statement shows that your current view is FIRST sorted by `node_created_order`. Though from your question it seems that you want it to be sorted by "start date of the event".

So just delete the first field in your list of SORT CRITERIA and see what happens next ...
> 0 votes

---
Tags: views
---


title: Stylize Field based on Boolean value

text:
# Question
Title: Stylize Field based on Boolean value
In Views showing as a table, I have 3 fields, field\_checkbox1, field\_checkbox2 and field\_checkbox3, and values set to either Yes or No.
I need to add color to them, if the checkbox is set to Yes(on, checked, "1" or any other value that denotes a positive value that Drupal recognizes) the border of its should be set to "2px solid #00ff00". \*****************************EDIT\******************************

Which css file (there are 6) governs class="views-field views-field-field-checkbox1 green"? How Macro do I have to get?

# Answer
> 2 votes
Add class to views (Advance -\> Class) and then through css, do something like this:

`.className .Alpha["value=1"]{
 border: 2px solid #0f0;
}
.className .Alpha["value=0"]{
 border: 2px solid #f00;
}`

Value may slightly differ and you can simply check it through "inspect" of your browser's contextual menu.

# Answer
> 1 votes
**If you're using Drupal 8:**

Click on your boolean field, and click on REWRITE RESULTS

Checkmark ☑ Override the output of this field with custom text

On the text box put:

```
{% if field_name == 'yes' %}
  <div class="green">{{ field_name }}</div>
{% else %}
  {{ field_name }}
{% endif %}

```

Click on replacement patterns, to see the pattern/token you can use. You will only see patterns/tokens that are from the field, or arranged above the field.

More info about Twig If Statements

# Answer
> 0 votes
**Here is a Drupal 7 solution:**

Use the Views Conditional module

Add Views Conditional as a field. Make sure your boolean field is arranged above the Views Conditional field, other wise, it won't show up as an option.

Then set condition, if field\_name is equal to `yes`

Then output this...

```
<div class="green">[field_name]</div>

```

Otherwise, output this...

`[field_name]`

---
Tags: views, entities
---


# Question
Title: Send notification E-Mail to x when x’s content is commented
How to notify an author of a node, when her content is commented by another user on Drupal 7?

# Answer
> 5 votes
Use Rules module. Create the following Rule:

1. Event: after saving a new comment. You will probably want to restrict this by content type as well.
2. Add action: send mail. Arguments:
    * To: switch to data selection and choose `comment:node:author:mail`
    * Subject: whatever you want, for example "A comment has been posted to your blog post"
    * Add the message
    * Condition: NOT `comment:node:author:uid` and `comment:author:uid` so that the user does not receive emails for his own comments.

Here's how to insert the name of the node author:

Formatted username:

```
Dear [comment:node:author:name], [...]

```

Specific field (e.g. if you have first and last name fields and you want to use only first name):

```
Dear [comment:node:author:field-first-name], [...]

```

---
Tags: 7, comments, notifications
---


# Question
Title: Setting a default checkbox value in FAPI
Trying to set a default value on an entity reference field.

```
$unitid = node_load($unit);
$form['field_choose_a_service']['und']['#default_value'] = $unitid;

```

> Warning: Illegal offset type in form\_type\_checkboxes\_value() (line 2390 of /homepages/43/d503288075/htdocs/example.co.uk/includes/form.inc).
>
> Notice: Object of class stdClass could not be converted to int in form\_process\_checkboxes() (line 3316 of /homepages/43/d503288075/htdocs/example.co.uk/includes/form.inc).

And targeting the nid from that loaded node...

```
$unitid = node_load($unit);
$form['field_choose_a_service']['und']['#default_value'] = $unitid->nid;

```

> Warning: Invalid argument supplied for foreach() in form\_type\_checkboxes\_value() (line 2389 of /homepages/43/d503288075/htdocs/example.co.uk/includes/form.inc).

The first one actually works, but kicks up the errors. What am I doing wrong?

Essentially I want to check if the nid im passing in the URL as a \_GET query matches an option in the entity reference checkbox options, and make that option selected if it does.

# Answer
Try this one:

```
$unitid = node_load($unit);
$form['field_choose_a_service']['und']['#default_value'] = array($unitid->nid);

```

And please note that `node_load` returns an object but not a ID. I see you use `$unitid` as the variable name. It can make people confused.
> 2 votes

---
Tags: 7, forms, entities
---


# Question
Title: How to decide between module_exists and function_exists?
I'm familiar with using `module_exists` in a module, and using it in situations like:

However, there is also `function_exists`, such as shown in the answer to "Is it possible to declare a Javascript library dependency at Hook.info?".

I have the impression that using `function_exists` is a more robust (safe) approach as compared to `module_exists`. Especially if you want to be sure that some function (added in a newer version of a module) is available, whereas by just using `module_exists`, you risk to run into errors like those:

* if a site is ***still*** using an ***old*** version of a module, which doesn't have that function ***yet*** (so you shouldn't try to use it ***yet***).
* if a site is ***already*** using an ***new*** version of a module, which doesn't have that function ***anymore*** (so you shouldn't try to use it ***anymore***).

**My question**: what are the typical criteria, or pros/cons, to decide for using either `module_exists` versus `function_exists`?

# Answer
The prior 3 (interesting) answers appear to me as somehow confirming my "perception" (as I described in my question). Interestingly enough, those answers were originally written independent from each other (they were posted at more or less the very same moment, as illustrated in the timeline of this question, use the "toggle format" to see "mins").

Jimmy Ko's answer (+ comments below it), illustrates some more examples of how using `function_exists` can make a module more robust with respect to possible changes in some other module that a module uses (depends on).

Clive's answer shows you could as well combine `module_exists` and `function_exists`, while the comment below it resolved my doubts about my `function_exists` example (ie it should rather use `module_exists`).

mpdonadio's answer (+comments below it) is, at least to me, the toughest to digest. But after reviewing Shawn Conn's comment below it, I found a few more links that provide more details about all this, i.e.:

**"My conclusion"** (after digesting the previous answers): Leave it to Drupal core to use `function_exists`, and contributed/custom modules should try, as much as possible, to stick to `module_exists` ... though there are exceptions ...
> 4 votes

# Answer
You should always program to the API and not the implementation. If Drupal provides a mechanism to do something, use it.

`module_exists()` should almost always be used for soft dependencies on something provided by a Drupal module. You can always get version info, and decide what to do, using `system_get_info()`. There have been cases where functions are available when modules have been disabled (some of the class autoloader modules have has this problem).

`function_exists()` should be reserved for checking whether a PHP feature or library is available. Core has some examples of this in some of the `drupal_` wrappers for string manipulation and character set conversion.
> 13 votes

# Answer
`module_exists` is a Drupal API function used to determine whether a module is *installed*, it isn't designed to give any guarantees of the functionality a module might contain, including what functions it declares.

`function_exists` is a PHP core function which literally determines whether a function with a given name exists in the current request.

As such, they aren't really comparable with one another, you use them for different things. In fact it would be easy, albeit potentially redundant, for them to complement one another, e.g.

```
// Do something with a specific module
if (module_exists('foo')) {
  // Check what's available
  if (function_exists('foo_bar')) {
    // ...
  }
  elseif (function_exists('foo_baz')) {
    // ...
  }
}

```
> 10 votes

# Answer
You are right, `function_exists` is a more robust way to check the existence of the API function provided by contrib module. It is very suitable for directly using the contrib module's API.

I use Session Cache API as an example:

```
if (function_exists('session_cache_set')) {
  session_cache_set($bin, $data)
}

```

However, some contrib modules only provides some extra properties or feature, it is very hard to say which dependent function is. In this case, you need to use `module_exists`

I use Elements as an example:

```
if (module_exists('elements')) {
  $form['url'] = array(
    '#type' => 'urlfield',
    // other code
  );
}
else {
  $form['url'] = array(
    '#type' => 'textfield',
    // other code
  );
}

```
> 4 votes

---
Tags: 7
---


title: How to add a new field image?

text:
# Question
Title: How to add a new field image?
These are the field thats I already created:

>

And this is how my page currently looks like:

>

The first image is the background of this page.

I want to add field image on the blue line. But when I add new field of image it doesn't show the second image.

Any suggestions about how to solve this problem?

# Answer
> 0 votes
Add the field to the content type; check your node/page template, and add some code to print the new image field. If there is no custom template for your content type, create one and customize the output to your wishes.
You might also check the display settings for the content type, and make sure your image is displayed.

---
Tags: views
---


title: Add "active" class automatically to Url

text:
# Question
Title: Add "active" class automatically to Url
I'm generating a URL with `Url::fromUri()` method.

Is there a way to add automatically an "active" class, like D7, if the page is the same of the URL?

Obviously without check manually the value of the generated URL and the page.

# Answer
> 3 votes
In the documentation is not present, but on $options array we can simply set "set\_active\_class" to TRUE (FALSE by default) and then drupal add a "is-active" class to the link:

```
Url::fromUri('internal:/progetti/selezionati', array('set_active_class' => TRUE)),

```

I think that this behaviour should be TRUE by default..

---
Tags: 8, uri
---


# Question
Title: Metatag is not showing on front page whereas the front page is set from custom content type
I have a custom content type "Community" and a page from this content type is selected as front page on the drupal 7 site (from system/siteinformation). i am using Metatag module. All other pages are showing the metatags but the front page does not.

I've also tried by overriding the metatags in `admin/config/search/metatags/config/global:frontpage/edit`, but still not showing up.

# Answer
If your are using `page--front.tpl.php` add the below line and clear the cache.

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

Meta tag will be added to the front page.
> 1 votes

# Answer
There is a know issue for the metatag not displaying on the front page. If you read the README.txt in the module file. Between line 281 and 292 you can find following description.

```
Troubleshooting / known issues
--------------------------------------------------------------------------------
* When using custom page template files, e.g., page--front.tpl.php, it is
  important to ensure that the following code is present in the template file:
    <?php render($page['content']); ?>
  or
    <?php render($page['content']['metatags']); ?>
  Without one of these being present the meta tags will not be displayed.
* An alternative method to fixing the missing-tags problem is to change the page
  region used to output the meta tags. The region used may be controlled from
  the settings page, it is recommended to test different options to identify the
  one that works best for a specific site.

```

If this is the case, you can look at this issue it you are using **customized template**.

*That issue has already been registered at the Metatag module's Issue section, SOLUTION: Metatags in front not working*

**Additional:** **If you wan to Add using Views**

You can get additional setting for the `Frontpage`. Go to `admin/structures/views` -\> There you can find one view name `frontpage`, which is not enabled by default. You can enable that view. That view is a front-page for your Drupal site.

It has been provided by `views` as default to open up new setting for front page. Now you can add, modify whatever field you want. I hope this way you are able to access that.
> 0 votes

---
Tags: 7, meta-tags
---


# Question
Title: How do I solve extra characters in a date format?
This seems to be a known issue in drupal, personal commentary redacted.

So I set up a date format, and any non date-format characters get reprinted at the end of the date.

I first had my formatter set up as `Y年m月`, but read in the issue that I need to escape characters, so:

Format: `Y\年m\月`

Preview in Date and Time preview area: `2016年08月`

Actual output: `2016年08月　年月`

Looking in views where the field is being output (to json in case that makes a difference), there is no custom option for the formatter, so I couldn't try recreating the date formatter in views to see if that would work better.

# Answer
> 0 votes
I needed to add the escape characters and then go back in and reassign the format to the type. Just changing the format didn't solve the problem.

---
Tags: 8, views, datetime
---


# Question
Title: How to manage reservations with a 2 hours duration without duplicate bookings?
I want to make a calendar view that will show when music teachers are available, so that students can register online and attend a lesson. The courses have all the same duration which is 2 hours. For this, I created a content type called "Lessons" (Fields: title, description, teacher name, teacher email, date/time) and a content type using node reference module for registrations to each specific lesson. In that way students can register online for music lessons.

There are 2 problems with this:

1. How can I have a fixed 2 hour duration in the day of the calendar view that won't let students register for more or less time than the two hours? I can not just hide the time fileds because the system must show them the time that the lesson takes place?
2. I want to allow **just one user** register for each lesson and then the system must show that lesson as booked. To be more specific, I want the calendar to show the whole day seperated in 2-hour periods and which periods are free. When a user registers for a lesson, the lesson changes color (I can do this with css) and is marked as reserved so that the "next" user can only register for another of the open lessons and so on.

Any ideas?

# Answer
If you don't want to re-invent the wheel, have a look at these contributed modules that are typically used for this (quotes are from their project pages):

* Availability Calendars.

> ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.
>
> An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.
* Simple Reservation.

> ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.
>
> The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.
>
> There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.
> 0 votes

---
Tags: 7, nodes, datetime
---


# Question
Title: How to add any plugin to ckeditor manually?
I'm trying to add a new plugin `ckwebspeech` in ckeditor module. Here is the plugin which I want to add.

So, that the final editor will look like mentioned in screenshot. Is there any way to add this manually?

# Answer
> 4 votes
The manual process is described on that plugin page itself, as you can see on the instruction page in first image(red circle.)

If you click that link which you have provided in your question, you can see the `Download` option on that page. If you click it will download and it will open up a new pop-up window.

**1.** As you can see in the image. Copy that file and paste to that path.

So, I did copy and paste at at `module/ckeditor/plugins/ckwebspeech`

**2.** Now second step says, put this code `config.extraPlugins = 'ckwebspeech';` So, I went to `admin/modules/ckeditor/config`. I did choose either Full or advanced, whichever my site is using. Clicked edit, went to `Advanced options` And paste the second step as shown in the step-2. Saved it ans clear the cache.

>

**3.** Now again went to same place at described in step-2. Instead of `Advanced option` went to `Editor appearance` and move the `webSpeechSetting` and `webSpeechEnabled` button to the custom toolbar as shown in following image.

>

**4.** Now if I scroll down further on the same page, I will have all option of the plugins then I enabled that plugin as shown in following image.(see second option which i checked). Saved cleared cache.

>

**5.** Now went to any page where I can see my editor, and, it showed up in editor.

>

---
Tags: 7, wysiwyg, plugins
---


# Question
Title: How to send one time login url with Rules?
I have a rule to create a user and an action to send login url to user's email. I didn't find any action to send login url, so added an *Send HTML Email* action and added the `[user-created:one-time-login-url]` token in mail body. but it appears as it is(*\[user-created:one-time-login-url\]*), and is not translated to login url.

Then I used this php function to print the same url:

```
<?php
print user_pass_reset_url($user_created);
?>

```

It prints a url but also prints the following notices:

```
Notice: Undefined property: stdClass::$uid in user_pass_reset_url() (in line 2299 /var/www/web/modules/user/user.module).
Notice: Undefined property: stdClass::$pass in user_pass_reset_url() (in line 2299 /var/www/web/modules/user/user.module).
Notice: Undefined property: stdClass::$login in user_pass_reset_url() (in line 2299 /var/www/web/modules/user/user.module).

```

`$user_created` is the php variable referring to the user created in the previous action. But it seems it's not a user object(because of notices).

What's the proper way to send one time login url?

# Answer
> 4 votes
Try out Login one time module

> The use case for this is where your users can't figure out how to use a username and password - so they request an email link to what they need.

# Answer
> 1 votes
You need to use the token\_replace function like this

```
$newly_created_user = user_load(101);
$subject =token_replace('Hello  [user:field-your-first-name]  [user:field-your-last-name], here is your password reset link [user:one-time-login-url] ', array('user' => $newly_created_user), array('callback' => 'user_mail_tokens', 'sanitize' => FALSE));

```

ultimately you need to add extra third parameter to the token\_replace function

```
array('callback' => 'user_mail_tokens', 'sanitize' => FALSE)

```

# Answer
> 0 votes
The solution was adding an `Save entity` action before using `user_pass_reset_url()` function or login one time action.

---
Tags: 7, rules
---