Install using Composer doesn't create .htaccess file Followed instructions at (https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-and-manage-dependencies) to install Drupal with Composer using the command:

"composer create-project drupal/recommended-project my_site_name_dir"

Composer download all the files and displayed that Drupal was ready to install. However, when trying go to the page in a browser get "Forbidden You don't have permission to access / on this server. "

Looking in the "my_site_name_dir" there is no .htaccess file so the server doesn't know to go into the "/web" subdirectory. The "my_site_name_dir" directory has only the following files:
   /Vendor
   /web
   .editorconfig
   .gitattributes
   composer.json
   composer.lock

Should the .htaccess file be created automatically by Composer? I thought Composer used to do this in earlier installations. Is there a recommended .htaccess template to use. Thanks.

Environment: Windows 10, PHP Version 7.1.20, Apache 2.4

Both drupal-composer/drupal-project and drupal/recommended-project create Drupal installations with a relocated DOCROOT, or web root.  So, the .htaccess folder isn't in the root of the installation.

You need to point Apache to the 'web' directory, which is where the .htaccess and index.php files are.  This is done at the Apache config level, not .htaccess level.

For example, on one of my servers, I have my git checkout in /var/www/prod.  The config looks like

DocumentRoot /var/www/prod/web
<Directory /var/www/prod/web>
  AllowOverride All
  Options -Indexes
  Options +FollowSymLinks
  Require all granted
</Directory>


wysiwyg in rules text field I've got some rules sending email messages to users. The content of the email is defined in a field in a 'send mail' action and I were wondering if it's possible to use wysiwyg there?

Yup. You can use hook_FORM_ID_alter() to change any field into text area into a WYSIWYG field:

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

  //Set the type to text format
  $form['parameter']['message']['settings']['message']['#type'] = 'text_format';

  //Replace 'full_html' with 'filtered_html' or any other input format that has a WYSIWYG profile
  $form['parameter']['message']['settings']['message']['#format'] = 'full_html';
}


Not able to find login form anymore on Drupal We are not able to find the login form anymore on Drupal. We can't find the form on site.com/user/login... We can't find it anywhere.

How can we login?

Maybe a problem of clean urls?

Try site.com/?q=user


Email field on registration page not working When I try to register a new account using the standard settings for my site no matter what I put in the email field it gets highlighted in red and I can't register a new user. Has anyone experienced this before or know any solutions to this?

There you must receive a message with the error. If you don't see it, please, check if your theme have enable the messages.
Check if the mail is not register in the site. Just try to reset the password using that email address and you will see if was registered or not.


How can I display the price field twice? I am using commerce kickstart 2. Here's a screen shot of my product display

I've set a VAT tax rate in Drupal Commerce, so the price in that screenshot is the price of the product, plus the 20% VAT tax.

How can I display the price excluding VAT?

You should use Commerce Extra Price Formatters module.

Extra Price Formatters Implemented So Far

RRP / Your Price

Allows you to display the Retail Price and the User Price
for a product and optionally the amount the customer
will save.

Allows you to switch the display back to a single price if
there is no discount available on a particular product.
Formatted Price with Prefix and Suffix

Allows you to present a price in the style just £9.99 ex
VAT or only £9.99 for a limited time only.
Formatted Price with no decimal places

When you are selling items with whole unit prices, you
don't necessarily want to see £10.00. This formatter
lets you change the display to show £10. (use this with
care!)

There's a video demo here: http://www.youtube.com/watch?v=-WR3mKjou8M

Then you should add two price fields in your product content type. In your manage display tab you would be having a settings option to calculate your price excluding or including tax and other parameters and thus you can add two price fields.


Main Menu link to all newsletters and another for Articles I am very new and not a developer. I would like to create two main menu links for newsletter content type (simplenews) and the core articles type. I want the behavior to be the same as blog.

I assumed that simplenews would add the link when installed but it did not. I have been searching the net for hours, I cannot find a solution.

Thank you in advance for your help.

How much I understand go to structure > menu > main menu and click "add link" for Drupal 7 and structure > menu > main navigation for Drupal 8

 and for this, you need to create two views one is for newsletter content type and second is for article content type. You can make the view by going to structure > views > add new view for both Drupal 7 and 8. The view type must be page not block.

All the pictures are for Drupal 8. If you need more assistance please let me know.


Open a Make Meeting field inside colorbox I am using the Make Meeting Scheduler for my site, which is a Doodle-like scheduler module. This module makes it possible to insert a field (only field, not available as block) into a node. However, I need to open this field inside Colorbox.

I know a possible workaround would be to create separate nodes with only the Make Meeting field and then connect them to the original nodes where I need them, but this is definitely not an elegant solution.

I'm really not good with Drupal templates and that is why I haven't come up with a better solution. I suppose I should edit the template, print a link with the class "colorbox-load" and have that link point to the Make Meeting div. Problem is, I am currently clueless as to how to do that.

The easiest way to do this is through views. You can configure a view with an "Contextual Filter" of the node id to show and then configure it to show your makemeeting field here. Here's a screenshot of a view that worked for me (note the important parts are marked with arrows.

Then when I go to /meeting-popup/6 (where 6 is the id of a node with a meeting field) i see the following.

Then you can add a link to /meeting-popup/ on the nodes page using the lightbox-load class so it will showup in a popup.

Lastly you can theme the meeting-popup pages so that they only show the content and don't show any regions/sidebars, etc.

Alternatively you can have views make it into a "block" if you know of a good way to do it that way.


How to theme Bean block in drupal 7 I have create a custom block using Bean. It have a field collection and that field collection have 8 values. I have create a bean.tpl.php to override block. Now i need to know how can i get that field collection values using loop inside bean.tpl.php file.

First you need enable for create tpl name bean.tpl.php call for every bean type.

$conf['theme_debug'] = TRUE;

In this tpl you get $content variable . Please print_r($content) in tpl or install devel module to dmp($content). I suggested you install devel module. After that you can find your field collection

Load field collection like this

Thank you


Form Field Containers How do I get rid of the outer box around the location field for example. I don't like how the location title + background colours are repeated twice for additional fields.

I have this issue on every template, not just the one displayed so can answers please be generic so I can do it on every template.

Drupal uses renderable arrays, so there is probably something like this:

'location_outter' => array(
  '#type' => 'fieldset',
  '#title' => 'location',
  'location_inner' => array(
     '#type' => 'fieldset',
     '#title' => 'location',
     'city' => array(
        '#type' => 'textfield',
        '#title' => 'City',
     ),
   ),
);

So i think you can, if it is form, try use alter hook, for example yourmodule_user_form_alter and modify that renderable array.


Export menu links with features I'm trying to export menu links with features but it saves the node id in the feature, but obviously the nid is different in dev, test and production.

I can't use UUID because nodes are created in every environment.

Is there a way to export menu links with alias and not with nids?

http://webwash.net/tutorials/import-and-export-menus-menu-import-module-drupal-7 shows how to use http://drupal.org/project/menu_import which uses path aliases instead of UUID.

I think this would work.


Show last node of every term in one Views How to show the last node of every term using only one View? That's what I want to get:

news/football - last node of the football term

news/boxing - last node of boxing term.

How can I do it?

Create a view to show content
Add page display and set path setting to news/%
Add contextual filter "Has taxonomy term ID"
Add sort criteria "Authored on (desc)"
In pager settings check "Display a specified number of items" and set "Items per page" setting to 1.

Note that this will produce URLs with numeric term IDs (i.e. news/123).
To make use of term names you need to configure a relationship to the term so you get the information about the term into view, then use term name contextual filter.


Generate classname from variable in template In the template file for a view with grouped rows, I would like to add the group title as class name, but the rendered class name from the title variable is just _ on every group. This is the generated HTML markup for the group whose title is 1.

1

What's wrong here?
This is the template file content.
{#
/**
* @file
* Default theme implementation to display a view of unformatted rows.
*
* Available variables:
* - title: The title of this group of rows. May be empty.
* - rows: A list of the view's row items.
*   - attributes: The row's HTML attributes.
*   - content: The row's content.
* - view: The view object.
* - default_row_class: A flag indicating whether default classes should be
*   used on rows.
*
* @see template_preprocess_views_view_unformatted()
*
* @ingroup themeable
*/
#}
{% if title %}
  {%
    set classes = [
      'views-group',
      'group-' ~ title|clean_class,
    ]
  %}

{{ title }}

{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}

    {{- row.content -}}

{% endfor %}

Valid CSS identifiers (for example, element names, classes, and IDs in selectors) cannot start with a digit, or a hyphen followed by a digit. Html::cleanCssIdentifier(), which is called when a CSS identifier is created from a string, contains the following code.
  // Valid characters in a CSS identifier are:
  // - the hyphen (U+002D)
  // - a-z (U+0030 - U+0039)
  // - A-Z (U+0041 - U+005A)
  // - the underscore (U+005F)
  // - 0-9 (U+0061 - U+007A)
  // - ISO 10646 characters U+00A1 and higher
  // We strip out any character not in the above list.
  $identifier = preg_replace('/[^\\x{002D}\\x{0030}-\\x{0039}\\x{0041}-\\x{005A}\\x{005F}\\x{0061}-\\x{007A}\\x{00A1}-\\x{FFFF}]/u', '', $identifier);

  // Identifiers cannot start with a digit, two hyphens, or a hyphen followed by a digit.
  $identifier = preg_replace([
    '/^[0-9]/',
    '/^(-[0-9])|^(--)/',
  ], [
    '_',
    '__',
  ], $identifier);

As a digit is only replaced when it's the first character, or the second character when the first character is a hyphen, it's enough to  first concatenate a string that is an acceptable CSS identifier, as in the following code.
{% if title %}
  {%
    set classes = [
      'views-group',
      ('group-' ~ title)|clean_class,
    ]
  %}
  <h3{{ content_attributes.addClass(classes) }}>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{- row.content -}}
  </div>
{% endfor %}

The only difference with the code shown in the question is using ('group-' ~ title)|clean_class, instead of 'group-' ~ title|clean_class. The parentheses are necessary because | takes precedence over ~.
That is the only change needed to avoid that the first digit in the node title is replaced with an underscore. There is no need to change the code to add a single CSS class instead of two CSS classes.


Difference between .info files hook_menu() file key? What is the difference between declaring the files[] in a module's .info file and declaring the file inside a hook_menu() item?

According to the Drupal Documentation on .info files...

  When a module is enabled, Drupal will rescan all declared files and index all the >classes and interfaces that it finds. Classes will be loaded automatically by PHP >when they are first accessed.

And the documentation on the files key for hook_menu() is...

  A file that will be included before the page callback is called; this allows page >callback functions to be in separate files. The file should be relative to the >implementing module's directory unless otherwise specified by the "file path" >option.

This sounds a little redundant to me. Aren't the files being "included" when you declare them in the .info file? So why would i need to list the file location for a function inside hook_menu when it should already be included?

I'm sorry you do not understand my question, however, I believe the question was pretty straightforward. After discovering some interesting articles I think worked out my confusion.

The files[] entry in the module .info file is not used for "including" php files. It is meant only to auto load your classes and interfaces for your application (if you're writing your module using object oriented methodologies). It could be thought of as the "import" statement in Java.

The following articles go more into detail about PSR-0 standard and auto loading in php.
previousnext.com.au/blog/drupal-8-now-psr-0-code-drupal-7/
riceball.com/d/book/export/html/1200

That being said, the purpose of the file key inside the hook_menu() $item[] is to specify where the file containing the page_callback function exists. If your page_callback function is defined inside a class (statically), then you do not have to provide the file and filepath keys. The callback would look something like this,
    'page_callback' => array('MyClass::myfunction');

For more information on OO Page callbacks in Drupal 7, read the following article.
previousnext.com.au/blog/object-oriented-page-callbacks-drupal-7

If your page_callback is not inside a class, but just inside a file then you'll need to provide the file and filepath keys so that Drupal can include this file when your page is created.


Why is my migration status table empty? I wanted to delete all migration modules because of that I use

drush config-delete migrate_plus.migration.ID

After that, I create a new migration module and enable it with

drush en migrate_NAME

and rebuild the cache.
I look at the status table with

drush migrate:status

but the table shows no migration. If I enable the migration again I get the message "Already enabled". When I try to import something I get the message "No migrations found".
Does anyone have any idea why this might be?

I think that you are mixing up things. By doing

drush config-delete migrate_plus.migration.ID

you are just deleting migration_plus configuration but you are not disabling the module, it is still enabled. If you really want to disable the module and of course the configuration, you'll have to drush pm migrate_plus.

Concerning the "No migrations found" message, your custom module has to define correctly the new migrations (.yml files).


Organic Groups Views Contextual Filters We have a country based site that needs to have an unfiltered view of various content types and a filtered view per country. We have implemented the countries with Organic groups but can't seem to get the contextual filters to limit the view based on the OG name in the URL. Is there anyone that has done something like this with OG?

Under Relationships, I choose "OG membership: OG membership from Node".

Then under Contextual Filters, I choose "OG membership: Group ID".

The last step is to select the Provide default value and choose "Type: Current OG group from context" under the WHEN THE FILTER VALUE IS NOT IN THE URL heading. Attached is a picture of what I mean.

Contextual Filter setup


Print date and timestamp in views-view-field--blog--block-1--image.html.twig How to print date and timestamp in views-view-field.html.twig ?

This is my html code

27 Mar

And this is code for timestamp

        6 mins ago

To look like this. This is html look.

Date and timestamp need to be add in

views-view-field--blog--block-1--image.html.twig

I am assuming that the template is for a date field and you want to display the date field in the format that you specified above.

Here is the article that might help http://twig.sensiolabs.org/doc/filters/date.html

For PHP date formats you may refer to http://php.net/manual/en/datetime.formats.date.php

Similar question : https://stackoverflow.com/questions/8318914/how-to-render-a-datetime-object-in-a-twig-template


How do I get node revisions to use my custom template? I have a custom node template for my content type of Listing, node--listing.html.twig. It is quite heavily customised for the client. However when we go to view a revision (e.g. /node/144/revisions/273/view) it doesn't seem to bother loading a template at all, not even node.html.twig - the fields just get dumped onto the page.
Any ideas how to force it to use the custom template?

You can try my patch from Make node_is_page() work on revisions and previews as well. If that doesn't fix it, you can probably use the relatively simple code update from inside node_is_page() to add your own template suggestions using hook_theme_suggestions_alter.


Add soft hyphen () in titles (in views) or other method to break words in a language-sensitive way I have an Austrian site here (and the German language loves compound nouns).

A view produces a raster of 6 article teasers, but some titles exist of one single word of more than 30 characters - and no, it cannot be shortened because it is a proper name.

I'd like to be able to manually add  tags into these titles, as everything else will not be language-sensitive. CSS word-wrap or word-breaks are no options (not breaking at syllable boundaries).
Also, adding an ellipsis is also not an option.

This is Drupal 8, so no "HTML Title" modules available.

The theme does a simple

{% if title %}
  <h1>{{ title }}</h1>
{% endif %}

I am aware of possible security implications and only want to allow this one tag. Alternatively, I am open to other suggestions fulfilling the stated need!

Our workaround inhouse: We've trained our editors to use Alt + 240 (hold alt key and press 2 4 0 on numeric pad) to manually add soft hyphens in title fields.

Is a bit weird because your editors don't see the hyphen in a text input field, but you can prove its existance by deleting it (backspace after such a hyphen will NOT delete the visible letter on first press)


Add fix amount to all orders as packaging price I want to add  a fix amount to all orders as packaging price in commerce,I think first I need custom line item and named it as packaging price, then add that to orders with rules or in custom module, but this is just a idea.
 Anybody know how can I add a fix amount to all orders as packaging price (I also have discount in our commerce system and used it) ?

I think you should check this module commerce fees maybe help you


sign-up pop-up on webform I'm going to make a sign-up website. When the user has clicked on Sign-up link it will take them to this pop-up window on the browser itself giving them one option (to input mail) then a submit button. I know how to setup the thing in webform but how do I make a sweet pop-up window for the user to enter the value? Is there any module for this?

Any suggestions are welcome

thanks

The Modal Form Module supports modal window for webform, you can also use shadowbox module which creates a modal window for anything.


Solr server URL needs to include a scheme? Recently I am facing a issue with all my D7 websites which I have migrated to a new server. The case is as follows

-> All Sites have been setup with Apache Solr and working fine on my old server

  After I migrated the sites to new server I am getting this error

URL Format Used :

  http://USERNAME:PASSWORD@XXX.XXX.XXX.XXX:8983/solr/CORE_NAME

Note: I migrated to new server with latest version of LAMP. Also I use remote Solr server.

OLD Server : Ubuntu 12.04, PHP 5.3.10, Nginx 1.8.0, MySql 5.5.X

New Server : Ubuntu 16.04, PHP 7.0.28, Nginx 1.10.3, MySql 5.7.X

The issue was with the '#' character in the password which was failing the parse_url called in the module.


How to let users post questions and appear anonymous? I want logged in users to be able to post questions or answers using the Answers module "anonymously"... that is, to appear anonymous but actually still be logged in, be able to follow their post, etc.

Edit: I thought this module could already do this but am not finding any settings for it.

Using Answers 7.x-4.0-rc2

Criteria:

anonymous/not logged in users should not be able to post
I want to give users the option to post anonymously but default to show the author
if a user posts "anonymously", the post would have do something about their avatar

on a per-post basis

Our site is complex with many other features, such as blogging, so changing usernames isn't an option; we want their usernames to show up everywhere else

To my knowledge, the Answers module (you know the drill .. Disclosure: I'm a co-maintainer) does not have such setting that you were looking for. However, by using the Rules module (also), you should be able to get this to work, as further detailed below ...

Step 1: Create a (blocked) user 'Somebody'

Create an extra user with a user name that will be shown instead of the user name that you want to appear anonymous. I decided to name such user "Somebody", and it was created with uid=68. Moreover, I decided to make it a blocked user (not to be used for any other purpose).

Step 2: Add a dedicated field to relevant content types

For every content type for which you want this facility to be available (e.g for types Question and Answer), add an extra field that an editor (author) of a node can use to indicate if the node should  appear anonymous.

In my case I have a selection list field with machine name field_optionlist and which has 2 possible values, like so:

A (= Appear anonymous).
S (= Standard author display).

Step 3: Create a custom rule

Below is custom rule (in Rules export format) that will set the node author to "Somebody" (= the user name from Step 1) whenever value "A" is selected via the dedicated field from Step 2 (and whenever a node of type Question or Answer is saved):

{ "rules_optionally_hide_node_author" : {
    "LABEL" : "Optionally hide node author",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : {
              "answers_answer" : "answers_answer",
              "answers_question" : "answers_question"
            }
          }
        }
      },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "A" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : "68" },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched user" } }
        }
      },
      { "data_set" : { "data" : [ "node:author" ], "value" : [ "user-fetched" ] } }
    ]
  }
}

Adapt the uid=68 value in the above rule to fit your dedicated user, and replace the machine name of field_optionlist to fit your case (prior to trying to import the above rule).

That's it ... at least to make it work in my setup.

Step 4: Extra refinements

For the sake of completeness, you should create a variation of this custom rule to set the node author to "current user" whenever the field value is different from "A".

Bonus feature ...

By using the above approach, and by using a user name like Wiki, you can implement logic that is pretty close to "wiki" questions / answers on SE-sites also. Because for those kinds of questions/answers the original author will not have any user points (like reputation) changes anymore for any upvotes or downvotes of such question or answer.


use different "From" header for different actions when sending emails So for example, when a user's creating an account, I want to have the sent email use "From: register@example.com" header.

But also, when I will approve his content I want to use the header "From: info@example.com"

Right now, all emails sent are using the same "From" email header provided in the "Site information" settings.

Any ideas on how to achieve this? Thanks

use hook_mail_alter function in your custom module and change the from address based on your requirements.


What does INTERNAL form properties mean? On the Drupal form-API page, there is this paragraph that reads:

  Note that internal properties are not included in the table below, but
  are included in the Properties list. These include: #built, #children,
   #error, #id, #input, #printed, #validation_arguments

What does "internal" mean, as compared to other form element property types?

Internal means that these properties are not supposed to be used by module developer.


Flippy Pager No Results I am using the Flippy Module to build an article pager on a client website.

Everything is working well, but I have encountered an issue where several thousand articles have been imported, many of which without an attached image. This of course disrupts Flippy as it sources its thumbnail from the article content type's image field.

Unfortunately Flippy doesn't appear to have any kind of no results behaviour built-in out of the box.

Anyone else encountered this issue too, or may be able to point me in the direction of a patch that may add this functionality to the module?

I would like to set a default image as a fall-back if no image is found.

TIA.

You can use flippy.tpl.php template. Copy this template in your theme and modify it what ever you want.

$image_arr = array(
        'path' => $file->uri,
        'style_name' => '<Style Name>',
        'alt' => '',
        'title' => '',
      );

print theme('image_style', $image_arr);


Turning on delay of superfish menu For some reason I cannot find the settings to turn on the delay for my superfish menu. I was able to get to it a couple of weeks, but not any more.

All I see when I go to /admin/config/user-interface/superfish is the ability to change the number of blocks and paths to superfish library.

How do I get to the settings where I can turn on delay?

The settings for the menu is on the same page as the menu block settings page. You'll find your menu block at /admin/structure/block where you click configure for your menu block, and you'll be able to change the settings.


Migration SQL Source with Track Changes I have a D8 migration from a SQL source to nodes which is working perfectly apart from track_changes is not working, in my YAML I simply have:

source:
  plugin: job
  constants:
    slash: /
  track_changes: true

I discovered track_changes does not work when the map is joinable and applied the patch, but every time I run the migration I get:

[notice] Processed 0 items (0 created, 0 updated, 0 failed, 0 ignored) - done with 'job'

Do I need to add anything specific to the source plugin? For now I'm getting round this by updating the whole migration each time, but I would prefer not to. If necessary I will have to use the high_water_property instead.

I had an issue like you did and i solve it by changing my:
track_changes: true

on
  high_water_property:
    name: changed
    alias: n

But the problem with this way that you need to:

Manually delete, NOT update your database destination fields.
Import old data.(Before check your source plugin, it must have changed field!)
Update your database with new data.

(and only than high_water_property will work)

About this two Source Plugins
Declaring highwater property in Migrate
About track_changes


Display messages in bootstrap file I have a file that I have bootstrapped and I am trying to print messages but I can't get it to work. Here is the code does anything look wrong (mysite was changed)?

<?php
define('DRUPAL_ROOT', '/home/mysite/public_html');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
?>

<html>
<body>
 <div class="description">
  <?php global $user;

     print "Welcome " . $user->name;
     drupal_set_message(t("Don't panic!"), 'warning');
     print $messages;
  ?>
</div>
</body>
</html>

To get the list of the messages set with drupal_set_message(), you should call drupal_get_messages().

Drupal doesn't use any global $messages to store those messages. They are stored in $_SESSION['messages'], but you should really use drupal_get_messages().

drupal_get_messages() returns an array; this means you cannot simply use the following code.

$messages = drupal_get_messages();
print $messages;


User Register page is different if there is a destination parameter in the url I'm trying to find where to go in Drupal to find out how a user register form is displayed.

If the url is user/register, a person is routed to a standard registration form.

However, if the url is user/register?destination=voucher, then that person is routed to a user registration form that mimics our popup modal registration form, however, is not in a popup. This is not the regular registration form.

I want to find where this is set so that if a destination parameter is in the url, to go to the standard registration form.

The drupal_get_form() returns a form array for rendering. In your case drupal_get_form('user_register_form'). You can use drupal_render() with the result to render the html output.

If you need to override the form, use hook_form_alter() and change the $form_state['redirect'][] = 'your/redirect/path'. Also try removing the destination param with unset($_GET['destination']).

Here are some references:

Form Redirect not working if 'destination' is in URL
https://stackoverflow.com/questions/1175687/redirect-after-registration-in-drupal
http://www.brianvuyk.com/story-type/changing-redirect-value-drupal-node-form-d6


Is there a way to delete/purge all generated image style images without re-generating them? I'd like to delete all generated image style images without re-generating them immediately.  I want to do this in order to remove them from my backups, because as the number of files on the site increases, it's taking up an exceedingly large amount of space.

I also have the option of making the backup script more complicated and not backing up those directories, but I was wondering if there is a quick way just to remove the generated files only.

You just have to do drush image-flush --all. Source : http://www.drushcommands.com/drush-6x/image/image-flush

Examples of using the drush image-flush command:

drush image-flush - Pick an image style and then delete its images.
drush image-flush thumbnail - 'Delete all thumbnail images.
drush image-flush --all - 'Flush all derived images. They will be regenerated on the fly.'


Permissions Rebuild fails After I installed a quiz module on my Drupal 7 site, it asked me to rebuild permissions. when I try to rebuild it throws this error:

I've tried everything that I found online, including:

increasing web server RAM
max_execution_time = 1600
max_input_time = 180
max_input_nesting_level = 300
memory_limit = 512M
disabling batch mode from node.module core file

nothing seems to work.

There are about 600k records in the node table. I know this is a lot, and probably it causes my issue, but what is the workaround? How can I rebuild permissions with this many nodes easily?

Wherever that "Illegal access" Ajax error comes from, I recommend to rebuild node access from the command line instead. With Drush the following command should do it.

$ drush php-eval 'node_access_rebuild();'

With that many (600k) records in your database it may also be better to have that done by some more advanced process like the one provided by the Node Access Rebuild Progressive module. It also provides its own Drush command.

$ drush node-access-rebuild-progressive

  Approach

  The module works by processing nodes in chunks, from highest node.nid
  to lowest, until all nodes have been recomputed, storing the last
  processed nid in a variable (d7) / as state (d8). This ensure no nodes
  can be skipped, while avoiding having to populate a Queue or other
  equivalent mechanism, which can be heavy in itself.


How to get page statistics with views? I need to do a lot of sort criteria based on the number of profile pages viewed in Views , but I do not have any fields related to statistics and I cannot find any module which would help me to add fields to Views displays. Is there any module that would do the job or what do I have to do to get statistics about certain pages?

Someone said to alter the view query but how do I know in which table and what reference is between that table and the page that I want the statistics for?

For this you have to enable the Statistics module which is provided by  Drupal Core.
Follow these steps :
1. First enable Statistics Module
2. Then make a view and add a field provided by Statistics module. It basically provides three options:

Most recent view
Total Views
Views today

and then use Total Views as mentioned in your requirement.


Trouble with maximum registrants for RNG I've tried to create an event with a maximum of 5 registrants and a maximum of 5 registrations to limit my tests on these modules. I was unable to limit the number of registrants to 5 when users can create multiple people registrations for an event.

Could you explain how to set an event with authenticated users able to register several other users without going out of the maximum registrant? I've already tried to set the Conflicts on Maximum registrants without success.

The current minimum and maximum registrant fields as found in RNG 1.5 are per registration.

Perhaps you are looking for maximum registrants per event?


What is the good way to pass a value from form creation function to its submit handler? I am newbie in Drupal, I have a query that i want to pass some value from form creation function to its submit handler.

Right now, I am saving that value in a form element of hidden type.

$form['product_nid'] = array(
 '#type' => 'hidden',
 '#value' => 12,
)

But this is not safe, anyone can change value on client side.

It is easy to do by using $form_state['storage'],

Just define $form_state['storage']['something'] = ;
This value will not show in browser and You will get this value in submit handler. see this code you will understand.

/**
 * Returns the form.
 */
function my_module_form() {
  return drupal_get_form('my_module_my_form');
}

/**
 * Returns the render array for the form.
 */
function my_module_my_form($form_state) {

  $form_state['storage']['product_nid'] = 12;

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

/**
 * Add a submit handler/function to the form.
 *
 * This will add a completion message to the screen when the
 * form successfully processes
 */
function my_module_my_form_submit($form, &$form_state) {
  $product_nid = $form_state['storage']['product_nid'];
}


How to add UniqueField constraint on integer field? The title basically says it all. I have the following field definition in an Entity class:

$fields['code'] = BaseFieldDefinition::create('integer')
        ->setLabel(t('unique code'))
        ->setDescription(t('Some unique code'))
        ->addConstraint('UniqueField')
        ->setTranslatable(false)
        ->setRequired(true)
        ->setDisplayOptions('view', array(
            'label' => 'above',
            'weight' => 4,
        ))
        ->setDisplayOptions('form', array(
            'weight' => 4,
        ))
        ->setDisplayConfigurable('form', true)
        ->setDisplayConfigurable('view', true);

Creating a new entity in the UI works as expected as long as I do not set the code value to something already in the database. However, as soon as I try to create a new entity with an already existing value for code (thus triggering a constraint violation), I get the following error:

The website encountered an unexpected error. Please try again later.
TypeError: Argument 1 passed to Drupal\Core\Form\FormState::setError() must be of the type array, null given, called in /var/www/html/web/core/lib/Drupal/Core/Field/WidgetBase.php on line 454 in Drupal\Core\Form\FormState->setError() (line 1156 of core/lib/Drupal/Core/Form/FormState.php).

If I change the field definition to use a string instead everything works as expected:

$fields['code'] = BaseFieldDefinition::create('string')
        ->setLabel(t('unique code'))
        ->setDescription(t('Some unique code'))
        ->setSetting('max_length', 5)
        ->addConstraint('UniqueField')
        ->setTranslatable(false)
        ->setRequired(true)
        ->setDisplayOptions('view', array(
            'label' => 'above',
            'weight' => 4,
        ))
        ->setDisplayOptions('form', array(
            'weight' => 4,
        ))
        ->setDisplayConfigurable('form', true)
        ->setDisplayConfigurable('view', true);

So the question is how do I add a unique constraint for an integer field? Is there another validation class I can use, am I setting up my integer field definition wrong thus causing the error, or?

This seems to be an open bug in core. I have filed a bug report containing a makeshift solution on Drupal.org: https://www.drupal.org/node/2784015/

Edit the file 'core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/NumberWidget.php' to let the errorElement function return $element[0]['value'] instead of $element['value']. So far, I don't understand why it is happening.


Is there a way to see what fields are used in Rules? There is an field list overview in the reports for Views that shows the fields used.

Here is a sample of it:

Is there a quick way to find out which fields are used with Rules? It would be enough to check if a certain field is used by Rules.

SOLUTION:

As I don't have a special SQL tool drush works too by entering a query similar to what's included in the accepted answer:

drush sqlq "SELECT id,plugin,active,name,label FROM rules_config WHERE data LIKE '%points_dec%'"

Consider a rule as in this (random) sample (in Rules export format):

{ "rules_new_node_with_special_optionlist_value" : {
    "LABEL" : "New node with special optionlist value",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "C" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A new node got created with option list value =  \u0022[node:field-optionlist]\u0022" } }
    ]
  }
}

Obviously, the above rule uses a field with machine name field_optionlist.

Execute an SQL query on the Drupal database which looks like so:

SELECT id,plugin,active,name,label
FROM `rules_config`
WHERE `data` LIKE '%optionlist%'
LIMIT 3

The results I get by using this query (limited to the first 3 results only) looks like so:

id  plugin         active  name                                           label

20  reaction rule  0       rules_verify_updates_to_node_properties        Verify updates to node properties
21  reaction rule  0       rules_new_node_with_special_optionlist_value   New node with special optionlist value
28  rule           1       rules_set_an_initial_value_for_a_text_field    Set an initial value for a text field

Obviously, the result with id=21 matches with my (random) sample rule.

To execute the above query, you can use whatever SQL query tool, such as PhpMyAdmin. Or if you rather want to have a site building tool, just use the Forena module (disclosure: I'm a co-maintainer). After you enable this module, these are the steps required to find the answer to your question:

Use relative link /admin/structure/forena/data/add (= Create New SQL Query).
Select a "Data source" in which the SQL statement (= data block) will be stored (saved).
Enter the above SQL statement, and use the Test Changes button (to prototype your SQL).
Voilà, there is the (prototyping) result.

The above should answer the "It would be enough to check if a certain field is used by Rules" part of your question, but if you want to further improve this prototype, use the power of Forena to build a custom report from it, and make all sort of magic happen, eg:

export it to a CSV.
eMail it to somewhere.
...

Note: the above approach works for all sorts of "Rules queries" ... after all, in the above query I used (part of) the machine name of some field (= optionlist). Do an educated guess what kind of results you get if you would use the machine name of:

a content type, e.g: article.
a rules component, e.g: rules_send_email_notification.
a module that some rule(s) depend on, e.g: webform_rules.


When adding a relationship to the author, I'm unable to see any custom field I'm trying to get the username of a blog last poster; I created a view that shows the blog's fields. If I click on "Add field" I can see all custom fields. However, when I add a relationship for Author, I now loose all custom content fields including any author-related fields. The only fields available are the ones like "Content: Nid" and "Content: Path."

Can anyone help me understand what is going on? I've tried everything and it's now day 2 hung up on this. Is Views broken?

Ideally it should work... Please find exported view below which displays Author Name of last blog post.. You can able to add more fields to the same view..

$view = new view();
$view->name = 'blog_last_poster';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Blog Last Poster';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Blog Last Poster';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'blog' => 'blog',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');


How to get new migrations to show up in the Migrate UI My question is a general one: how do you get new migrations, which you've created via a custom module using Migrate, to show up in the Migrate UI at /admin/content/migrate ? What lines of code are necessary in your custom module for this?

Specifically, I'd like to know what's missing from a particular custom module (called ea_hub_migrations.module) that I've created. I created this by cutting down the migrate_example module, but after enabling ea_hub_migrations.module the migration group it defines isn't showing at /admin/content/migrate . By contrast, the migration I created with the module at https://drupal.org/node/1285276 does show up there. Here is the code for my custom module - I'd be very grateful if someone could take a look and tell me what's missing:

ea_hub_migrations.migrate.inc (included via ea_hub_migrations.info) - http://pastebin.com/KWMHd3gx

First, the function *_migrate_api() in *.migrate.inc should include the $api with the key api of 2, and the key migrations of the array for your migration.

If you have newly added your migration, drastically changing the code etc, you perhaps need to make Drupal recognise the hook you have just created in your migration module; a guaranteed way for that is to disable once and (re)enable your migration module.

Then you need register your migration.  If you use Drush,

drush migrate-register --group=YourMigrationGroupName

would do a job.  After Flusing all caches (drush cc all etc), you will see the migration in your migration UI (hopefully!).

I am not an expert, but the above is based on my recent experiences.


How to create a drop-down block? I created a view block to display my content in a boostrap grid.

My question is simple:

How to create a "Header" in my view to create an "Accordion" link and display My content when I click on it?

I want to display on the link "Accordion", the number of elements of the view

I would like to do like this page, but with the contents of my view instead of the text :

https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_collapsible_accordion&stacked=h

I think the Ajax Docs gives a pretty good example. Here are the pseudo steps:

You render your view block with 5 elements with "read more" submit as a form. The wrapper is is "my-ajax-block".
Clicking on the submit will create an ajax call (with help of built in ajax mechanism of Drupal).
You will make a call for all the items you need (50 pieces in your case), hopefully with the same service you provide the 5 one.
And you just send back the ajax response which will override the "my-ajax-block" with the fetched content.


404 page not found error even though the page exists On my Drupal 7 website, I'm getting a 404 page not found error on the front page: http://mydomain.com even though I can view the page just fine. Google Webmaster tools wouldn't validate my site; w3 website validator stops with 404 error.

I looked at my error logs in the database, and noticed that this is coming from node/1 which doesn't exist anymore. I set my home page to a different node, node/133.

This doesn't make sense to me. Either a page exists or it doesn't!

I finally resolved this after a lot of hair-pulling and gnashing of teeth by adding a URL alias from node/133 to node/1. Google Webtools now validates, and do does w3 link validator.

I discovered the solution by looking in the error logs:
 - admin/reports/page-not-found

I noticed that the specific page throwing the error was node/1 . Neither google Webmaster Tools, nor the validator helped as they reported only the 404 on the main domain name.


8 - How do I load a Term entity from an EntityReferenceItem? I have a content type with a taxonomy term. I can load the first EntityReferenceItem using

$node->country->get(0)

then I can tid doing ->target_id (and then manually load the Term object via Term::load.

But is there a function of EntityReferenceItem that I can call to get it to load the corresponding term? I'm thinking something like:

  $node->country->get(0)->getReferenced()

I don't see anything at the Drupal API reference

$node->country->entity.

See http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet, where it lists the properties of common field types.

If you want to see the properties of a field type, one way to do that is by looking at the propertyDefinitions() method of the field type class, in this case EntityReferenceItem.


Where to a place a custom php file in the directory I have a hard coded form that i need to send to a php page that i have built. With drupal i am a bit confused on where i would place this php page so it doesnt cause any problems.

I was thinking here but i wanted to check first.
/httpdocs/newsite/PHP-HERE
(Same directory as index.php)

Where would i place this php page?

Everything including forms can be integrated nicely within drupal. i would recommend reviewing FAPI. it will save you time/effort in the end.

however, if you absolutely need this not to be built around/within/whatever using drupal's FAPI, what i would do is put the page either directly in your theme folder or make a subfolder and drop it in there. so lets make many assumptions here (awful i know). say your form is called newform.php. rename it to page-newform.tpl.php and drop it into one of those folders. create a page just to give you a node place holder and a path like /newform. then in your template.php file under the THEMENAME_preprocess_page() function, check the URL with either $_GET['q'] or arg() (arg is preferred). if the url is going to /newform simply adjust your $variables['template_file'] to be something like $variables['template_file'] = 'page-newform'. this will pick up your page specifically.

so with a lot of assumptions and very little go on with what you are doing. this could be done.

function themename_preprocess_page(&$variables, $hook) {
 if (arg(0) == 'newform') {
   $variables['template_file'] = 'page-newform'
 }
}


What is the form id used in user profile edit form? I'm trying to alter some fields in the user profile form but I'm not sure why the form_id user-form is not working.

What I'm trying to achieve is to bring back the REQUIRED status of the password field which I turned off in user register form.

//USER REGISTER FORM
function MYMODULE_form_user_register_form_alter(&$form, &$form_state,
$form_id) {
$userID = \Drupal::currentUser();
$userRole = $userID->getRoles();
if($userRole[1] == 'ROLETOCATCH'){
$form['account']['pass']['#required'] = FALSE;
$form['account']['mail']['#required'] = TRUE;
$form['account']['roles']['campaign_manager']['#default_value'] =  TRUE;
$form['account']['notify']['#default_value'] = TRUE;
}
}

//USER FORM UPDATE
function MYMODULE_form_user_form_form_alter(&$form, &$form_state,
$form_id) {
    kint('hello');
}

To override the user form (when editing user profile) you can use hook_form_alter with user_form id.

On the following example code the current_pass is required so anyone making changes will need to enter it.  Also we assume that any administrator would not be forced to enter the password.

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  $user = \Drupal::currentUser()->getRoles();
  //admin's probably should not be forced to enter password
  if(!in_array("administrator", $user) && $form_id == 'user_form') {
    //$form['account']['pass']['#required'] = TRUE;
    $form['account']['current_pass']['#required'] = TRUE;
  }
}

The user register form can be overriden with either one

function MODULENAME_form_user_register_form_alter(&$form, &$form_state, $form_id) {
   //
}

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "user_register_form"){
    //
  }
}

The module has to be enabled and/or the cache should be rebuild for the system to see those functions


How to use custom code to change the node form layout and group fields while maintaining values? I am trying to alter the node form layout in a form alter hook.

I altered the node form and added a field set in which I grouped couple of existing fields into a fieldset. Then hid the existing fields so that they don't show up twice:in the fieldset and standalone.

However, after changing the structure, the field content are not being saved on submission. I thought this is due to drupal internal validation. So I thought I would use a validation hook to map the new fields structure  to their existing (hidden fields). But I am facing couple of issues:

can't retrieve the values in the validation function using $formstate->getValue().
Changing the structure causing the fields to not be processed correctly.

    // Group 2 fields: 1 date field and another text field in custom group
    $form['custom_group'] = [
      '#tree' => TRUE,
      '#type' => 'details',
      '#title' => t('Custom Group'),
      '#weight' => 19,
      '#collapsible' => TRUE,
      'existing_field_1' => $form['existing_field_1'], // is a date field
      'existing_field_2' => $form['existing_field_2'],
    ];
    // Hide the original fields.
    $form['existing_field_1']['#access'] = FALSE;
    $form['existing_field_2']['#access'] = FALSE;

    // Add our validation to try to force the values to be saved:
    $form['#validate'][] = 'my_module_form_node_form_validate';
    // make my validation first but probably unnecessary:
    $form['#validate'] = array_reverse($form['#validate']);

And in the validation function:

function my_module_form_node_form_validate($form, $form_state) {
  // grab the field values:
  $my_values = $form_state->getValue('custom_group')
}

But I cannot access them this way.

After digging into the issue I was able to access the values:

    function my_module_form_node_form_validate($form, $form_state) {
      $values = $form_state->getUserInput();
      $form_state->setValue('existing_field_1', $values['custom_group']['existing_field_1'];
    }

However issue #2 remains.
For example, ->getUserInput(); is returning the raw value of the existing_field_1 which has type date. And the value is just a raw string instead of the normal DateTime object.  So it's failing validation. To clarify ->getUserInput() returns raw string as expected 01-01-2019 and not valid datetime. So I end up with datetime validation error.

I could do the processing myself but that would be an overkill. So, in short, is it possible to use an alter hook two group fields (date/text/esle) into a field set and let drupal process the values?

$form_state is an object, not an array. You should be able to get the values like $my_value = $form_state->getValue('custom_group'). Or get all values like $values = $form_state->getValues().

See: Introduction to Form API


jQuery only works if I hard code it into the html.tpl.php Running into this issue where my custom jQuery code only works in my drupal theme if I end up adding <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> in the <head> tag of the html.tpl.php file.
I tried all the other ways via template, info and still none of them work other then doing this.
Suggestions?
Thanks,
.-C

Drupal core ships with jQuery. You can check the version in your <drupal_install_directory>/misc/jquery.js file. If you want to use the later version of the library, you need to install the jQuery Update module.

  Upgrades the version of jQuery in Drupal core to a newer version of jQuery.
  Updates...

  Drupal 5 to jQuery 1.2.6
  Drupal 6 to jQuery 1.3.2
  Drupal 7 to jQuery 1.5.2/1.7.1/1.8.2, and jQuery UI 1.8.11


Change Sent By in Drupal 6 Webform Module? Is there a way to make it appear the email is coming from the person who submitted it, instead of the site it resides on? The webform has an email field, and I'd like to use that as the source of the email.

Depending on the Webform version, you can accomplish this  in one of two ways:

Webform 2

When you edit the webform, look under Webform mail settings for E-mail from address. As long as you have an email field attached to the webform, you can select that field under the Component option.

Webform 3

Click on the E-mails task underneath the Webform tab when viewing a webform node. Within the E-mail header details fieldset, you'll see an option to change the E-mail from address.

The one caveat: Drupal sets the Sender:, Errors-To:, and Return-Path: headers to the site's email address. You can, however, change these headers using hook_mail_alter().

If you wanted to make sure the email field is set to user's email address (for a logged in user), you should've noticed the User email as default checkbox in the email field's settings, which will accomplish this and will work with the setting I mentioned above.


Problem with installing a module I need to import a new config without some files because when I try to install the profile module it says that profile.type.main, system.action.profile_delete_action, system.action.profile_publish_action, system.action.profile_unpublish_action already exists in the current config and this doesn't allow me to install that module

You can use Drupal console commands to delete the existings configs. New install will only be possible when the existing configs are deleted.
use Drupal config:delete active profile.type.main

If you dont have drupal console installed then deleting the configs from db is other work around for this issue.

Go to the config db table and delete the configs which are existing.

Thank you


Check the current page is a view Is there a way to determine if you are on a view page, similar to   \Drupal::request()->get('node') used to check if the current page is a node page?

I need to adjust breadcrumbs for view generated pages with hook_system_breadcrumb_alter().

You could use the name of the current route:

$current_route_name = \Drupal::service('current_route_match')->getRouteName();

The route names from views are built like this view.[view_name].[display_id].

You can list the existing routes with Drupal Console:

drupal router:debug


How can authenticated users of a site join a group implemented using Groups module? Pre-requisite knowledge:
I am using Group module to implement "Group" functionality on my drupal site similar to what Organic Groups module implements. I have a user role community-leader whose users have been granted the permission (under People > Permissions) - Technology : Create New Group so that they can create new groups of type Technology, but normal authenticated users have not been granted this permission so they cannot create groups.
Group module provides separate permissions on its configuration/overview page under Group Roles. These group roles are for users involved in a particular group. In my case, users who create the group (essentially of Community-leader role or a user-role with higher permissions) are assigned Group-leader role and then there is a Group-member role supposed to be assigned to users who will join the group created thereafter.
For these roles (both Group-leader and Group-member), permissions like Join Group, Request Group Membership, etc. are disabled (no checkbox available instead a 'x' sign is present). I believe this is because since a Group-leader created a group, he automatically joined the group and there is no meaning of these permissions for him.
Note: The above roles (both Group-leader and Group-member) are global group roles, not group-type specific roles.
Problem Statement
An authenticated user on my site is unable to access a particular group's page and thus has no way available to join the group. There is no granular(specific) permission available for this purpose.
Moreover, even Group-leader or Group-member role users cannot access groups other then their own group. How to allow that?
Could someone please guide me on Group Access Control for a better understanding?

Drupal 7

Download and activate Group.
Activate submodules Group add (gadd) and Group node (gnode).
Click on Group that now appears in your menu bar next to Content (/admin/group). This is the main overview for administering Group, here is where new functionality will appear when you activate more submodules.
Go to Group Types, in a tab on the page (/admin/group/type)
Add a group type, you only have to choose a name
Click "edit permissions" (/admin/group/type/manage/partner/permissions)
Activate suitable permissions. "Outsider" are logged in users that are not part of the group. Add at least view and add permissions for one content type for members, and "View group" permission.
Go back to the Groups start page (/admin/group)
Create a new group
Click on your group name, then click Add member
Add some members
Log in as one of those members, go to your account, click the Group tab, click on "view group"
Add some content

Now you have the basics of a group. Users, content, permissions and some ways to interact. Look through the rest of the tabs on all pages you visited, go into the detailed settings screens, activate more submodules, group roles, group permission etc. Extend using the group api hooks. Set up a suitable user interface using standard tools (views, VBO, rules, fields on the group).

For other settings you can visit following urls :

https://www.drupal.org/node/2711123
https://www.drupal.org/node/2711049
https://www.drupal.org/node/2711119
https://www.youtube.com/watch?v=w2Ol19OzNAQ

Drupal 8

Watch this video for a excellent and complete use-case configuration.

Hope this will clear all doubt.


multidomain, multilanguage, keep indicization, multiheadache I am trying to figure out how to migrate a website with multidomain and multilanguage settings, keeping SERPs.

PREFACE:
I have 17 website all identical, except language, in pure html. All 17 website got good SERP positions...
site.com
site.de
site.fr
site.ch
site.co.uk
site.pt
site.ca
...

PROBLEM:

I have installed drupal, create the template and fill up the CMS with all content necessary. I have used the i18n module to translate the website. Basically I have one node for each content.

node/1 ABOUT US
node/2 QUI SOMMES NOUS
node/3 CHI SIAMO
node/4 QUIENES SOMOS

They are linked so when I click on the languageflag the content change based on the languauge:
site.com/fr/qui-somme-nous.html
site.com/en/about-us.html
site.com/es/quienes-somos.html
site.com/it/chi-siamo.html

The old web pages are structured like this:

site.fr/qui-somme-nous.html
site.co.uk/about-us.html
site.es/quienes-somos.html
site.it/chi-siamo.html

and now the source of enormous headache...

How can i set up drupal in order to got on the same drupal installation the different topdomain and different multilanguage content, keeping the search engine position?

Hoping to have enough explain my situation.

Cheers

One way to would be to build this with domain access use a different domain for each language to meet your criteria. Repoint the old urls to the new ones.

Another way would be by indicating the language in the url.  Read more about it here: http://indico.cern.ch/event/216222/contribution/10/attachments/345315/481614/multilingual-training.pdf Start at page 37.

Probably a few other ways.


Drush Core Update Failed in Docker I'm running a local dev Drupal 8 install in Docker using the Docker4Drupal project. I tried to run drush up to update my core from Drupal 8.2.4 to Drupal 8.2.6 and got the following errors:

rmdir(/var/www/html/aadlorg/drupal-8.2.6/core/lib): Directory not empty filesystem.inc:150                [warning]
Destination directory /var/www/html/aadlorg/drupal-8.2.6 already exists.                                    [error]
Updating project drupal failed. Attempting to roll back to previously installed version.                    [error]
rmdir(/var/www/html/aadlorg/drupal-8.2.6/core/modules): Directory not empty filesystem.inc:150            [warning]
Destination directory /var/www/html/aadlorg/drupal-8.2.6 already exists.                                    [error]
Unable to move /home/www-data/drush-backups/drupal/20170303142739/drupal to                                 [error]
/var/www/html/aadlorg/drupal-8.2.6.
Could not restore backup and rollback from failed upgrade. You will need to resolve manually.               [error]
Backups were restored successfully.                                                                            [ok]
Backups were restored successfully.                                                                            [ok]
require_once(/var/www/html/aadlorg/core/includes/errors.inc): failed to open stream: No such file or      [warning]
directory bootstrap.inc:562
[03-Mar-2017 14:32:40 UTC] PHP Fatal error:  require_once(): Failed opening required '/var/www/html/aadlorg/core/includes/errors.inc' (include_path='.:') in /var/www/html/aadlorg/core/includes/bootstrap.inc on line 562
Fatal error: require_once(): Failed opening required '/var/www/html/aadlorg/core/includes/errors.inc' (include_path='.:') in /var/www/html/aadlorg/core/includes/bootstrap.inc on line 562
Drush command terminated abnormally due to an unrecoverable error.                                          [error]
Error: require_once(): Failed opening required '/var/www/html/aadlorg/core/includes/errors.inc'
(include_path='.:') in /var/www/html/aadlorg/core/includes/bootstrap.inc, line 562

Now my Drupal install is totally broken:

Warning: require_once(autoload.php): failed to open stream: No such file or directory in /var/www/html/aadlorg/index.php on line 14

Fatal error: require_once(): Failed opening required 'autoload.php' (include_path='.:') in /var/www/html/aadlorg/index.php on line 14

I'm logged into the container as the www-data user and all the directories are owned by that user. So did I do something wrong? Should I try to run drush as root? Just not use drush to update core?

Try using 2.0 version of docker4drupal, in the new version drush installed globally for www-data user to avoid potentials problems with permissions.


Drush and database credentials from external sources For some specific automation reasons, I use the following snippet in settings.php rather than defining db credentials directly in it.

$databases = array(
  'default' => array(
    'default' => array(
      'database' => $_SERVER['DB_NAME'],
      'username' => ini_get('mysql.default_user'),
      'password' => ini_get('mysql.default_password'),
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

And when I try to use drush, it won't pick up database credentials. How can I give the right database credentials to Drush? Can I define something in drushrc files per project?

The following is what I get from drush status.

  Drupal version         :  7.22
      Site URI               :  http://default
      Database driver        :  mysql
      Database hostname      :  localhost
      Database username      :
      Database name:
      Default theme          :  garland
      Administration theme   :  garland
      PHP configuration      :  /etc/php5/cli/php.ini
      Drush version          :  5.4
      Drush configuration    :
      Drupal root            :  /home/oep/www/dev/docroot
      Site path              :  sites/default
      File directory path    :  sites/default/files

As you can see, drush is run from command line interface, so it uses cli/php.ini and not regular one. If you feel like keeping password and username in ini file, you need to make sure there are synchronized between WWW and CLI php.ini files.


How to add db_select condition by using two concatenated fields? So I have users with a field_first_name and a field_last_name and I need my query condition to be something like:

"field_first_name + ' ' + field_last_name LIKE :q".

Currently I have:

->condition(db_or()->condition('fn.field_first_name_value', $q, 'like')->condition('ln.field_last_name_value', $q, 'like'))

so if first name is "John" and last name is "Smith" and I search for "John S" I get nothing because it doesnt match the first OR last name, I need to check if it matches the firstname + the last name.

How do I do this in Drupal 7?

You can try something like the following. You build the name with a small sql expression and then can use it within the where clause.

$select = db_select('people_table', 'p');
$select->addField('id');
$select->addExpression("CONCAT(p.first_name, ' ', p.last_name)", 'full_name');
$select->condition('p.full_name', $some_name, 'LIKE');
$results = $select->execute();


What is the fastest/simplest way to add/manipulate PHP on a page? As a PHP developer familiar with MVC frameworks, I am having some difficulty figuring out Drupal.

I like the block setup. I am looking for some simple step-by-step guide to:

Add a block with my own PHP code.
Alter the html/php of other blocks.

Failing that, I would like to see some code which does these things.

Here is what I've been trying to do, more specifically:

There is a button. When it is clicked a DB query is executed.
Hide the "create new account" link on the login dialog. No account for you!

You are in fact asking four questions here.

As jhedstrom said, you need to use the hook_block_info() / hook_block_view() hooks. A quick google search pointed to to this example: http://www.summasolutions.net/blogposts/how-create-basic-block-code-new-drupal-7
You can use the hook_block_view_alter() or hook_block_view_MODULE_DELTA_alter() hooks.
You can find detailed information about how to create a form in drupal in the quickstart guide. Note that this is for Drupal 6 but works the same way in Drupal 7 for the most part.
This does not require any code at all. In fact, doing this with code is doing it the wrong way. Instead, you can disable account registrations by visitors at Configuration > Account settings, set "Who can register accounts?" to Administrators only.


How do I use form_set_error() the right way? In my Drupal 7 module, I have a form and its validation handlers. I call my form from a field.tpl.php with print render(drupal_get_form('my_form')); it works as expected.

The problem is in case of wrong input value.

It requires two incorrect submissions before displaying the error message: The first time, there is red border around my wrong input, and the second time, the error message is displayed (with the red border).

So, what's the right way to use form_set_error()?

You should be looking at form_set_error instead

if you have an element like this:

function my_custom_module_form() {
  $form = array();
  $form['my_element'] = array(
    '#type' => 'textfield',
    '#title' => 'My Text field',
    '#default_value' => 'Some default text.',
  );
  return $form;
}

in your validation callback function do this if you find that the values in $form_state['values'] aren't valid

function my_custom_module_form_validate($form, &$form_state) {
  // Do some checking on $form_state['values'], if you don't like it.
  form_set_error('my_element', 'This is the error message that will be displayed.');
}


Does Commerce Kickstart distribution include "advanced search" capabilities? By default the Commerce Kickstart distribution include a Search block. Just wondering if this distribution include a feature to add advanced search capabilities.

The advanced search would allow the user to filter by taxonomies terms.

Commerce kickstart includes the commerce search API module. http://drupal.org/project/commerce_search_api

Automatically created Search API db server, if none is found.
Auto-generated search index that includes all product display node types* and related product data.
Auto-generated facets for all node type categories and product attributes.
Optional integration with Search API Ranges (allowing for a price slider, for example).
Search API Filter class for product display node types* (allowing for an index composed only of product displays)
Facet API Filter class for removing facet items that do not change search results.
Facet API Filter class for hiding certain facets on the initial search (so that product attribute facets are only shown after the initial search, for example).


prompt in IE8 for secure pages produces altered layout My Drupal 7 website looks fine in most browsers, but in IE8 I am getting the prompt:

    "Do you want to view only the webpage content that was delivered securely? This webpage contains content that will not be delivered using a secure HTTPS connection, which could compromise the security of the entire webpage."

Then a "Yes" or "No"

If the person selects "yes" they are presented with MOST of the page, but odd things like the sidebar CSS and body content don't display properly. Is this an issue with securepages module or something else? Initially I had secure pages turned off because I moved from a dev server (without SSL) to production. But even after turning it on, I get this message. I have:

Cleared the cache
Run the security review module (passes on all
points)
Ensured the core and all modules are up to date.

Also, I have the following lines in my settings.php file:

$base_url = 'https://my-website-here.org';

and

$conf['404_fast_paths_exclude'] = '/\/(?:styles)\//';
$conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpe? g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';
$conf['404_fast_html'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa-1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"><title>404 Not Found</title>
Not Found

The requested URL "@path" was not found on this server.
';

Also, could jquery menu or Client-side adaptive image be causing a problem? The context module? These were all additions from the previous site that ran fine.

Any help appreciated!

The message you're getting in IE 8 is due to the fact that you're viewing your site through HTTPS, but some of your site's assets / resources are still being loaded through HTTP. If you look at the site in Chrome, you'll notice an icon to the right of the address bar which indicates the same warning about insecure content.

I would recommend going through all your templates / custom modules to make sure that any JS, CSS and iFrames (hope you have none of those heh) are all being served via HTTPs and not HTTP. Once nothing is being served via regular HTTP you shouldn't get that message anymore.

Hope this helps!


Manually Send Ajax request to a PHP file It seems that the Drupal Ajax  API are comming a little un handy for my current project so i was trying to do the ajax request the good old way with actual Javascript.

I have this code

valdBut.click(function(event){
    event.preventDefault();

            jQuery.ajax({
            type: "POST",
            dataType: 'json',
            data: grabValue(),
            url: urkl,
            success: function () {

                alert(back)

            }
        });
    alert(grabValue())

})

What i am wondering is how should i link that URL value to my module page, so that my user_login hook receive the data sent via Ajax ?

Thanks for any help,
Manu

For most functionality that you require with drupal, there is typically a module that already does what you are after or close to it.

I would recommend either:

using the module http://drupal.org/project/ajax_register
or looking at the code for the above module and make one that suits your exact needs

Hope this helps


Why doesn't hook_preprocess_node() get triggered? I use the following code in a theme whose machine name is yokai.

// works like expected, output visible
function yokai_preprocess_html(&$variables) {
  dpm('yokai_preprocess_html');
  dpm($variables);
}

// does not work, no output visible
function yokai_preprocess_node(&$variables) {
  dpm('yokai_preprocess_node');
  dpm($variables);
}

Why doesn't hook_preprocess_node() get triggered?

The problem is with dpm(). This uses drupal_set_message(), which uses the session variable to store messages:

function dpm($input, $name = NULL, $type = 'status') {
  if (\Drupal::currentUser()->hasPermission('access devel information')) {
    $export = kprint_r($input, TRUE, $name);
    drupal_set_message($export, $type, TRUE);
  }
  return $input;
}

When the node template is processed, the page is already built with the session variables at this point. Any messages that come later will not make it on the page. In this case better use kint(). dpm() is more usefull for debugging code that doesn't produce a page output, like form validation.


Views exposed filter error "An illegal choice has been detected. Please contact the site administrator." I am having a very odd problem with an exposed filter in one of my Views. The page I am talking about is here: http://epsindustry.org/eps-packaging-map2

When I select one of the last 2 options in the menu (EPS Packaging Recyclers or Loose Fill Recycling Drop-off) I get an error that says An illegal choice has been detected. Please contact the site administrator. This is really weird to me because it only happens with these 2 options. I don't believe they are set up any differently than the other taxonomy terms. There's nothing all that special about them, its just a term that the admin selects when creating a location for the map.

Any ideas as to why this is happening or how to fix it?

I was having the same issue. In my case the 'illegal choice' message was displayed when changing the country from 'United States' (the default value) to 'United Kingdom' and selecting 'North Yorkshire' as state/province and saving.

I did the following to fix it:

Go to the Configure page of the Location field (by editing the node type and going to 'Manage fields').
In the 'Events settings' section (not the 'Locative information' section), there is a drop down group called 'Default value'. I set 'Country' to United Kingdom.
Save field settings.
Done.

Using:

Drupal 6.28
MySQL 5.1.72
PHP 5.3.3.7+squeeze17
Location: 6.x-3.3-rc3+6-dev (2013-Oct-25)
GMap Location: 6.x-2.0-beta5+1-dev (2013-Sep-30)

Hope it helps.


Drupal Commerce products sales limited by date I'm building a foodhub site using Commerce. A foodhub works by having a collection day every week, so sales of products need to be attached to one of the collection days, such that what the consumer bought will be available on the day they selected (typically the next upcoming day). At a certain time, e.g. 24 hours before, sales for the next collection day should be disabled.

I am wondering how I can approach this using Commerce, or a with a Commerce extension.

I'm thinking one approach would be to create a "collection day" content type that would show all the products that have been purchased and added to that day. A number of collection day nodes could be created defining upcoming days. A field on a product would show which collection day it will be added to.  This would show the next upcoming day but can be changed (I need to figure this part out).

Is this a good approach, or is there a better way to tackle this problem?

What you can certainly do is proceed as you've outlined it and then create a view of all products that don't have their collection day within the next 24 hours. This will display all the products that can be bought in time for your collection preparations.

Approach 2: Set up a rule that checks after an order has been saved or before payment is done whether there is any product that has its collection day within the next 24 hours and if so, display an error message and set the number of these products in the cart to 0.

Approach 3: Set up a rule that runs periodically (say every day) and loops through all the products and disables those that have their collection day within the next 24 hours.

If you want more detailed information on how to achieve any of these, comment.


How to select a random user from a list of users that have flagged a content? I'm trying to make some kind of contest site, in which users can publish random old stuff, which will be raffled later between the users that have marked that content.
I crated a specific content type for this, let's call it "kiwi", with a winner field.
Then created a flag for that content, so, every content created has the button saying "I want this", when you click, you are kind of "subscribed" to that content.
I want to create a rule, which chooses a random user from the list of user that have flagged the content.

I've been struggling with this for a lot of time, I don't have any more ideas on how to solve this.

Thank you very much

Well I finally did it. The modules used were:

Rules
Flags
Views
Views rules (This one was the key, allows to execute a view inside a rule, even as loops.)

Two thins were done, first, a component which would be executed every hour, and second, inside that component, every hour, a winner would be chosen for every content that had a contest date matching the hour.

Creating scheduled component

Create a rule set component, which receives a parameter of type date.

Add a rule action schedule component evaluation, in this component created, and set as the value, the component you are editing, this will program this component to be executed one hour after it is executed.
Save everything, and go to Settings > Rules > Components and press "execute", with the value "now".
Component now is being executed every hour.

Selecting random winner

Install all the modules listed above.
Create a simple component that receives a user, and a node as parameters, then add the conditions you need, and finally add an action which sets the winner field inside the node as the user given.
Create a view and add a "Rule" display, this will be like the first query.
Lets call it "Select content programmed for now", and filter it by a given date, then add the fields that will display, "nid" is the most important.
Change the section "edit field info", inside "Rules settings", setting the type of the output, choose "Node" type for the nid (this gives the reference to the node instead of a number).
Create another view, called "choose random winner", make it receive a "nid" and return the list of flagged user "uid", sort it with a global random criteria, and set max results with 1.
Repeat 4 for this view, but with "User" type.
Go to the component which executes every hour, add a view loop action in your rule.
Select the view that filters the content for the current date.
Add a view loop inside that loop, with the new rule.
Add an action containing the component created at the beginning with the parameters you now have available.


How to change (re-order) the deltas programmatically in node_presave In a node, I have a multi-value field "field_MV" containing 3 items

I don't think it is important, but field_MV  is of type "Entity reference revisions" and the items are paragraphs of only one type.

Each paragraph (item) have a field "field_quantity" containing a number.

Here is my exemple:

$node->field_MV[0]->field_quantity->value=5 (paragraph at delta 0)
$node->field_MV[1]->field_quantity->value=3 (paragraph at delta 1)
$node->field_MV[2]->field_quantity->value=7 (paragraph at delta 2)

In hook_node_presave, I would like to loop in the paragraphs to change their delta according the the value of field_quantity (descending)

Here is the result I would like to have:

$node->field_MV[0]->field_quantity->value=7 (previously paragraph delta 2)
$node->field_MV[1]->field_quantity->value=5 (previously paragraph delta 0)
$node->field_MV[2]->field_quantity->value=3 (previously paragraph delta 1)

My question is not how to order (I can handle this), but how to change the delta with something like:

$node->field_MV[0]->set("delta",1);
$node->field_MV[0]->save();

You would want to set the field value to an array in the order you want them. Since you are doing this inside hook_node_presave, you don't have to bother saving the node. It will be done for you.

Something like this should work:

$values = $node->get('field_mv')->getValue();

... your sorting function ...

$node->set('field_mv', $values);


How do I add an element to a fieldset? When creating a webform in version 5.18 each element had an option to include it in a selected fieldset.  Worked like a charm.
Now, on version 6.22 I cannot find this option anywhere.  I can't believe they've done away and my research only yields php code which user form creators are not going to use.
Can someone please advise where to find or what to add to bring this feature back?  One post I found elsewhere talks about an 'advanced' area but again, cannot find it anywhere.
Suggestions please?  Thank you.

In fact in Drupal 6 there is no need to select the parent from the drop box anymore: You drag your field under your fieldset and push it to its right.

As result, you get this.


drupal_set_title not setting $title variable I'm trying to use drupal_set_title() in my node.tpl.php but the text I'm setting the title to is only showing up in the $head_title (html.tpl.php) variable and not the $title variable. The $title variable is still set to the node's title.

This is in Drupal 7. I've used drupal_set_title() multiple times like this in Drupal 6 and it has worked perfectly.

Is this broken in D7?

This is how it is being used in node--news.tpl.php:

$actual_title = $title; // save for later use
drupal_set_title('News');

By the time you've hit node.tpl.php it's too late to set the title as $head_title has already been set in template_process_html() and the $head_title variable has already been output.

You'll need to use template_preprocess_node() or similar to set your title as desired.


How to retrieve the link and description in a custom file field twig template I have a field field_file. I've created a template field--field_file.html.twig.

How can I access the link, description (and attributes and icon ) separately in this file?

I have:

{% for item in items %}
  {{ item.content }}
{% endfor %}

which just spits out themed content.

I've debugged with dump() and there seems like the possibility of at least retrieving the 'description' somehow, but item.description does not work, for example.

File link: {{ file_url(item.content['#file'].getFileUri()) }}

File description: {{ item.content['#description'] }}


Sorting in views not working for drupal commerce products In the product views of my drupal commerce site, I want to list the products sorted by amount(price).

The product has 4 categories. They are added as relationships in the view:

Now to sort them by price, I am doing the following:

This is working perfectly fine in another view where I am using Contextual filters(Product category).

But in this view, where I am displaying products of all categories, the sorting is not working.
What is happening in this case is:

First all the Poultry items are coming in sorted(by price) order.
Then all the Fish items in sorted(by price) order.
And so on.

What I want is :

All Items should be collectively sorted by price.

This isn't working as configured because you're using separate product reference fields per content type. This instructs the query to attempt a sort based on non-existent values for those rows where the content type does not have the expected reference field. To sort this View properly, you'd need the base table to be the Products and then some sort of a reverse reference to content referencing those products.


Triggering the Feed Import module I have a Drupal 7 website that is intend to be fed by a JSON file.
This file, is actually processed and updated by a ETL tool that runs periodically (each 3 hours by example).

Once my ETL tool has processed the output JSON file, I need a way to tell the Drupal Feeds module to start the import.

Is it possible ? Or do I need to do this with CRON ?

Ideally, this job would be trigged by a specific URL call (just like the CRON can be called manually by visiting a specific url).

Based on @Gaydabura clues, I've created a module.
Here's the answer :

1. use hook_menu to define you own path

function toot_menu() {
  $items = array();
  $items['toot/import'] = array(
    'page callback' => 'toot_callback',
    'title' => 'Import tool',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

2. write function using docs to parse your data

function toot_callback($key = '') {
  if ($key != 'defined_key') {
    return t('Unauthorized access');
  }
  else {
    $myFeed = feeds_source('feed_unique_id');
    while (FEEDS_BATCH_COMPLETE != $myFeed->import());
    return t('Import successfull');
  }
}


How do I print a username of current profile? I am making a profile page for users on my site, and would like to print out their username. If I do print $user->name it will just print out the username of the currently logged in user, I want the username of the profile I am looking at.
Thanks.

It depends on how you build the profile page (which modules you use), but usually you will get the user info on profile templates by accessing $account, while $user is the logged in user.

So, in short, $account->name should be what you are after. Again, this depends on how you create the profile page. For a profile page built with Views, this would not help, but you could add the name in the View itself.


I cannot delete Devel generated content because I get an error about a not existing table I'm trying to delete some generated content but I get an unhandled exception in the log.

  Drupal\Core\Entity\EntityStorageException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'databasename.url_alias' doesn't exist: SELECT u.pid AS pid FROM {url_alias} u WHERE (source = :db_condition_placeholder_0) OR (source LIKE :db_condition_placeholder_1 ESCAPE '\'); Array ( [:db_condition_placeholder_0] => /node/178 [:db_condition_placeholder_1] => /node/178/% ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->delete() (line 794 of /var/www/html/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

The site is running on Drupal 8.8.0, and I installed the Pathauto module version 8.x-1.3.

How can I fix this issue?

Solved the issue by updating module Pathauto to 1.6 apparently the version I was using (1.3) had a compatibility issue with Drupal 8.8.0 on how path aliases are being handled now.


How feasible is a Drupal 8 with a different language depending on its subdomain So, let's say I have this massive content-heavy site with all sorts of paths like mysite.org/category/date/slug or mysite.org/someterm/subterm/date/slug. Let's say all this content is in English, and now I've gotten my hands on a Spanish version of all of my content. How feasible is it to integrate the Spanish content into the site, using the same installation, but only having the site show up in Spanish when people go to es.mysite.org, es.mysite.org/category, or es.mysite.org/someterm/subterm/date/slug.

How scalable is Drupal 8 in this regard? If we want to have several different language sites, potentially with different templates, would it be best to use different installations of Drupal 8 or does it facilitate this kind of set up I explained above so that one installation is perfectly logical?

Multilingual has seen a big improvement for Drupal 8. All you need can be done with Drupal 7, so it it's possible with Drupal 8 too.

You have to set Language Negotiation to subdomain. This way Drupal sets the content language depending on the domain accessed. For example, example.com/en/node/1 is English content and example.com/es/node/1 is Spanish content (you can also configure so no subdomains maps to a certain language).

Regarding performance Drupal 8 has a very good caching system that is much better than Drupal 7 (specially when we talk about cache invalidation).

What I don't recommend in any case is to have two separate Drupal installations one for each language. No benefits from this approach and lot of issues instead. Just think on content sync, user sync, config sync, etc. Drupal can manage two and much more languages without having performance issues.


Display average from a column? EDITED: This has been altered to include the code suggested by Dooshta.

I need to fill a computed field with the average value of all entries in a certain field, and only from nodes that have a specific node reference field.

What I have right now in my Computed Field is:

$nids = db_query('
  SELECT entity_id FROM {field_revision_field_venue_reference_review}
  WHERE field_venue_reference_review_target_id = :nid',
  array(':nid' => $entity->nid)
)->fetchCol();

$entity_field[0]['value'] = db_query('
   SELECT AVG(field_payment_review_value) FROM {field_data_field_payment_review}
   WHERE entity_id IN (:nids)',
   array(':nids' => $nids)
)->fetchField();

This is working, and displays the correct average from the correct nodes. However, I get a PODexception error on some pages that do not include the above code. This is confusing to me, because it seems that if there is bad syntax, then I should get the error on the page using the code as well as pages not using the code, right? Either that or it just shouldn't work.

As requested by Booshta, here are screenshots of the tables I'm querying.
The first is the table containing the entity reference field in the $nids part of the query

The second is the table containg the values being averaged in the $entity_field part of the query

I'm not familiar with the computed field module and not sure I completely understand the relationships between your nodes and fields, but here's about how you should be able to get things working.

The first query seems like it would be alright if you'd remove that extra closing bracket and used fetchField() to retrieve the value:

$entity_field[0]['value'] = db_query('
   SELECT AVG(field_payment_review_value) FROM {field_data_field_payment_review}
')->fetchField();

The second one needs some more work. I'm assuming that you have review nodes with the ratings and every review node is linked to a business node with a reference field of some sort.

First I would get the nid-s of those review nodes that are linked to the current business node as an array (using fetchCol()) with something like this:

$nids = db_query('
  SELECT entity_id FROM {field_data_field_business_reference}
  WHERE field_business_reference = :nid AND entity_type = :type AND bundle = :bundle',
  array(':nid' => $entity->nid, ':type' => 'node', ':bundle' => 'review')
)->fetchCol();

Then get the average:

$entity_field[0]['value'] = db_query('
   SELECT AVG(field_payment_review_value) FROM {field_data_field_payment_review}
   WHERE entity_id IN (:nids) AND entity_type = :type AND bundle = :bundle',
   array(':nids' => $nids, ':type' => 'node', ':bundle' => 'review')
)->fetchField();

UPDATE:

To avoid the error you're getting you can try wrapping the code inside some if statements to make sure it won't be executed when necessary criteria is not met:

$node = menu_get_object();
if (isset($node->type) && $node->type == 'venue') {
  // put the query that retrieves the nids here.
  if (is_array($nids) && !empty($nids)) {
    // put the query that calculates the average here.
  }
}

If that's too restrictive you might get away with just this much:

  // put the query that retrieves the nids here.
  if (is_array($nids) && !empty($nids)) {
    // put the query that calculates the average here.
  }


How do I get $view->the actual row number? How do I get the actual rows number in views-view-field--title.tpl.php in Drupal7 and views3?

I know how to get the total by

$view = views_get_current_view();
$view->total_rows;

But how do I get the actual row number? To print
1/4
2/4
3/4
4/4

user1090003 has the right answer.

  in views-view-fields.tpl.php or... you can have the row index like this $view->row_index

Further explanation:

In views-view-field--title.tpl.php (suggestion of views-view-fields.tpl.php), you already have the $view object available.   That view object has a property "row_index" that equals the current row number starting at zero.

Example of use:

    <?php print $view->row_index; ?>
    <?php print $output; ?>

Example results:

    0
    Node Title 1
    --
    1
    Node Title 2


Drupal 7, language changes back to EN after clicking on any link I have 8 languages on my website. When I visit the website with different language prefix such as mysite.com/da and scroll down to click on any link. The language prefix changes to EN in URL. For example mysite.com/en/about

Can anyone please help me on it?

Thanks
Saeed Afzal

in configuration, admin/config/regional/language/configure, modify language detection, the order there determinies wich language to use, it depends on how your languages are set, try moving on first place what you think how is confugured your site, set defalut value last. here are my settings on one site, your may be different.