title: How do I disable the user login block

text:
# Question
Title: How do I disable the user login block
I think I might found a bug(?)

Only administrators can create content on my site, so I am trying to remove the login form from the front page, its okay that the login page can be accessed at `site/user/login`, but not on the front page, I have tried quite a few things.

I have followed the guide in https://www.drupal.org/node/13777

Im using the bartik theme, I have sub-themed it, but I have barely changed anything in it, basically just a little css.

And I have tried the following:

1. `admin/structure/block` and hide the user login block.
2. `admin/structure/block` and completely removed the block.
3. `admin/structure/block` and moved it to a specific location and then hiding it based on page.
4. `admin/structure/block` and moved it to a specific location and then hiding it based on role.
5. `admin/config/people/accounts` and disabled `register/login` for anonymous users, which I guess works as they can't register, but the login form is still on the front page.
6. Hide the block with CSS, which works, but then I can't ever login before I change the CSS back.

Adding some images + github link: Github link: https://github.com/DenLilleMand/christianssite Imageone(frontpage):

Imagetwo(structureblock):

Imagethree:

# Answer
> 1 votes
I had a similar problem.

As described in the issue, we had the same problem in Drupal 7 with the "No front page content has been created yet" message. In Drupal 8, if you have no content on the page the default is to display the user page. If the user is not logged in, it defaults to the login page.

The best solution to this is to have content on the front page. However, assuming you want a blank front page except for some custom blocks, you can remove the Login Form by either creating or editing the existing page--front.html.twig file in your theme.

Since you don't have any content on the front page, you can remove the "Content" region and then remove the "Header" region to remove the tabs.

*EDIT: I just found that if you do remove the "Content" region from the page--front.html.twig file, this will also remove it from the login page, which is a problem. Not sure why this is. Still working on a solution.*

Finally, make sure that you leave the "Front Page" setting blank = 'Manage \> Configuration \> System \> Front Page'

These are the two blocks I removed from my theme

```
   {# Content #}
    {% block content %}
      <a id="main-content"></a>
      {{ page.content }}
    {% endblock %}

  {# Header #}
  {% if page.header %}
    {% block header %}
      <div class="col-sm-12" role="heading">
        {{ page.header }}
      </div>
    {% endblock %}
  {% endif %}

```

# Answer
> 0 votes
If you've done all of those block things and it's still showing then we can be pretty sure it's not that login block that is coming out on the site.

Hard to help without seeing the code.

You might be getting the access denied page for your homepage, worth a look

---
Tags: 8, users
---


title: Change Webform URL

text:
# Question
Title: Change Webform URL
I had successfully submitted a webform. When I click on edit, it will go to this URL "node/254/submission/929/edit". Can I change to "form\_a/user\_name/edit"?

# Answer
> 0 votes
No. Using `hook_menu_alter()` to change the `node/%webform_menu/submission/%webform_menu_submission/edit` route would break the local task display as it would no longer be a subpath of the `node/%webform_menu/submission/%webform_menu_submission` route.

Aside from that, even if you created your own custom route that evoked the same webform callbacks, you'd have to deal with the issue that a webform/username alias combo wouldn't be enough information to map to a unique submission (webforms can have duplicate titles, users can submit multiple submissions).

---
Tags: 7, webforms
---


# Question
Title: How do I add a private file to node's file field from Base64 in code
I'm struggling to add file to node in code. I know about `File::create()` but I want to add file to node based on field configuration of the file field on that particular node's content type, and file's data comes as Base64, not URL or form post.

How do you do it? I'm asking as I want to add file via custom REST call as Base64.

I am using the following code.

```
$node = Node::load($data['case_id']);
$files = $node->field_file;  // unlimited files
/* @var $df \Drupal\field\Entity\FieldConfig */
$df = $node->getFieldDefinition('field_file'); // ??? can i get this config for saving new file?
$file =  file_save_data(base64_decode($data['data']), ??path??);
$files->appendItem($file)->validate();
$node->save();

```

Am I on the valid course? I have no clue how to set config from `$df` and before save. How do I use the configuration of that file field during save?

Yurii

# Answer
my final solution was next:

```
$node = Node::load($data['case_id']);
$files = $node->field_case_file;
$dfSettings = $files->getDataDefinition()->getSettings();
$destination = $dfSettings['uri_scheme'].'://'.$dfSettings['file_directory'].'/'.$filename;
$destination = \Drupal::token()->replace($destination);
$file = file_save_data(base64_decode($fileData), $destination, FILE_EXISTS_RENAME);

$violations = $files->appendItem($file)->validate();

if(count($violations)) {
//throw error
}

$node->save();

```
> 3 votes

---
Tags: nodes, 8, files
---


# Question
Title: How to enable ckeditor in the emails templates at admin/config/people/accounts?
Just that.

I need to enable ckeditor to write the text body for the **welcome e-mail message** at `admin/config/people/accounts`

How can I do this?

# Answer
1. Create custom module for Drupal 7;
2. Add below code to your module;
3. **replace all** MODULENAME in code to your module name;
4. clear cache;
5. refresh /admin/config/people/accounts page

For all textarea fields there's text selector appear - you should select format, where ckeditor attached:

```
/**
 * Implements hook_form_FORM_ID_alter() for user settings page.
 */
function MODULENAME_form_user_admin_settings_alter(&$form, &$form_state, $form_id) {
  _MODULENAME_form_user_admin_settings_elements($form);
}

/**
 * Scan through elements.
 */
function _MODULENAME_form_user_admin_settings_elements(&$elements) {
  // Recurse through all children.
  foreach (element_children($elements) as $key) {
    if (isset($elements[$key]) && $elements[$key]) {
      if (isset($elements[$key]['#type']) && ($elements[$key]['#type'] == 'textarea')) {
        $elements[$key]['#type'] = 'text_format';
      }
      else {
        _MODULENAME_form_user_admin_settings_elements($elements[$key]);
      }
    }
  }
}

```
* be warn, that placeholders signs \[bla-bla:something\] can be replaced by unicode symbols (&XXXX;), check before to show your client.
* if you want add text format only for certain textarea use Devel module dpm function for seeking that element and setting next code `$elements[CERTAIN_ARRAY_PATH2ELEMENT]['#type'] = 'text_format';` without scanning through all elements.
> 2 votes

# Answer
In my answer I'm only going to focus on **Welcome (no approval required)** email body field.

* First make sure to install HTML Mail module and its dependencies
* Create **Full HTML** format if its not being created yet `admin/config/content/formats`
* Implement the following code in a module and replace `mymodule` with your own module name

**Code:**

```
/**
 * Implement hook_form_alter().
 */
function mymodule_form_user_admin_settings_alter(&$form, &$form_state) {

  // alter type textarea to text_format
  $form['email_no_approval_required']['user_mail_register_no_approval_required_body']['#type'] = 'text_format';

  // alter default format to full_html (you need to create this format before you assign it)
  $form['email_no_approval_required']['user_mail_register_no_approval_required_body']['#format'] = 'full_html';

  // add validation function to alter field value before submit (before saving it to variable tables)
  $form['#validate'][] = 'mymodule_system_settings_form_validate';
}

function mymodule_system_settings_form_validate(&$form, &$form_state) {

  // get submitted value
  $html = $form_state['values']['user_mail_register_no_approval_required_body'];

  // set value of the submitted value
  form_set_value($form['email_no_approval_required']['user_mail_register_no_approval_required_body'], $html['value'], $form_state);
}

```

The reason I'm using validate function is to alter field value before submitting value and store it into `variable` table. Without altering the value Drupal will store value as **array (value, format)** and users will start getting `Array` as text instead of the actual text that you need them to see.
> 1 votes

# Answer
if the field format is choosen as long text

in the

```
  admin/config/people/accounts/

```

click on modify then select

```
 treatment: filter text

```
> 0 votes

---
Tags: emails, wysiwyg
---


# Question
Title: How to add variables to Drupal.settings using form#attached?
I found this example: http://deeson-online.co.uk/labs/how-use-formattached-javascript-setting-drupal-7-form-api

I tried:

```
   $form['#attached']['js'][] = array(
            'data' => array(
                'my_module' => array(
                    'xx_code' => 'dsadsad',
                    'xx_key' => 'sadasd',
                ),
            ),
            'type' => 'setting',
        );

```

but with no luck, Drupal.settings.my\_module is undefined

# Answer
Documentation is available:

Form API

```
$settings = array('id' => 'mymodule-element-1');

$form['#attached']['js'][] = array(
  'data' => array('mymodule' => $settings),
  'type' => 'setting',
);

```

Managing JavaScript in Drupal 7

```
$element['#attached']['js'][] = array(
  'type' => 'setting',
  'data' => array('myModule' => array('key' => 'value')),
);

```

Both are roughly the same as what OP (@drupality) said worked for him in a comment on Jun 14 2013.

The code in the original question that the OP said he tried but fails seems roughly the same as the working code, so I can't see what the original error was.
> 4 votes

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


# Question
Title: Adding title attribute to #type password_confirm
Is it possible to add a title attribute through a form\_alter to element #type 'password\_confirm'?

For example, I have a form with the following fields:

* email
* password
* password confirm

To apply a title attribute to the email element is fine...

```
$form['account']['mail']['#attributes']['title'] = 'enter your email address';

```

When I dump the contents of $form in search for the input elements for 'password\_confirm', I only get the following:

```
[pass] => Array
                (
                    [#type] => password_confirm
                    [#size] => 25
                    [#description] => We will not spam you or give your email address to third parties.
                    [#required] => 1
                )

```

I'm not seeing 'pass1' and 'pass2' in the array.

Please could someone point me in the right direction?

# Answer
> 5 votes
The password confirm element is converted to two fields in a process function (`form_process_password_confirm()`), so adding your own process function to the password element would do the trick.

Per this issue it seems you actually need to overwrite the existing #process array instead of just appending to it, e.g for the user register form password element:

```
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['pass']['#process'] = array(
    'form_process_password_confirm',
    'MYMODULE_password_confirm_process',
    'user_form_process_password_confirm'
  );
}

function MYMODULE_password_confirm_process($element) {
  $element['pass1']['#attributes']['title'] = 'Title';
  $element['pass2']['#attributes']['title'] = 'Title2';
  return $element;
}

```

# Answer
> 1 votes
In my case with drupal 7, I corrected with:

```
function MYMODULE_password_confirm_process($element) {
  $element['pass1']['#title'] = 'Title';
  $element['pass2']['#title'] = 'Title2';
  return $element;
}

```

# Answer
> 0 votes
Slightly improved version of Clive's answer (based on a comment from the issue he linked in his answer):

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id)
{
    switch($form_id)
    {
        case 'my_form':
            // Get default process function array:
            $element_info = element_info('password_confirm');
            $process = $element_info['#process'];
            // Add our process function to the array:
            $process[] = 'MYMODULE_process_password_confirm';
            $form['account']['pass']['#process'] = $process;
            break;
    }
}

function MYMODULE_process_password_confirm($element)
{
    $element['pass1']['#attributes']['title'] = 'Title';
    $element['pass2']['#attributes']['title'] = 'Title2';
    return $element;
}

```

The call to the `element_info` function is necessary because the '#process' array can be affected by other modules.

---
Tags: 7, forms
---


title: Using Drupal variables in CSS?

text:
# Question
Title: Using Drupal variables in CSS?
I'm using CSS to implement a banner image in my theme:

```
#banner {
    background: url("../images/banner.jpg") no-repeat fixed
}

```

Site users would like to be able to change the image within Drupal. I'm thinking of adding a file upload field to the Site Information admin form, and insisting that only a file with the same name (banner.jpg) is uploaded.

I wonder if it would be possible to use a Drupal variable in my CSS instead? Then a file name change wouldn't matter. I've used CSS in .php files before (setting the content type back to CSS in the header), but never tried this in a Drupal theme.

# Answer
> 1 votes
You can apply css styles from php. Use the drupal\_add\_css() function

```
<?php
drupal_add_css('#banner { background: url("../images/banner.jpg") no-repeat fixed }',$option['type'] = 'inline');
?>

```

# Answer
> 0 votes
Well, simply create a content type called `banner` which contains images and then create a view of it called `banner-view`; you should create a block display of it. In this view display only the last image. Now instead of creating background, simply use this code:

```
<div id='your-banner-wrapper'>
    <?php print views_embed_view("banner-view","block"); ?>
</div>

```

Now the last image that is uploaded to the content type will be the banner.

# Answer
> 0 votes
Coming a bit late to the party but from project page of the Style (CSS) Settings module:

> Configure CSS values from the UI for any module, theme or custom CSS just by wrapping CSS values in a code comment. The CSS is functional even without the module being installed (soft-dependency). Form API elements are provided to have a color picker or a slider (e.g. for opacity).

Apart from the form API elements offered by the module, to have predefined field values you can use the Drupal core form API fields select or checkboxes.

For a **site's custom CSS**, rename the existing dedicated file '*sites/all/modules/style\_settings/css/example.custom.css*' to *'custom.css*'. This file gets scanned for CSS values wrapped in comments and will be rewritten if so. In any case, it gets loaded as last stylesheet so you can be sure your custom CSS will not get overridden by module or theme CSS. Neither it will be overwritten when you upgrade the module.

You still have to define the form yourself by writing some code but the module takes care of rewriting the desired values in your CSS. Furthermore it offers form API elements especially for CSS property values (including validation) so that task is made as easy as possible.

The module has a demo and documentation.

---
Tags: 7, theming
---


# Question
Title: How to insert a link in a private message by code?
I am sending a message to some users when a specific function is created. However, the content of the message that I send is always in plain text, meaning that it does not render links. What can I do?

This is the function that I use:

```
$message="A user has requested to join your group ".$group->title.". You can go to the group's page now to approve or decline their request.";

privatemsg_new_thread(array($user), 'New membership request for '.$group->title, $message);

```

I would this to work:

```
$message="A user has requested to join your group ".l($group->title,'group/'.$group->gid).". You can go to the group's page now to approve or decline their request.";

```

Any suggestions?

# Answer
This is how I do it:

```
function _send_notifications($entity, $recipient) {
    $params = set_params($recipient, $entity);
    $sent = privatemsg_new_thread(array($recipient), $params['message_subject'], trim(token_replace($params['message_body'])));
}

function set_params($account, $entity) {
    if (isset($entity->nid) && $entity->type == 'entity_type') {
        $author = user_load($entity->uid); // Load the node author.
        $params = array(
            '!first_name' => $account->field_first_name[LANGUAGE_NONE][0]['value'],
            '!last_name' => $account->field_last_name[LANGUAGE_NONE][0]['value'],
            '!node_type' => drupal_ucfirst(str_replace('_', ' ', $entity->type)),
            '!node_title' => $entity->title,
            '!node_url' => url(drupal_get_path_alias('node/' . $entity->nid), array('absolute' => TRUE)),
        );
        $data['message_subject'] = t('New node type has been created');
        $data['message_body'] = t(
            "Dear !first_name !last_name,\na new !node_type has been posted with the title \"!node_title\".\n\nYou can view the post here:\n!node_url\n\n--  [site:name] team", $params
        );

    return $data;
}

```
> 0 votes

---
Tags: privatemsg
---


# Question
Title: hook_form_FORMID_alter select list default value
I created a custom module to override some fields in an exposed form created by views. One of the filters is the between filter on a number field. The between filter produces min and max fields for every field in the form. What I want to do is replace the min and max text fields with lists of integers that the user can select from. Where I am stuck at is the default value of the lists. I keep getting the following message: "An illegal choice has been detected. Please contact the site administrator." Below is a snippet from my module file:

```
$sale_price_min_options=array(
  'All'=>t('-Any'),
  10000=>'10000',
  20000=>'20000',
  30000=>'30000',
  40000=>'40000',
  50000=>'50000',
  60000=>'60000',
  70000=>'70000'
);

$form['field_sale_price_value']['min']=array(
          '#type' => 'select',
          '#options' => $sale_price_min_options,
          '#default_value' => "",
      );
      $form['field_sale_price_value']['max']=array(
                '#type' => 'select',
                '#options' => $sale_price_min_options,
                '#default_value' => 70000,
            );

```

Please let me know where did I go wrong. Many thanks in advance

# Answer
Change 'All' to ''. The key should be blank. The default value is not matching the option list.
> 1 votes

---
Tags: forms, views
---


title: How to use NOT EXISTS condition?

text:
# Question
Title: How to use NOT EXISTS condition?
I have 2 tables:

```
|users |       |users_roles|
--------       -------------
| uid  |       |uid| rid   |
--------       -------------
|  1   |       | 1 |   3   |
|  2   |

```

For the authenticated users the role is missing in users\_roles table. User with uid=1 is an admin. I want to write the following query in Drupal DB API:

```
SELECT
        uid
FROM
        users
WHERE
        NOT EXISTS(
SELECT
        NULL
FROM
        users_roles
WHERE
        users_roles.uid=users.uid
)

```

I tried with this code, but don't know, how to write the query for notExists condition.

```
$query = db_select('users');

$query->addField('users', 'uid');

$query_exists = db_select('users_roles');
$query_exists->addExpression('NULL');
$query_exists->condition("users_roles.uid=users.uid"); //<- how to do this. Doesn't work.

$query->notExists($query_exists);
$result = $query->execute();
foreach ($result as $record) {
        var_dump($result);
}

```

# Answer
I did it! Here is the code:

```
$query = db_select('users');

$query->addField('users', 'uid');

$query_exists = db_select('users_roles');
$query_exists->addExpression('NULL');
$query_exists->where("users_roles.uid=users.uid");

$query->notExists($query_exists);
$result = $query->execute();
foreach ($result as $record) {
        var_dump($result);
}

```
> 5 votes

# Answer
Why not use a simple `db_query()`? In many cases, this is a perfectly adequate way of doing things; you can still use named parameters, and you can build your query as you'd like. It actually performs (very) slightly better than a `db_select()` anyways (see: http://drupal.org/node/1067802 and https://drupal.stackexchange.com/a/1205/26).

The only reason to not use a `db_query()` for a particular select query is if you need the query to be easily extended or changed by some other module.

```
$result = db_query('SELECT uid
  FROM users
  WHERE NOT EXISTS(SELECT NULL
    FROM users_roles
    WHERE users_roles.uid = users.uid
  )')->fetchCol();

```

Anyways, your particular query is a little more complex than normal, but can still be done using D7's DB API. See:
> 5 votes

# Answer
I had to use something similar:

```
$query = db_select('users', 'u');
$query->leftJoin('users_roles', 'ur', 'u.uid = ur.uid');

$result = $query->fields('u', array('name'))
  ->condition('u.name', '%' . db_like($string) . '%', 'LIKE')
  ->isNull('ur.rid')
  ->range(0, 10)
  ->execute();

```
> 0 votes

---
Tags: 7, database
---


# Question
Title: Newbie question - where do I find the php file for the desired link?
I hope my question is asked properly since I have been seriously looking for about 2-3 hours how to find the php file to the url on the drupal website.

Lets say the url is www.example.com/profile/account

Where do I find profile.php or how do I know the name of the php file in order to edit it?

If someone gets offended by my post being too "lazy" its not true, I am exhausted of looking and I might be totally dumb but I cannot seem to understand where to find it.

ANY help is appreciated

# Answer
The answer is basically that Drupal is more oriented towards modules and interface rather than raw coding, so editing a site is most likely not going to be the regular procedure of finding a file with the name of the link. However, to understand Drupal, which is not too hard, you just have to try try try and fail until you make it.

I am still new and dont get much, but I am starting to understand how to edit different things. My new obstacle is understanding how groups work, which I have 0 idea about, but thats the new challenge!

Hope this helped someone "understand" Drupal abit better. If im wrong, anyone is welcome to correct me or edit my post.

Wish you a happy friday
> 2 votes

---
Tags: uri
---


title: Webforms messed up 'Add content' button

text:
# Question
Title: Webforms messed up 'Add content' button
After I installed and enabled the webform module, my admin toolbar got messed up.

Whenever I click on 'Content -\> Add Content' I immediately get redirected to `#overlay=node/add/webform`. I can still go to the separate content types by altering the link (eg. '#overlay=node/add/news').

I have tried disabling the module and uninstalling / reinstalling, but to no avail.

Is there a way to restore the functionality?

EDIT: Apparently my content types have disappeared...

# Answer
**SOLUTION**:

Discovered that the items for basic page and article had both been marked as disabled (though not by me) in the navigation menu. Re-enabling them under admin/structure/menu/manage/navigation fixed the problem immediately.

D7 Add Content is missing content types
> 0 votes

---
Tags: webforms, dashboard
---


# Question
Title: How can I produce a non-blocking process to modify newly created nodes of custom content type?
I have a custom content type called a `Scan` where the only required field is `ISBN`. Nodes of this type are created when a user POSTs to my REST API endpoint with an ISBN number. That's all working fine, nice and quick (which it needs to be).

Now I want some additional process that -- in it's own time without blocking the API request -- goes over these newly created `scans`, querying an API (Google Books/ISBNdb/OpenLibrary) to fill out the other fields. I can confidently write the plain PHP to do this but I'm trying to learn how I would do this in the Drupal spirit?

* I have learned custom modules so I've got an idea my code is going to sit in the controller (Yes?).
* I have looked at Rules & Actions but these aren't working in Drupal 8 yet (Right?).
* Cron seems to only run every few hours which would be too slow as I want my code to run within minutes of node creation.
* I found hook\_ENTITY\_TYPE\_create but not sure exactly how to create one? In my custom module?

Please help :-)

Disclaimer: I am new to Drupal and am self-teaching Drupal version 8. I am a senior PHP developer with a good understanding of good-old OO PHP but have just never done Drupal. Be gentle with me.

# Answer
One easy way would be to add a hook\_cron to your custom module:

https://api.drupal.org/api/drupal/core%21core.api.php/function/hook\_cron/8.2.x

These get run when drupal runs it's periodic cron hook.

Then you could query for nodes that have the ISBN field but lack some other field you would fill-in with a second API call. So you could get a list of nodes that need updating with a query and then run your code to update them.

If you want it to run more frequently you could set a crontab on your server to hit a page callback that triggers a script. So set up a custom route using mymodule.routing.yml and set it up to require a secret key (to prevent DOS attacks), so for example ?accesskey=12345, and if that page is hit with the access key run your script to update the nodes. This way you could run it every minute.

Another alternative to creating a page callback is to create a custom drush command called from a crontab on your server. Creating custom drush commands is very easy.

Another alternative to using a query to identify items that need updating is the queue api. This would allow you to set up a list of items to process, although it doesn't process the queue, you'd still need some sort of cron job to do that. https://api.drupal.org/api/drupal/core!core.api.php/group/queue/8.2.x Although a query to find items that need processing from a cron process might be easier in this case.

I would recommend against calling APIs using hook\_ENTITY\_TYPE\_create or hook\_ENTITY\_TYPE\_update. If the API call fails, you can't edit the content. Better to offload it to a process not connected to a page load, such as cron, or a process called from a custom cron job.

For examples of cron hooks look at function hook\_cron() in /core/core.api.php

https://api.drupal.org/api/drupal/core!core.api.php/function/hook\_cron/8.2.x this has examples, of using a Drupal queue as well as an entity query.

Here's an example of a type of query where you'd check isbn to see if nodes with isbn filled out have empty data in another field, say, field\_api\_title:

```
$db = Drupal::database();

$query = $db->select('node__field_isbn_longer', 'isbn')
   ->fields('isbn', array('entity_id'));

      $query->leftJoin('node__field_api_title', 't', 't.entity_id = isbn.entity_id');
      $query->condition('tags.field_api_title_target_id', NULL, 'IS NULL');

$nids = $query->execute()->fetchCol();

```

A left join allows you to join to tables that are missing data. It will return rows where there is an ISBN, but the api title hasn't been retrieved. Then you can run your code to update those nodes.
> 1 votes

# Answer
As an alternative to the cron job, this sounds like the queue system might be better.

The main difference is that in your hook\_cron(), you have to execute queries to find data to process. With a queue, you listen to new entities being saved (hook\_entity\_insert()) and put them in your queue.

Then Drupal will manage the list of tasks (queue items) and will automatically invoke your callback for each of them. It will also handle time management and process the configured amount of queue items until the time you configure on your queue is up.

There are plenty of examples and blog posts to be found, this one seems pretty good: https://www.sitepoint.com/drupal-8-queue-api-powerful-manual-and-cron-queueing/. It seems to be very close to your use case, with a hook\_entity\_insert() than then does stuff with the new entities. It's pretty complete and does some more advanced things like a form where you can check the pending items and fire them off manually. You can of course skip that if you don't need it.
> 4 votes

---
Tags: 8, rules, hooks, actions
---


# Question
Title: How to assign twig templates dynamically on basis of field value of custom block?
I have a list box in my custom block with different theme options. On basis of the List box field value I would like to assign the specific twig template dynamically. What will be the best approach to do it and how ? If possible please provide a code snippet for the same.

# Answer
See https://drupal.stackexchange.com/a/211157/31 for an existing related answer.

You implement the theme suggestions hook, the block\_content entity is in `$variables['elements']['content']['#block_content']` as shown there, then you can access your field values from there and provide any kind of template suggestions that you want.
> 2 votes

---
Tags: theming, 8
---


# Question
Title: Drush do not autocomplete files and directory names
I'm using Linux Mint 18 XFCE. Drush perfectly works, except for this annoying issue that it does not let me autocomplete file or directory names in a drush command.

Lets say that I want to sync my production files folder to my local files folder, so the command is:

```
drush rsync @site.prod:sites/default/files sites/default/files

```

When I'm typing the following parts I can pres `tab` and they are autocompleted:

* drush
* rsync
* @site.prod

But when I'm typing `sites/default/files` it is not autocompleted, so I have to manually write the whole text, twice in this example.

It should be possible to do it in Linux because that's the normal behavior in Mac.

Just in case, here is the drush status result:

```
 Drupal version                  :  7.50
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  localhost
 Database username               :  icolma
 Database name                   :  icolma
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anónimo
 Default theme                   :  cornelius
 Administration theme            :  seven
 PHP configuration               :  /etc/php/7.0/cli/php.ini
 Drush version                   :  5.10.0
 Drush configuration             :
 Drush alias files               :  /home/juankvillegas/.drush/aliases.drushrc.php
 Drupal root                     :  /home/juankvillegas/git-repositories/icolma
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Private file directory path     :  sites/default/files/private
 Temporary file directory path   :  /tmp

```

# Answer
The problem is caused by the Drush version (5.10.0) that is the one available in Linux Mint repositories.

Once I disabled that version and installed the most recent one following the instructions in http://docs.drush.org/en/master/install/ it started working.
> 0 votes

---
Tags: drush
---


# Question
Title: How to add Attributes to the input tag of a field
I am trying to find out how to modify a text input for one field of a quiz so that I can disable spellcheck.

Can I create a .tpl.php and add it to my theme folder to override it?

At the moment, it looks like the following:

```
<input autocomplete="off" type="text" id="edit-question-832-answer" name="question[832][answer]" value="" size="60" maxlength="256" class="form-text">

```

I simply with to add the following attributes to just that one field.

```
<input autocomplete="off" autocorrect="off" autocapitalize="off"  spellcheck="false"/>

```

I have looked inside modules/field/theme/field.tpl.php but do not see a way to modify the way text input fields are handled.

Which file am I supposed to edit to make this happen for a specific field?

Thank you.

# Answer
If you can write your own module, you can implement the hook\_form\_alter:

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the_form_i_want_to_change') {
    $form['the_field']['#attributes']['autocorrect'] = 'off';
    $form['the_field']['#attributes']['autocapitalize'] = 'off';
    $form['the_field']['#attributes']['spellcheck'] = 'false';
  }
}

```
> 1 votes

# Answer
Do not edit any files for this. Use hook\_form\_alter in a custom module to target this form and that form input and change its attribute.

See: https://stackoverflow.com/questions/9194821/alter-and-set-a-id-attribute-for-a-field-in-drupal-7
> 1 votes

# Answer
Inspect your form and find out what is your `form_id`

and put this code in your `template.php` file in your theme directory

```
function YOURTHEME_NAME_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'YOUR_FORM_ID') {
      // Merge new attributes with existing ones.
      $form['YOUR_FIED_MACHINE_NAME']['#attributes'] += array(
        'autocorrect' => 'off',
        'autocapitalize' => 'off',
        'spellcheck' => 'false',
      );
  }

```

}

**if you have custom module you can also use HOOK\_form\_alter there**
another solution is override your field.
How to override a field in drupal 7.

as example copy `modules/field/theme/field.tpl.php` to `sites/all/themes/YOUR_THEME_NAME/templates/YOUR_FIELD_MACHINE_NAME--YOURCONTENTTYPE.tpl.php` add your markup to it and clear the cache.
> 1 votes

# Answer
You could start by making more 'visible' to yourself which field is rendered by which tpl.php. One way of doing this is by following the following.

1. First add the line `$conf['theme_debug'] = TRUE;`to your settings.php file (you can find this e.g. in *sites/default/settings.php* or *sites/yoursitename/settings.php*
2. Clear your cache
3. Now visit the page where your field is displayed and look at the source code of the page. You will see, in html comments, the tpl.php files used for rendering this field.
> 0 votes

---
Tags: 7, entities
---


title: Taxonomy Term showing strange text

text:
# Question
Title: Taxonomy Term showing strange text
Having taxonamy term issues - as glossary terms showing with text below the text saying "There is currently no content classified with this term."

does anyone know how to remove or hide the statement mentioned?

Drupal 7

# Answer
> 0 votes
override default with the "taxonomy/term/%" views

or

```
function THEME_preprocess_page(&$vars) {
  if(isset($vars['page']['content']['system_main']['no_content'])) {
    unset($vars['page']['content']['system_main']['no_content']);
  }
}

```

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


# Question
Title: How to create a responsive views block in bootstrap?
I created a content type with one field collection field using Field collection module which accepts up to 4 values.

* Field Collection: Field collection field has 3 fields (text1(40 char), text2(255 char), link). I added one content. Now I have one content with 3 field collection items.
* View: I created a views grid block. Grid settings \> number of columns = 1. I selected the above field collection item as field. On the block configuration page, I gave class col-xs-12.

When I visit the page in mobile, I have to scroll to right to see the full content. I gave bootstrap class col-xs-12, why does it not fit into into mobile screen. Can you please help?

**Image-1**

>

**Image-2**

>

# Answer
The grid default format is not responsive, you can trie Semantic Views
> 0 votes

---
Tags: theming
---


# Question
Title: AJAX doesn't work for "flag" field print in node.tpl
In node.tpl I use this code:

```
<?php print flag_create_link('prova', $node->nid); ?>

```

Flag links work fine, but JavaScript toggle not. The flag link doesn't change to "Unflag link" after click. Any idea?

Why put me on hold? What's not clear about that?

---

Update

At moment I solved with views. Set view full content node and set "Ajax" and "Flag refresh" under Other settings of views. In original node view the problem remains.

# Answer
> 2 votes
It might be too late to add the required JS in the node template. Try adding your flag link to `hook_preprocess_node` in template.php instead.

e.g

```
function MYTHEME_preprocess_node(&$vars){
  $vars['flag_link'] = flag_create_link('prova', $vars['node']->nid);
}

```

then in your node template

```
<?php print $flag_link; ?>

```

---
Tags: 7, flags
---


# Question
Title: Change image background colour when cropping
Is it possible to change the black background colour to another colour (e.g. white) when cropping an image that is smaller than the crop size?

I'm using the "image styles" settings in Drupal 7 to first scale the image to the correct width and then cropping to get the desired height. This results in some of the images having black borders that really don't look nice (and the client doesn't like).

Any other suggestions to fixing this would be appreciated.

# Answer
You could try with ImageCache Actions module. Enable Imagecache Canvas Actions module that is shipped with ImageCache Actions and than change your style effects order to:

1. Scale
2. Define canvas (set your color and scale dimensions)
3. Crop
> 24 votes

# Answer
For Drupal 8 you'll use the Image Effects module. This will provide additional options for your Drupal "image styles". The most effective way I have found to do this is to create an image style with the following effects:

* Scale either a width or height.
* Set canvas - Exact size. Give it the width and height of the final image style and provide a background image. It defaults to transparent so uncheck that and provide your own colour.
* Crop to size (the width and height you applied to the canvas above).

Image atached of an example with a red canvas
> 5 votes

# Answer
These two modules can meet your requirement.

Image effect kit module.

> Image effect kit provides some image effects to be used on an image styles. It includes the following effects:
>
> * Border effect
> * Rounded corner effect
> * Padding effect
> * Watermark effect
> * Resizing effect
> * Overlay effect
> * Filter effect

image effect module.

> Resize an image to an exact set of dimensions size without any crop, stretch, or shrunk, but will add white background if need.
> 1 votes

---
Tags: 7, media
---


# Question
Title: How to alter a function in a contributed module?
I am using a module Simple hierarchical select in my website.

I have a taxonomy in which I have some parent terms and there children terms, I am getting two select list with this module. In one select list I am getting all parent terms, and the module is filtering the second select list as per the parent selected, showing children terms of parent term selected in select list 1.

I need to add some condition to the values I am getting in the select lists to alter this function ***shs\_json\_term\_get\_children*** using custom module.

The function declaration in the module is:

> function shs\_json\_term\_get\_children($vid, $parent = array(), $settings = array()) {}

So I tried using:

> function hook\_shs\_json\_term\_get\_children\_alter($vid, $parent = array(), $settings = array()) {}

and

> function hook\_shs\_json\_term\_get\_children\_alter(&$vid, $parent = array(), $settings = array()) {}

but neither worked.

Any suggestions?

# Answer
As far as I know, you can only alter the functionality the module exposes using hooks defined by that module, and you cannot alter just any function defined in the module. For instance, `shs_json_term_get_children` is just a callback, and you cannot alter it.

The SHS module defines several hooks that are listed in the `shs.api.php` file. For instance, there is a hook called `hook_shs_term_get_children_alter`, that allows you to modify the list of terms displayed to the user: http://cgit.drupalcode.org/shs/tree/shs.api.php?h=7.x-1.x#n73

```
/**
 * Alter the list of terms within a level of the term hierarchy.
 *
 * @param array $terms
 *   List of terms displayed to the user (single hierarchy level).
 * @param array $alter_options
 *   - vid: ID of vocabulary or field name
 *   - parent: ID of parent term
 *   - settings: Additional settings (for example "language", etc.,)
 */
function hook_shs_term_get_children_alter(&$terms, &$alter_options) {
}

```

In your module, you would need to implement that hook like that:

```
function YOURMODULENAME_shs_term_get_children_alter(&$terms, &$alter_options) {
  // Your code here.
}

```
> 2 votes

# Answer
There are some wrong assumptions:

* `shs_json_term_get_children()` is not a hook, but a simple callback
* Even if it were a hook, implementing a similar hook doesn't override any other hook, except in the case of alter hooks, which are those hooks whose names end with `_alter`
* Implementations of hooks are not named like `hook_shs_json_term_get_children_alter()` if *hook* is not the machine name of the module implementing it

As said in the answer for Is there any way to validate taxonomy terms? the module defines `shs_json_term_get_children()` as callback using the following code.

```
$callbacks = array(
    'shs_json_term_get_children' => array(
      'callback' => 'shs_json_term_get_children',
      'arguments' => array(
        'vid' => 'is_numeric',
        'parent' => 'is_array',
        'settings' => 'is_array',
      ),
    ),
    'shs_json_term_add' => array(
      'callback' => 'shs_json_term_add',
      'arguments' => array(
        'vid' => 'is_numeric',
        'parent' => 'is_numeric',
        'name' => 'is_string',
      ),
    ),
  );
// Let other modules add some more callbacks and alter the existing. (!)
drupal_alter('shs_json_callbacks', $callbacks);

```

So, if you need to completely override that callback (i.e. not rely on the values returned from that callback), you can implement code like the following.

```
function mymodule_json_callbacks(&$callbacks) {
  $callbacks['shs_json_term_get_children']['callback'] = 'mymodule_json_term_get_children';
}

```

(Replace *mymodule* with the machine name of the module you are implementing.)

Your callback will receive the same arguments received from the original callback.

If, instead, you just want (for example) add a few terms to the ones returned from `shs_json_term_get_children()`, or remove a few terms from the ones returned from that function, you implement `hook_shs_term_get_children_alter()`.

```
function mymodule_shs_term_get_children_alter(&$terms, &$alter_options) {
  // Alter $terms, or $alter_options.
}

```
> 1 votes

---
Tags: 7
---


title: DrupalDateTime class not work

text:
# Question
Title: DrupalDateTime class not work
I try to use the `DrupalDateTime` class in my theme to show native date and time in custom format based on special TimeZone in my nodes.

According to New Datetime API `DrupalDateTime` should be used instead of the PHP `DateTime` class or to functions like `date()`, `gmdate()`, or `strtotime()`.

I am using the following code in a theme.

```
function MyThemeName_preprocess_node(&$variables){
  $node_date = $variables['node']->getCreatedTime();
  $date = new DrupalDateTime($node_date, 'UTC');
  $date->setTimezone(new \DateTimeZone('Asia/Tehran'));
  $variables['date'] = $date->format('Y/m/d');
}

```

I get this error

> Exception: DateTime object not set. in Drupal\Component\Datetime\DateTimePlus-\>\__call() (line 308 of core\lib\Drupal\Component\Datetime\DateTimePlus.php).

# Answer
> 3 votes
The code you are showing is wrong because `DrupalDateTime::__construct()` is expecting a string, while you are passing an integer, which is what `Node::getCreatedTime()` returns.

Instead of `DrupalDateTime::__construct()`, you should use `DrupalDateTime::createFromTimestamp()`.

```
$date = DrupalDateTime::createFromTimestamp($variables['node']->getCreatedTime(), 'UTC');

```

Since the static method also accept a `\DateTimeZone` object as second parameter, your code could be similar to the following one.

```
if (isset($variables['node'])) {
  $date = DrupalDateTime::createFromTimestamp($variables['node']->getCreatedTime(), new \DateTimeZone('Asia/Tehran'));
  $variables['date'] = $date->format('Y/m/d');
}

```

Since you seem interested to get strings in a specific language, you should also set the language code.

```
if (isset($variables['node'])) {
  $date = DrupalDateTime::createFromTimestamp($variables['node']->getCreatedTime(), new \DateTimeZone('Asia/Tehran'), ['langcode' => 'the language code for the language you need']);
  $variables['date'] = $date->format('Y/m/d');
}

```

# Answer
> 1 votes
if you want to retrun date in Shamsi(jalalian) try to convert it with

```
 if (isset($variables['node'])) {
 $timestamp = strtotime($variables['node']->getCreatedTime());
 $format = 'Y/m/d';
 $timezone = date_default_timezone_get();
 $date = new \IntlDateFormatter("fa_IR@calendar=persian", \IntlDateFormatter::FULL, \IntlDateFormatter::SHORT, $timezone, \IntlDateFormatter::TRADITIONAL);
 $date->setPattern($format);
 $variables['jdate']  =  $date->format(intval($timestamp));
}

```

---
Tags: 8, i18n-l10n, datetime
---


# Question
Title: How to change date_popup date format in form?
I am working on configuration page for the custom module, using datepicker with date module.

When i set #date\_format to 'd-m-Y' its ok, i need a day-month-year format but when i submit form and trying to get variable from variable\_get(), i see only year-month-day format,

**GOAL:** i need this variable to show up as default value or maybe placeholder in proper date format ('d-m-Y'),

*minor goal:* also i want this datepicker not showing up "today" but i need date position in calendar to stick on variable from variable\_get(). Thanks!

```
function mymodule_admin($form, &$form_state) {

$form['mymodule_start_date'] = array(
    '#type' => 'date_popup',
    '#title' => t('Start date'),
    '#date_format' => 'd-m-Y',
    '#attributes' => array('placeholder' => variable_get('mymodule_start_date'),
    '#datepicker_options' => array('maxDate' => 0),
    '#date_year_range' => '-3:+0',
    '#date_label_position' => 'above',
    '#theme_wrappers' => array('date_popup'),
    '#required' => TRUE,
);

return system_settings_form($form);

```

};

EDIT: my resource datepicker API

# Answer
> 2 votes
EDIT: fixed by setting up drupal date format and using datepicker\_options:

```
$form['mymodule_start_date'] = array(
'#type' => 'date_popup',
'#title' => t('Start date'),
'#date_format' => 'd-m-Y',
'#datepicker_options' => array(
    'maxDate' => 0,
    'dateFormat' => date_popup_format_to_popup('d-m-Y'),
    ),
'#date_year_range' => '-3:+0',
'#date_label_position' => 'above',
'#theme_wrappers' => array('date_popup'),
'#required' => TRUE,

```

);

---
Tags: 7, forms
---


# Question
Title: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away'
My website was working till a few days ago. It suddenly stopped working and showing white screen on every page ***only when some users including administrator are logging in to it***. I added the following line at the top of the `index.php`

```
error_reporting(E_ALL); ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

The following error is displaying

> Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away' in /home/\******/public\_html/includes/database/database.inc:2204 Stack trace: #0 /home/\******/public\_html/includes/database/database.inc(2204): PDOStatement-\>execute(Array) #1 /home/\******/public\_html/includes/database/database.inc(683): DatabaseStatementBase-\>execute(Array, Array) #2 /home/\******/public\_html/includes/database/database.inc(2383): DatabaseConnection-\>query('SELECT expire, ...', Array, Array) #3 /home/\******/public\_html/includes/lock.inc(167): db\_query('SELECT expire, ...', Array) #4 /home/\******/public\_html/includes/lock.inc(146): lock\_may\_be\_available('theme\_registry:...') #5 /home/\******/public\_html/includes/theme.inc(449): lock\_acquire('theme\_registry:...') #6 /home/\******/public\_html/includes/bootstrap.inc(455): ThemeRegistry-\>set(Array) #7 \[internal function\]: DrupalCacheArray-\>\__destruct() #8 {main} thrown in /home/\******/public\_html/includes/database/database.inc on line 2204

I really have no idea what to do. thanks in advance

# Answer
> 1 votes
99% of the times I've seen that error it is because the website is trying to save more data than the amount expected by MySQL.

It is fixed increasing the value of the mysql variable `max_allowed_packet`

The value of this variable is given in bytes, and by default it is set to `1048576` (1 Mb).

You can try to modify it to something bigger, like `4194304` (4 Mb) and keep increasing it to a value that do not give you this error.

---
Tags: 7, database
---


title: Privatemsg Module and custom timestamp

text:
# Question
Title: Privatemsg Module and custom timestamp
By default the Privatemsg Module has three timestamp displays for various lengths the message has been sent. After a certain point the listed 'time' changes.

What I want to do is append the next timestamp to the end of the current one. This way it remains the details of minutes and date posted as time moves forward.

**Example: after 24hrs, instead of it just saying 'Oct 8' I want it to say 'oct 8 12:45' and after a year '2014 oct 8 12:45'**

I think I found the code in the module where timestamps are printing, I just can't figure out how to add to it.

```
function privatemsg_date_formats() {
  $formats = array('g:i a', 'H:i', 'M j', 'j M', 'm/d/y', 'd/m/y', 'j/n/y', 'n/j/y');
  $types = array_keys(privatemsg_date_format_types());
  $date_formats = array();
  foreach ($types as $type) {
    foreach ($formats as $format) {
      $date_formats[] = array(
        'type' => $type,
        'format' => $format,
        'locales' => array(),
      );
    }
  }
  return $date_formats;
}

function privatemsg_date_format_types() {
  return array(
    'privatemsg_current_day' => t('Privatemsg: Current day'),
    'privatemsg_current_year' => t('Privatemsg: Current year'),
    'privatemsg_years' => t('Privatemsg: Other years'),
  );
}

function privatemsg_format_date($timestamp) {
  if ($timestamp > ((int)(REQUEST_TIME / 3600)) * 3600) {
    return t('@interval ago', array('@interval' => format_interval(abs(REQUEST_TIME - $timestamp), 1)));
  }
  if ($timestamp > ((int)(REQUEST_TIME / 86400)) * 86400) {
    return format_date($timestamp, 'privatemsg_current_day');
  }
  if ($timestamp > mktime(0, 0, 0, 1, 0, date('Y'))) {
    return format_date($timestamp, 'privatemsg_current_year');
  }
  return format_date($timestamp, 'privatemsg_years');
}

```

# Answer
Add these two date formats (in `admin/config/regional/date-time/formats`):

```
M d H:i

Y M d H:i

```

After that choose above created date formats (in `admin/config/regional/date-time`) in

**Privatemsg: Current year** & **Privatemsg: Other years** respectively.
> 3 votes

# Answer
Day --- --- d Day of the month, 2 digits with leading zeros 01 to 31 D A textual representation of a day, three letters Mon through Sun j Day of the month without leading zeros 1 to 31 l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday N ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) 1 (for Monday) through 7 (for Sunday) S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday) z The day of the year (starting from 0) 0 through 365 Week --- --- W ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year) Month --- --- F A full textual representation of a month, such as January or March January through December m Numeric representation of a month, with leading zeros 01 through 12 M A short textual representation of a month, three letters Jan through Dec n Numeric representation of a month, without leading zeros 1 through 12 t Number of days in the given month 28 through 31 Year --- --- L Whether it's a leap year 1 if it is a leap year, 0 otherwise. o ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) Examples: 1999 or 2003 Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003 y A two digit representation of a year Examples: 99 or 03 Time --- --- a Lowercase Ante meridiem and Post meridiem am or pm A Uppercase Ante meridiem and Post meridiem AM or PM B Swatch Internet time 000 through 999 g 12-hour format of an hour without leading zeros 1 through 12 G 24-hour format of an hour without leading zeros 0 through 23 h 12-hour format of an hour with leading zeros 01 through 12 H 24-hour format of an hour with leading zeros 00 through 23 i Minutes with leading zeros 00 to 59 s Seconds, with leading zeros 00 through 59 u Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds. Example: 654321 Timezone --- --- e Timezone identifier (added in PHP 5.1.0) Examples: UTC, GMT, Atlantic/Azores I (capital i) Whether or not the date is in daylight saving time 1 if Daylight Saving Time, 0 otherwise. O Difference to Greenwich time (GMT) in hours Example: +0200 P Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) Example: +02:00 T Timezone abbreviation Examples: EST, MDT ... Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400 Full Date/Time --- --- c ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00 r » RFC 2822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200 U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

and you can used : $date = date("character");
> -1 votes

---
Tags: 7, privatemsg
---


# Question
Title: Add new tags to Chosen Widget or Display All on Autocomplete Deluxe
Trying to find a combination of the features provided by the Autocomplete Deluxe widget and the Chosen module.

They're both great in their own right, but I either need Autocomplete Deluxe to display all options when you click the field (like it does in Chosen) or be able to add new terms to a Chosen field (like you can with Autocomplete Deluxe).

Chosen documentation implies it has this functionality, but I haven't been able to work out how to do it from a select list. And Autocomplete Deluxe, which should be pretty basic, I can't figure for the life of me how to trigger the drop-down to show.

Has anyone been able to do this successfully?

# Answer
> 0 votes
For Autocomplete Deluxe, there looks like there's a bug in the code.

Update line 287 of the js file autocomplete\_deluxe.js to include a question mark, as shown in the third last line of this block of code:

```
Drupal.autocomplete_deluxe.SingleWidget.prototype.setup = function() {
  var jqObject = this.jqObject;
  var parent = jqObject.parent();

  parent.mousedown(function() {
    if (parent.hasClass('autocomplete-deluxe-single-open')) {
      jqObject.autocomplete('close');
    } else {
      jqObject.autocomplete('search','?');
    }
  });
};

```

Also update the maximum results shown in line 30 of the module by changing to $limit = 0 (the default of 10 overrides whatever you have set for the field):

```
function autocomplete_deluxe_taxonomy_callback($field_name, $tags_typed = '', $limit = 0) {

```

---
Tags: taxonomy-terms, ajax
---


title: lost admin toolbar and stock file

text:
# Question
Title: lost admin toolbar and stock file
I am a total Drupal newbie so need advice.

I installed a new module commerce\_shipping\_postal\_code\_weight-7.x-1.x-dev, and tried to activate it. I was then advised a couple of other modules needed authorising. I authorised everything and then returned to my home screen. My left hand column had disappeared which contained my login box, my stock file has disappeared, and so has my admin toolbar. Logging in using /?q=user doesn't reveal the toolbar, but I am logged in. I've restored all my files from 24 hours ago with no joy and now am waiting for our ISP to send me a backup database. The only error message I get is :-

```
    Notice: Undefined index: search_api_views_fulltext in
 views_handler_filter->accept_exposed_input() (line 1273 of
 /homepages/11/d95668464/htdocs/drupaltest/profiles/commerce_kickstart/modules/contrib/views/handlers/views_handler_filter.inc).
 Notice: Undefined index: table in
 entity_views_plugin_row_entity_view->init() (line 20 of
 /homepages/11/d95668464/htdocs/drupaltest/profiles/commerce_kickstart/modules/contrib/entity/views/plugins/entity_views_plugin_row_entity_view.inc).

```

I had only downloaded and enabled the modules, and they had not been used so I have no idea of how I could have prevented it.

# Answer
The fault turned out to be that a lot of modules had become de-selected. A good procedure would probably be to print off a module list with all the selected ones shown, this could then easily be checked by future webmasters.
> 0 votes

# Answer
In a drupal website if multiple users use modules page at a time, than there is a chance of disabling of the modules which are already enabled. In that case most of the drupal features will not be available as in the above case. So, we just need to figure out which one are get disabled and enable them all. We can access modules page directly using /admin/modules or /?q=admin/modules

This will lead you directly to the module listing page, where you can find disabled modules and can enable them.
> 0 votes

---
Tags: commerce, database, debugging
---


# Question
Title: Is there any way to combine views block to homepage?
Is there any way to combine views block to homepage?

Example: I created different views blocks like team, about us, portfolio, services and sliders.

The first homepage has about us, portfolio and services.

The second homepage has team, services and sliders.

I can set one of them to front page without adjust the arrangement of views block in structure/blocks.

How do I make the changes of frontpage more efficiently with just change it to first homepage or second homepage?

# Answer
> 2 votes
I am not sure which Drupal you are using. But the procedure is pretty same for D7 & D8.

---

## Normal Drupal Approach:

**1.** Create a block/views-block and set it's visibility to as shown below, do it for all blocks which you want to show on front.

>

**2.** Go to Structures/blocks & place all views-blocks/normal-blocks under the `content` region as shown in following image, in order in which you want to display.

>

**3.** Front page: Now, all three blocks with their content are visible only on the front page as shown below.

>

For Second-home page: Do the same thing as above just apply the visibility to `second-home-page` url in the first step.

---

## Using Panels module

You can use Panels module to get more settings, but if your purpose serves with above approach, do not add extra module in your site. But with Panels module, you can achieve any display setting what you can think of.

---
Tags: views
---


title: Adding Comodo TrustLogo code

text:
# Question
Title: Adding Comodo TrustLogo code
I have a Comodo certificate for my site to serve content using HTTPS.

I would like to add the Comodo TrustLogo (https://trustlogo.com/) so that it appears on every content page. The problem is that the JavaScript comprises of two parts that must be placed in specific locations according to Comodo:

a) One piece must be loaded just before the HTML HEAD closing tag.

The generic code Comodo wants me to include is:

```
<script type="text/javascript"> //<![CDATA[
  var tlJsHost = ((window.location.protocol == "https:") ? "https://secure.comodo.com/" : "http://www.trustlogo.com/");
  document.write(unescape("%3Cscript src='" + tlJsHost + "trustlogo/javascript/trustlogo.js' type='text/javascript'%3E%3C/script%3E"));
  //]]>
</script>

```

b) The second piece must be included just before the HTML BODY closing tag.

The JavaScript is this - anonymised for site-specific content:

```
<script language="JavaScript" type="text/javascript">
  TrustLogo("https://www.example.com/path/to/image.png", "CL1", "none");
</script>
<a href="https://www.positivessl.com/" id="comodoTL">Positive SSL Wildcard</a>

```

Since Bartik and other themes do not meddle with the HTML page stuff (only with the actual content) I looked into messing with the file

> core/modules/system/templates/html.html.twig

and add some content there, but stuff does not appear - it seems ignored as it doesn't even appear in the HTML source...

Please help!

Thanks, Michel

# Answer
First of all, I hope you didn't edit any files in core :)
Secondly, you can of course add the custom scripts in the HTML twig file, but you need to add this template to you active theme and clear theme registry (or all) cache in order for the changes to appear.

Here is a complete html.html.twig file code:

```
{#
/**
 * @file
 * Default theme implementation for the basic structure of a single Drupal page.
 *
 * Variables:
 * - logged_in: A flag indicating if user is logged in.
 * - root_path: The root path of the current page (e.g., node, admin, user).
 * - node_type: The content type for the current node, if the page is a node.
 * - head_title: List of text elements that make up the head_title variable.
 *   May contain or more of the following:
 *   - title: The title of the page.
 *   - name: The name of the site.
 *   - slogan: The slogan of the site.
 * - page_top: Initial rendered markup. This should be printed before 'page'.
 * - page: The rendered page markup.
 * - page_bottom: Closing rendered markup. This variable should be printed after
 *   'page'.
 * - db_offline: A flag indicating if the database is offline.
 * - placeholder_token: The token for generating head, css, js and js-bottom
 *   placeholders.
 *
 * @see template_preprocess_html()
 *
 * @ingroup themeable
 */
#}
<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
    <script type="text/javascript"> //<![CDATA[
      var tlJsHost = ((window.location.protocol == "https:") ? "https://secure.comodo.com/" : "http://www.trustlogo.com/");
      document.write(unescape("%3Cscript src='" + tlJsHost + "trustlogo/javascript/trustlogo.js' type='text/javascript'%3E%3C/script%3E"));
      //]]>
    </script>
  </head>
  <body{{ attributes }}>
    {#
      Keyboard navigation/accessibility link to main content section in
      page.html.twig.
    #}
    <a href="#main-content" class="visually-hidden focusable">
      {{ 'Skip to main content'|t }}
    </a>
    {{ page_top }}
    {{ page }}
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
    <script language="JavaScript" type="text/javascript">
      TrustLogo("https://www.example.com/path/to/image.png", "CL1", "none");
    </script>
    <a href="https://www.positivessl.com/" id="comodoTL">Positive SSL Wildcard</a>
  </body>
</html>

```

You can put this file in your active theme /templates folder, clear cache and it'll load the logo on every page.
There are other ways to do so like using custom module to inject the code, but for simplicity, you can use this solution.
> 1 votes

---
Tags: 8
---


title: How can I check if a module is enabled?

text:
# Question
Title: How can I check if a module is enabled?
In Drupal 7, you can use module\_exists() to check whether a module is enabled (as well as whether it exists).

For example,

```
if (module_exists('devel')) {

```

How can you check whether a module is enabled in Drupal 8?

# Answer
> 60 votes
Just like Clive mention....

> injecting the `module_handler`service would be preferable to using \Drupal (assuming it's an option in current context)

Here is an example of checking if a module is enabled using a service (without injecting it).

```
$moduleHandler = \Drupal::service('module_handler');
if ($moduleHandler->moduleExists('devel')) {
  // Code Here
}

```

# Answer
> 25 votes
Like this:

```
  if (\Drupal::moduleHandler()->moduleExists('devel')) {

```

---
Tags: 8
---


# Question
Title: (solved) send mail with Rules when a term in multi value vocabulary is selected
Trying to get an mail-update when a tag is selected (if a node is inserted or updated).

The debug shows that 'till the second condition, everything is working fine. The second condition should be comparing if tid = 22 is selected. And i can't get this working ..

The name of the vocabulary is 'zichtbaarheid' (dutch for visibility).

```
{ "rules_vinkje_k_n_mail" : {
    "LABEL" : "Vinkje K\u0026N \u003E mail",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_zichtbaarheid" } },
      { "data_is" : {
          "data" : [ "node:field-zichtbaarheid" ],
          "value" : { "value" : { "22" : "22" } }
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "\u003Cfoo@bar.com\u003E",
          "subject" : "[node:title]",
          "message" : "[site:current-date]\r\n\r\n[node:body]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

The debug shows

```
...
10.619 ms The condition entity_has_field evaluated to TRUE [edit]
11.293 ms The condition data_is evaluated to FALSE [edit]
...

```

**=== EDIT ===**

The correct config is as following. Events: after saving new content & after updating

1. First condition (to 'load' the terms): \[entity has field\] \> in Data selector \[node\] & in Field the correct vocabulary
2. Second condition: \[List contains items\] \> Data selector: node:\[fieldname\]. In next screen, switch to \[direct input mode\]. Terms should be visible in a dropdown-menu. Choose the right value

And the export is (you should alter some settings, like the name):

```
{ "rules_twee_vinkje_k_n_mail" : {
    "LABEL" : "TWEE Vinkje K\u0026N \u003E mail",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_zichtbaarheid" } },
      { "list_contains" : { "list" : [ "node:field-zichtbaarheid" ], "item" : "22" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "\u003Cfoo@bar.com\u003E",
          "subject" : "[node:title]",
          "message" : "[site:current-date]\r\n\r\n[node:body]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

(replace node:field-zichtbaarheid with your term-name, like field-tags)

And, as bonus to prevent recursion: I've added the term 'mail send' in the vocabulary. This term is hidden, but updated with an action. When firing the rule, the second condition is now to check if the term 'mail send' is checked or not. If checked, the output is false and the rule is not further executed.

# Answer
I see 2 possible reasons that may cause your problem:

1. Maybe it's a data type conversion issue. You may be more lucky to get that 2nd condition to work if you'd use a text comparison (= "`text_matches`") instead of a data comparison (= "`data_is`").
2. Maybe your zichtbaarheids-field is a multi value field?

To further investigate this, just add a "Display a message" (within System) as your very first Rules Action, to display the actual value (using an appropriate token for your field), after you temporary remove that 2nd rules condition (to ensure the Rules Actions are performed). If that doesn't help either, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".
> 1 votes

---
Tags: taxonomy-terms, rules
---


title: Save new revision of custom entity

text:
# Question
Title: Save new revision of custom entity
I created a custom entity in my module and I can edit and save it just like any other entity in core. I also want to save revisions for this entity but I couldn't find any help so far. I tried this (from node module) but it doesn't work:

```
$entity = $this->getEntity();
$entity->new_revision = true;
$entity->save();

```

I have the revisions tables declared in `@ContentEntityType` annotation, I have the `revision_id` field declared in `baseFieldDefinitions()` but I don't know how to actually save a new revision.

# Answer
For Drupal 8 most intern values like the revision flag (newRevision) is protected, which means that you aren't allowed to set them directly. There is a good reason for this, as Drupal wants to do stuff in some cases when these values are set.

Instead you need to use the `::setNewRevision` method on the entity. This will throw an exception if the entity doesn't support revisions. So if you don't know what entities you are dealing with, you could do something like this.

```
function save_new_revisions(EntityInterface $entities) {
  foreach ($entities as $entity) {
    if ($entity->getEntityType()->isRevisionable()) {
      $entity->setNewRevision();
    }
    $entity->save();
  }
}

```
> 2 votes

---
Tags: 8, entities
---


title: .module file not being discovered

text:
# Question
Title: .module file not being discovered
I am developing a custom Drupal 8 module on my local VM. When I first created and enabled my module, it did not have a `.module` file (just a controller). Now I have added a `.module` file so I can add an implementation of `hook_entity_insert()` but Drupal is not discovering it. I have tried going to Configuration \> Performance \> 'Clear all caches' but no joy!

How can I get Drupal 8 to discover the `.module` file in my custom module?

# Answer
> 6 votes
Just clearing cache is not enough, you need to *uninstall* and then *re-install* your module in order for the `.module` file to be discovered.

In the **Admin panel** go to **Extend** and select the **Uninstall tab**. Select your custom module and click the **Uninstall button**. Now go back to the **List tab** and re-enable your module as before. Your implementation of `hook_entity_insert()` should now be recognised.

---
Tags: 8
---


# Question
Title: Creating mulitple contact forms in drupal 7
I have installed the contact and contact\_forms modules. I have created different categories in the contact settings page.

I want multiple contact forms as I have multiple domains. For each domain I should have a separate contact form.

But that categories displayed in the drop down of the contact form.

Is it possible with the contact module to create multiple contact us forms like contact/site1, contact/site2, contact/site3 etc?

# Answer
Did you consider using Webform Module. I generally prefer this over contact forms on my websites.
> 2 votes

# Answer
Webforms is great but if you just need separate pages for the categories you can use https://www.drupal.org/project/contact\_forms .
> 0 votes

---
Tags: 7, emails
---


# Question
Title: How to render in template file with some conditions?
I want to use render function but I don't want to show all the data which is there in the particular field. So how can restrict something from rendering in template file. Scenario is:

I have reference one field to another contentype, and I am rendering field in template file. But problem is even though the referenced node is not published, that data is displaying in the rendered field. So how can I restrict like if node is published then only I want to display that data.

One more concern is if it is possible with inbuilt functions only that will be great that saves my time of writing code and designing the data.

# Answer
You should be putting the business logic of deciding what you want to show (or hide) in a preprocess function in your template.php and make use of the show and hide functions to specify what you want rendered.
> 0 votes

---
Tags: 7, theming, nodes, entities
---


title: WSOD after chaning subtheme templates

text:
# Question
Title: WSOD after chaning subtheme templates
I've added the `page.tpl.php` and the `theme.api.php` file to my bootstrap subtheme's template folder, refeshed and everything was fine.

I added `<h1>TEST</h1>` to the `page.tpl.php` to check where it would show up. Moved it a bit until I was satisfied where it was.

However I changed my mind and deleted the files in the template folder and got the WSOD...

The two files are still in the original folder and adding them back to the templates folder does nothing.

Is there a way to fix this? Right now the whole site is blank and no errors show up.

Checking the watchdog table leads me to this function:

```
// Use a default value if $message is not set.
  if (empty($message)) {
    // The exception message is run through check_plain() by _drupal_decode_exception().
    $message = '%type: !message in %function (line %line of %file).';
  }

```

# Answer
Clearing the caching tables did the trick! Thanks CodeNext!

However I could not use Drush, so I cleared them manually in PHPmyAdmin using this post
> 1 votes

---
Tags: 7, theming, wsod
---


# Question
Title: How do I fetch the ID of the current entity?
I am using an entityform as rendered entity reference field of an eck entity as 'landing page'

I need the form submission to include the title of the landing page. My solution is to add an entityform field and make rules copy paste the landing page title into the field, when submitted.

The Rules trigger is 'After saving a new entityform submission'.

Now I need to somehow fetch the entity ID of the landing page, but how to get the ID from the current entity?

I tried to create a rules component that uses php to get the entity ID of the current entity (landing page) as follows:

```
{ "rules_get_node_from_current_path" : {
    "LABEL" : "Get landingpage from current path",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules" ],
    "USES VARIABLES" : { "current_landing_page" : {
        "label" : "Current landing page",
        "type" : "domain",
        "parameter" : false
      }
    },
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : {
              "select" : "site:current-page:path",
              "php" : { "code" : "list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);\r\nprint $id;" }
            }
          },
          "PROVIDE" : { "variable_added" : { "nid_txt" : "NID txt" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "nid-txt" ] },
          "PROVIDE" : { "conversion_result" : { "nid" : "NID" } }
        }
      },
      { "entity_fetch" : {
          "USING" : { "type" : "domain", "id" : [ "nid" ] },
          "PROVIDE" : { "entity_fetched" : { "landing_page" : "Landing page" } }
        }
      },
      { "drupal_message" : { "message" : "Current landing page title: [current-landing-page:title]" } }
    ],
    "PROVIDES VARIABLES" : [ "current_landing_page" ]
  }
}

```

..but that gives me the following errors:

> Notice: Undefined variable: entity in eval() (line 1 of /home/cdt/public\_html/sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code).
>
> Notice: Undefined index: entity keys in entity\_extract\_ids() (line 7874 of /home/cdt/public\_html/includes/common.inc).

# Answer
> 0 votes
I ended up using panels and used %node:ID context token.

---
Tags: rules, entities
---


# Question
Title: Replace textfield value on ajax callback
1) Am i missing something here? it's not replacing the textfield value.
2) Also how do i replace if i have a multiple textfield and multiple button in a form.

```
<?php
    function test($form, &$form_state) {
      if (isset($form_state['values']['your_name'])) {
        $name_value = $form_state['values']['your_name'];
      }
      else {
        $name_value = "";
      }

      $form = array();
      $form['your_name'] = array(
        '#title' => t('Your or your company name'),
        '#type' => 'textfield',
        '#value' => $name_value,
        '#prefix' => '<div id ="subscribers-name">',
        '#suffix' => '</div>',
      );
      $form['load_settings'] = array(
        '#type' => 'button',
        '#value' => t('Load my settings'),
        '#ajax' => array(
          'wrapper' => 'subscribers-name',
          'callback' => 'simplenews_mod_load_subscriptions_ajax',
          'method' => 'replace',
        )
      );
      return $form;
    }

    function simplenews_mod_load_subscriptions_ajax($form, &$form_state) {
      $form_state['values']['your_name'] = "loaded value";
      return $form['your_name'];
    }

```

# Answer
> 0 votes
```
function test($form, &$form_state) {
  $form['your_name'] = array(
    '#title' => t('Your or your company name'),
    '#type' => 'textfield',
    '#prefix' => '<div id ="subscribers-name">',
    '#suffix' => '</div>',
  );
  if (isset($form_state['values']['your_name'])) {
    $form['your_name']['#value'] = 'if';
  }
  else {
    $form['your_name']['#value'] = 'else';
  }
  $form['load_settings'] = array(
    '#type' => 'button',
    '#value' => t('Load my settings'),
    '#submit' => 'simplenews_mod_load_subscriptions',
    '#ajax' => array(
      'wrapper' => 'subscribers-name',
      'callback' => 'simplenews_mod_load_subscriptions_ajax',
      'method' => 'replace',
    )
  );
  return $form;
}

function simplenews_mod_load_subscriptions_ajax($form, &$form_state) {
  return $form['your_name'];
}

```

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


# Question
Title: How to fix my Rewriterule in .htaccess to transparently redirect any domain alias?
I want to transparently redirect any domain alias in .htaccess of a Drupal 7 site. However, the rewriterule I use, has no effect while it should work. So something in the default drupal 7 .htaccess that comes out of the box, prevents this rewriterule from working:

This rewriterule should redirect the homepage for any alias domain example.com to /landingpage/example-com except from the companysite.

```
  # Rewrite Request for parked domains '/' to landing page
  RewriteCond %{HTTP_HOST} !=companysite.com
  RewriteCond %{HTTP_HOST} (.+)\.(\w+)
  RewriteRule ^/?$ /landingpage/%1-%2  [L]

```

I am posting the whole .htaccess file including this rewriterule (between double white lines) here:

```
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|install|make|module|profile|po|sh|.*sql|theme|twig|tpl(\.php)?|xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock))$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
  </IfModule>
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Add correct encoding for SVGZ.
AddType image/svg+xml svg svgz
AddEncoding gzip svgz

# Most of the following PHP settings cannot be changed at runtime. See
# sites/default/default.settings.php and
# Drupal\Core\DrupalKernel::bootEnvironment() for settings that can be
# changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value assert.active                   0
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
  # PHP 5.6 has deprecated $HTTP_RAW_POST_DATA and produces warnings if this is
  # not set.
  php_value always_populate_raw_post_data   -1
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Set a fallback resource if mod_rewrite is not enabled. This allows Drupal to
# work without clean URLs. This requires Apache version >= 2.2.16. If Drupal is
# not accessed by the top level URL (i.e.: http://example.com/drupal/ instead of
# http://example.com/), the path to index.php will need to be adjusted.
<IfModule !mod_rewrite.c>
  FallbackResource /index.php
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/foo will be redirected to http://www.example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/foo will be redirected to http://example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

  # Redirect common PHP files to their new locations.
  RewriteCond %{REQUEST_URI} ^(.*)?/(install.php) [OR]
  RewriteCond %{REQUEST_URI} ^(.*)?/(rebuild.php)
  RewriteCond %{REQUEST_URI} !core
  RewriteRule ^ %1/core/%2 [L,QSA,R=301]

  # Rewrite install.php during installation to see if mod_rewrite is working
  RewriteRule ^core/install.php core/install.php?rewrite=ok [QSA,L]

  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rewrite Request for parked domains '/' to landing page
  RewriteCond %{HTTP_HOST} !=corvalan.domain.trade
  RewriteCond %{HTTP_HOST} (.+)\.(\w+)
  RewriteRule ^/?$ /landingpage/%1-%2  [L]

  # For security reasons, deny access to other PHP files on public sites.
  # Note: The following URI conditions are not anchored at the start (^),
  # because Drupal may be located in a subdirectory. To further improve
  # security, you can replace '!/' with '!^/'.
  # Allow access to PHP files in /core (like authorize.php or install.php):
  RewriteCond %{REQUEST_URI} !/core/[^/]*\.php$
  # Allow access to test-specific PHP files:
  RewriteCond %{REQUEST_URI} !/core/modules/system/tests/https?.php
  # Allow access to Statistics module's custom front controller.
  # Copy and adapt this rule to directly execute PHP files in contributed or
  # custom modules or to run another PHP application in the same directory.
  RewriteCond %{REQUEST_URI} !/core/modules/statistics/statistics.php$
  # Deny access to any other PHP files that do not match the rules above.
  # Specifically, disallow autoload.php from being served directly.
  RewriteRule "^(.+/.*|autoload)\.php($|/)" - [F]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

# Add headers to all responses.
<IfModule mod_headers.c>
  # Disable content sniffing, since it's an attack vector.
  Header always set X-Content-Type-Options nosniff
</IfModule>

```

# Answer
> 2 votes
This worked: I had to use the `?q=` inside the last rewriterule like this:

```
RewriteRule ^/?$ ?q=landingpage/%1-%2 [L]

```

---
Tags: 7, redirection, .htaccess
---


# Question
Title: How to link 1000 parked domains to nodes, each with node title corresponding to the domain name
I want to build a drupal site in D7 that can host thousands of parked domains as landing home pages. The purpose is to create a system for a domain broker to host many parked domains, each with its own sales page on its parked domain root.

The domain access module serves similar purpose but my experience is that it works for up to 10 domains, after that there are serious usability and performance issues arising.

So I'm looking for a simple alternative. What I need is only one page per domain, with the domain as title (example.com) and a contact form that potential buyers of the domain can use.

Assumption: the 1000 domains have been parked on the drupal installation domain.

If I create 1000 nodes hwith corresponding titles (example.com) how do I make each node the homepage of each parked domain? Maybe using .htaccess rewrites, but Im not good at that. The parked domain must stay as browser address when redirected.

Alternative might be to create one custom panel page and use tokens to use the domain URL in the title and the sales text and contact form. The contact form is just a standard contact form that sends an email to the site administrator.

# Answer
> 0 votes
Although the answer of rovr138 works for rendering the landingpage node on the homepage, it is rendered inside another node by modifying its template. The drawback of this solution is that tokens or panel context keywords are not available for the landingpage, since its rendered inside another node. Including landing page info on the forms in the landingpage is essential. There may be a workaround for this, but I eventually chose for the simple solution of including the folling rewriterule in my .htaccess file, in which 'example.com' is my company homepage:

```
  # Rewrite Request for parked domains '/' to landing page
  RewriteCond %{HTTP_HOST} !=example.com
  RewriteCond %{HTTP_HOST} (.+)\.(\w+)
  RewriteRule ^/?$ ?q=landingpage/%1-%2 [L]

```

# Answer
> 1 votes
I'm assuming you have a field on your nodes with the name `field_domain`.

On your website:

1. Create a new node. This will be a place holder.
2. Get the NID.
a) Go go `/admin/content/`
b) Click edit on this placeholder node c) Check the url. It will be in the form:
`/node/<NID>/edit`
Get that `NID`.
3. Go to your theme.
4. On the templates folder, create a file with the name:
`node--NID.tpl.php` so something like: `node--78.tpl.php`
5. On this file, put the following content:

```
  <?php
    $query = new EntityFieldQuery();

    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->propertyCondition('status', 1) // published
      ->fieldCondition('field_domain', 'value',  $_SERVER['SERVER_NAME'], '=');
    $result = $query->execute();

    $nid = array_keys($result['node'])[0];
    if($nid) {
      $nodeObj = node_load($nid);
      $nodeRndr = node_view($nodeObj);
      print(drupal_render($nodeRndr));
    }

```

You need to update 2 things:

`article` to the machine name of the content type you're using.
`field_domain` to the machine name of the field you're using.

6. Now, go to `admin/config/system/site-information`
7. Change the front page to `node/NID` where NID is the value from #4.

**Explanation:**

What that code does is checks `$_SERVER['SERVER_NAME']`. This should be the domain that's being used. Using that, it looks to see if there's a `node` with the field `field_domain` that has a value that matches `$_SERVER['SERVER_NAME']`.

If there's a match, it will load the node and render it.

If not, it should still load the placeholder node you created. This could be your default home page.

Hope this helps.

---

**Original comment:**

Have you considered writing some custom code?

If the only thing different is the title. I would create a small module that:

1. On installation creates a table with a domain and a title column.
2. When a page loads, reads the table and matches the domain and selects the title.
3. With the title, on... `hook_preprocess_page` (probably) you can set the title

---

I think there's a bit more functionality you want. If you're acting like a broker or if it's only a single owner, you probably are sending an email. So you would need the domain that was visited in the form as a minimum.

You can do this by having a hidden field and setting the value on load as well.

Or when submitting the form, reading it and processing it.

---

If it's more like a marketplace and you're sending an email to the owner which would vary per domain.

I think that processing that after the fact and only having one form would probably be more efficient than having a form per domain.

---

It depends on the use case. Just offering another option.

# Answer
> 0 votes
You can think of having multi site architecture, basically different sites sharing same code base or they can have site specific codebase but different database.

OR

You can try following:-
\- Comnination of Subdomain and Organic Group.
\- Just Subdomain module

---
Tags: 7
---


title: How to render data from external API

text:
# Question
Title: How to render data from external API
With my current module I have a simple form where a user inputs some information, that information is then sent to an external API, and that API sends some data back.

How do I display the data that is returned from the external API?

Thanks

```
<?php
/**
 * Implements hook_menu();
 */
function find_rep_menu(){
    $items = array();
    $items['find-representatives/%'] = array(
        'title' => 'My Form',
        'page callback' => 'find_representative_value_callback',
        'page arguments' => array(2),
        'access callback' => TRUE,
    );
    return $items;
}

/**
 * My form
 */
function find_rep_form($form, &$form_state) {
    $form['address'] = array(
        '#type' => 'textfield',
        '#title' => t('Your Address'),
        '#size' => 60,
        '#maxlength' => 128,
        '#required' => TRUE,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Find Rep'),
    );
    return $form;
}

/**
 * Submit handler for the find_rep_form.
 */
function find_rep_form_submit($form, &$form_state) {
    $address = $form_state['values']['address'];
    fetchGeocode($address);
    $fetchGeocode = fetchGeocode($address);
    fetchStateInfo($fetchGeocode['returnedLat'], $fetchGeocode['returnedLong']);
    $form_state['redirect'] = 'find-representatives/' . $form_state['values']['address'];
}

function find_representative_value_callback($address) {
    return t('Value: @value', array('@value' => $address));
    //Once I was able to get this working, I was going to push my returned data through here
}
    /*
     * The fetch code
     */
    function fetchGeocode($userAddress) {
        $userAddress = urlencode($userAddress);
        $fetchUrl = "https://api.mapbox.com/geocoding/v5/mapbox.places/" . $userAddress . ".json?country=us&proximity=38.8977%2C%2077.0365&types=address&autocomplete=true&access_token=APIKEY";
        $result = drupal_http_request($fetchUrl);
        if (in_array($result->code, array(200, 304))) {
            $geoResponse = json_decode($result->data);
            $long = $geoResponse->features[0]->geometry->coordinates[0];
            $lat = $geoResponse->features[0]->geometry->coordinates[1];
            return array('returnedLat' => $lat, 'returnedLong' => $long);
        } else {
            drupal_set_message("Geocode returned: " . $result->code); //For testing purposes
        }
    }

    function fetchStateInfo($userLat, $userLong) {
        $userLat = urlencode($userLat);
        $userLong = urlencode($userLong);
        $fetchUrl = 'http://openstates.org/api/v1//legislators/geo/?lat=' . $userLat . '&long=' . $userLong . '&apikey=APIKEY';
        $result = drupal_http_request($fetchUrl);
        if (in_array($result->code, array(200, 304))) {
            $stateInfo = json_decode($result->data, true);
            drupal_set_message($stateInfo[0]['full_name']);
        } else {
            drupal_set_message("State API Returned Error: " . $result->code);
        }
    }

```

I was taking some examples from example two on this comment here

# Answer
> 2 votes
If you don't need to save the data returned by the external source in your drupal database, then you can go through below mentioned points,

* In hook\_form\_form\_id\_alter declare a custom submit function

$form\['#submit'\]\[\] = "my\_module\_form\_submit\_handler";
* in the custom submit function redirect after submission.(are you using cURL to send and receive data to and from external api.)

$value1 = 'value returned from external api'; $value2 = 'value returned from external api'; $form\_state\['redirect'\] = 'myurl/' . $value1.'/'.$value2 ;

* Create a menu item with hook\_menu and pass the values as argument

$menu\['myurl/%/%'\] = array ( 'title' =\> 'some title', 'page callback' =\> 'my\_page\_callback', 'page arguments' =\> array(1, 2), // 1 and 2 are the first and second indexes of the URL - the location of the wildcards 'access callback' =\> TRUE, );
* in page callback function pass the variables

function my\_page\_callback($val1,$val2) { return theme('custom\_data\_page', array('val1' =\> $val1,'val2' =\> $val2));

}
* implement hook\_theme

function mymodule\_theme($existing, $type, $theme, $path) { return array( 'custom\_data\_page' =\> array( 'variables' =\> array( 'val1' =\> val1, 'val2' =\> val2 ), 'template' =\> 'your\_template\_filename', // do not include .tpl.php 'path' =\> 'path-to-your-template-file' ) ); }

* Create the template file in templates folder
* Clear cache. Let me know if you face any issues

# Answer
> 0 votes
***You can complete this by two way:***

```
1. You can render the output on same page where the form is:

```

After submitting the form, simply redirect to the same page with a query param and display the result based on the query.

```
2. You can render the output on another page:

```

On submit the form, you can get the response data and store it in session, then redirect to another page and render the data.

To render data you have to define an theme function like

```
function my_module_theme() {
  $themes = array(
    'response_data' => array(
      'template' => 'template/response_data', // path of template file
      'variables' => array('data' => NULL), // pass args
    ),
  );
  return $themes;
}

```

for more info theme\_function, theme\_function

Now create an tpl file in the module directory template/responce-data.tpl.php and render all the data there.

**Note:** Do not forget to clear cache

# Answer
> 0 votes
My solution here would be to store the responses in a variable from your function:

```
if (in_array($result->code, array(200, 304))) {
        $stateInfo = json_decode($result->data, true);
        // drupal_set_message($stateInfo[0]['full_name']);
        return $stateInfo;
}

```

Then create a hook\_theme function that sets the theme vars and tpls etc. and use that in you callback, eg something like this:

```
return theme('your_theme_var', array('data' => $data));

```

---
Tags: forms
---