default routing of custom module I'm trying to write my first module and am using the hook_menu to route the pages. The module consists of a multi-step form and two static content pages.

/**
 * Implements hook_menu().
 */
function order_menu() {
  $items = array();

  $items['order/form'] = array(
    'title' => 'Order Form',
    'description' => 'Order multistep form.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('order_form'),
    'access callback' => TRUE,
    'file' => 'order_form.inc',
    'tpe' => MENU_CALLBACK,
  );

  $items['order/cancel'] = array(
    'title' => 'Order Cancelled',
    'description' => 'Order cancelled.',
    'page callback' => 'order_cancel',
    'access callback' => TRUE,
    'file' => 'order_form.inc',
    'type' => MENU_CALLBACK,
  );

  $items['order/success'] = array(
    'title' => 'Order Success',
    'description' => 'Order Successful.',
    'page callback' => 'order_success',
    'access callback' => TRUE,
    'file' => 'order_form.inc',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

What I want to do is be able to access 'example.com/order/form' from 'example.com/order' but when I change the menu hook from $items['order/form'] to $items['order'] it displays as page not found.

Any suggestions as to how to how to get the module to display the content I want from example.com/order?

Did you force Drupal to rebuild the menu, after you changed the code? If you don't do that, Drupal will use the previously defined menus.

To force Drupal to rebuild the menus, you just need to visit the modules page (the administration page showing the list of all installed modules), disable a module, and re-enable it. The last two operations are not strictly necessary; you would probably get the same effect if you click on the "Save" button present on that page without to enable or disable any module at all.
Drupal will call any implementation of hook_menu() and hook_menu_alter(), and it will grab the last menu callbacks defined from your module.

Alternatively, you can call menu_rebuild() from code, or install Devel, which has a block containing a link that allows to force Drupal to rebuild the menu list it caches.


drupal_add_js best practice to include inline code or script file While reading the API page for drupal_add_js, I kept wondering what is the best practice to include inline JavaScript or a JS file.

It seems like it works exactly the same even if you omit 'file', 'external' or 'inline' like in this example :

Without 'file'

drupal_add_js('misc/collapse.js');

With 'file'

drupal_add_js('misc/collapse.js', 'file');

So the question is rather simple. Why would I choose one over another and what is the standard way of coding this ?

Thanks !

They are both and the same. The fileparameter you have specified in your second example is the same as the first example as it's the default type.

  type: The type of JavaScript that is to be added to the page. Allowed values are 'file', 'inline', 'external' or 'setting'. Defaults to 'file'.

Source: drupal_add_js

If your question is about whether it's best practice to use inline or file then it depends on your requirements. If you need to load a JavaScript library or a large amount of JavaScript then I would use file type. If you are just loading say some tracking code, or a few lines of JavaScript then I would probably use inline as it's one less HTTP request.


adding image field to "Taxonomy term view" I try to create a product catalog instead of using drupal commerce in drupal 7 with current updates.
I create product types related to categories which are taxonomy terms.
I create a menu as taxonomy terms.
If select a taxonomy terms from menu , it is listed all products under that terms.
Listing is controlled by taxonomy term view. There we can control only node title.
I want to find a way to add image related to that node also. Is there a module for that purpose? Or how could it be achieved?
Regards,

when you click on term you see teasers of nodes. few solutions for you:

You can change teaser of node in node display settings.
You can enable taxonomy/term/% view and customize it as you want
Also here is some article


Automatize user accounts I have a database with x users. I would like to add those accounts on my drupal database without having to recreate them one by one.

I would like to do a script mike that but i'm not really sure it would work out :

username = select name from mybase;
pw = select password from mybase;
mail = select mail from mybase;

drush ucrt username --mail=mail --password=pw

Obviously it would be a loop for every user, but i just wanted to share the idea.
First of all, is it possible to do this in shell ? The database is in another server, i'm not sure i can connect and take bake information (maybe using ssh ?)
Also the password is hashed in the other database, won't it generate a bad password (by hashing a hashed password). Even so, this point is not a problem, i can reinitialize their password to their login.

You can achieve this with the Migrate module.  As it has a 'destination' class that deals with User imports for you.

The easiest way is to import into your database and use the 'MigrateSourceSQL' class as your 'source.

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


Steps for Changing the Order of the Payment Methods on Checkout I have two payment methods: Cheque and PayFlow Pro enabled for my products. However, they are showing up on the checkout form in an undesirable order:

Pay by Cheque (selected by default)
Pay by Credit Card

I'd like to reverse those and make Credit Card the default option. This question APPEARS to be answered here, but I don't understand the answer.

Would someone kindly provide the steps needed to make this happen?

Edit the payment method and click on SETTINGS on the bottom of the page.


Why Are Changes / Updates to User Account Fields Not Persisted (Lost on Page Refresh) Drupal version 7.52.

Updating a user account page, e.g. changing their email or name, results in the page being reloaded with the changes persisted in the form, but when you refresh the page the changes are lost.

It's as if some validation errors are blocking the user update function but no feedback is being displayed.

Checked all logs and no errors reported.

Turns out it was down to Clientside Validation modules. I disabled the following and it now works as expected:

clientside_validation_fapi
clientside_validation_field_validation

The other clientside validation modules work fine, just these two seem to block updates to user accounts with no errors, warnings or notices.


my urls are not replacing spaces with hyphens I have url aliasing and clean urls. They are making the content have good urls, but for some reason it's not always rendering with hyphens. It leaves the spaces and breaks pages.

It's because you haven't updated the paths yet. So you need to go to the BULK UPDATE tab

Select CONTENT Paths and click on update.


custom page template not showing up I have created a new page template page--membership.tpl.php and placed it in the /templates folder inside of my theme (the same folder as my regular page.tpl.php file). I flushed the cache, but my page sitename.com/membership is not picking up the changes. (I even tried deleting all of the content of the tpl file to see if it would mess up the page, but nothing.) Any ideas?

Reason of page--membership.tpl.php not working for sitename.com/membership may be:
Drupal used templates as page--[front|internal/path].tpl.php based on the internal path of the current page. Do not confuse the internal path to path aliases (Pathauto module uses path aliases) which are not accounted for.

To create the template for page--membership.tpl.php one may try one of the following methods:

Create template as page--node--[NODE_ID].tpl.php, here replace the [NODE_ID] with the node id of membership page.
To get recognize the aliased paths, you have to add the aliased path as part of the theme suggestions: https://groups.drupal.org/node/130944#comment-425189


How to disable Webform form element validation without removing required flag? I inherited a website which contains a Webform made form to which I was asked to make some modifications.

The form contains two drop-down selection lists, one with predefined options, one who's content is dynamically filled in by making a request to a web-service based on the selected value of the first drop-down list.

Filling the second drop-down list is not the problem, but since it's marked as required this means that the form is also validated and that's where the error pops up: An illegal choice has been detected. Please contact the site administrator.

Now, since the content of the drop-down is dynamically generated the error itself makes sense as the selected value is compared to the available options. I want to disable the validation without removing the required flag from the form element.

I tried modifying the element options both via hook_form_alter() and a custom validate function, various combinations and I can see that the variable is set and contains the value, yet it is still validated.

$form['submitted']['ss_function']['#needs_validation'] = FALSE;
$form['submitted']['ss_function']['#webform_validated'] = TRUE;

How can I disable the actual form validation without removing the required flag from a Webform form?

After some more trial and error I found my mistake. The '#needs_validation' property of the element is set at a later stage than the hook_form_alter() call.

In my hook_form_alter() implementation I added a custom validation function in which I unset the property. The trick is to actually unset it, because it's only validated with an isset() call.

function mymodule_webform_client_form_FORMID_alter(&$form, &$form_state, $form_id) {
  array_unshift($form['#validate'], 'mymodule_validate_FORMID');
}

function mymodule_validate_FORMID(&$form, &$form_state) {
  unset($form['submitted']['FIELDNAME']['#needs_validation']);
}


how to know block id in class which extend from BlockBase I am trying to get block id in my custom module  in build function of class which extends BlockBase.

How can i do this?

i want to use this block_id in another class controller to have configuration of that block so i think best place to get block id and send it to controller class is build function like below code

        class XController extends ControllerBase{
        ...
        $block = \Drupal\block\Entity\Block::load($block_id);
        if ($block) {
        ...

any other suggestion to do this is appreciated.

BlockBase is a plugin, and as such has a getPluginId method. As you need this inside the class itself, it's as easy as:

$id = $this->getPluginId();


Drush install fails within Vagrant Puppet I originally posted this on SO but thought I'd probably get more traction on the Drush side of things from you guys.

I've just gotten a new MacBook running Mavericks.

Unfortunately, I can't get our current project running on it.

We're using Vagrant and Puppet and during the vagrant up phase, I get a message telling me err: /Stage[main]/Drush::Git::Drush/Exec[first drush run]: Failed to call refresh: /usr/bin/drush status returned 255 instead of one of [0] at /tmp/vagrant-puppet-1/modules-0/drush/manifests/git/drush.pp:32

I can successfully vagrant ssh into into the instance but it's clear that Drush doesn't exist.

The only difference between the 2 systems is the operating system. All other files are from the same git repo and same branch.

Any insight would be welcome as this is a total ball-ache.

Thanks,

Steven

The drush.pp you are using is out of date.  I have used that one successfully in the past, but just a few days ago, Drush switched to using Composer to install, so running drush status will no longer download the console table.  Instead, you must run composer install after pulling Drush, or just install Drush via composer.  See the Drush project page for details.

The Drush Puppet module you mention will need to be updated to adjust for this change in procedure.

Note:  The drush.pp you are using would probably work if you told it to check out one of the Drush 6.x tags instead of using master (the default).  Haven't tried that, though.


Drupal 8 register link? I have a clean Drupal 8 install with bootstrap theme.
I just want to add a simple link to the registration form in the user account menu and to it only be visible if you are not logged in.

The login and my account links are already standard in, why isnt the register button there? What would be the solution to this?

Creating the link normally in the menu -> add link option makes it visible all the time.

We've contributed a small module which solves this issue: https://www.drupal.org/project/registration_link


Generate a random image on front page each time it is loaded I'd like to have a random image appear on the front page of my site each time the page is visited. Is there a module set up to do that? Any suggestions as to how to accomplish this?

You can use Views slideshow Module to get the same. In the view all you need to make is a random query.


No body text saved when creating a node with I18n and specific language set Drupal 7

I'm creating a event type nodes, using data from an external database.  It's a multi-lingual site, and the primary language is english.

My code creates the node correctly, when the language is set to LANGUAGE_NONE, but when it is set to "en", the body text is not saved in the database.

foreach ($results as $record) {
  echo '<br/>Creating event: ' . $record->name;

  $node = new stdClass();
  $node->type = 'event';
  $node->uid = 1;
  node_object_prepare($node);

  $node->title    = $record->name;
  $node->language = "en";
  //$node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value'] = 'This is a body text for '.$record->name;
  $node->body[$node->language][0]['summary'] = 'Here goes a summary for '.$record->name;
  $node->body[$node->language][0]['format'] = 'raw';

  $path = 'content/programmatically_created_node_' . date('YmdHis');
  $node->path = array('alias' => $path);

  $instance = field_info_instance('node', 'body', 'event');
  print_r($instance);

  $node = node_submit($node);
  node_save($node);
  dpm($node);
}

When $node->language = LANGUAGE_NONE, a record is created in the fields_data_body table. I can see the body text, but cannot translate it.  I guess this is correct.

But when $node->language = "en", no record is created.  This is my problem.  I need this set to "en" as it's a multi-lingual site, and without it, there is no "translate" tab when editing the node (Internationalization module drupal.org/project/i18n)

There is some back history to this issue here..  No "body" when creating a node programatically, with Internationalization ..but it's not essential to read it.

It should be showing 'und' for language neutral nodes. Have you checked the value of the $node->language parameter?

You could also try creating one of these nodes with the user interface. Then install the devel module and use the php executor (whatever.com/devel/php) to load the node and output with dpm() to see the contents of the node. You probably have something wrong with the structure.

Example (after the sample node is created):

$node = node_load(21);
dpm($node);

That will output the node contents for you to help you better explore what you are creating.


Unable to add css class to a Panels region I wish to add custom css classes to specific regions in a panels page.

I understand from this question Add a class to a panels pane
that I should be able to do this pretty trivially from the settings menu on the pane or region itself, however, there is absolutely no option to do so.

I am using panels 7.x-3.5 with Panels Bootstrap in Drupal 7.

No matter what layout setting I use - Boostrap, custom style etc - I never get any option to add css classes.

The boostrap settings has a handful of drop down boxes, the custom style settings has a heap of options but no ability to add css classes.

Do I need to over-ride a template somewhere? This should be trivial...

The option to add a CSS class is on the actual pane content. In a Bootstrap panel region the cog on the left gives you the option to set the grids up. If you need to add a class to that you will need to find the template file for the region you are using and copy it to your theme/sub-theme and add the class there or write a cTools plugin for that yourself. The ability to add a class is on the actual content panes that you add inside the region, so for instance if you were to add a view pane into the left region inside your panel you could place that view inside a bootstrap .well or bootstrap .alert using the cog on the right hand side (the cog on the content inside the region) of the content pane. So you can add the class to the content pane via settings that way.

If you need to add a class to the whole region you need to copy your template file for your layout to your theme. So if you were using Bootstrap three column stacked you would copy bootstrap-threecol-stacked.tpl.php to your templates folder in your theme. And modify the outer div for the region you want inside that template file. The regions are actually listed in that template file (you will see them inside the file). You can modify any of those template files inside the module, if you want to see what template files have what markup turn theme debug on and inspect your HTML of the page (see here for how to do that).

There is this module where you can add the alert or well into a region: https://www.drupal.org/project/panels_bootstrap_styles but I've never actually used that one and it looks limited. I would stick to the bootstrap panel layouts and proper templating, or cTools plugins for these types of things work great also. You can write them like that module does for just about any markup you need :)

You can also use a module like Semantic Panels to do this, it was a little overkill for something like adding a CSS class so I didn't add it before but you may find it easier to use.


How to add an attribute in an input date field I want add the attribute autocomplete="Off" in the input field of the date field.
I've created a modulo with hook_form_alter but not works.
This is my code:

function no_input_autocomplete_form_alter(&$form, &$form_state, $form_id) {
    if($form_id === 'prenotazione_node_form'){
        $form['field_periodo_prenotazione_to']['#attributes'] = array('autocomplete' => 'Off');
    }
}

I've noticed that with other field type works as I expect.

How can solve it?

Try with

$form['field_periodo_prenotazione_to']['widget'][0]['value']['#attributes'] = array('autocomplete' => 'Off');


What is the difference between core.entity_form_mode and core.entity_form_display? I'm trying to learn how to configure content types and form modes programmatically in Drupal 8. I've created the following using the UI:

A content type named book
A form mode for content, named foo
A view mode for content, named bar

When I run drush cget, I get this list:

...
[36] core.entity_form_display.node.book.default
[37] core.entity_form_mode.node.foo
[38] core.entity_form_mode.user.register
[39] core.entity_view_display.node.book.default
[40] core.entity_view_display.node.book.teaser
[41] core.entity_view_mode.node.bar
[42] core.entity_view_mode.node.full
[43] core.entity_view_mode.node.rss
[44] core.entity_view_mode.node.search_index
[45] core.entity_view_mode.node.search_result
[46] core.entity_view_mode.node.teaser
[47] core.entity_view_mode.user.compact
[48] core.entity_view_mode.user.full
...

What is the difference between the entity_form_display configuration (36) and the entity_form_mode configurations (37, 38)?

entity_form_mode would be the form mode (/admin/structure/display-modes/form)

37 - Form mode foo available for use on node entities (shows as
content on the link above)
38 - Form mode register available on
user entities.

entity_form_display is the configuration for that mode on a specific bundle - how the fields are arranged (/admin/structure/types/manage/book/form-display/{form_mode}) - in your case form_mode would be foo.

36 - Form display settings for the default display on the book bundle (content type) of the node entity.

The reason 36 is default is because you have arranged your form display (/admin/structure/types/manage/book/form-display) but you haven't enabled your foo mode.

At the bottom of that page is a fieldset called "Custom display settings". Expand that and you can enable your foo display for that content type.

In the picture, I have a created a form mode called Inline Entity Form, yours should say foo


Complex Shipping Rule: €3 Flat Rate for order's first 2kilos + extra €1.2/extra kilo charge Well, the title is quite descriptive about what I'm trying to do with Rules for my e-shop.
I have a flat rate for shippable products and I want to charge extra shipping costs to customers according to order's total weight. I'm already using physical fields for weight so I could use the field's value for this rule. Note that some products won't have anything in the weight field and in this case I don't want to take them into consideration for the shipping cost calculation.

So, I want to charge €3 (flat rate's base charge) if the order is 0-2 kilos.
In case the total order's weight is more than 2 kilos, I want to add €1.2 to shipping cost for every additional kilo.

e.g. order has 3 products.
Product 1 - 2 kilos
Product 2 - 0 kilos (or no value in weight field)
Product 3 - 2.5 kilos
Total order's weight: 2+0+2.5 = 4.5 kilos (ie 2.5 kilos to be charged extra)

So the shipping charge should be €3 (flat rate's base) + €1.2*2.5 = €6.

I really need some guidance here on how I'm going to make this happen using Rules.

One of the problems with Commerce (and Ubercart for that matter) is that it takes awhile for someone to come around with weight based calculations. I have done something similar but it might not work for you.

1) I made each increment I wanted to allow a single product (i.e. 1lb of Product X is 1 QTY, if they want 2lbs of Product X, it's the same as saying Product X with 2 QTY.)
2) Then I created bundles for what I wanted to allow.
3) In shipping, you can set up a rule that allows extra for each extra QTY ($6 for 1 QTY and $2 for each additional QTY.)

For you, it might be possible to set your rule to multiply but you would have to create a module that would allow you to set percentages on QTY if you wanted someone to be able to add 1.2 QTY to their cart. For me, it was easier to do by whole increments and much cleaner on the rules. You can also set your shipping rule to line items so that the first line item is the base and the remaining are the additional.


Can I run drush command from composer with custom script I have a nested root Drupal 8 site.  I would like to create an import and deploy script that runs multiple drush commands.  Is this possible via custom script?

I was able to do this. Here is a simple example:

First, create a file called import.sh and place it in the scripts folder.

#!/bin/bash

# Exit immediately on errors, and echo commands as they are executed.
set -ex

# Run coniguration import.
cd web
echo "Running coniguration import (config split imoprt)"
drush config-split-import -y

# Clear Cache.
drush cr

Second update composer.json by adding the script to the scripts folder.

"scripts": {
  "import": [
    "./scripts/import.sh"
  ]
},

Now you can run composer import


How do I clear the order cache? I manually update an order using the following code.

db_update('uc_orders') // Table name no longer needs {}
  ->fields(array(
    'order_status' => 'payment_received',
  ))
  ->condition('order_id', $order->order_id)
  ->execute();

Then I visit /admin/store/orders/view, but the value for the order still shows a Pending. If I clear the cache, the new status is Payment received, as it should be.

How do I clear the specific order cache so that it updates immediately?

The following code does what I want, but I would prefer clearing the cache for the specific order that is manually updated.

$orderEntity = Order::load($order_id);
$orderEntity->setStatusId('payment_received');
$orderEntity->save();

\Drupal::service('entity_type.manager')->getStorage('commerce_order')->resetCache([ORDER_ID]);

This service which used in OrderReassignTest.php will help you to Reload the order based on Order ID.


Views Custom Field Handlers tokens I am using simple views custom field handler. And I would like to make list of custom tokens for this $data array I have. How could I do that?

class custom_views_handler_field_hostname extends views_handler_field {

  function render($value) {

     $location = get_some_data_from_outside;

     foreach ($location as $key => $value) {
      $data [] =  $key. ': ' . $value;
    }

    if (!is_array($value)) {
      return theme('item_list',
          array(
            'items' => $data,
            'title' => NULL,
            'type' => 'ul'
          ));
    }
  }

The first hook, hook_token_info(), is used to declare any custom tokens.

    /**
 * Implements hook_token_info().
 */
function module_name_token_info() {
  $info = array();
  // Define a new token type.
  $info['types']['my_custom_tokens'] = array(
    'name' => t('My custom tokens'),
    'description' => t('A token type for my custom tokens.'),
  );
  // Define any new tokens.
  $info['tokens']['my_custom_tokens']['my_cool_token'] = array(
    'name' => t('My cool token'),
    'description' => t('A token I use to show that I am cool.'),
  );
  return $info;
}

We are creating our own custom token type here too but if you just want to put your token in an already existing type, you can get a list of the existing tokens and types by calling token_get_info().

Now that our new token is good and defined, we just need to give it some content with hook_tokens().

     /**
     * Implements hook_tokens().
     */
    function module_name_tokens($type, $tokens, array $data = array(), array $options = array()) {
      $replacements = array();

      if ($type == 'my_custom_tokens') {
        // Loop through the available tokens.
        foreach ($tokens as $name => $original) {
          // Find our custom tokens by name.
          switch ($name) {
            case 'my_cool_token':
              // Work out the value of our token.
              $value = 'Whatever we want the token to be';
              // Give our token it's value!
              $replacements[$original] = $value;
              break;
          }
        }
      }
   return $replacements;

}

That's it! Our token should now be available and appear in the list of tokens wherever tokens are available.


How do we set required for new & optional for existing fields - when adding basic field to content type? How do we set required for new & optional for existing fields - when adding  basic field to content type?

When using Drupal 8 following this how to article shows the steps to take to add a basic field to content types. https://www.drupal.org/docs/user_guide/en/structure-fields.html

What I want to learn how to accomplish is to make the new field "Required" for all newly created content types however for existing content I want the field to be optional.

In the admin I see the required checkbox however this will make all of them required. Below is an image of what I am viewing:

Any & all feedback is greatly appreciated.

You can use hook_form_alter or hook_form_FORM_ID_alter to set require for that field.

function my_module_form_alter(&$form, $form_state) {
  $entity = $form_state->getFormObject()->getEntity();
  if ($entity->isNew()) {
    $form['my_field']['#required'] = TRUE;
  }
}

And, not set the field 'my_field' as required field.
Not tested, but it is a way to go.


How to redirect old url alias to new url alias? Is there any way to redirect old URL alias to the new URL alias?

I want example.com/good-news to redirect to example.com/good-news-index, automatically.

You can use redirect module to redirect url from "old url" to "new url".

  This module allows you to specify a redirect from one path to another
  path or an external URL

There is also global redirect module which provide the same functionality.

  Checks the current URL for an alias and does a 301 redirect to it if    it is not being used.
  Checks the current URL for a trailing slash, removes it if present    and repeats check 1 with the new request.
  Checks if the current URL is the same as the site_frontpage and    redirects to the frontpage if there is a match.
  Checks if the Clean URLs feature is enabled and then checks the    current URL is being accessed using the clean method rather than the
  'unclean' method.
  Checks access to the URL. If the user does not have access to the    path, then no redirects are done. This helps avoid exposing private
  aliased node's.
  Make sure the case of the URL being accessed is the same as the one    set by the author/administrator. For example, if you set the alias
  "articles/cake-making" to node/123, then the user can access the
  alias with any combination of case.
  Most of the above options are configurable in the settings page. In    Drupal 5 you can access this after enabling the globalredirect_admin
  module. In Drupal 6, the settings page is bundled into the module


Replace the URLs entered in a textarea with "url_removed" I am using Drupal 8.9.1 and Webform module 8.5.16. I looking for the best way to either replace all URLs that a user might enter in a text area with "url_removed" or not allow the user to enter a functioning URL.
The goal is to prevent webform submission emails from having potentially malicious links within them the body of a comment.

When adding your text area to the webform you can set form validation and use a regex that makes sure the text is free of urls.  Something like:
/^(?!.(http|www|ftp|file|data|irc)).$/gmi
You definitely want to revise the actual regex as Im sure this one is not all inclusive.  I'm far from a regex expert.


Show new content count on the taxonomy term list view I have a view that lists the terms in a specific vocabulary. I can also mark the terms if there is a new content tagged with this term. My view looks like this:

  Term 1
  Term 2
  Term 3 (new)
  Term 4
  Term 5 (new)
  ...

However, what I would like to achieve is a view that shows the count of the new contents tagged with a term. Like this:

  Term 1
  Term 2
  Term 3 (2 new)
  Term 4
  Term 5 (7 new)

My current views configuration is like following:

Showing taxonomy terms of a specific vocabulary
Added a relationship of Taxonomy term: Content using my vocabulary
Added field Content: Has new content: This has caused duplicate rows for the terms that has more than one new content. For example, if a term has three new contents, it was listed three times. So I did the next step.
Activated Aggregation, and set the aggregations settings of the field Content: Has new content to SUM: This has solved the duplicate rows issue, but it doesn't show the sum of the contents as I actually wanted to achieve.

Is there any possibility that I can show the number of new contents on this view?

Solution A: Use Views Field View

Using the Views Field View module it is possible to embed the results of one view into another view.

First create a view for nodes without a page/block (you only need the master display) and name it New content count by term. Add a context filter Content: Has taxonomy term ID. Ensure that only the Nid is listed in the fields section, add the filters Content: Published (Yes) and Content: Has new content, then enable aggregation, choose Count from the Aggregation settings of the Nid field and finally remove any pagers.

Now you may embed the New content count by term view into your principal view (taxonomy terms) by adding a "Global: View"-field (provided by the Views Field View module). In order to specify the tid-parameter of the embedded view, make sure that the Term id is also exposed as a field in the principal view. If you do not want to show it to the end user, just choose Exclude from display in the field settings. After the output of the tid field can be used as a parameter (token [tid]) for the embedded view.

Solution B: Use hook_views_query_alter

There is a function in the forum module responsible of returning the number of new posts on a topic (term) on behalf of a given user (_forum_topics_unread). Use this query as a starting point for your own implementation of hook_views_query_alter.

I recommend to go for solution A and only try to implement B when performance is degraded beyond acceptable limits.


Your site was unable to contact Apache Solr server I have both Apache Solr Search and Search API modules installed on drupal 7.  I have installed SolrPhpClient version r22 (that was recommended in a site vs. r60) in sites/all/libraries/libraries folder.

When I place XML files from Apache Solr Search on Solr Server, Search API would not index. When I place XML files from Search API on the server, Search API seems to work fine but I get Your site was unable to contact Apache Solr server error message on Status Report. In this case I can see mysite:8983/solr/admin but when I click on PING button it shows 500 error message.

Is this supposed to be this way? Can I trust the Search API working fine (is the error message pertained to Apache Solr Search not having its XMLs on server and can be ignored)? Any suggestions to fix this?

Any help would be greatly aprectiated and let me know if you need more info.

Thanks alot.

Some days ago I had a similar problem.

I've download the SolrPhpClient in the .zip file and Search API was not able to connect to the Solr Server (I don't know Apachesolr, I don't use it).

But if I download the .tgz version of the client.. it works. I think that in the .zip version there is some problem with permissions.

So: if you've download the .zip version, try the .tgz.

And obviously try also the r60 version, I use it alwyas.


Indentation in Drupal 8 form I have a drupal 8 form as follows:

   $form['extra_fields']['email'] = [
        '#type' => 'checkbox',
        '#options' => ['email' => 'email'],
        '#title' => $this->t('Email')
    ];

   $form['email']['required'] = array(
        '#type' => 'radios',
        '#default_value' => 0,
        '#options' => array(0 => $this->t('Required'), 1 => $this->t('Not Required')),
    );

which shows up as:

I would like to have the radios a bit indented. Is it possible to achieve this? Also, how to make the radio buttons inline?

Thanks.

Assuming you built this form programmatically (custom module):

Wrap your radios field inside a class using #prefix and #suffix

   $form['email']['required'] = array(
        '#type' => 'radios',
        '#default_value' => 0,
        '#options' => array(0 => $this->t('Required'), 1 => $this->t('Not Required')),
        '#prefix' => '
',
        '#suffix' => '
',
    );

Use CSS to alter the look.

Create a CSS file.

my_module/css/myform.css

  a bit indented

.indent {
  margin-left: 10px;
}

  make the radio buttons inline?

.indent .js-form-type-radio {
  display: inline-block;
}

Create a library

my_module/my_module.libraries.yml

form-stuff:
  version: 1.x
  css:
    theme:
      css/myform.css: {}

Attach library to your form so it loads your CSS

$form['#attached']['library'][] = 'my_module/form-stuff';


Non-tabs in quicktabs I'm using QuickTabs on a Drupal 6 site. I have a block in which I need to have some normal tabs and some pseudo-tabs, which look like tabs but are actually just links that load a whole new page. Is there a way to do this with quicktabs configuration? In particular, could I use theme_quicktabs_tabs() for this? If so, where do I start?

You could always copy the tab HTML and put it somewhere outside the QuickTabs output, and then position them using CSS where you want them on the page.


Using classes in nodes I need a little bit of guidance, I made a custom class and im trying to use it in a node but of course it throwing a white screen at me. So my question is how can I go about using a custom class for d7 so I can include the tag in my node via php.

I put this code in the template.tpl.php file and tried using it in my node but it then gave the white screen.

<?php class Colors {

  public function red_form() {
        echo 'color red is here';
  }

    public function blue_form() {
        echo 'color blue is here';
  }

    public function green_form() {
        echo 'color green is here';
  }

    public function purple_form() {
        echo 'color purple is here';
  }

    public function yellow_form() {
        echo 'color yellow is here';
  }
}

$colorforms = new Colors();

?>

and im using this in the node.

Text here here and here.

<?php $colorforms->red_form(); ?>

More text here here and here.

the output im trying to get using the code above is.

Text here here and here.

color red is here

More text here here and here

is there a module or something for this? or anything to that nature, im a little in the dark on this.

Quick fix: declare the class in template.php but instantiate it in your node template (if you check your php error log you probably had something like "Call to a member function red_form() on a non-object in ..." in it).  Also, I am assuming it's a typo that you had $colorforms and $color_form in your example above.


Trying to get property of non-obJect Custom Module Notice: Trying to get property of non-object in speakerdetailblock_preprocess_block() (line 42

This error occurs when you are getting language from a non object. To fix this check that whether the node is a object and check that 'language' exists in the $node or not.

if(is_object($node) && isset($node->language))

Then check the stuff that you are going to do.


How do I get a paginated view to display rel="next/previous" tags? Using Drupal 7.

I've got several views (most of which listing articles which have been posted) that paginate and I'd like to add;

<link rel="prev" href="http://example.com/recent-articles?page=0" />
<link rel="next" href="http://example.com/recent-articles?page=2" />

links to them.

How do I do this? A module is preferred, changing the php files would preferably be avoided.

Things I've tried:

Lightbox2 (module)
Metatag (module)
Meta tags quick (module)
Views controls themselves
REL Links (module)

You just need to override theme_pager_previous() and theme_pager_next() (easiest to do in your theme):

function MYTHEME_pager_previous($vars) {
  $text = $variables['text'];
  $element = $variables['element'];
  $interval = $variables['interval'];
  $parameters = $variables['parameters'];
  global $pager_page_array;
  $output = '';

  // If we are anywhere but the first page
  if ($pager_page_array[$element] > 0) {
    $page_new = pager_load_array($pager_page_array[$element] - $interval, $element, $pager_page_array);

    // Changes from core function start here.
    $attributes = array('rel' => 'prev');

    // If the previous page is the first page, mark the link as such.
    if ($page_new[$element] == 0) {
      $output = theme('pager_first', array('text' => $text, 'element' => $element, 'parameters' => $parameters, 'attributes' => $attributes));
    }
    // The previous page is not the first page.
    else {
      $output = theme('pager_link', array('text' => $text, 'page_new' => $page_new, 'element' => $element, 'parameters' => $parameters, 'attributes' => $attributes));
    }
  }

  return $output;
}

And the same thing for pager_next.


Errors when saving node Im at a bit of a loss here, this error started happening when saving a new node, or updating an existing node.

It says The website encountered an unexpected error. Please try again later..

The error on the screen is...

  Notice: Undefined index: fid in file_field_update() (line 276 of
  C:\wamp\www\thelhp\modules\file\file.field.inc).

  Notice: Undefined index: fid in file_field_update() (line 302 of
  C:\wamp\www\thelhp\modules\file\file.field.inc).

  Notice: Undefined property: stdClass::$fid in file_usage_add() (line
  689 of C:\wamp\www\thelhp\includes\file.inc).

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Le
  champ 'fid' ne peut être vide (null): INSERT INTO {file_usage} (fid,
  module, type, id, count) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4); Array (
  [:db_insert_placeholder_0] => [:db_insert_placeholder_1] => file
  [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] => 196
  [:db_insert_placeholder_4] => 1 ) in file_usage_add() (line 696 of
  C:\wamp\www\thelhp.co.uk\includes\file.inc).

I am now not able to create nodes, or update existing ones.

HOWEVER, after further testing, I have found that if I upload an image to the optional image field, nodes save and update just fine. When no image is uploaded, the errors show up. help! :-(

I had custom code in my module...

function custom_node_presave($node) {

  if(isset($node->field_gallery_images)) {
    $node->field_gallery_images[LANGUAGE_NONE][0]['alt']=$node->title;
    $node->field_gallery_images[LANGUAGE_NONE][0]['title']=$node->title;
  }

}

Commenting it out stopped the error


Drupal Commerce: line_item field in user profile? Im trying to achieve the add to favorites function, but I cant reference the commerce_product/product_display becose the items that are sold in my situation get customized by the user (add text, images, whatever).

I have a custom line item type called custom, where I added the field to handle the customization my users can do.

For the add to favorites functionality, i thought to add a line_item field in the user profile, put in it the custom line items created, and when he want to buy it all I have to do is create a new line item copying the fields value and then add it to the cart.

But i have some trouble: when i try to add (for test) the line items in the user's profile page throught the standard widget, I dont get any error message but the line items doesnt get saved..

Are them bounded to commerce_orders only?

Yes, I would not use a line item reference field outside of the order entity type. You might try using an entity reference field instead with the inline entity form module for line item creation / editing.


How to flag node when "event date" has passed and send notice to authors of flagged nodes? I have a "delivery date" field in my content type that users choose when creating a node. When this date passes I want the notice to be sent to the nodeauthor.

As far as I see, I need to flag the node with expired date with Flag module. I know that it's possible to set exiry date when node is created. In my case I need to compare the user set "delivery date" and current date.

Can I do it with the Rules module?

Yes it's perfectly possible to produce such notification using the Rules module. But I don't see any reason why you'd want, or need, to flag (using the Flag module?) such nodes.

Instead you can use an approach which is pretty similar to what I described in my answer to "How to send an email to an author on a specific date using date field specified in a node?", which uses the Rules Scheduler (submodule of Rules):

Change the weaning date to your expiration date.
Add some additional Rules Condition (in Step 3) to avoid sending such notification to checks if the delivery is still outstanding (if it is delivered already, you may not want to send such notification anymore ...). For that you could simply add some boolean field like "Delivered? (Yes/No), which you'd that use in that Rules Condition to be added.

Happy Rules-ing!

PS: should you have some reason to flag the node anyway, then that would be a straight forward enhancement you could add to this solution also.


How can i remove duplicate encoding meta tag I have repeated charset meta tag in all my drupal pages. I have been using my metatag module.

To optimize SEO results, this error is reported as primary to fix.

I have used jquery(ready & load event) to remove from client side, removes in dom element but the page source shows 2 charsets.

No configuration in meta tag refers to charset.

If the <meta charset="utf-8"> tag is appearing twice in the rendered HTML, chances are one of the instances is hard-coded in your theme's html.tpl.php template, while the other is inserted by the metatag module.

I'd recommend checking your theme templates. In some cases, freelancers with little Drupal knowledge may create several page level templates duplicating the head, header, and footer markup too.

As Alfred noted in his comment, removing this tag should be done server side and not via javascript.  While it does add a few bytes to download of the page, it does not critically effect search engines from detecting the page's content for indexing.


Redirect to page before login Now i know there are some ways that a redirect on login can be setup, ie using views etc, but i think my issue maybe a bit more complicated.

When a user accesses a node for example where they are prompted to login, from here they are directed over to the /user/login page.

I want the user to be redirected back to the page they were before they came to the /user/login page, with a few exceptions of course.

How can i get the user journey to be...Node -> user/login -> redirect back to Node?

There is a module that takes care of this called Login Destination.

  The Login Destination module allows you to customize the destination
  that a user is redirected to after logging in, registering to the site
  (7.x), using a one-time login link or logging out (7.x). The
  destination can be an internal page or an external URL. It is possible
  to specify certain conditions like referring pages or user roles and
  make the destination depend upon them. You may use PHP snippets to
  provide custom conditions and destinations. It is also possible to
  keep users on the currently visited page after logging in or out.

Also available for Drupal 8


Responsive CSS in Bootstrap theme (more specifically "Tweme") I am running the Bootstrap theme "Tweme" (however, this question will most likely apply to all Bootstrap themes) and would like to add responsive CSS. Adding commands like

@media (min-width: 1200px) {
  body {
    background: rgb(0,0,0);
  }
}

to my style.css does not have any effect. What is the best way to add responsive CSS to Drupal themes that are built on the Bootstrap library?

Your basic CSS is right. I would check to make sure:

1- Your css file is actually loading

I go to view source and look for my file name. If the file name appears in a giant weird JS object, but not in the css declarations that means the file can't be found (most likely a 404)

2- Your base theme isn't writing some overly specific CSS that you need to override.

Using the web inspector or a similar tool inspect the element you're trying to change, get your width where it should be to have your change apply (in that case greater than 1200 width) and see if there are styles overriding the one you wrote.

An easy temporary way to get around #2 would be to use !important at the end of your style, just to see if you're in the neighborhood, but that !important should be deleted of course :)


How do you get the options from a select form? As a follow-up to my last question regarding creating a dynamic select using JavaScript and the Forms API, I'm now wondering how do you actually get the options from that select list in a submit function. I've read "How to get All options of a 'select' field?" but I have yet to get it working with my code. Maybe because this person is using a CCK field and I'm using the Forms API which as far as I've read works differently. I've also tried pulling the data from the $form_state as well as the $form with no luck. Below is my code for a more complete picture of what I'm trying to do:

function _jstest_form($form, &$form_state) {
  $form['list'] = array(
    '#type' => 'select',
    '#options' => array('1', '2', '3'),
    '#size' => 4,
  );

  $form['text'] = array(
    '#type' => 'textfield',
  );

  $form['add_button'] = array (
    '#type' => 'button',
    '#value' => t("Add"),
    '#after_build' => array('_jstest_after_build'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#submit' => array('_jstest_submit'),
    '#after_build' => array('_jstest_after_build'),
  );
  return $form;
}

function _jstest_submit($form, &$form_state) {
  //  Do stuff with options from select
}

$form is the array build on server side, and it is not modified from JavaScript code executed from the browser, as that array is never passed to the browser. That is the reason why $form['list']['#options'] contains only the values set from the form builder.

The code that retrieves the value of $form is the following one, contained in drupal_build_form():

  // If the incoming input contains a form_build_id, we'll check the cache for a
  // copy of the form in question. If it's there, we don't have to rebuild the
  // form to proceed. In addition, if there is stored form_state data from a
  // previous step, we'll retrieve it so it can be passed on to the form
  // processing code.
  $check_cache = isset($form_state['input']['form_id']) && $form_state['input']['form_id'] == $form_id && !empty($form_state['input']['form_build_id']);
  if ($check_cache) {
    $form = form_get_cache($form_state['input']['form_build_id'], $form_state);
  }

When the form is submitted, that code retrieves the value of $form used to build the form.


"$.fieldValue is not a function" alert on login form submit In Drupal 7, with Devel, CTools and Ajax Login/Register plugins, I get an alert on submitting the login form on http://p262957.mittwaldserver.info/drupal/user/login.

I am using a custom child theme based on bootstrap project. I already tried the instructions on https://www.drupal.org/node/1008664 that says I should be sure to load jquery.form.js before ajax.js.

Does anybody have an idea?

In the parent theme was a ajax.js override function that caused the error. It can be found in theme_root_dir/js/misc/. You just have to empty it. Don't forget to empty your cache afterwards. Now it should work.


Can't get custom content type page template to load I'm running Drupal 7, and working with the Zen theme. I'm pretty sure I created a child-theme of Zen. My file structure looks like sites/all/themes/mytheme, with the original zen being located in sites/all/themes/zen. Not sure if any of that matters.

Anyway, I've created a custom content type and now I'd like to style the page differently (not just the node, but the entire page).

I've copied my page.tpl.php file and renamed it page-mycustomcontenttypename.tpl.php. This file is located in the same directory as my page.tpl.php file, which is sites/all/themes/mytheme/templates.

I then added the following code to template.php, which is in my theme's root folder:

<?php
/**
* Add / modify variables before the page renders.
*/
function phptemplate_preprocess_page(&$vars) {

// custom content type page template
  // Renders a new page template to the list of templates used if it exists
  if (isset($vars['node'])) {
    // This code looks for any page-custom_content_type.tpl.php page
    $vars['template_files'][] = 'page-'. str_replace('_', '-', $vars['node']->type);
  }
}

I then clear my site cache, but the changes I make to the custom template don't show up.

There's about a million places I could make a misstep here, so I'm not sure where to start? Any help is appreciated!

I'm totally an idiot. I tried this code previously but it didn't work, which is why I ended up with the code above (also didn't work).

I realized that in the code I tried the first time I failed to change the first line to my theme's name:

<?php
function thisshouldhavebeenmythemename_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__node_' . $variables['node']->type;
  }
}
?>


Duplicating Database For Local Development I've recently started putting some Drupal installations in to source control. Editing modules and the like is pretty easy since they're obviously just text files. I run in to issues with the database though.

My current idea is to run a cron job to pull in database from the live server every night to keep things up to date.

The current method is to just drop the local db and then mysqldump the live one on to my local machine.

I'm pretty sure doing it the way I currently am could cause me to lose things like content types and fields if I make new ones on the local machine and then the 'outdated' live db gets pulled in.

What is the best way to approach this situation?

It's important to understand the differences between the data of your site and the structure. You probably don't need all the data (new nodes, user information...) updated every day in your development site, What you need is to upload the new structural changes to your live site once you reach a stable point in your development.

I've been using a combination of git + features to develop my sites and keep them in sync between develop and live enviroments. With Features you can upload the structural changes to your live site without overwriting the database. When you reach a stable point in your development site you prepare a feature with the changes (content type, image style, views... whatever), save it to code and upload to your live site with the source control program.

Then only sometimes, when the content difference really is important I download the database to my local site, usually with drush.


Use Chart.js in Drupal page I am new to Drupal. I created a page and I want to embed charts in that page. I am trying to use chart.js and I have question regarding how to import the script of chart.js in the page i created?

is it like this

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>

or some other way to do it? I also dont understand how you add javascript code to a drupal page. Thank you.

You need to define it in either a module, or the libraries.yml file of your theme. Then you need to attach it to the page. See the "CDN / externally hosted libraries" of this doc page:

https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module

Then you need to attach the library - this is fairly straightforward in mytheme.theme.

Example mytheme.theme file:

function mytheme_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'mytheme/chartjs';
}


How do you include a translatable string in an update hook In D7 you had to use get_t() in order to include translatable strings in an update hook. Is there a similar procedure for D8?

No. Just call t().

get_t() was actually for early install and things like that, update functions AFAIK didn't need it (calling t() there is however often pointless, as it is highly unlikely that there is a translation for it already when you run the updates.)

t() calls a service now, and it will use the correct one depending on the situtation automatically.


How to build my own view for apache solr module After successful integration of apache solr module in drupal 7 and displaying the result Ii found that it is using the view files (search-results.tpl.php & search-result.tpl.php) from the core search module to display the result.

How can I use my custom files similar to (search-results.tpl.php & search-result.tpl.php) inside the apache solr module folder to display the result?

Since I am new to drupal and just started can somebody guide me to implement it.

This is a duplicate of the question https://stackoverflow.com/questions/12496764/how-to-build-my-own-view-for-apache-solr-module so the answer is the same as well. Let me quote:

The .tpl.php files are theme template files, and you can override them by using identically named files in your own theme. Some deeper reading at Drupal docs.
Or you could use the search features provided by Google, as I did, and find an already existing answer on a related site.


warning: Illegal offset type in isset or empty I am running drupal 6 and I get this warning on every page.

warning: Illegal offset type in isset or empty in /var/www/my-website/includes/common.inc on line 915.

And this is what I have from lines 914 to 917 in common.inc file

// Custom strings work for English too, even if locale module is disabled.
if (isset($custom_strings[$langcode][$string])) {    /* Line: 915 */
  $string = $custom_strings[$langcode][$string];
}

What could be the possible reasons for the warning and how to get rid of it? Any help is appreciated. Thanks.

Edit:
   This warning appears only for anonymous users and it is not visible for authenticated users.

I have fixed the problem. I think this will help you. For me it works perfectly:

BEFORE:

// Custom strings work for English too, even if locale module is disabled.
if (isset($custom_strings[$langcode][$string])) {
  $string = $custom_strings[$langcode][$string];
}

AFTER:

// Custom strings work for English too, even if locale module is disabled.
if ($custom_strings[$langcode] && isset($custom_strings[$langcode][$string])) {
  $string = $custom_strings[$langcode][$string];
}


Generate 1D bar code based on user defined input My requirement is to generate 1D bar code based on user defined input in the text box.
 for example if user give 10 as input in the text box then he should able to generate 10 bar code with different serial number after saving the content ....
so far, I have used bar code module to generate the bar code and serial module for different serial number and I am able to generate single bar code on saving the content.

now my problem is how to generate series of bar code based on the number which we give as input.

I am not getting how to map the input text box field to content and call multiple time.can any one help on this.

You have content of type A and it contains a field called B , B is your serial fieldneedrst of all your field B must get multiple values , this can be set through Field UI. If you are going to collect more than 10 values per each content you can select unlimited values , but this has some DB overhead , after that drupal itself will create the form with multiple value , if you have chosen a specific number for that field for example 3 values , there will be 3 widget to get values , else if it is unlimited you will have an ajax add element button .
If this is not what you want and you want to enter the number of barcodes at the beggining then you must alter the form using hook_form_alter (you must write a module) , inside that hook add a counter element to your form (it gets the repeatation s count) and then use ajax to add widget to your form .
Each widget must be added to your field in your form , so drupal will understand that all the data inserted in these widgets relates to your field.
If you want to do it by writing a module and need some code ,I can add some code later.


How can I override the default forums and container pages with a view? I need to override the default pages that come with forums with views. I need to still include the default info as per the screenshots. I can't seem to get the right relationships and the correct aggregation for the counts. Any insight would be appreciated.

You can use Advanced Forum module, which provides many advanced features, and overrides the default forum listing with views and panels. It is not a replacement module for core forum but an enhancement.

If you don't want to use it, you can at least take a look at how they've overriden the core forum listing and make your own implementation.


How to allow users to create groups with Organic Groups How do I allow users on my site to create groups. I've done the initial configuration of Organic Groups, there is no 'Create Group' button by default. I want users to be able to create groups under a Parent Group.

Groups are just a special kind of nodes, so you just need to go to Permissions and grant users the right to create nodes of that bundle. Users can create groups by going to yourwebsite.com/node/add/nameofyourgroupnode. There is also a menu link by default.


How to delete data from a field programmatically I have a content type called companies
In this cck I have an Image field and user can add more than one image

I want to make a form programmatically that will display all images in a grid and under each image a button to delete it

Is there is a way to delete it from the node (this specific image only or I should make node_load to get all fields and then check for all images and node_save the node again)

I think it's already answered here. You just need to build an interface to display images in grid format using views and a delete button is just a link where you pass the node id and delta value of field value to delete.

Once you call the link which will be a custom menu path with callback which executes the code shown in above link to delete the delta field value.


How do I reinstall the Forum module in Drupal 7? I did something really stupid: I deleted the taxonomy_forum field (Forums) from the content type. Now I'm get all sorts of errors.

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'flo1121202154643.field_data_taxonomy_forums' doesn't exist:
  SELECT field_data_taxonomy_forums0.entity_type AS entity_type, field_data_taxonomy_forums0.entity_id AS entity_id, field_data_taxonomy_forums0.revision_id AS revision_id, field_data_taxonomy_forums0.bundle AS bundle FROM {field_data_taxonomy_forums} field_data_taxonomy_forums0 WHERE (field_data_taxonomy_forums0.deleted = :db_condition_placeholder_0) AND (field_data_taxonomy_forums0.bundle = ..........

How do I reinstall the Forum module in Drupal 7 from scratch (including recreating the database schema)?

To uninstall a module, you follow these steps:

Deselect the checkbox shown for the module in admin/modules, and click on the "Save configuration" button at the bottom of the page
Select the "Uninstall" tab (admin/modules/uninstall), and in that page select the checkbox shown close to the name of the module you want to uninstall ("Forum")
Click on the "Uninstall" button
In the next page, click again on "Uninstall"

When you execute the first two steps, you are only disabling the module, which is not yet uninstalled. It is when you execute the last two steps that you uninstall the module.

To re-install it, you need to:

Return to the page listing all the modules (admin/modules)
Select the checkbox shown for the module you want to install ("Forum")
Click on the "Save configuration" button at the bottom of the page

Uninstalling a module should already clear the cache, but to be sure you can manually clear the cache before to re-install the module.
Once the module is uninstalled, installing it back will let Drupal create the database tables used by the module again. The same tables are deleted from Drupal when the module is uninstalled.

I noticed a little issue that happens when you uninstall and re-install the Forum module: The default taxonomy term used by the module is created again all the times you re-install the module, and it seems it is not removed when the module is uninstalled. This is the result of uninstalling and re-installing the module more than once; each time the taxonomy term is created, even if it was already present.

Actually, it is not even required to uninstall, and re-install the module; it is enough you disable, and then re-enable the module, as the code that creates the missing field is not contained in forum_install(), but in forum_enable(), which the function executed when the module is enabled.

I was going to suggest a different way to resolve this issue, and which consisted in manually creating the missing field, but I noticed it doesn't work. The problem is that the module that allows to create a field through the user interface always add "field_" at the beginning of the field names for the fields you create, but the field created from the Forum module doesn't have that prefix; the result is that some database tables and a field present in a table don't have the name the module is expecting, and the module throws errors.


How to specify a twig template for a custom Drupal 8 page? I'm trying to create a custom Drupal 8 route with predefined content, like /about-us, which is not a node, just a standalone page.

The following tutorial is good only up to the point where I need to add the page content using #markup: https://www.drupal.org/node/2116767

How can I specify a twig template that I would like to use for page content?

I got that to work. Here's my solution.

Create a template in path/to/your/module/templates/my-custom-page.html.twig.

/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path)
{
    return [
        'my_custom_page' => [
            'render element' => 'custom_page',
            'path' => $path . '/templates',
            'template' => 'my-custom-page',
            'variables' => [
                'var1' => 'default value for var1',
            ],
        ],
    ];
}

I couldn't figure out what render element is for, but it is required.

variables element defines the variables available in your template and provides default values for them. You can override them in your controller.

use Drupal\Core\Controller\ControllerBase;

/**
 * Class CustomPageController
 */
class CustomPageController extends ControllerBase
{

    public function getPage()
    {
        return array(
            '#theme' => 'my_custom_page',
            '#var1' => 'Actual value for var1',
        );
    }

}

Clear the cache and visit your custom page route. Everything should work.

Helpful links:

Render API
overview
hook_theme()


Offload cached pages to different Apache process On our Drupal 6 and Drupal 7 sites each idle Apache process averages 60-100MB each.  When the page gets loaded from cache only about 10MB is really needed, but sometimes a page is not cached yet so the process jumps up to 60-100+MB.

We use prefork, so each apache process stays about 60-100MB in size, when in reality 99.99% of the page loads are cached and the processes could easily be down to 10MB.

Our MaxClients settings could be about 5x greater if there were a way to keep the apache sizes down to 10MB.

Is there a way to have two apache processes available, one with a low maxclients for non-cached pages and one with a high maxclients for cached pages?  And also, is there a way to route cached & non-cached requests to different processes?

It is not a direct answer to your question, but play around with setting MaxMemFree and MaxRequestsPerChild in the prefork section of your httpd.conf.  MaxMemFree should force Apache to free memory that it doesn't need, and MaxRequestsPerChild will force Apache to fork a new process (and free memory in the process) after servicing a particular number of requests.  You may have some performance impacts, but gain memory improvements.


Update problems when updating to Varbase I updated a Drupal 8 site to Varbase release 16. After running update.php I get the following error.

  Symfony\Component\Routing\Exception\RouteNotFoundException: Route "content_lock_timeout.settings_form" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 190 of core\lib\Drupal\Core\Routing\RouteProvider.php).

Has anybody a idea how to proceed?

The https://www.drupal.org/project/varbase/issues/2953417 shows Varbase is using Content locking module, which is causing the reported error. Try temporarily disabling it to proceed.


Theme table with html I am using custom module to insert and rendering data from Drupal Database.Is it possible rendering data using  theme table in my custom div block

You could render content as table using Theme Table

<?php
$table_element = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' =>t('Your table is empty'),
);
drupal_render($table_element);
?>

Here are some Examples for it:

Examples of theme_table() in Drupal 7
A Drupal theme table example
Drupal for Beginners: How to Create a Table Using theme_table()


How to programmatically render a node's teaser using the theme layer? How do I programmatically render a node's teaser using the theme layer?

node_view() is the standard function for rendering nodes, e.g.

$node = node_load(1);
$view = node_view($node, 'teaser');
$rendered = drupal_render($view);

There is a node theme defined by the node module (in node_theme()) but I've never actually seen it used.


Why doesn't loading a form in the view header work? I've been checking for the past 2 days on how to do a drupal_get_form() for Drupal 8 and everyone seems to give me the following answers which don't seem to work. Let's just say I want to take the following Basic Page creation form and embed it into a Views header:

The ID of the form is: node-page-form or node_page_form if we were using drupal_get_form() from Drupal 7. But this time its the following:

$form = \Drupal::formBuilder()->getForm(Drupal\user\Form\NodePageForm::class);

I'm assuming "NodePageForm" is the parameter I'm suppose to use. If not how can one find this out from viewing the source of that page?

I then put the following PHP code in the Views header of my page like this:

I click save and update... my header is blank. What did I do wrong?

I'm trying to be as descriptive as I can explaining this problem. End result I just want to be able to take ANY form from any D8 page and be able to render it anywhere that takes PHP. That's my end goal. So no 3rd party modules as a solution.

sEntity forms should be built using the entity.form_builder service. You'll need an entity to work with, for a node your code might change to something like this:

$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create(['type' => 'page']);

$form = \Drupal::service('entity.form_builder')->getForm($node);

print \Drupal::service('renderer')->render($form);

As noted in the comments, this won't actually work in the context you're using it, regardless of how you render the form. The views_php area handler renders the output of the custom PHP using #markup, which will strip out the <input> and other form tags. You'll need a custom or contributed module, or to alter the views_php module directly, to make this work.

Here's a simple area handler that adds support for common form tags:

<?php

namespace Drupal\foo\Plugin\views\area;

use Drupal\Component\Utility\Xss;
use Drupal\views_php\Plugin\views\area\ViewsPhp;

/**
 * Views area PHP text handler with support for common form tags.
 *
 * @ingroup views_area_handlers
 *
 * @ViewsArea("foo")
 */
class ViewsPhpForm extends ViewsPhp {

  public function render($empty = FALSE) {
    if (!$empty || !empty($this->options['empty'])) {
      $content = $this->renderViewsPhp($this->options['content']);
      $form_tags = ['form', 'input', 'select', 'fieldset', 'option', 'button', 'textarea', 'optgroup'];
      $allowed_tags = array_merge(Xss::getAdminTagList(), $form_tags);

      return [
        '#type' => 'inline_template',
        '#template' => Xss::filter($content, $allowed_tags),
      ];
    }

    return [];
  }

}

This code should be in src/Plugin/views/area/ViewsPhpForm.php and will need updating for the name of your module.

You'll also need to make views aware of it with a hook either in your .module file, or foo.views.inc:

/**
 * Implements hook_views_data().
 */
function foo_views_data() {
  $data['views']['php_with_form'] = [
    'title' => t('PHP with form'),
    'help' => t('Use PHP code with support for form tags.'),
    'area' => [
      'id' => 'foo',
    ],
  ];

  return $data;
}

After a cache rebuild you'll be able to add a new area handler, PHP with form, and your form should be rendered.


Which hook occurs last before rendering the exposed filter widgets? I'm trying to edit the variables that go from Views into the form array editted by hook_form_alter() and the tpl file views-exposed-form.tpl.php. Specifically, I'm trying to use the contents of $view->exposed_input for form theming, without resorting to using $view = views_get_current_view();

I've tried working my way up the order of execution defined here:

  hook_views_pre_view
  hook_views_pre_build
  hook_views_post_build
  hook_views_pre_execute
  hook_views_post_execute
  hook_views_pre_render
  hook_views_post_render

...but I'm stuck. At hook_views_pre_render(), $view->exposed_widgets gives me already-rendered HTML, so it's clearly too late, but the earlier ones don't give me anything at all.

Based on How to choose between all the views hooks?, I've tried using a preprocess hook based on the tpl file name, like hook_preprocess_views_exposed_form(), but the view isn't in scope here, I'm looking for the last views hook before this where I can find data from the view to these variables.

What I want to do, is take the contents of $view->exposed_input, and pass it through to the exposed form tpl file so that I can add a facet-like summary of current filters to my view. Which is the Views hook where I can do this?

I'm using Better Exposed Filters module, so if there are any hooks or tricks specific to that,they'd be welcome.

You can do what you need by adding a custom property to your form array via form alter:

function yourmodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  // get the related view
  $view = $form_state['view'];

  // get the exposed_input and store it into a custom property
  $form['#exposed_input'] = $view->exposed_input;

}

The form array is directly available as a variable in your views-exposed-form.tpl.php, try adding the following to the end of that tpl file:

<?php print_r($form['#exposed_input']); ?>

Hope this helps!


Save Commerce Order and Customer Profile on validation fail I'm using Commerce Postal Code Filter to blacklist some delivery postcodes.

When a delivery matches the blacklist validation fails and form_set_error is applied.

The problem here is that this means the Customer Order fields and Customer Profile Shipping fields are not saved.

I know this is normal, because failed validation in other tests could mean illegal entries.

For the postcode filter however, I'd still like to save data on failed validation. This will allow the client to see the user's input delivery address and telephone in order to make a call.

Any ideas how to go about this?

Ideas
- Set to validate, but change order status - could this make it serve  first checkout page?

You can can implement hook_form_alter in your custom module and add one more validation handler on top of validation handlers stack, so your is called first.

Inside your validation function follow the way the module Commerce Postal Code Filter is putting the validation, I assume it should be as simple as calling a function. Now if depending on what value it returns you can programmatially update current order status.


Review your selections and rate them in Webform within Drupal 7 I have created a Form with the help of amazing Webform module in Drupal 7. It's a kind of various selections (through checkboxes) user makes.

This is all working fine but the problem is the last step.

I want user to review all the selections he made in the last page and give a priority to each selected option.

Now there are two things I want to do:-

Review the selections made in the Form at the end.
Prioritize them; by selecting a number 1-5 with each entry.

Please pardon my ignorance, but is it even possible with Webform?

Many Thanks.

Preview functionality is now part of the 7.x-4.x branch. There is an involved discussion about it here: Summary/review/preview page before final submission in multistep forms.

As for prioritizing, I think you would want to add a rating field for each field, and theme the form and the preview such that the initial form would not show the rating field, and the preview would.

Depending on what you want to do with those ratings, you may want to use a module like Star Rating (which is a simple module that doesn't have any other dependencies) or FiveStar (which is more complex and has more functionality).


An AJAX HTTP error occurred using commerce coupon percentage I'm able to create coupons with no errors. When I enter coupon code into the field and click on the submit button I get the following error.

An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /system/ajax
StatusText: Service unavailable (with message)
ResponseText:

Drupal version 7.28

Commerce Coupon Percentage 7.x-1.0-beta7

dblog messages

// first error
Rules Warning:
  Unable to get a data value.
Error:
  Unable to get the data property code as the parent data structure is not set.
// second error
Rules Warning:
  Unable to evaluate condition commerce_coupon_discount_coupon_codes_exist_on_order.
// second error
PHP Error:
  EntityMetadataWrapperException:
  Unable to get the data property coupon_id as the parent data structure is not set.
  in EntityStructureWrapper->getPropertyValue()(line 438 of /homepages/
  36/d385915579/htdocs/bbp/sites/all/modules/entity/includes/entity.wrapper.inc).

This seems an error in Commerce Coupon Percentage module. Your problem comes from the EntityMetadataWrapperException: when processing the AJAx petition something goes wrong and an Exception is throw. This is fatal, so Apache ends the petition with the status 500.

I think this a bug in the module code, so you may go the issue queue for this module and create a new bug report with your problem.

By the way, the Commerce Coupon Percentage is only comptabible with Commerce Coupon 1.x, check your are using a 1.x release.


create a custom form based on user fields I created  new menu item witch I want to insert a custom form to edit some user fields :

$items['user/%user/edit-custom'] = array(
        'title' => 'Knowladge',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('user_profile_form_custom', 1),
        'access callback' => 'user_edit_access',
        'access arguments' => array(1),
        'type' => MENU_LOCAL_TASK,
    );
    return $items;

Then the custom function that return the form :

function user_profile_form_custom(){
    module_load_include('inc', 'user', 'user.pages');

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

    $form = drupal_get_form('user_profile_form', $user, 'account', 'custom');

    return $form;
}

When visiting "user/%user/edit-custom" page I can see the profile page, then with some logic code in hook_form_alter I can hide some fields and show up only needed fields...

But the problem that I can't save the form, I get this error :

  Fatal error: Call to undefined function user_profile_form_validate()
  in path_to_drupal/includes/form.inc on line 1514

this solution is inspired from answers described in this post .

Have you any idea please how to solve this, or if you have another way to get some user fields, edit them in a custom page, and save the changes.

Thanks in advance.

Is it possible you missed the comment (below)? It's on the post you linked to.

  "module_load_include('inc', 'user', 'user.pages'); should be added to hook_init() otherwise all profile form functionalities that require AJAX calls will return the error 'Call to undefined function user_profile_form_validate().'"


MYSQL injections: Are they a threat? For a while now, all my Drupal 7 and Drupal 8 instances have been under constant attack from South America or Asia, where the attacker  is trying to infiltrate Drupal with MySQL injections.

The attack is done by adding some MySQL queries to at the and of the
    URL:

www.example.com/) AND 8205=8205 AND (2155=2155
www.example.com/ AND 4874=9552
www.example.com/ AND 8205=8205
www.example.com/') AND 5487=2530 AND ('Kcfy'='Kcfy
www.example.com/') AND 8205=8205 AND ('nUHc'='nUHc
www.example.com/' AND 9068=8481 AND 'wbYZ'='wbYZ
www.example.com/' AND 8205=8205 AND 'DeAs'='DeAs
www.example.com/%' AND 7985=5834 AND '%'='
www.example.com/%' AND 8205=8205 AND '%'='
www.example.com/ AND 5913=3547-- BaJk
www.example.com/ AND 8205=8205-- jBam
(SELECT (CASE WHEN (1873=3317) THEN 1873 ELSE 1873*(SELECT 1873 FROM INFORMATION_SCHEMA.CHARACTER_SETS) END))
(SELECT (CASE WHEN (9523=9523) THEN 9523 ELSE 9523*(SELECT 9523 FROM INFORMATION_SCHEMA.CHARACTER_SETS) END))
www.example.com/) AND (SELECT 1687 FROM(SELECT COUNT(*),CONCAT(0x71717a6a71,(SELECT (ELT(1687=1687,1))),0x716b716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) AND (3698=3698
www.example.com/ AND (SELECT 1687 FROM(SELECT COUNT(*),CONCAT(0x71717a6a71,(SELECT (ELT(1687=1687,1))),0x716b716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a)
www.example.com/') AND (SELECT 1687 FROM(SELECT COUNT(*),CONCAT(0x71717a6a71,(SELECT (ELT(1687=1687,1))),0x716b716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) AND ('XLCQ'='XLCQ
www.example.com/' AND (SELECT 1687 FROM(SELECT COUNT(*),CONCAT(0x71717a6a71,(SELECT (ELT(1687=1687,1))),0x716b716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) AND 'Witz'='Witz
www.example.com/%' AND (SELECT 1687 FROM(SELECT COUNT(*),CONCAT(0x71717a6a71,(SELECT (ELT(1687=1687,1))),0x716b716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) AND '%'='
www.example.com/ AND (SELECT 1687 FROM(SELECT COUNT(*),CONCAT(0x71717a6a71,(SELECT (ELT(1687=1687,1))),0x716b716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a)-- OHLo
www.example.com/) AND 3711=CAST((CHR(113)||CHR(113)||CHR(122)||CHR(106)||CHR(113))||(SELECT (CASE WHEN (3711=3711) THEN 1 ELSE 0 END))::text||(CHR(113)||CHR(107)||CHR(113)||CHR(107)||CHR(113)) AS NUMERIC) AND (3563=3563
www.example.com/ AND 3711=CAST((CHR(113)||CHR(113)||CHR(122)||CHR(106)||CHR(113))||(SELECT (CASE WHEN (3711=3711) THEN 1 ELSE 0 END))::text||(CHR(113)||CHR(107)||CHR(113)||CHR(107)||CHR(113)) AS NUMERIC)

Can somebody tell my, what these attacks are about? Was there a bug in Drupal making it vulnerable for those attacks? Is somebody else experiencing those attacks?

Can somebody tell my, what these attacks are about?

They're requests from bots fishing for vulnerabilities in your website.

  Was there a bug in Drupal making it vulnerable for those attacks?

Vulnerable to the specific attempts you've listed? Looking at the exact nature of the URLs, probably not. But there was, of course, Drupalgeddon once upon a time, so maybe.

  Is somebody else experiencing those attacks?

It's highly likely that they are. These attacks are usually orchestrated against as many potential victims as possible, and not built to target a single site. If the attacks you're experiencing were tailored, you would probably expect to see less generic and more Drupal-focused approaches.

You may wish to consider installing and configuring something like Fail2Ban to help with keeping the bots out.


How to disable Review step in Drupal commerce implementation? I am implementing Drupal Commerce module in one of the website. It works fine, but now the requirement came is like, they don't want to show the Review step which comes after the Cart page. So is there any way to disable/skip this step and move forward? Any suggestions will be appreciated.

Just remove any checkout panes from it in your checkout form configuration.


How do I properly pass values from PHP to JavaScript? I am currently writing a module and I am trying to pass some variables to the Drupal.settings.

My module uses the following code.

function bcc_preprocess_views_view(&$vars) {
    drupal_add_js(array('modulname' => array('key' => 'value')), 'setting');
    drupal_add_js(drupal_get_path('module', 'modulname') .'/script.js');
}

The script.js content is the following.

(function ($) {
    console.log(Drupal.settings.modulname);
})( jQuery );

The output I find in the log is undefined, but when I check the content of  Drupal.settings.modulname from the browser, it gives me the desired value.

When I add this code, the log shows the right values.

drupal_add_js('jQuery(document).ready(function({console.log(Drupal.settings.royal)});', 'inline');

What is wrong with that? What is the correct code to use?

You first JS snippet executes before the page is done loading.  Is it not the same syntax as the shorthand for declaring the document.onready event handler.

You working example runs from an onready, but the Drupal best practice is to use a behavior, eg:

(function ($, Drupal, undefined) {
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      console.log(settings.mymodule);
    }
  };
})(jQuery, Drupal);

Take a look at Managing JavaScript in Drupal 7 for more information.


How to list comments of certain node in a PHP How to list comments of certain node in a PHP ( preferably in XML / RSS format )?

You can use the Views module to create custom lists of nodes, comments, users etc. In your case, you will need to:

create a view of comments
add a 'Feed' display
add a 'Contextual filter' for 'Comment: Nid' (this will allow you to specify the node ID in the url)
set the feed url to something like comments/%/rss, where the % is a placeholder for the Node ID
save the view

Now you can find an rss feed of comments for node 32 at http://example.com/comments/32/rss

Here is an export of such a view:

$view = new view;
$view->name = 'comments_rss';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'comments rss';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'comments rss';
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'comment';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = 1;
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['subject']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['subject']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['subject']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['subject']['alter']['trim'] = 0;
$handler->display->display_options['fields']['subject']['alter']['html'] = 0;
$handler->display->display_options['fields']['subject']['hide_empty'] = 0;
$handler->display->display_options['fields']['subject']['empty_zero'] = 0;
$handler->display->display_options['fields']['subject']['link_to_comment'] = 1;
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Comment: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'comment';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'not found';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['nid']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['nid']['break_phrase'] = 0;
$handler->display->display_options['arguments']['nid']['not'] = 0;
/* Filter criterion: Comment: Approved */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'comment';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status_node']['id'] = 'status_node';
$handler->display->display_options['filters']['status_node']['table'] = 'node';
$handler->display->display_options['filters']['status_node']['field'] = 'status';
$handler->display->display_options['filters']['status_node']['relationship'] = 'nid';
$handler->display->display_options['filters']['status_node']['value'] = 1;
$handler->display->display_options['filters']['status_node']['group'] = 0;
$handler->display->display_options['filters']['status_node']['expose']['operator'] = FALSE;

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

/* Display: Feed */
$handler = $view->new_display('feed', 'Feed', 'feed');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['style_plugin'] = 'rss';
$handler->display->display_options['row_plugin'] = 'comment_rss';
$handler->display->display_options['path'] = 'comments/%/rss';
$handler->display->display_options['displays'] = array(
  'default' => 'default',
  'page' => 'page',
);


User can't change language after redirection from custom module I'm using custom module to redirect users from Serbia on Serbian language. So, if user comes from Serbia on front page, in URL will be added '/sr'. The problem is that user can't change the language on front page because it always will be redirected.

Can someone help me to fix this issue and make visitor able to change language on front page?

There is the code of custom module:

global $user;
function smart_ip_redirect_init() {

  if(
    // if country is detected
    !empty($_SESSION['smart_ip']['location']['country_code']) &&
    // if is front page and anonymous user
    drupal_is_front_page() && user_is_anonymous()
  ) {
    // load some global variables, language contains information about current language, base_url is base url
    global $language, $base_url;
    // load all active languages
    $languages = language_list();
    // resolve the country code to language, you have to make cases for your needs
    function country_to_language() {
    switch ($_SESSION['smart_ip']['location']['country_code']) {
        case 'RS':
            return 'sr';
        break;

        default:
            return '';
        break;
    }
    }

    // if the URL have no lang parameter
    if(strtoupper(request_uri()) == strtoupper("/")  )
    {
         // does the visitors language exist in our Drupal
      if(array_key_exists(strtolower(country_to_language()), $languages))
      {
        // redirect user to the designated language
        drupal_goto($base_url.'/'.strtolower(country_to_language()));
      }
    }

  }

}

Now your code redirect always, and you only want to redirect once. It means you need implement logic similar to the one below:

Test $_SESSION to see if redirection evaluation took place already. If yes, end.
Create element in $_SESSION, to mark this session as already evaluated against redirection
Decide if you want to redirect or not.
Perform redirect if needed.

That way you will run code responsible for redirection once and only once per user session, and that's seems what you want to do.


Make EntityQuery Block Table sortable I made a custom EntityQuery Block Plugin with a table output and managed to make the headers sortable using this $header definition:
        $header = [
            'title'      => [
                'data'      => t('title'),
                'field'     => 'title',
                'specifier' => 'title',
            ],
            'mydate'       => [
                'data'      => t('mydate'),
                'field'     => 'field_date_paragraph',
                'specifier' => 'field_date_paragraph',
            ]
        ];

Then I added a tablesort when retrieving the nodes:
    $nids = \Drupal::entityQuery('node')
        ->condition('status', 1)
        ->condition('type', 'project')
        ->tableSort($header)
        ->condition('field_exhibition.target_id', \Drupal::routeMatch()->getRawParameter('node'))
        ->execute();

The output looks fine and column headers are clickable - but nothing happens. Actually the GET parameters get correctly added to the URL and look something like:
?sort=asc&order=mydate

I think the problem is date field (field_date_paragraph) which is a paragraph field. Inside the paragraph I have a date field and it is this one which should get ordered. What do I have to add to $header definition to make reference to the date field inside field_date_paragraph?

I think you need to specify a filed name inside a paragraph in the header array, like field_date_paragraph.DATE_FIELD_NAME (This behavior is, also supported inside condition method)
And here is the issue about lack of documentation https://www.drupal.org/project/drupal/issues/1924622


Updated >= Drupal 8.0.5+: Rendering forms/entities programmatically on theming level There are several attempts and questions already asked about near to that topic in combination with the new Drupal core (8), but non of them came down to the bottom of the basic question. And non of them are up-to-date enough (2015) since many late changes in core arrived afterwards (2016). Answering the basic question will hopefully lead to answers for many depending questions and open HOWTO topics and could be a good basis for updated docs on drupal.org.

The basic question is:

How to programmatically render path/page based forms or any other entity bundles on the theming level to display them path independently, e.g. in blocks or other pages other than the given pages/paths of itself? And how can I find the right routing for the correct system calls or class paths for the needed preprocess functions in the new D8 core logic if I am new to D8?

The question arises from 2 points of view:

Why should a form be hard binded to a page view or fixed path? It's a page element, not a page. It should be available easely in any
other places without complicated coding struggles in a website
building CMF like Drupal on the theming level. It's part of theme
design to decide to have a form on frontpage, for example. (ok, this is arguable, I know, but in some cases it is)
From the basic structure how Drupal is build and what it tries to achieve in these times (the goal to rather build web applications
instead of classic and static websites), it should be easily
reachable to maintain such task like a form on the bottom of a
one-page site or to build a survey or render entities on unexpected
pages.

To keep with the form example:

here are some links to questions regarding this topic and I've tried already to interfere there and suggest to inform about changes in core here and there to update the posts or to link to sources:

How to programmatically render a contact form in a theme in D8
Rendering contact_form
Embed a contact form

The basic structure

.. how it works is common, mostly clear, and not so far from how it worked in D7:

You will use a preprocess_xxx() function in your D8 twig YOURTHEMENAME.theme file to call and pipe the form or entity array into the region variable array, to be able to render it via {{ var }} twig-tags in your xxx.twig file: e.g. block.html.twig or page.html.twig, since the form or entity is maybe not known in this layer (enviroment variable) by default.

Just an example (needs update and correction) of your THEMENAME.theme file:

preprocess_page(){
  $form = Drupal::routeMatch()->getParameter('contact_form'); // ???
  $message = \Drupal::entityTypeManager() // ???
  ->getStorage('contact_message')
  ->create(array(
      'contact_form' => $form->id(),
  ));
  /// ???
  $form = Drupal::service('entity.form_builder')->getForm($message);
  $variables['contact_form'] = $form;
}

Just an example page.html.twig file:

<header>
  {{ header_region }}
</header>
<div id="main"> ... </div>
<footer>
  {{ contact_form }} <!-- from $variables['contact_form'] = $form; -->
</footer>

But now comes the tricky part:

The docs are not up-to-date enough to make clear how to build the preprocess_xxx() function correctly, demonstrated with \\ ??? here. Using the demo example here as-is (atm) will cause an almost empty frontpage, only rendering html.html.twig but without the nested page.html.twig, obviously caused by a wrong coding in the preprocess function.

Somebody who tries to find updated docs or QA for that will have a hard time ...

I'm still new to drupal but here is what i did to render a form in node.html.twig:

//file themename.theme
function themename_preprocess_node(&$variables) {
  if(isset($variables['node'])){
    $node = $variables['node'];
    if($node->getType() == 'application') {
        $message = \Drupal::entityTypeManager()
            ->getStorage('contact_message')
            ->create(array(
            'contact_form' => 'webentwickler_job', //ID(Machine name) of form
        ));
        $form = \Drupal::service('entity.form_builder')->getForm($message);
        $variables['application_form'] = $form;
    }
  }
}

//file node--application.html.twig
{{ application_form }}