Restricting Content by License / Code I'm working on migrating a custom coded site over to Drupal and am having trouble with one piece of functionality.

Currently, if a user wants to download a certain file, they have to enter a serial number into a form. That serial is compared to a list of serials in the db. If the serial matches, the end user can download the file.

Is there any way to create this same type of functionality? I'm willing to use any Commerce add-on, as Commerce will be used for other products.

Take a look Commerce File & its dependency Commerce License. These module enable a licensing product functionality tied to some sort of digital file. This will get you a good way there, but you'll probably add extra features for your particular use (e.g. some sort serial code validation before displaying the download link).


How can I wrap form content in bootstrap divs? I am fairly new to Drupal and I want to change the "add article" form a bit. Currently I have the following displayed:

I want to wrap these <input> fields in a few <div> so that I can apply bootstrap to it. I don't exactly how to do this, so I tried to alter the .twig files that are being called. For example MY_THEME/templates/form/input.html.twig. However all I can see is an <input> calling {{ children }}

If I place this in a div, it just wraps the whole form in this div. Is there a way to place the individual <input> fields in separate divs so that I can apply bootstrap to it?

The way you are suggesting works fine. (I just tested it). Try to clear your cache and hard refresh the page. If you do:

<input{{ attributes }} />{{ children }}

you will have your form inputs wrapped in that div.

The other options is to use the form-element.html.twig or you can use the hook_form_alter and add prefix and suffix to your fields.


How to find an article title for specific post So, I am new to drupal, and I am using a small pdo library to directly fetch from database list of articles, to display them on a page that is not running drupal. But, the articles are posted using drupal cms.

My problem is that, also I am able to fetch the article content, node id ... but I can't seem to find the title of article itself.

I looked in my table, and these are all the data I have.

mysql> describe field_data_body;
+--------------+------------------+------+-----+---------+-------+
| Field        | Type             | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+-------+
| entity_type  | varchar(128)     | NO   | PRI |         |       |
| bundle       | varchar(128)     | NO   | MUL |         |       |
| deleted      | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id    | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id  | int(10) unsigned | YES  | MUL | NULL    |       |
| language     | varchar(32)      | NO   | PRI |         |       |
| delta        | int(10) unsigned | NO   | PRI | NULL    |       |
| body_value   | longtext         | YES  |     | NULL    |       |
| body_summary | longtext         | YES  |     | NULL    |       |
| body_format  | varchar(255)     | YES  | MUL | NULL    |       |
+--------------+------------------+------+-----+---------+-------+
10 rows in set (0.00 sec)

Just as example, I am doing

$db = new DB(...);
$stmt = $db->query("SELECT *, entity_id as id, body_value as content from field_data_body where entity_id < 10  LIMIT 8");
$result = $stmt->fetchAll();

foreach($result as $row){
  echo $row['title']; //error.
}

As with everything there are a few ways to do this. Here are a couple, if you know the node id.

Do a query on the node table:select title from node where nid = KNOWN_NODE_ID

Use a Drupal function:
$node = node_load(KNOWN_NODE_ID);
$nodeTitle = $node->title;


Programmatically turn off body summary My apologies if this is a duplicate, but I spent two days using my Google-foo to find this information and never did. So, now that I've figured it out, I'll post it here.

The Question

How do I turn off the body summary programmatically?

I placed this code directly after my call to node_add_body_field('my_node_type').

  $field_instance = field_info_instance('node', 'body', 'my_node_type');
  $field_instance['settings']['display_summary'] = FALSE;
  field_update_instance($field_instance);

References

node_add_body_field()
field_info_instance()
field_update_instance()


Help with hook_form_alter So I've got a custom module that builds a page (/simple-ajax-form) and has a form on it with the ID "payment_form" and other fields with IDs like "number_1". My module name is "Drupalup Simple Custom Form" for reference.

The problem I can't figure out (as I'm new to hook_form_alter) is that on the form ID instead of it being "payment_form" the ID gets rendered as "payment-form" and then on the input fields instead of it being "number_1" the ID get rendered as "edit-number-1".

What code do I need to make the form render as "payment_form" and inputs without "edit" and to also have underscores? And where does this code go - in my custom module?

Figured it out - put it the ID request in to an array:

$form['#attributes'] = array('id' => array('payment_form'));

Instead of

public function getFormId() { return 'payment_form'; }


Metatag migration from html Drupal 8.8
Modules: Metatags & Migration plus.

I am trying to convert a tag in an XML file to an open graph image metatag.

File:
modules/custom/my_module/dataxml.html
This is the url that has to be converted to the image metatag.

<ImageUrl>
  <![CDATA[https://via.placeholder.com/300.jpg/09f/fff]]>
</ImageUrl>

File: modules/custom/my_module/config/install/migrate_plus.migration.content.yml
These are the source field for the required metatag.

source:
  fields:
     - name: og_image_url
       label: Image
       selector: ImageUrl

Process for the required metatag

process:
  field_meta_tags:
    source: og_image_url
    plugin: prepare_meta

File: modules/custom/my_module/src/Plugin/migrate/process/PrepareMeta.php
The plugin links the metatag with the required value and serializes the mapped result

<?php

namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

/**
 * Plugin to prepare the meta tags.
 *
 * @MigrateProcessPlugin(
 *   id = "prepare_meta",
 * )
 */
class PrepareMeta extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $metas = [];

    // This should likely work with an array later on, but for now, it'll do.
    if (!empty($value)) {
      $metas[$this->configuration['source']] = $value;
    }

    return $metas ? serialize($metas) : [];
  }
}

When I run xDebug $metas has the following value:
$metas = [
og_image_url => "https://via.placeholder.com/300.jpg/09f/fff"
];

The node is created and the other field are migrated perfectly. However the  metatag field og:image:url remains empty and doesn't trigger an error. I don't really know what I'm doing wrong here. If someone could point me in the right direction, that would be much appreciated.

Turns out I used the wrong field name. My field is called field_meta_tag instead of field_meta_tags as used in the question above.


Create custom form and store form data into database I am start working with Drupal just some days ago. I am really a amateur in Drupal . I just want to know how can I create a form in Drupal with textbox or check-boxes and store the value of the form in the database.

Like a registration form script in PHP.

Creating the module structure
The first step in creating the module is to create a folder for the module. You should put this in "sites/all/modules/{name of your module}." Keep in mind that whenever I say "{name of your module}," you should insert the name of your module. For example, we will use the module directory "sites/all/modules/form_example."

Now, create two empty text files called "{name of your module}.module" and "{name of your module}.info."

These two files are required by your module. The .info file contains information about what your module does, while the .module file contains the actual code including hooks. Hooks are functions with special names that will be called by Drupal when actions occur. For example "form_example_menu()" is called when menu information is gathered. In many examples, you will see names such as "hook_menu()" or "my_theme_menu()" and in these cases "my_theme" and "hook" should be replaced by the name of your module or theme.

Build the basic module files

Here is what we will put into the form_example.info file. This tells Drupal and users about your module.

core = "7.x"
description = "An example module used to learn module development and forms creation."
name = "Form Example Module"

There are more options that you can put in the .info file, but the ones above should be added.

Here is the start of our form_example.module file. This will create a very basic form that only has one field, a submit button.

<?php
function form_example_form($form, &$form_state) {

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

  return $form;
}
?>

Note: Do not include the last "?>" part of the PHP code and leave a trailing blank line at the end of the file. This is the Drupal standard.

The module right now contains one function that will create a form. It is important to note that the function takes the inputs $form, and a reference &$form_state. This function will be called when Drupal tries to build the form "form_example_form."

The process for creating a form is mainly two steps. The first is to build an associative array $form that contains all the fields. The second step is to return that $form variable.

To add a field, you set the variable $form[{name of your field}] = array(); Each field can then have a number of attributes, such as "#type" and "#value." Most of these attributes are named with a proceeding "#" sign.

The field we added above is a submit button with the text "Click Here!" on the button. Note that t() will output text and is a Drupal function that plays nice with translation.

Now that we have a form, we need to add two more function: form_example_form_validate, and form_example_form_submit. These two functions are hook functions that will be called when Drupal validates the form and when it submits the form (assuming it validated).

form_example.module:

<?php
function form_example_form($form, &$form_state) {

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

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
}
function

form_example_form_submit($form, &$form_state) {
}
?>

You will note that these three functions take the same variables. $form is the original form information and can be seen as the original structure of the form. $form_state holds all of the submitted values as well as other information, some of which you can add yourself. These two functions need to named similar to the other form, but with "validate" and "submit" at the end.

We want to see the form!!! We will add a menu link to this form.

form.example.module

<?php
function form_example_menu() {
  $items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return

$items;
}
function

form_example_form($form, &$form_state) {

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

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
}
function

form_example_form_submit($form, &$form_state) {
}
?>

Now enable your module and try to access the link. You will probably need to clear the cache.

Add more functionality to the form.

Now we will add one more field to the form.

form_example.module

<?php
function form_example_menu() {
  $items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return

$items;
}
function

form_example_form($form, &$form_state) {

 $form['price'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Price?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => TRUE, //make this field required
  );

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

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
}
function

form_example_form_submit($form, &$form_state) {
}
?>

Here we have added a new textfield and made it required. We have also set the maximum length. You'll see if you try to submit the form, that Drupal will automatically produce an error for the user if they don't fill in the required fields. We will add some more validation in the next step.

Add validation

form_example.module

<?php
function form_example_menu() {
  $items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return

$items;
}
function

form_example_form($form, &$form_state) {

 $form['price'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Price?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => TRUE, //make this field required
  );

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

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
  if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }
}
function

form_example_form_submit($form, &$form_state) {
}
?>

You will now see that the form will not submit unless price is a positive number. We do this by checking the value of price, in $form_state['values'][{name of your field}]. There are similar variables for all of your fields.

We then set an error with form_set_error. Adding this error will alert Drupal that the form did not pass validation.

What to do when your form is submitted?
From this point, you will want to either save the form data, send an email, or display some information. That is beyond the scope of this How To at this point.

I have built some module "tools" or "calculators" using the above method and included the calculation steps in the submit function. You can set the variable "$form_state['rebuild'] = TRUE;" in the submit function so that Drupal does not clear the form. You can therefore edit the $form_state to change a "markup" field type to have your output.

This can also be done with AJAX so that the form displays the calculated values without a page load. That gets a little more complicated and may be added as a separate How To.

Conclusions
Hopefully this is helpful for people interested in writing a module, or adding a form to a module.

Reference: How to Make a Simple Module with a Form and Menu Link


Adding a link to download the original image to a view I would like to add at the end of the description a link like saying "Download HiRes Image" at the end of the caption of the image in this view, but I don't know how. I did try with the module DownloadFile but there is no documentation about it.

http://www.nellens.com/home/photos-full/segunda-serie

You can use the DownloadFile module, which allows you to download Files or Images, and it's usable in views.


Commerce module: Why this commerce_order_ui_form_commerce_order_ui_order_form_alter won't work? I have this commerce order, and I want to hook into it when an administrator review the order (edit it to set it as complete, canceled, or whatever state).

I want at that moment to use a specific field to check using ajax if the name I'm typing in a specific field, already exists as a username.

So I checked out how it works the username_check module, and found that it does add that automatic checking using ajax. It does that check when the user types her desired username at the register form.

How may I adapt it in order to use that functionality for other fields?

The field machine name is field_commerce_username

I've looked into commerce_order.api, at hook_form_alter api, commerce_order_ui and specially commerce_order_ui_form_commerce_order_ui_order_form_alter in order to know what to do.

The username_check module uses hook_form_alter:

function username_check_form_user_profile_form_alter(&$form) {
  $mode     = variable_get('username_check_mode', 'auto');
  if($mode != 'off'){
    _username_check_profile_load_resources($mode);
    $form['account']['name']['#field_suffix'] = '&nbsp;';
    $form['account']['name']['#suffix'] = '

';
  }

So, I thought in doing something like this:

function commerce_order_ui_form_commerce_order_ui_order_form_alter(&$form, &$form_state) {
  $mode     = variable_get('username_check_mode', 'auto');
  if($mode != 'off'){
    _username_check_profile_load_resources($mode);
    $form['element']['#field_name'] = 'commerce_customer_profile';
    }
}

Now, if I try to add that example code to the username_check.module (just for testing purposes), I get this error:

Fatal error: Cannot redeclare commerce_order_ui_form_commerce_order_ui_order_form_alter() in /home/sitio/public_html/sites/all/modules/username_check/username_check.module on line 75

(75 line if where I declare my function).

I just need to be pointed to the right direction here, why is this error?

commerce_order_ui_form_commerce_order_ui_order_form_alter() wasn't declared before in the file... and it won't work even if I comment all _form_alter functions in the module.

I'm guessing by your rep that you already know most of the following but it pays to check:

Hooks can only exist once per module
Hooks must begin with the module name

So this means commerce_order_ui_form_commerce_order_ui_order_form_alter(&$form, &$form_state) won't work inside username_check.module

If you really want to put the code inside the username_check module call it:

username_check_form_commerce_order_ui_order_form_alter(&$form, &$form_state)

[edit:]

Of course, you shouldn't put test code inside an existing module.  The best way to test code is to make your own custom module, which is pretty easy once you get the hang of it.


Create a node from XML on request Is it possible to import XML and create a node upon request?

For example, if a user clicks a link http://www.site.com/item-1, can the corresponding XML file http://www.othersite.com/path/to/item-1/doc.xml be imported as a node at that time, and the user redirected to the new node?

(The XML file is massive, with about 200 fields I need to bring in.)

The short answer is: "yes, it is possible".

There may be different ways of approaching this, but one approach is to use some sort of URL rewriting (e.g. Apache RewriteRule) to let Drupal pick up the external xml file, and then have a custom module that picks up and parses the XML and programatically creates a node with this data stuffed into the appropriate fields and redirects the user to this node.

I've written a custom module for a client that does exactly what I describe above.


Get user role by user field how can I access to my user role thanks to my user custom field ?

I have an user field called "custField" and it's value (example : 123456). I need to check all users that have "123456" as value.

Then, I need to check if this user as the role "director".

But I don't know how to access role thanks to another field.

EDIT :

See this loop :

foreach($retraitDoublons as $valUnique){
  $users = \Drupal::entityTypeManager()->getStorage('user')
    ->loadByProperties(['field_custVal' => $valUnique]);
  $user = reset($users);
  $user_has_role = $user && $user->hasRole('directeur_cr_');

  dump($user);
  dump($user_has_role);

  echo $valUnique . "<hr>";
}

Similar to this question:

I have an user field called "custField" and it's value (example : 123456). I need to check all users that have "123456" as value:

$users = \Drupal::entityTypeManager()->getStorage('user')
  ->loadByProperties(['field_custField' => '123456']);

Then, I need to check if this user:

$user = reset($users);

has the role "director":

$user_has_role = $user && $user->hasRole('director');


Display price in add to cart form BEFORE add to cart button the logical flow of choosing attributes is seeing price adjustments based on the attributes chosen before the buy button ... how can i display the price in the form itself so it appears BEFORE the add to cart button?

here is an example of what i am talking about ... you have attributes, then you have price calculations based on attributes selected and very last thing is the buy button ... this is logical and i can't figure it out.

i did try using jquery to append the price to a div inside the form .. but that is a mess. all sorts of problems with ajax etc and not the correct approach anyway.

I spent weeks on trying to find a clean solution using the commerce-product.html.twig template but to no avail. The problem is the fact that the variation fields and add-to-cart button are packed together into one component (product.variations) in a way that is difficult to decompose. I cannot think of a way to insert the price in there somewhere. Someone should create an issue about this.

Here is a hacky CSS-workaround.

First, create some space above the add-to-cart button:

.commerce-order-item-add-to-cart-form .form-actions {
   margin-top: 4em;
}

Now place the price div into the created space:

article .field--type-commerce-price {
   position: absolute;
   bottom: 2.5em;
}

This also works when the price is updated.

Still looking for a cleaner solution.


Unable to Search or Sort through Webform Submitted Data I created an exposed filter for my View that aggregates user-submitted webform data.  I was hoping this would allow them to search the View for specific webform entries.  Unfortunately, the View remains unsortable by column (although I checked the option to make every column sortable), and whenever I search via my exposed filter, it comes back with 0 results.

I've attached images of my Filter and View settings...  am I doing something wrong?

Thanks!

View Settings:

Filter Settings:

Table Settings:

Check your FORMAT -> Format: Table | Settings for a checkbox that says Override normal sorting if click sorting is used and turn it on if it is not already.


Remove the cache for a particular Twig file I'm showing the name of the currently logged-in user in header, using \Drupal::currentUser()->getUsername(), but it's showing an already cached  page. I know I can disable the cache for a particular page using \Drupal::service('page_cache_kill_switch')->trigger(), but this won't work with the header.html.twig file.

How can I achieve it without affecting the performance?

You need a cache context and a cache tag of the user:

$variables['username'] = [
  '#markup' => \Drupal::currentUser()->getUsername(),
  '#cache' => [
    'contexts' => [
      'user',
    ],
    'tags' => [
      'user:' . \Drupal::currentUser()->id(),
    ],
  ],
];

You can add this directly in a preprocess hook, but then the rendered output will vary for each user. For large numbers of users you might want to put this in a lazy builder callback, which will then match the auto-placeholder conditions and can be lazy-loaded through BigPipe without affecting page load performance.

See https://www.drupal.org/docs/8/api/render-api/auto-placeholdering


How do I tell Drupal 8 to use my custom module's theme template when rendering an image that is linked? I'm building a custom module to extend the default image field. It adds additional attributes that relate to the image field on a per content type basis. At this point it will take and store the attributes => values and when calling hook_preprocess_field() they can be returned (printed) so I can rest assured that they are indeed storing and relating correctly. The final part of the puzzle is to assign my twig template and insert my custom attributes. I thought that hook_theme() would do the job but so far I have failed and I can't find any suitable documentation on the subject when it comes to fields or image fields.

How do I tell Drupal to use my custom module's template when rendering an image that is linked?

Answering my own question. The solution was to use: hook_theme_registry_alter()

/**
 * Implements hook_theme_registry_alter
 */
function MY_MODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['image_formatter']['path'] = drupal_get_path('module', 'MY_MODULE') . '/templates/field';
}

In my module I have the templates/field directory with the template image-formatter.html.twig, so no other changes were necessary.


How can I increase memory_limit for batch processes only? I have a batch process that occasionally exceeds the memory_limit, which is currently 96M. Of course I know the ways to increase the memory limit for the whole site, but I prefer to increase the memory limit for batch pages only.

One way I could think of, is to implement hook_init in a custom module and do ini_set('memory_limit', '200M'); whenever arg(0) == 'batch', but I'm not sure if that is the best solution.

What do you recommend? I guess I could do it in .htaccess, but regex isn't exactly my forte...

[update]
Meanwhile, more searching tells me (Stack Overflow, Webmasterworld) that it is not possible to add a conditional php_value directive to .htaccess.

I think that @kantu's answer is the proper thing to do, but I am going to offer up an alternate solution that is a little hackish.

If you don't want to do a module, then you could add the setting to settings.php wrapped in a conditional.  Just note that this is included really early in the bootstrap process, so you don't have access to the vast majority of the API.

You could try adding

if (strpos($_SERVER["REQUEST_URI"], "/batch") === 0) {
  ini_set('memory_limit', '200M');
}

to the file.

I would also double check the PHP doc about memory_limit (or post a question on one of the sister sites).  I believe that PHP doesn't allocate this during startup; it is just a safety limit to prevent imploding your server.  I am pretty sure you can just bump up this limit globally.

If you are worried about Apache hanging on to this memory, then you can play with the MaxMemFree setting for Apache.  A while ago, I did a site that would need huge amounts of memory very infrequently.  Tweaking this parameter, along with a MaxRequestsPerChild, kept my server running happily.


What module would give an image thumbnail list in a slider format? Which module would give the following slider effect? So i have a list of image thumbnails and I want to be able to scroll through them by clicking on the left or right arrows and have it show X number of them depending on my screen size.

I used jCarousel for views: --- its a bit outdated so you need the updated patch.

You have to apply the following patch: https://drupal.org/node/1548484#comment-8260283 to make it responsive.

If you have a better solution. Do let us know! :)


Web form integrate with views I working on project where user search for nearest shop. so configured view and output result  user get list of shops. in that result I want to provide a button Email us and when user click on that button have to one form will appear and user fill up the data and click on SEND, Then that mail should be send to the shopkeeper`s mail id and also to the user who sent it.
I want to display a button on every single result with fetching mail field according to user into webform
I used profil2 for user profile and  webform modules.

we have a webform views module
which may help you I suppose


check for multiple roles This code I use when checking if user has a role

if (in_array('administrator', array_values($user->roles)))

How to check for multiple roles? I tried something like this

if (!in_array('administrator', 'operator',  array_values($user->roles))

I made it work like this

if (in_array('administrator', array_values($user->roles)) && in_array('operator', array_values($user->roles)))

but there must be some less code solution.
but it is not working. Thank you.

Look at PHP's array_diff() function:

http://php.net/manual/en/function.array-diff.php

This will compare an array of the roles you're checking for against the array of the user's roles, and return an array containing the leftovers.

<?php
$roles_to_check_for = array('administrator', 'operator');
$users_roles = array_values($user->roles);

if (array_diff($roles_to_check_for, $users_roles)) {
  // User does not have all of the $roles_to_check_for.
}
else {
  // User has all of the $roles_to_check_for.
}


drupal_view or views_embed_view doesn't show translated content I have a block view on a multi-language website. Rendering Language is set to Content language selected for page and the translated content is displayed correctly in the admin page.

I embed this view like {{ drupal_view('ipa_projects_map') }} inside twig but at that page the content in original language is displayed, ignoring the content language selected for page setting.

Any ideas why?

PS: drupal_view is provided by "Twig Tweak" module and utilizes views_embed_view

I found the problem. The view is configured to be a "block" and the "rendering language" setting belongs to the "block" definition I guess. So I added the block id and now it renders in the correct language:

{{ drupal_view('ipa_projects_map', 'block_1') }}


How to print a message when a Pane is empty? I've rewritten the node pages on my website with a Panel page (using node_edit) and added the node's comments as a Pane. When no comments have been published yet, the Pane is hidden. However, I'd like to still display the Pane's title and a sentence underneath that says something like: Be the first to react.

I already have a template panels-pane--node-comments.tpl.php and added some lines under if(!$content}{print t('Be the first to react.');}, but as the Pane isn't displayed, the template isn't activated. What should I do?

I know that I could create a View that shows all the node's comments and set a value when there aren't any, but maybe that's overkill?

Create a new pane with that text and set a visibility rule on it - there should be an existing rule that you can use. If not a ctools rule plugin is pretty simple to write and you can have that rule plugin check to see if comment count is 0.


how to do a list navigation into a node content I have a content type with some custom text fields. when the node displays I'd like to show it like this:

node-title

field-1 (link)
field-2 (link)
field-3 (link)

field-1-content

field-2-content

field-3-content

this is for a new site, so I'd like to do that on Drupal 8 (with bootstrap theme).

For this requirement you should go for twig to your content type:

  node--content-type.html.twig

In hook_preprocess_HOOK render all the fields you would like to show in twig file.

For better understanding of twig file follow this.


How to search both Users and Nodes simultaneously in drupal 7 I have a url for search nodes like "?q=search/node/article/xyz"
   and
  I have a url for search users like "?q=search/user/xyz"

now i want to search both at a time simultaneously so, what is the url for this
  in drupal 7.

I have links for Search Like "Article Search",  "User Search", and  "All Search",

I have url for both article and user but not for All Links that's the problem
  please help.

As AyeshK noted in the comments, you can't get this functionality with Drupal core (or even Views).

There are a couple of modules you can try though:

Search API multi-index (relies on Search API)

  This module is an addition to the Search API module which allows users to search on several indexes at once.

  When the module is enabled, you'll get a new Views base table where you can search all enabled Search API indexes at once. Performance might suffer, though, if not all indexes lie on the same Solr server (or other backend server that supports this feature).

  Please note that, since multi-index searches aren't supported explicitly by the Search API, most other Search API add-on functionality (facets, autocomplete, saved searches, search pages, etc.) won't work with searches created with this module.

Entity Backend Search (in alpha)

  This module enables highly customizable search pages for any entity type on a site for the editorial staff. It does not require any modules outside Drupal Core and is very easy to configure.


Taxonomy exposed filter in views I have a content type with a field 'field_departimage' which uses entity reference to reference a taxonomy I have set up which holds the name and image.

I would like to filter by the taxonomy 'name' in views but I'm having some issues linking them

I am able to display the taxonomy but they don't seem to be linking to node to filter correctly. I'm probably doing something wrong with the contextual filters or in the relationships section.

In views you need to add in relationship "Taxonomy term: field name" and in contextual filters you need to set "(field_name) Taxonomy term: Name" or "(field_name) Taxonomy term: Id".


Drupal Rest services "access denied user anonymous" I have created a custom service where I am passing parameters and retrieving result from another file.

So to test it I tried on Postman and I put URL with sitename/endpoint/resource and passed parameters in key value.
When I submit I get an error as access denied user anonymous.

I have return my custom services under hook_services_resources() function

function mymodule_services_resources() {
 $api = array(
  'blog' => array(
    'actions' => array(
     'math' => array(
      'help' => 'Retrieves posted blogs',
      'file' => array('type' => 'inc', 'module' => 'MYMODULE', 'name' => 'mymodule'),

      'callback' => 'mymodule_blog_retrieve',
      'access arguments' => array('services_access_menu'),

      'access arguments append' => TRUE,
      'args' => array(
        array(
          'name' => 'var1',
          'type' => 'string',
          'description' => 'variable 1',
          'source' => array('data' => 'var1'),
          'default' => '0',
        ),
        array(
          'name' => 'var2',
          'type' => 'string',
          'description' => 'variable 2',
          'source' => array('data' => 'var2'),
          'default' => '0',
        ),
      ),
    ),
  ),
),

 );
  return $api;
}

and inc file just takes parameters var1 and var2 and adds it and returns the sum.

Please help me finding out where i have done mistakes.

Here is running code with access callback function:

function mymodule_services_resources() {
 $api = array(
  'blog' => array(
    'actions' => array(
     'math' => array(
      'help' => 'Retrieves posted blogs',
      'file' => array('type' => 'inc', 'module' => 'MYMODULE', 'name' => 'mymodule'),
      'callback' => 'mymodule_blog_retrieve',
      'access arguments' => array('views'),
      'access callback' => '_blog_access_provide_access',
      'access arguments append' => TRUE,
      'args' => array(
        array(
          'name' => 'var1',
          'type' => 'string',
          'description' => 'variable 1',
          'source' => array('data' => 'var1'),
          'default' => '0',
        ),
        array(
          'name' => 'var2',
          'type' => 'string',
          'description' => 'variable 2',
          'source' => array('data' => 'var2'),
          'default' => '0',
        ),
      ),
    ),
  ),
),

 );
  return $api;
}

/** * Access callback */
function _blog_access_provide_access() {
  return TRUE;
}

I hope this would help you.


Is there a module that allow to access a page using a specific URL? I remember seeing this module a while ago, but can't for the life of me finding it. What it did was to only allow a page to be accessible by a specific link you set for it. So, if you just entered the URL into your browser, you would be redirected to, say, your home page.

Does anyone recall this module?

I remember doing something similar with the Rules module a while ago.

Take a look at the integrations for extended functionality - I think you can use the Tokens module with it.


How to theme content edit page I themed page to create custom type node and named it page--node--add--book.tpl.php
It works well, but when I tried to theme content edit page and named it page--node--edit--book.tpl.php
nothing happening. Help to fix this.

Tried suggestions:

function bookhive_theme() {
  return array(
    'book_node_form' => array(
        'arguments' => array('form' => NULL),
        'template' => 'book-node-form',
        'render element' => 'form',
    ),
  );
}

and
suggestion from here

http://www.wdtutorials.com/how-to-override-forms-using-custom-template-drupal-tutorial/7

Ok, I find an answer. In my case the proper theme suggestion was html--node--edit.tpl.php I used theme debug mode to find it.

Also, to make page--node--edit.tpl.php works I need to delete my page--contenttype.tpl.php file. To customize my content type page I just used simple check in page.tpl.php if($node->type == 'book'):

<!-- THEME DEBUG -->
<!-- CALL: theme('html') -->
<!-- FILE NAME SUGGESTIONS:
   * html--node--edit.tpl.php
   * html--node--209.tpl.php
   * html--node--%.tpl.php
   * html--node.tpl.php
   x html.tpl.php
-->


I get image field upload errors with a custom node_add() form I've exposed a node_add form and styled it for certain roles to use. The form is being displayed in panels, through an 'article' node type using the PHP text filter. Users can create new nodes with no issues, but there are errors displayed when users try to upload an image in the form:

  Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 795 of /var/www/html/includes/form.inc).
  Notice: Undefined index: #node in comment_form_node_form_alter() (line 1193 of /var/www/html/modules/comment/comment.module).
  Notice: Trying to get property of non-object in comment_form_node_form_alter() (line 1210 of /var/www/html/modules/comment/comment.module).
  Notice: Undefined index: #node in menu_form_node_form_alter() (line 629 of /var/www/html/modules/menu/menu.module).
  Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 629 of /var/www/html/modules/menu/menu.module).
  Notice: Undefined index: #node in menu_form_node_form_alter() (line 630 of /var/www/html/modules/menu/menu.module).
  Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 630 of /var/www/html/modules/menu/menu.module).
  Notice: Undefined index: field_obs_image in file_ajax_upload() (line 271 of /var/www/html/modules/file/file.module).
      Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of /var/www/html/modules/file/file.module).

The actual node form code looks like this:

module_load_include('inc', 'node', 'node.pages');
$form = node_add('observation');
print drupal_render($form);

I have also tried this code with the same results:

$node_type = 'observation';
$form_id = $node_type . '_node_form';
// maybe add current users info
global $user;
// create a blank node

$node = new stdClass();
$node->uid = $user->uid;
$node->name = (isset($user->name) ? $user->name : '');
$node->type = $node_type;
$node->language = '';
node_object_prepare($node);
$output = drupal_render(drupal_get_form($form_id, $node));

print $output;

The content type being added is 'observation'. I am also using the identical technique on another page with a different content type, and it results in the exact same error. The error appears directly above the image field during the AJAX image upload call.

I have also done a debug_backtrace() near line 795 of form.inc and can post the results if requested.

I have read all of these articles, to no avail:

"Notice: Undefined index: field_xxx in file_ajax_upload()" and "Undefined index: #suffix in file_ajax_upload"
D7 Image field upload errors with custom node_add() form
How to disable AJAX for a file field
The Field module shows an error when I call drupal_get_form()
Can't use file field in custom form - gives AJAX errors

Does anyone have an idea as to where I can start looking? This seems to be a tough problem. Thanks for your time!

I believe the problem is, roughly, that while you've ensured the include happens before initial form build, that include doesn't happen when the AJAX file upload processing attempts to rebuild the form... So node_form() function is undefined and things fall apart.

The solution that worked for me was to use form_load_include() in place of module_load_include(). According to its documentation, this alternate function exists for this express purpose - "ensures that the include file is loaded whenever the form is processed."


xmlrpc_server has no settings How do I configure xmlrpc_server?

I am using the Service module, and I need xmlrpc_server. I installed, and enabled it, and it is showing me the following error:

  xmlrpc_server has no settings
  The server doesn't have any settings that needs to be configured.

What would you want to configure?

As this message tells you, there is no need to configure anything when using the XMLRPC server. That's all. This isn't an error.


How to upgrade only core with drush? There's a huge security leak in <7.32. So I want to upgrade all my Drupal sites asap without too much worrying about breaking stuff.

But...

$ drush dl drupal-7.32
It's forbidden to download drupal core into an existing core.

This one works:

$ drush up

But that's not what I want now.

How can I only upgrade core to latest version?

drush up drupal is not sufficient on its own:
(Sorry about the Dutch. You'll get the gist.)

$ drush up drupal
Controle of updategegevens beschikbaar zijn ...                                                            [ok]
Update information last refreshed: di, 10/14/2014 - 20:57

Update status information on all installed and enabled Drupal projects:
 Naam                               Geïnstalleer  Proposed     Status
                                    de versie     version
 Administration menu (admin_menu)   7.x-3.0-rc4   7.x-3.0-rc4  Actueel
 Drupal                             7.31          7.31         Actueel
 Chaos tools (ctools)               7.x-1.4       7.x-1.4      Actueel
 Service links (service_links)      7.x-2.2       7.x-2.2      Actueel
 Entity API (entity)                7.x-1.5       7.x-1.5      Actueel
 Google Analytics                   7.x-2.0       7.x-2.0      Actueel
 (google_analytics)
 Localization update (l10n_update)  7.x-1.0       7.x-1.0      Actueel
 Module filter (module_filter)      7.x-1.8       7.x-1.8      Actueel
 Pathauto (pathauto)                7.x-1.2       7.x-1.2      Actueel
 Redirect (redirect)                7.x-1.0-rc1   7.x-1.0-rc1  Actueel
 Token (token)                      7.x-1.5       7.x-1.5      Actueel
 Views (views)                      7.x-3.8       7.x-3.8      Actueel
 Webform (webform)                  7.x-3.20      7.x-3.21     Nieuwe versie beschikbaar

No code updates available.

In this case, it looks like you need to do

drush rf    # pm-refresh

before you do

drush up drupal

This will refresh the list of available updates so Drush knows there is a new release for Drupal.


Content Type Content Theme Template Is it possible to make a template based on node content?
For instance, is it possible to page--[node-type]--%.tpl.php or block--[content-type].tpl.php or page--[content-type]--%.  I tried node--[content-type].tpl.php but to no avail.  When I use the theme developer module, it shows me that my content is being created as a 'block.tpl.php' template.

What I want to do is theme the content of node name 'vehicle'. I want to put custom headings, styles and classes for divs in, and display suite is not giving me these options.  Any other suggestions would be awesome.

Thanks

You are right node--[content-type].tpl.php is what you are looking for ,, but you need to get the fields values which can be done with print_r($node) inside the tpl file.

clear your cache to be sure to see the result.


Template name for the user login block I have been trying to create a template to control the user login block given in Drupal 7.  I've referred to the template suggestions documentation page and have tried block--user-login.tpl.php, block--user.tpl.php and am getting no love.
What is the template name for the user login block?.

Since I answered this in IRC, I'll rewrite the answer.

block--user--login.tpl.php

The easiest way to find all of the possibilities for naming template files is to put print_r($variables['theme_hook_suggestions']); at the end of your theme's template_preprocess_HOOK(). Doing so works great for block, node, page...


Display block on two different pages I'd like to view my block on pages where the content type = booking and where the address is node/add/booking (basically add, edit and view nodes), how can I accomplish this? So far my code only shows on pages where content type = booking (i.e. view and edit nodes).

<?php
// Change the type to the one you want to match on
$desired_type = 'booking';
if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
   return $node->type == $desired_type;
}

return FALSE;
?>

You can do it like this. It uses exactly the same principles as your existing if statement.

// Change the type to the one you want to match on
$desired_type = 'booking';
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $node = node_load(arg(1));
  return $node->type == $desired_type;
}
elseif (arg(0) == 'node' && arg(1) == 'add' && arg(2) == $desired_type) {
  return TRUE;
}
return FALSE;


How can I track all Flagging/Unflagging history for statistics? Is there any way to track the flag/unflagging of a node/user without the Heartbeat module? Or a way to track all user/node interaction to use it after for statistics?

Yes there is a way ... using a combination of these (commonly used) modules:

Rules
Message
Views

Long story short:

Create a "Message Type" that you'll use for creating some type of custom logging (for the events you're asking about).
Use the Rules module to capture the events, with rules actions to create appropriate messages (= records in your custom log).
Use the Views module to browse the messages that got created.

For a variation of your question, where a similar technique can be used, refer to my answer to "Is there a way to send emails when someone logs in?".

PS: this answer applies to D7 ...


Set the back-office theme to a specific url (On drupal 6)

On some of the websites i have to manage, the translation page of a node ( mywebsiteurl.com/node/NodeNid/translate) use the main theme instead of the back office theme.

I have some ideas about how force the back office theme, but i doubt it's the right way.

I create a specific module and use a preprocess_page function to force a

$GLOBALS['custom_theme'] = variable_get('theme', 'mybackofficetheme')

if i am in a translation page. But it doesn't works, so can you suggest me the best practice?

I'm not familiar with using translation pages, but I've had good success using the themekey module for changing themes based on URL:
https://www.drupal.org/project/themekey


Get value for drupal date pager next or prev or current I am looking around a way to get the date pager next/prev/current value inside the current view.I am listing events in a month and have used date pager.Display is of month type so in header it shows the month value.and in the next and prev it shows the next month. I need to know the value for the pager navigation.
Thanks in advance.
Arpit

I found a work around, keeping in mind that the pager works for calendar view by changing date in the URL.

I created a custom form with fields as day, month, year whose field type is select (dropdown).

This is the code for the form and the submission handler.

function mymodule_get_event_view_date_filter($form, &$form_state) {
  $form = array();
  $year = date('Y');
  $year_options = array(
    $year - 4 => t($year - 4),
    $year - 3 => t($year - 3),
    $year - 2 => t($year - 2),
    $year - 1 => t($year - 1),
    $year => t($year),
    $year + 1 => t($year + 1),
    $year + 2 => t($year + 2),
    $year + 3 => t($year + 3),
    $year + 4 => t($year + 4),
  );
  $month = date('m');
  $month_options = array(
    '1' => 'Jan',
    '2' => 'Feb',
    '3' => 'March',
    '4' => 'April',
    '5' => 'May',
    '6' => 'June',
    '7' => 'July',
    '8' => 'Aug',
    '9' => 'Sep',
    '10' => 'Oct',
    '11' => 'Nov',
    '12' => 'Dec',
  );
  $form['event-date-container'] = array(
    '#type' => 'container',
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['event-date-container']['year'] = array(
    '#type' => 'select',
    '#options' => $year_options,
    '#prefix' => '
',
    '#default_value' => isset($_SESSION['event']['year']) ? $_SESSION['event']['year'] : $year,
    '#suffix' => '
',
  );
  $form['event-date-container']['month'] = array(
    '#type' => 'select',
    '#options' => $month_options,
    '#prefix' => '
',
    '#default_value' => isset($_SESSION['event']['month']) ? $_SESSION['event']['month'] : $month,
    '#suffix' => '
',
  );
  $form['event-date-container']['submit_form'] = array(
    '#type' => 'submit',
    '#value' => t('Apply'),
    '#submit' => array('_mymodule_event_view_date_submit'),
  );
  unset($_SESSION['event']);
  return $form;
}

function _mymodule_event_view_date_submit($form, $form_state) {
  global $base_url;
  $_SESSION['event']['year'] = $form_state['values']['year'];
  $_SESSION['event']['month'] = $form_state['values']['month'];
  drupal_goto('calendar-node-field-event-date/month/' . $form_state['values']['year'] . '-' . $form_state['values']['month']);
}

Now call this form in your calendar view in view header print.

drupal_render(drupal_get_form(mymodule_get_event_view_date_filter));


Reason for javascript disabled in drupal site? I am using multisite module to maintain three sites. In that i have used "hierarchical_select" module for a form.

In one of my multisite this form is working great, But in the same form for other site, I am getting following error.

I have attached a screen shot of the error.

As it is using the same files, i am thinking that it should be an configuration issues. But i have checked thrice for all the configuration and unsuccessful.

Please help.

Thanks in advance for any help

Hierarchical select adds that info box but removes it with JavaScript. This means that this error can happen for three reasons:

The hierarchical_select.js file is not loaded on the page.
You have an js error on the page before the hierarchical_select.js file is executed.
You have changed the markup for that info box, so that it is not removed by the JavaScript.

The most obvious reason is a that a JavaScript error breaks this page for you, but that is something you'll have to debug yourself...

To do so open firebug on Firefox or the preinstalled Developer Tools on Chrome (strg+shift+i). If you use firebug first enable the Console. Then reload the page and if there is a Javascript Error it will be indicated  with a red warning.


How to migrate Drupal Commerce configuration between environments I'd normally use features to migrate changes from a dev server to a live one, however it seems drupal commerce doesn't fully support features, which leaves me in a tight spot.

How would you suggest to migrate the changes over without causing disruption? The live site is updated constantly.

Any help would be much appreciated.

Commerce Features has helped me in the past.

Apart from that, you're looking at update hooks (or possibly the Configuration Management module).


Using RNG with a seminar with multiple optional sessions I just installed the RNG module and have been playing around with it a bit - but I'm still unsure as to the best way to set it up for my situation.

I help to organize several seminar events a year that run for about three time blocks a day, and each time block has up to 10 different, optional sessions to sign up for.

Each registrant can only register for one session each time block, and each session needs to have a variable maximum number of registrants allowed as they're all held in different rooms of varying sizes.

I think I've sussed out that each session will need it's own event, so that I can define a maximum number. But I'm not sure how to tag certain events/sessions as belonging to a specific time block, and then how to ensure each user can only sign up for one session in each block and that once a session has reached max it will be disabled/greyed out/removed as an option.

Thanks for your time, and thanks for the great module!

What you have so far sounds good, and you're on the right path by setting each seminar to be an RNG event. Unfortunately there is no "conference track" support built in, so you will have to write some code to prevent new registrations based on predefined constraints.

What I would do is add a date field on each session, then another field indicating which track each session is on.

RNG uses the entity reference plugin system to determine if a user is eligible for each event. What you can do is create a hook_query_alter implementation in a custom module. In that hook, you can determine which event the query is for. Then with partial assistance from the RNG API, determine if there are any events the user is registered with the same constraints as the queried event. If you want to allow the user then you do no modifications to the query. If you want to prevent the user from registering, you can add on a condition hack which never evaluates such as $query->condition('uid', NULL, 'IS NULL');

I understand this solution may be complex, especially if you are not a coder or familiar with Drupal 8 API's. Check out UserRNGSelection.php for some inspiration.

Side note: I am maintainer of RNG.


Freshly installed Drush is unresponsive I'm on an Amazon Linux machine.

I ran:

$ composer global require drush/drush
Changed current directory to /home/ec2-user/.composer
Using version ^8.1 for drush/drush
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files

Then I added composer into the PATH so it reads like this:

$ echo $PATH
/home/ec2-user/.composer/vendor/bin:/home/ec2-user/.composer/vendor/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/opt/aws/bin:/home/ec2-user/.local/bin:/home/ec2-user/bin

Then if I try this I get an error:

$ composer show drush/drush

  [InvalidArgumentException]
  Package drush/drush not found

show [--all] [-i|--installed] [-p|--platform] [-a|--available] [-s|--self] [-N|--name-only] [-P|--path] [-t|--tree] [-l|--latest] [-o|--outdated] [-D|--direct] [--] [<package>] [<version>]

And if I run the drush command the cursor stays there waiting:

$ drush

What did I miss?

So after a little investigation I realised I had a folder called drush in my home directory as well as something added by composed inside my home directory/.composer/vendor/bin/. I deleted these drush directories and ran composer again after which drush works fine.

[ec2-user@ip-... ~]$ ls
composer.json  drush  vendor
[ec2-user@ip-... ~]$ sudo rm drush
[ec2-user@ip-... ~]$ cd .composer/
[ec2-user@ip-... .composer]$ ls
cache  composer.json  composer.lock  vendor
[ec2-user@ip-... .composer]$ cd vendor/
[ec2-user@ip-... vendor]$ ls
autoload.php  composer  drush          nikic  psr  symfony
bin           dnoegel   jakub-onderka  pear   psy
[ec2-user@ip-... vendor]$ ls -la
total 52
drwxrwxr-x 12 ec2-user ec2-user 4096 May 12 07:25 .
drwxrwxr-x  4 ec2-user ec2-user 4096 May 11 20:59 ..
-rw-rw-r--  1 ec2-user ec2-user  183 May 12 07:25 autoload.php
drwxrwxr-x  2 ec2-user ec2-user 4096 May 11 20:59 bin
drwxrwxr-x  2 ec2-user ec2-user 4096 May 11 20:59 composer
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 dnoegel
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 drush
drwxrwxr-x  4 ec2-user ec2-user 4096 May 11 20:59 jakub-onderka
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 nikic
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:58 pear
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 psr
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 psy
drwxrwxr-x  6 ec2-user ec2-user 4096 May 11 20:59 symfony
[ec2-user@ip-... vendor]$ sudo rm -rf drush
[ec2-user@ip-... vendor]$ cd ../
[ec2-user@ip-... .composer]$ cd ../
[ec2-user@ip-... ~]$ composer global require drush/drush
Changed current directory to /home/ec2-user/.composer
Using version ^8.1 for drush/drush
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing drush/drush (8.1.2)
    Loading from cache

    Skipped installation of bin drush for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.launcher for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.php for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.bat for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.complete.sh for package drush/drush: name conflicts with an existing file
drush/drush suggests installing drush/config-extra (Provides configuration workflow commands, such as config-merge.)
Generating autoload files
[ec2-user@ip-... ~]$ drush
Execute a drush command. Run `drush help [command]` to view command-specific help.  Run
`drush topic` to read even more documentation. ......rest of output ommited


Reduce installation time and increase the installation speed using drush command "site-install" Can anyone tell me how to increase the installation speed and reduce installation time using drush command "site-install".

or

Is there any alternate way to install the distribution via drush with minimal time.

Because, I am trying to install the larger size distribution via drush using "site-install" command. It takes more time to complete the installation and even some of the distributions are broken during installation after 10min time.

Is there any min requirement in-terms of hardware to install the distribution via drush. Or does it require any additional configuration in php.ini or httpd.conf config file.

We already tried to changing the config in php.ini file for the following attributes.

max_execution_time
memory_limit
max_input_time

Regards
Arun

Is there any min requirement in-terms of hardware to install the distribution via drush

No, there aren't any minimum hardware requirements. If your machine can run the software that Drush relies on, Drush can run.

  does it require any additional configuration in php.ini or httpd.conf config file

It depends on your environment - the project page has all the information you'll need.

  Is there any alternate way to install the distribution via drush with minimal time

I don't see how there would be. The Drush guys aren't going to have made that process intentionally slow, so it'll probably be as quick as it can be.

  Can anyone tell me how to increase the installation speed and reduce installation time using drush command "site-install"

That's down to the specs of your machine; the obvious (if slightly patronising) answer is simply to buy better hardware if yours isn't up to the task you want to use it for.

Bottom line, if you're installing a "larger size distribution" you can expect it take more resources. If that amount of resources is more than you have to give, it's time to look at buying better hardware.


Override function image_style_path doesn't work? I work with the S3FS module on Drupal 7.

In this module the function _s3fs_image_style_deliver of file s3fs.module call the function image_style_path in that line :

$derivative_uri = image_style_path($style['name'], $image_uri);

This function comes from drupal core module image.

I need a way to override this function or the function _s3fs_image_style_deliver from s3fs module.
If someone have an idea ?

Thx :)

I find a way to modify/rewrite the url for each files image style with s3fs module for amazon S3.
It's not really easy to explain, but it work, so i try :

In module s3fs :

Edit file S3fsStreamWrapper.inc line 310 in function getExternalUrl
line 331 replace :

if ($path_parts[0] == 'styles' && substr($s3_key, -4) != '.css') {

by :   if (substr($s3_key, -4) != '.css') {

This will stop checking whether the first path element is the 'styles' folder.

Line 337 replace:

array_unshift($path_parts, 's3','files');

by : array_unshift($path_parts, 't','f','s');

The listening url for creating the derivatives image will be changed from s3/files/ to t/f/s in part to not signal at any time that we are working with an S3. But it's url is not show to normaly user. We can not delete these folders because Drupal expects in 4th position the name of the style like s3/files/style /your-style-name we will see later why I added a folder "s".

Edit file s3fs.module :
line 116 replace :

$items['s3/files/styles/%image_style'] = array(

by : $items['t/f/s/%image_style'] = array(

We changed the listening url in the S3fsStreamWrapper.inc file so we need to modify the listener.

In function _s3fs_image_style_deliver :
Line 206 replace :

$scheme = array_shift($args);

par : $scheme ='s3';

In the previous modification we no longer send information on the scheme. That is read normally through the s3/files url which is now t/f/s. So here we have to say manually what is the scheme.

Line 210 replace :

if (!variable_get('image_allow_insecure_derivatives', FALSE) || strpos(ltrim($filename, '\/'), 'styles/') === 0) {

by : if (!variable_get('image_allow_insecure_derivatives', FALSE) ) {

Another line that check that in first position we have style but we change it afterwards so we change that.

Edit directly Core module image in module/image/image.module.
Rewrite function image_style_path line 1096 :

function image_style_path($style_name, $uri) {
  $scheme = file_uri_scheme($uri);
  if ($scheme) {
    $path = file_uri_target($uri);
  }
  else {
    $path = $uri;
    $scheme = file_default_scheme();
  }
  $tabpath=explode('/', $path);
  $namefile = array_pop ($tabpath); //array_pop delete the last element of array $tabpath and put is value to $namefile
  $path=implode('/', $tabpath);

  $total= $scheme . '://' . $style_name . '/' . $path . '/' . $namefile;
  return $total;
}

The new variable $total allows to rewrite the address of the image by keeping the name of the style first so that the drupal core recognizes it. This is the final address. I did not want it to be like /styles/your-name-style/path but directly /your-name-style/path. As a result, this requires the previous changes in the derivatives creation url so that the style name is in the same location.

Save the files and create the new images for each style:
Empty the Drupal cache with command : drush cc all

And flush the old file to create the news :

Execute this dursh function and when it ask choose all :  drush image-flush

I hope it help someone !


Fetch view results from mymodule_preprocess_page hook We have a View page that is coming from myview. Using the header setting in the view we have added @total results already, which displays in the views-view--myview--page-1.html.twig using the {{ header }} variable.

We want to be able to fetch the view results within our mymodule_preprocess_page() hook. On the View page, we added facet blocks that will return a list of checkboxes (this is from the Article's category tag).

Issue

When we modify the facet value to some value such as value1, the ksm($view->total_results) returns NULL value.

Questions:

How would i fetch the results using mymodule_preprocess_page() hook?
Is there a way to do it without running a query within mymodule_preprocess_page() hook?

View Setup

Display: page

Format

unformatted list
rendered entity | "my_view_mode"

Filter criteria

published = true
content type = article

Header

Global: result summary (global: result summary)

Other
 - Machine name: page_1
 - Use Ajax = yes

What we tried:

function mymodule_preprocess_page($variables) {
  $view_id = \Drupal::routeMatch()->getParameter('view_id');
  $display_id = \Drupal::routeMatch()->getParameter('display_id');

  if($view_id == 'myviewId' && $display_id = 'page_1') {
    // first check we are on view page.
    $view = \Drupal\views\Views::getView($view_id);
    ksm($view->total_results); // returns null.
  }
}

The easiest way would be to execute the View again in the page preprocess hook.

If you want to avoid executing the View twice the task is getting a bit more tricky. This is because in D8 page elements are not necessarily rendered downstream in the order you expect. The element could have been cached in a previous request or in case the element doesn't qualify for caching it could have automatically been placeholdered and the page has been built without it, postponing the rendering until the cached page is finally delivered.

In Drupal 8 elements often need to send information upstream despite being cached or placeholdered, like cache tags or libraries. The mechanism for this is bubbleable metadata. You can use this for other things, too. See for example  Add an attribute to $variables from a Controller

In case of the views results you can try this:

/**
 * Implements hook_views_pre_render().
 */
function mymodule_views_pre_render($view) {
  if (isset($view) && ($view->id() == 'my_view')) {
    $view->element['#attached']['placeholders']['

']['#markup'] =
      '
' . $view->total_rows . '
';
  }
}

Place the empty div container somewhere on the page, for example in the body field of a custom block or directly in page.html.twig:

AJAX

When you enable AJAX the code above only works for the first page load. To update the results when the View gets refreshed via AJAX add your own command in a response event subscriber.

Getting the executed View then is straightforward, Views AJAX implementation keeps it in the response, so that you can use it when altering the response, see ViewAjaxResponse::getView.

/src/EventSubscriber/ViewAjaxResponseSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\views\Ajax\ViewAjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Response subscriber to handle View AJAX responses.
 */
class ViewAjaxResponseSubscriber implements EventSubscriberInterface {

  /**
   * Adds an AJAX command to ViewAjaxResponse.
   */
  public function onResponse(FilterResponseEvent $event) {
    $response = $event->getResponse();
    if ($response instanceof ViewAjaxResponse) {
      $view = $response->getView();
      if (isset($view) && ($view->id() == 'my_view')) {
        $response->addCommand(new HtmlCommand('#my-view-results', $view->total_rows));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['onResponse'];
    return $events;
  }

}

mymodule.services.yml

services:
  mymodule.view_ajax_response_subscriber:
    class: Drupal\mymodule\EventSubscriber\ViewAjaxResponseSubscriber
    tags:
      - { name: event_subscriber }


how to add a form to a build array I am creating a custom module that has the following as the build:

$build = array(

          '#type' => 'markup',
          '#markup' => $html,
          '#attached' => array(

             'library' => array('pup_viewfiles/sortfiles_libraries'),
            ),
        );

    return $build;

I have a Form that I get with the following line :

$form=\Drupal::formBuilder()->getForm(pup_viewfiles\pager),

The question is how can I incorporate this form into the build ?

getForm() returns a render array, and a render array can have other render arrays as children, so:

$build = [
    'form' => $form,
    ...
];


what POST values are required to update nodes containing CCK Date fields via cURL? In brief:

I am tasked with maintaining a Drupal based site but can only access it via the web.

I have several hundred nodes that are incorrectly formatted/missing content
I wrote a class to simplify batch create and update activity via cURL and can successfully update moderately complex content types
I cannot update nodes that have date fields and recurrence, when I try, the return is the form you'd find at /node/$id/edit with the fields populated with the same values I tried submitting and with this error:

An illegal choice has been detected. Please contact the site administrator.
An illegal choice has been detected. Please contact the site administrator.
The UNTIL value is required for repeating dates.

I also cannot create a new node of any type that has a date field.

I am assuming the problem has something to do with the date fields. Pages, which do not have a date field, update without complaint.

The default values I'm submitting, in addition to taxonomy, cck text fields, the standard title and body, and identical start and end month/day/year values and are:

"field_date[rrule][FREQ]" => "NONE",
"field_date[rrule][UNTIL][tz]" => 'America/New_York',
"field_date[rrule][UNTIL][all_day]" => 1,
"field_date[rrule][UNTIL][granularity]" => 'a:3:{i:0;s:4:"year";i:1;s:5:"month";i:2;s:3:"day";}',
"field_date[rrule][exceptions][EXDATE][0][tz]" => 'America/New_York',
"field_date[rrule][exceptions][EXDATE][0][all_day]" => 1,
"field_date[rrule][exceptions][EXDATE][0][granularity]" => 'a:3:{i:0;s:4:"year";i:1;s:5:"month";i:2;s:3:"day";}',
"field_date[rrule][additions][RDATE][0][tz]" => 'America/New_York',
"field_date[rrule][additions][RDATE][0][granularity]" =>'a:3:{i:0;s:4:"year";i:1;s:5:"month";i:2;s:3:"day";}'

All of which were found in the POST values sent when manually saving one of these nodes both with and without changes.

I've been banging my head against the wall on this one for a couple of days now. Can anyone tell me what I'm doing wrong?

Thank you.

All the CCK fields has access rights settings in actions-roles permission matrix. Normally the access is restricted. Please confirm the permission on date field for your role.

An illegal choice has been detected. Please contact the site administrator. is normally reported when some extra fields are added to the form which are not originally the part of form. It is a security measure from Drupal core.

I do not know how cURL request cycle maintains user session that should be associative with proper role that is allowed to edit date field.


Devel dpq() not working? I am trying to print the sql generated from the view but its not working. Below is the error message I am getting:-

Fatal error: Call to a member function arguments() on a non-object in /var/www/Exaxmple-Site/sites/all/modules/devel/devel.module on line 1834

I have seen many of them using this function to print the sql statement but in my case its giving error. Below is the code how I am calling the function.

function example_views_query_alter(&$view, &$query) {
    if ($view->name == 'search_jobs'){

        dpq($view->build_info['query']);
    }
}

Has anyone experienced this issue before?

If you want show sql query you can use code below:

function example_views_pre_execute(&$view) {
  if ($view->name == 'search_jobs'){
        dpq($view->build_info['query']);
    }
}

In your code function dpq error because variable $view->build_info['query'] is NULL. The function dpq only run when variable is An object that implements the SelectQueryInterface interface.


Why isn't the custom validation handler fired in hook_form_alter()? I am adding a custom validation handler to the node edit form, using the following code.

function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id != 'node_article_edit_form') {
    return;
  }

  // ...

  $form['#validate'][] = 'my_module_node_article_edit_form_validate';
}

function my_module_node_article_edit_form_validate(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // ...
}

The validation handler is not invoked, though. What is wrong with the code I am using?

Validate and submit handlers can be placed on the form level or on specific buttons. If they are defined on a button, only those will be executed; it only falls back to the top-level if nothing is defined on the pressed button.

The node form, like all entity forms has the callbacks defined on the button, which is complicated by the fact that there are multiple buttons (save as published, save as unpublished and so on). You must define your validate callback on all of them.

Also, for validation of an entity, you should instead use validation constrains on the fields or the entity.


What is the best method for getting vendor files on the server? I'm fairly new to Drupal 8 development, and I've been a little frustrated with the complications that Composer has added. Nonetheless, I'm trying to determine the best way to get the necessary /vendor files on the server.

I understand that Composer recommends that you ignore the /vendor directory. However, if you don't have a build server in place, what's the best method to getting the /vendor files on the server? Is it common practice to load and run Composer on the server, or is that a big no-no?

You have two options.

Commit the entire project with Git.
Use Acquia BLT.

The first method is not preferred because it makes the repository size massive and unwieldy, but if you have no build server you have no build server. But not having a build server isn't necessarily the end, because...

The second choice would allow you to build locally and deploy to remote using a command BLT provides.

Here is an example. I want to build my develop branch and put it on the server. I can enter the repository url in my project.yml file (provided by BLT), and run this command:

blt deploy -Ddeploy.branch=develop-build -Ddeploy.commitMsg='PROJECT-000: Generating new build for PROJECT.'

This will generate a build artifact (which is not committed into your canonical repository), but instead committed to the remote repository being deployed to as develop-build or whatever you name the branch. You then switch your dev environment to run that branch instead of develop. For instance, my canonical repo lives on GitHub, my remote repo is on Acquia. GitHub won't ever have the -build branches committed to it, and the Acquia repo won't ever have develop or master - it will have the build artifacts of deployed branches. You could use the same repository for both, but its a drag IMO because you (or I, anyway) want the canonical repo to be clean and not be dragging around artifacts of this size.

It is easier with a CI server to automate all of this, but Acquia BLT is a viable option when you don't have a CI service to use because you can run the commands yourself from your machine.

Another option would be to build your own scripts to do this as well, but I'd say you are better off starting with BLT. It can be added to existing projects, and it is straight-forward to configure via project.yml.

So no, you do not need to run Composer on the production server. Most hosting companies would never allow this anyway.


What's The Security Implications for "Send arbitrary files" in Permissions For my webforms, I want to receive attachments, when I receive an email. I had issues receiving them until I set the permissions for Anonymous User to allow them to use "Send arbitrary files".
Underneath, there's a warning:

Give to trusted roles only; this permission has security implications.

Does anyone know what are the security implications?
Thanks!

It means that MimeMail (because that's a MimeMail permission) would be able to attach a file that's it not in the public files directory, like private files, settings.php or any other file in your filesystem.
However, using this permission is mandatory to attach private files, for example, because they are outside the public files directory.
What are the security issues? Well, it depends on what you attach to your email and how. For example, if the path of the attached file depends on some user input, the user can potentially craft a special input that may lead to attaching certain files like the settings.php file or any private file (if the malicious user knows the file path, or can guess it). If your code doesn't allow this you are probably safe.
For example, you may have private files in your nodes and your code just emails the private file of a certain node given its nid, and you get the nid form a button in the full node view page. On this scenario, it seems a malicious user can't craft any submission that attaches an arbitrary file as a result.
In MimeMail words:

The 'send arbitrary files' permission allows you to attach or embed
files located outside Drupal's public files directory. Note that this
has security implications: arbitrary includes even your settings.php!
Give to trusted roles only!

Also, check how MimeMail uses the 'send arbitrary files' permission


How do I run a site from a sub-directory? Maybe I'm making this way more complicated than I need to, but I want to serve my Drupal site that I've installed at example.com/drupal from example.com.  This particular site is an add-on site on my shared host, so the actual file structure is public_html/example.com/drupal.  What do I need to modify: .htaccess or add a redirect in cPanel?  I can't imagine I'm doing anything radical here, but there's no clear-cut answer in all my searching.

I just had the same problem. I have solved it with htaccess file(ie. not nginx) in the root directory with the following code(although I have tested it only with simple index file, not with fully installed Drupal):

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_URI} !drupal/
  RewriteRule (.*) /drupal/$1 [L]
</IfModule>


How to display comment status with radio buttons? How can I display the comment status (open and close) with radio buttons in the comment submit page? I want it be selectable during comment submission by the user.

Actually, I have a content type which has an comment field with two radio buttons:

Satisfied
Unsatisfied

My goal is that, when users select the "Satisfied" button, the comment will be closed automatically; when the "Unsatisfied" button is selected, the users are able to send the next comment.

I think you have to use rate module for your comment, then use Rules module to close the comment on specific node.


When to use mapping or sequence to define an array in a schema file? I need to define an array in my onlyone.settings.yml file to store this values:

onlyone_node_types:
  book: book
  test: test

In my onlyone.schema.yml file I have this:

module.settings:
  type: config_object
  label: 'Only One settings'
  mapping:
    onlyone_node_types:
      type: sequence
      label: 'Configured content types to have Only One node'
      sequence:
        type: string
        label: 'Content type machine name'

But I don't know if I need to use a sequence or a mapping type in my case.

I read in the Configuration schema/metadata page this:

  Note that you may also encounter a slightly different sequence
  definition where the type of the sequence items is defined as a
  strictly one item list. This format is deprecated and will be removed
  in Drupal 9:

So, I don't know if I need to use mapping or sequence in my case to define my array.

A sequence is an unlimited list of identically structured elements. A mapping is a limited set of keys, each key has a possibly different structure.

Your key has node types, so you're storing a list of node type ids, which means a sequence with an inner type string. Exactly what you have.

If you'd use a mapping, you could only store book and test, but test could be an integer (or mapping, or sequence, ...) while book is a string.

The note has nothing to do with sequence vs mapping, it just refers to an old way of defining the type in the sequence and would look like this:

onlyone_node_types:
  type: sequence
  label: 'Configured content types to have Only One node'
  sequence:
    -  type: string
       label: 'Content type machine name'

PS: I'd would convert that to a numbered list, which will then be stored like this:

onlyone_node_types:
  - book
  - test


'Unlinking' a link for users without permission I have a link which goes to a page created by a custom module. The module implements hook_permission and hook_menu so that when a user without permission clicks the link they get sent to the page and are shown the 'You are not authorized to access this page' message.

Is there way I can 'unlink'/'de-anchor' the link, so that the link displays as just unclickable black text to those without permission?

Thanks

Here's what I've come up with myself. It works fine:

if(user_access('edit record')) {
    $link = l(t('Edit this record'), 'edit-record/' . $nid);
} else {
    $link = t('Edit this record');
}

If you know of a 'cleaner' more 'correct' way. Please let me know. Thanks


drush 7 won't take a command without a site alias? I just installed drush 7.0-dev and with it all the composer and bash-completion goodness.  The installation went well and in a new shell it (drush 7) is now my default drush.

However it doesn't seem to want to take commands without aliases.  Is this really the new behavior or did I setup something wrong?

Here is a screenshot of a simple "drush dd files" command executed in my sites drupal root path.   I compare it to the drush 6 version which works fine without an alias.

Don't get me wrong I like aliases and all but this seems a bit draconian to force you to have to use them.

You need to specify path or create sym link based on your server os.. Check Drush Installation instructions for more details..

It's documented in Github page to under Install Manual..

  Configure your system to recognize where Drush resides. There are 3
  options:

  Create a symbolic link to the Drush executable in a directory that is
  already in your PATH, e.g.:

  $ ln -s /path/to/drush/drush /usr/bin/drush

  Explicitly add the Drush executable to the PATH variable which is
  defined in the the shell configuration file called .profile,
  .bash_profile, .bash_aliases, or .bashrc that is located in your home
  folder, i.e.:

  export PATH="$PATH:/path/to/drush:/usr/local/bin"

  Your system will search path options from left to right until it finds
  a result.

  Add an alias for drush (this method can also be handy if you want to
  use 2 versions of Drush, for example Drush 5 or 6 (stable) for Drupal
  7 development, and Drush 7 (master) for Drupal 8 development). To add
  an alias to your Drush 7 executable, add this to you shell
  configuration file (see list in previous option): $ alias
  drush-master=/path/to/drush/drush

  For options 2 and 3 above, in order to apply your changes to your
  current session, either log out and then log back in again, or re-load
  your bash configuration file, i.e.:

  $ source .bashrc

  NOTE: If you do not follow this step, you will need to inconveniently
  run Drush commands using the full path to the executable
  "/path/to/drush/drush" or by navigating to /path/to/drush and running
  "./drush". The -r or -l options will be required (see USAGE, below).

  Test that Drush is found by your system:

  $ which drush


Advice: change the name of the author by his role in a comment I would like to have some advice about my preprocess function i made this morning.

My goals was to replace the name by the role of the author in a comment.

I have many questions because i think my code isn't optimize and i would like to improve it:

I don't know, as a beginner, if it's better to do what i want to achieve in a module or in a preprocess function?
I used this path to change the comment author name : $variables['author'] It works but is it this variable we have to use if we want to alter the comment author.
I made my request inside my preprocess function, is it good to do that? I have only few comments for now, but when i'll have hundred of comments, do you think i'll have a problem of performance? Is there a way to improve it?

function bartik_extended_preprocess_comment(&$variables) {
 $result = db_query("SELECT users.uid AS uid, role.name AS  role_name
              FROM {users} users
              LEFT JOIN {users_roles} roles_id
                ON (( (users.uid = roles_id.uid ) ))
              LEFT JOIN {role} role
                 ON (( (roles_id.rid = role.rid ) ))
              WHERE (( (users.uid = :uid ) ))", array(':uid' => $variables['elements']['#comment']->uid));
$store = array();
foreach ($result as $row) {
  $store['uid'] = $row -> uid;
  $store['role'] = $row -> role_name;
}

if($variables['elements']['#comment']->uid == $store['uid']) {
   $variables['author'] = check_plain($store['role']);
}
}

Thanks,

Module VS preprocess function - modules can use preprocess functions as well. I guess that the question in your case is whether or not to do the changes in a custom module or theme. It's up to you, but generally speaking, keep the specific UI improvements in the theme and let the module do the hard work you will need in any case (if you change the theme for example). Also, it's better to pack the things you might need somewhere else in a module as it's easier to drop it to another site.
You can load the user object with user_load($uid);. This will also load all roles with role IDs and names. I suggest installing Devel and calling dpm($user); to have a better understanding of what you get in the user object.
If by request you mean database request - yes, it's alright, if there's not a way to do so already. As I mentioned in 2. you can use user_load function - this will reduce the code and also load the user object from cache. I think that Drupal already called user_load for rendering the comments, so calling it again will just get everything from cache and won't impact performance.

Hope this helps.


How do I change the original language in PHP files and Twig files? I have installed a Drupal 8.5 site in French (monolingual). Then, I added content.

Of course, there are many strings in the PHP files of my custom theme/module I pass to t(). There are also many strings in the Twig files I translated with {{ 'a string'|trans }}.

After a while, I added English.

Unfortunately, I discovered that all the strings (interface) I just mentioned are seen by Drupal as English string.

For example, using the Translation template extractor module, I don't have the choice to extract the strings in English. I have only 2 options for the extraction: Language independent template and Template file for French translations.
When I use the Translation Management Tool module, all the locale sources strings have Original language under the English column and Not translated under the French column.

How do I tell Drupal that all my strings (PHP and Twig) are French strings?
Alternatively, what is the process to be able to export/translate in English, and import files (PO or XLIFF) into my site?

How do I tell Drupal that all my strings (PHP and Twig) are French strings?

You can not. There is no setting for that, the source code must be english.

Drupal does allow to translate the code/system-english to the actual english if you enable the checkbox when editing the english language. I don't know what that does exactly to potx and I don't think TMGMT supports it either.


Region for Main page content block field is required Error? I have created a custom region called latest. And when I am assigning some block to that region from admin, while saving it returns this error

  Region for Main page content block field is required.

What might be the reason?

This post helped me get closer, but I thought I would provide a more concise answer for those following the same path.

If you are looking to remove all blocks from Drupal 7, like you would want to do if you were placing blocks by using Context, you want to make sure that core's "Main page content" is the last block removed.

Steps:

Select "- None -" for all other blocks, then click Save.
Then change the "Main page content" block's region to "- Select -" and
click Save.


How to create colored World maps? I would like my users to be able to select the countries they have visited and then highlight those countries on a world map.

I've come across a few commercial flash solutions with XML config files but would rather like to avoid flash and have jpgs or pngs generated.

This site is a good example of what it should look like.

You can probably use OpenLayers, with MapBox to create custom map layers with MapBox.com


How do you switch a site's language by using GET variables? Is there a module? Currently I'm using a module that displays a bunch of nodes on a single page.

And I also have translated content in different languages.

The core functionality to switch a sites language currently creates a prefix in the URL, but is there one for switching the language via a GET variable like www.example.com/node/8?lang=german?

Use the Language Switcher module for multiple Language.

  Language Switcher for Drupal 7 is an enhancement for core language switcher block in local module. It's very useful for websites with multi-languages where you want to display content in different languages side-by-side


What's the correct way to enable clean urls when Drupal is hosted in a sub directory (linux server)? Until recently, I've never used Drupal in a subfolder before, and having followed the directions in the .htaccess file as well as this page, I'm unable to get it working.

Drupal projects will be stored in the following structure:

localhost/drupal/project1
localhost/drupal/project2
...
localhost/drupal/project10

Here is where I am:

Per the .htaccess file I uncommented the rewrite rule for subdirectories so that it reads RewriteBase /drupal/project1
Per the link above I changed the httpd.conf file to read AllowOverride All so .htaccess overrides would work.

Yes, the rewrite module is installed and working. Yes, I've restarted Apache several times and cleared Drupal cache. I've even tried different variations of the rewrite base. Nothing.

Am I missing a step somewhere?

Locally, I only work with sub folders. The times I had problems with getting clean URL's working correctly, it was the rewritebase setting (part of the mod rewrite class of settings) that was not set correctly.


Inserting search term within "No results behavior" Within the 'NO RESULTS BEHAVIOR' section of Views in Drupal 8 how do I output the search term along with some custom text using the "Unfiltered text" option?

My desired output is "No results found for search term, please..."

Can anyone suggest a solution?

you can use template_preprocess_views_view

 function template_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  $variables['view_total_count'] = $view->total_rows;

  if ($view->total_rows === 0) {
    $exposed_input = $view->getExposedInput();
    $search_term = $exposed_input['your search input'];
    $variables['empty'] = 'No results found for'.$search_term.', please ...';
  }
}

then in your twig template, you print the empty variable.


Drupal 7 sites hogging my shared hosting account Two months back I launced 3 new Drupal-7 based sites on my shared hosting account but soon I found that my account was touching maximum process limit of 25 in my account and that my D7 sites were having only 400 or so page views daily. To compare it with D6 site, it could handle 4000 pages views without any problem.

Hostgator support confirmed too many processes of D7 sites. I've also checked it and I find that D7 index.php is running for much more time than D6 counterpart. So instead of it exiting in .5 second, I guess it's taking 3 seconds( rough estimate). I don't think those are eating too much of CPU in that case my sites would have been suspended.

To resolve it I'm moving my D7 sites to VPS so that process limit is increased.

I'm using all Drupal default install settings. No booster etc modules.

Any suggestions?

Shared hosting is the bane of the internet -- I recommend not using shared hosting if at all possible stick with the VPS. Did you turn on Aggregation, and caching in your drupal install? Did you install APC and configure drupal to use it. If you use APC and are a read-heavy anonymous traffic site, then APC can be configured to store all your pages in an in-memory cache and you never even hit the DB.

Tweaking a website to maximize server usage is really really website specific. The low hanging fruit is stuff like Performance settings in Drupal, APC, maybe Nginx for a webserver, etc. Beyond that profile your site.

Alternatively as you mentioned you could cache to disk by using like Boost.


Get content page field value I have a content page contain three field. Number A: Number B and Total Number. During add content page, I fill up Number A: 20 and Number B: 30. How to let Total Number auto display 20 + 30 = 50?

What do you mean by content page? if it is the node page and the fields name are field_number_a and field_number_b then install entity module and in the template.php and in hook_preprocess_node function and write this:

function YourTheme_preprocess_node(&$var){
    if($var['node']->type == "YOUR_CONTENT_TYPE"){
          $wrapper = entity_metadata_wrapper('node',$var['node']);
          $a = $wrapper->field_number_a->value();
          $b = $wrapper->field_number_b->value();
          $var['total'] = $a + $b;
    }
}

Then in the node page you can use $total variable as the sum of the a and b


Changing upload size I tried all solutions from google and i can not figure out how to increase from 2 MB to 70MB.

In WHM i did changes like from screenshots:

On the Drupal site, it went up to 8MB; whatever I tried with .htaccess, settings.php, it won't go more then 8. Adding php.ini to the Drupal root folder throws a fatal error.

I tried changing file upload size on image field to 65 and 75 MB, it gets saved but on node add, it still says 8 MB

How can I change the upload size globally ? I have access to WHM, Cpanel, SSH, FTP, root, whatever. Server is private, dedicated. Many mentioned changing php.ini, but where is it ? On various answers its on various places and i want to change this globally.

You may need to increase the post_max_size value in php.ini


Load content without refreshing page in views i am trying to create a view with pagination. In this view i have images and fivestar rating for it. When user clicks on next i want next image and fivestar to load with out refreshing page.

Thanks.

What you need is the views load more module

  This module has some very key differences then the other load more
  module.

  Provide ajax/no-ajax views load more
  Works with views default ajax implementation, no hacks (check/uncheck ajax)
  Supports the Waypoints module for loading on various points, Such as when the scroller is visable on the page.
  Supports the Fade effect when loading new content


I cannot log in, and I am said I have 5 failed logins I've setup a virtual host on one of my machines. The front page shows fine, but the other pages don't. When I put in my login information, and I click the "Log in" button, I get the "page not found" error.

If I go to www.example.com/?q=user, I get that page, but when I try logging in, I see the following error message:

  Sorry, there have been more than 5 failed login attempts for this account. It is temporarily blocked. Try again later or request a new password."

How can I solve this problem?

The quick solution is to login in your database
mysql -u <username> -p<password> or drush sql-cli

and execute this query

truncate flood;

Thats it and you'll able to login again.


When webform block submitted send email to node author and site admin -how? This is scenario which I try to reach on my website for free blogging:

There is created universal webform Contact author with fields name, email and text which is as block (display webform as block checked) displayed under every blog node type.
When reader submit this block, submitted values are send as email to author of blog post (node author), site admin (me) and possibly to submitter (reader) email.

Is there any possible solution involving webform? What's best combination of modules to do it so, if not webform (I prefer some webform solution)?

Update: For Webform 4.x I use token [current-page:node:author:mail] for "E-mail to address" in "E-mails" tab. You can find more details in this tutorial I wrote.

The best solution (IMHO) doesn't actually work: you should be able to use the Tokens module and use a proper token to fill a recipient field. For example:
[node:author:mail]

However, Webforms only appears to support its own %something tokens, and those only relate to the current user and the webform id (not the id of the node being read).

So instead, write the site's inevitable custom module and use hook_mail_alter() to change the To address.

Another resource I read (and have now lost) suggested setting the Webforms recipient to something easily recognizable, like "replace-me@mysite.com".

Then in your hook_mail_alter() function,

confirm the form's identity,
get the current post's author,
get that user's email address, and
use it in the Recipients. (Along with the admin & the poster, as you like.)


Fast 404 module and Drupal core I can see that Fast 404 module has been added to drupal core since 7.9 version.
So in order to use it on my drupal site(without installing Fast 404 module),is there I need to do in the settings.php module?
thanks

Go to the sites/default directory. Open up to the setting.php file. Around line 500 uncomment this drupal_fast_404(); by removing #

Source