How do I sort a date field in views without the time? Drupal 7

I have a view that sorts on three fields so the ORDER BY statement looks like:
ORDER BY

node_status ASC,
field_data_field_date_field_date_value DESC, field_data_field_sort_order_field_sort_order_value ASC

I need the sort of the date field to not be granular to the time. I just want it sorted by the date so that the sort order field will take it from there. When I run the query against the database itself, I see that the date field returned is showing the full value like: 2016-06-19 08:48:12, but some of the values are different by a second, causing the "incorrect" (not the desired) sort order.

How can I get it to sort on the date field without the "full date" field?

EDIT:
(adding screen shot of view)

you can change the granularity of the sort under the settings for the sort criteria:


Redirect all pages to a form unless the user has filled out some information (Drupal 7) I need to bring up some sort of dialog or form to collect user information when they first login. Is there anyway that the user can be redirected to a form that they must fill out before they can proceed when they first login?

I need to do this because we need to collect information from users who have already created accounts and will not have entered the information that we are adding to the user node.

EDIT: I really want to force the user to fill out this form if they have not, so what I am really looking for is a way to redirect all pages on the Drupal site to this form unless they have filled it out.

This should do it. although there might be a module that already does this as well.

https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook_user_login/7


Content organization for complex website I know this is a trivial question but before to continue I would like to hear some opinions from You experts. I am organizing my content in D7 website in two section "Activities" and "Our Projects". The "Activities" will have the bellow pattern:

activities/public-buildings/schools/project-1.

I've created a CCK for company projects (aka project-1,2,3 etc) However for each category I would like to have a landing page which will show its sub-directories. For example a landing page for "public-buildings" will include a text with images and also a list with "schools" etc. A landing page "schools" will include  a text with images and also a list with "projects".
Last, "Our Projects" section will again include projects. So the question is, which way should I proceed (taxonomy) or node reference or?

Taxonomy is the way designed just for this. You can override taxonomy term pages with Views, and in view settings you can easily add your own content. Or use any other approach. Nodereference feels awkward to me, but would work.

If you want to go taxonomy way, just do what feels natural for your kind of data. Make things as simple as possible, and not simpler! That said, if one tree is a subtree of another, yes, keep it as one hierarchical vocabulary. It makes sense and will allow you to filter more effectively in the future.


Setup existing drupal 6 site on local server so far I've worked with Drupal 7 sites and have no experience importing Drupal 6 site to local server, so maybe you could help. I have 2 folders and .sql database file.

First folder is named 'files' which has sub-folder 'design' which consist all files stored in site (css, images, js, models etc.).
Second folder is named 'sites' which has two sub-folders - 'themes', 'models' and settings.php file.

I'm using Acquia Dev Desktop 2. So far I've created new site and database importing .sql dump file. And have plain text entering the site. Where should I override these two folders and should I rename them? My project is called 'project.dd', should 'design' folder be called as project name?

Steps to setup a Drupal Site :

Place your Drupal 6 directory in your htdocs directory of xampp folder. All files and design folder should be at same place where they are on live version of site.
Open your settings.php, change the database credentials according to your local server.
Restore your database using phpmyadmin.
May be some image would not be shown up on site so you need to setup a domain in apache's vhost file.


Assigning permissions based on taxonomies I have a hierarchical taxonomy that looks like this:

School>Class>Project

That is you could have a project that is part of a certain class that is part of a certain school.  I would like to make it so that only students that are enrolled in a specific class can submit content to that class/project.  Also, I would like to have a semi-adminstrator role called teacher that can only enroll students into a class that they are administering but cannot enroll students into other classes.

I have found a depreciated module called taxonomy based permissions but it seems like it was abandoned after drupal 5 (I am using drupal 7).  Are there any new modules that might help me accomplish these goals?  If not, this problem seems a little bit outside of the intended functionality of taxonomies, I am wondering if I am using the wrong kind  of model for my site.  Any feedback on this though?

Organic Groups sounds like a better way to go in this situation. Each class is a group (can still categorize them using taxonomy), but will give you the sub-permissions you require per class (group) (e.g. teacher being able to enroll and administer their own group and students only being able to submit content in their own class)

OG enables users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.

They do so by posting the usual node types: blog, story, page, etc. A block is shown on the group home page which facilitates these posts. The block also provides summary information about the group.

Groups may be selective or not. Selective groups require approval in order to become a member, or even invitation -only groups. There are lots of preferences to configure groups as you need.


How can I filter nodes by term (entity reference) with jsonapi? My nodes contain an entity reference field, Ref Term.  I want to fetch a list of nodes that have a specific term with jsonapi.
In jsonapi, when I fetch nodes, the field with the taxonomy term reference is returned like this:
"field_ref_term": {
"type": "taxonomy_term--my_vocabulary",
"id": "b1a97358-9834-499d-aee0-ebb0302fb2c3"
},

So, first, I tried this:
/jsonapi/node/my_content_type?filter[field_ref_term]=f9c171db-1a1d-4d9a-bb55-5b0f8b033749

However, that gave me an error:
"title": "Bad Request",
"status": "400",
"detail": "Invalid nested filtering. The field `field_ref_term`, given in the path `field_ref_term` is incomplete, it must end with one of the following specifiers: `id`.",

So I tried adding [id]:
/jsonapi/node/my_content_type?filter[field_ref_term][id]=f9c171db-1a1d-4d9a-bb55-5b0f8b033749

That gave me a different error:
"detail": "You must provide a valid filter condition. Check that you have set the required keys for your filter.",

So I tried a longer version:
/jsonapi/node/my_content_type?&filter[term-filter][condition][path]=field_ref_term&filter[term-filter][condition][id]=f9c171db-1a1d-4d9a-bb55-5b0f8b033749

That gave me the first error again.  I read the documentation on filtering.
How can I filter my nodes based on which are tagged with a specific taxonomy term?  (In my case, each node has one and only one taxonomy term in its entity reference field.)

You were close, but your syntax was off. This is documented further down in your linked page, in the Filter Examples > Get nodes by a value of a entity reference section.
SHORT
filter[uid.id][value]=BB09E2CD-9487-44BC-B219-3DC03D6820CD

NORMAL
filter[author-filter][condition][path]=uid.id
filter[author-filter][condition][value]=BB09E2CD-9487-44BC-B219-3DC03D6820CD

So, in your example, you'd need to use:
SHORT
/jsonapi/node/my_content_type?filter[field_ref_term.id][value]=f9c171db-1a1d-4d9a-bb55-5b0f8b033749

LONG
/jsonapi/node/my_content_type?filter[term-filter][condition][path]=field_ref_term.id&filter[term-filter][condition][value]=f9c171db-1a1d-4d9a-bb55-5b0f8b033749


How to make custom content type as product in ubercart drupal 7? I want to make custom content types as ubercart products in drupal 7

Go to http://mysite.com/admin/store/products/classes
Enter the machine name of your content type in the 'Class ID' text field.
Enter a human-readable name for your new product class (and optional description)
Click save

Ubercart will now register the content type with the machine name that you added in the above steps as a product. Next time you add/edit content of that type you will see all of the Ubercart fields in the edit form.


Is 'file path' required in hook_menu()? I just started learning Drupal 7 Module development. In a tutorial I watched, the person said that

  "In hook_menu(), if we have a 'file' attribute then the 'file
  path' is a must and drupal wont work if it is not declared in drupal 7."

But when I read a book, it said that

  The 'file_path' is not required in drupal 7 provided that the file
  is present in the same directory.

As you can see, its a bit confusing. So my questions are

1) Is 'file path' required in Drupal 7 ?

2) When to use 'file path' ?

I've posted a snippet of the hook_menu implementation :

function modulename_menu() {
  $items['...'] = array(
    ....
    ....
    'file' => 'modulename.admin.inc',
    'file path' => drupal_get_path('module','modulename'),
  );
  return $items;
}

Note : Assume that the file is present in the same modules folder

The first sentence you quoted is wrong. "file path" is not a must, if you set "file"; in fact, by default Drupal will take its value is the directory containing the module implementing the menu. If you want to use a different directory, such as drupal_get_path('module', 'mymodule') . '/includes'), then you can set "file path."

_menu_router_build() contains the following code.

// Calculate out the file to be included for each callback, if any.
if ($item['file']) {
  $file_path = $item['file path'] ? $item['file path'] : drupal_get_path('module', $item['module']);
  $item['include file'] = $file_path . '/' . $item['file'];
}

$item['module'] is set by menu_router_build() using the following code.

  foreach (module_implements('menu') as $module) {
    $router_items = call_user_func($module . '_menu');
    if (isset($router_items) && is_array($router_items)) {
      foreach (array_keys($router_items) as $path) {
        $router_items[$path]['module'] = $module;
      }
      $callbacks = array_merge($callbacks, $router_items);
    }
  }

A module could implement hook_menu_alter() to alter $item['module'].


A large amount of Tokens slows down everything - Placeholder Tokens had anyone of you had a problem with too large amount of tokens? Because of having few content types (~8) with bunch of fields (~5-10 each) Token module generates too big table with replacement tokens. This is why I had to increase in settings.php available memory to avoid drupal from php error. I set 512M so it generates the output table now but it is so slow that it freezes Chrome.

It happens where I have this preview of available tokens. So it can be found in Pathauto or Custom Breadcrumbs.

This is how it looks like in Google Chrome HTML preview:

You can find some solutions for such a problem on Node references + Entity Tokens creates HUGE Token Tree UI table HTML.

Using the Token tweaks module also helps. I've tried and it works fine.

  Provides tweaks for tokens (mostly to improve performance)

  Disable token types or specific tokens.
  Modify the default depth limit for the token tree UI.


Override views_exposed_form I have a content type called Events. I would like to override the tpl file of exposed form in events listing.

I tried events_preprocess_views_exposed_form to add a template suggestion, I tried to add MYTHEME_preprocess_views_exposed_form to do the same thing, I tried simply to add views-exposed-form.tpl.php in my templates directory from MYTHEME directory but with no success.

From your question, I could understand that you're using views to show your events list with exposed filters and now you want to override the template of that exposed form.

To override the exposed form template for a particular view, you need to create a template in the following name pattern,

views-exposed-form--view_name.tpl.php

For example if your view name is event_list, then the overridden template will be views-exposed-form--event_list.tpl.php.

Once you added the template clear the cache, now view will use the overridden template for exposed form.

Take the views default exposed form template as base to theme your overridden template - Exposed form template

Note : To just override the template, you do not need any preprocess functions.


How can I print messages in a Panel layout template? Printing the drupal messages in page.tpl.php is easy:

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

How can I go about doing a similar thing in my Panel layouts?

Notes:

I realise there is 'status messages' pane you can use - I wish to avoid this since admin staff will forget to include it on new pages
I definitely wish to do it in the Panel template because there is a section above where the messages should display that is set by the admin staff
I have tried simply putting that code into mylayout.tpl.php, it didn't work

Here's an example of what I am trying to do:

Is there something I can do in a pre-process function to get this to work?

EDIT:

Thanks to @Beebee I rediscovered the template_preprocess_LAYOUT function in my layout's .inc file and added

$variables['messages'] = drupal_get_messages();

now both $variables['messages'] and $messages exist when the template is called but they contain an array of messages rather than the usual rendered output in a string.

What do you think about using Panels Everywhere?
You could then add a message pane to your Default site template and avoid 1.

Also you can disable Block from now on, because all parts of your site, are now panels.


Programmatically update a taxonomy term $term = Term::load($_tid);
$term->field_league_id = 'ID value';
$term->Save();

I am updating the terms by the code above but it's not working. Create the term by term->Save() is works normally. Everyone had experienced with that please help.

Updated:

$term = Term::load($_tid);
$term->field_league_id->setValue($league_id);
$term->Save();

This solution is not working, it's throwing:

  Call to a member function setValue() on a non-object in..

At the top, I declared ref. already.

use Drupal\taxonomy\Entity\Term;

The code for create new taxonomy is working fine, but not for updating.

$term = Term::create([
            'name' => $league->caption,
            'vid' => 'league',
            'field_league_id' => $league_id,
            'field_league_code' => $league->league,
            'field_league_year' => $league->year,
            'field_league_numberofteams' => $league->numberOfTeams,
        ]);

        $term->Save();

$term = Term::load($_tid);
$term->field_league_id->setValue('ID value');
$term->Save();

Additional info (requested in comments):

If you print out the object, you'll see that fields use the class core/lib/Drupal/Core/Field/FieldItemList.php.

By browsing through the methods, you'll see a few functions for interacting with the FieldItemList object, such as setValue(),

When I'm developing in Drupal 8, in order to learn the API, I use the

dump() function a lot to see what type of object I'm dealing with, and to inspect it's methods.

dump($term); die();

In fact, in my settings.local.php file I have an include

include 'my_settings.php';

and in there I have this function:

function nprint($obj) {
  dump($obj);
  die();
}

This is something I've been using for years to inspect objects.  Now that drupal is much more object-oriented, printing out objects to find what class they use is essential.

Another essential tool for me is using an editor that allows searching by file name (I use the free software Aptana Studio 3).

So if you see you're dealing with a "FieldItemList", you can do "command + t" to search by file name and type in "FieldItemList".  This saves a lot of web-based research.  And it helps you learn the code base.


List groups own content and all non-group content on groups page I building a site where some content (eg. news, events) that either belong a group (region) or not (national).

On the national part of the site I have a view in a block that presents all content filtered by type (news or events). No problem...

On the regional part(s) of the site I want to have a view that show all the news (or events) that is published by that region. This is no problem either. (OG contextual filter etc.)

But I also want to include all news that don´t belong to a region at all.... this part I can´t figure out.

What I want to happen (under the hood) in the SQL is this...

The WHERE-part that I get from Views:

WHERE ( ((og_membership_node.gid = '<gid>'))
  AND (( (node.status = '1') AND (node.type IN  ('news')) )) )

Change that to:

WHERE ( ((og_membership_node.gid = '<gid>') OR (og_membership_node.gid IS NULL))
  AND (( (node.status = '1') AND (node.type IN  ('news')) )) )

Perhaps hook_views_query_alter() or hook_views_pre_execute() can fix this...

Solved! I used hook_views_query_alter().

function MY_MODULE_views_query_alter(&$view, &$query) {
  if($view->name == 'VIEW_NAME') {
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if (strpos($condition['field'], 'og_membership_node.gid') === 0) {
          $condition_group['conditions'][] = array(
            'field' => 'og_membership_node.gid',
            'value' => NULL,
            'operator' => 'is'
          );
          $condition_group['type'] = 'OR';
        }
      }
    }
  }
}


How to save current User Points as field at moment of adding a node? The registered users on my website can create nodes from a content type called 'Stuff'. I'd now like to display the author's User Points he/she had when he/she created the node. That means: the value shouldn't be updated when the author's User Points change in the future.

How can I do that? Can I do a similar thing for comments?

Can this be done with a code/dynamic/preprocess field, provided by the Display Suite module?

@arpitr's tip for using the Computed Field module seems a pretty good idea, but as I replied to his answer, I don't know anything about PHP. I tried the following code, but it doesn't work.

global $user;
$entity_field[0]['value'] = "userpoints_get_current_points($user->uid)";

Simply add one more field to the Stuff content type and use Computed Field module for adding that field.Since field is on content type so its value will be added while adding the node with the value of user points user will have while creating it,afterwards it will be same or depends on php code computing value for this field.

  Computed Field is a very powerful field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of fields. So start cooking up your PHP based values!


Can solr point into a certain point in a document? I have very long documents (around 100 pages when printed) that I need to index with Apache Solr Search. Is it possible to index the pages with solr in such a way that clicking the result from the result page takes the user into the right document and into the right place in the document?

Not easily (unless there is a module I don't know of which does it).

Solr can return highlighted terms, you can use this highlighting, to preprocess the node when being displayed to insert an anchor tag (after removing the ems), you cold append this tag to the search results page.

Another way would be to index the pages separately. So you could at least link to the correct page (even if is a fragment id) when showing the results.


Render node content in page.html.twig level or blocks at node.html.twig level In a Drupal 8 site design there is expected a view block and a static block in the middle of node content.

I've been trying to figure out how to render node content around the block region (in page.html.twig level), render the block region in the middle of the node content (in node.html.twig level) or any other work around, for ages.

I imagine one way would be to render part of the node content in a view block with contextual filter and other node content fields in the node.html.twig, but I don't know how resource heavy would it be for the system?

If there are any suggestions/solutions anyone here could think of for solving this as efficiently as possible, I'd be very happy to hear about them.

Best,

Alari

So one thing is directly accessing the node object that you have available. E.g. {{ node.some_field.value }} (which prints the raw value of e.g. a text field, not what you want in most cases) or {{ node.some_field.view() }} (which views it using the default formatter configuration, you can also provide a view mode or formatter configuration to it).

See also the two related questions that I already added as a comment:  Render a node field inside page.html.twig AND Render image field from node in page.html.twig.

As you found out yourself, you can also use blocks for this. However, using views for that is a bit backwards. Views executes a query. So what it does is get the node from the already loaded ID, then does a query to get the node ID and then gets the node again for that Node ID ;)

As an alternative, blocks in D8 support context. So they can get things from the site injected and use it directly. See https://drupal.stackexchange.com/a/188629/31 for some explanation on this. You can implement a custom block yourself and print out what you want, or you can use the block that ctools provides that allows you to view a node with a specific view mode.


How to display webform results under the webform with contextual filters? I created a view listing webform fields
New View » Webform Submissions » Unformatted list of Rendered submissions

It gives me all the submitted data of all the webforms of the website.

I'm looking for a way to have under each webform its results.

So when i visit : website.com/webform/id678
under the form, i would like to have a block showing the previously submitted data i'll be using a pager to only display the 5 latest submissions and be able to browse through submissions if i want to.

This is possible with the contextual filter of Views but i can't seem to figure out how to configure it correctly

thanks

I'm using Drupal 7.56 and webform 4.16

1. create a views block display of your view

configure the view as you wish
but you have to add contextual filter by content:nid as shown below with setting: raw value from URL, path compoment 2

We have to specify validation criteria content: webform as shown below

2. add the views block in a block region

Now if you visit a webform will show under it the relevant submissions


How to print preprocess_html variables in page.tpl I have variable in template.php to use in different files like page.tpl, but written this in preprocess_html function as below, how can i print this in page.tpl and html.tpl file.

mytheme_preprocess_html(&$variables){
      $variables['xyz'] = $xyz;
}

In page.tpl file, I tried with print $xyz; but it is not printing, where as I can able to print in html.tpl file this variable. Initially tried to add my code in preproces_page function, but I can't able to get in html.tpl file in this case.

Yet another, perhaps simpler, to add variables to multiple templates, is too use an earlier hook_preprocess

  Preprocess theme variables for templates.
  This preprocess function is the first in the sequence of preprocessing and processing functions that is called when preparing variables for a template.

e.g:

/**
 * Implements hook_preprocess
 * @param $variables
 *   The variables array by reference.
 * @param $hook
 *   The name of the theme hook.
 */
function THEMENAME_preprocess(&$variables, $hook) {
  switch($hook){
    case 'html':
    case 'page':
      $variables['foo'] = 'my special variable';
    break;
  }
}

See also: template_preprocess


overall Information of content I have created content on 30/8/15 and the same created content is edited by other user on 1/9/15, when I go check in the dashboard or if i create view and see the edited only i could see, but in my case i want to see overall like when the content is created and by whom its created and also by whom edited?on what date for that particular content I want to see it in a view. how to achieve this please can any one suggest me?

First if you haven't enabled revisions for your content type, please enable like below:

admin/structure/types/manage/[your-content-type]

After that you need to create view to show revisions like below:

This will help you to achieve all information of event on node.

Thanks!


Appending output to a file? I am developing a custom module and I want to write debugging output to a log file so I can monitor it in real time, and not wait to navigate to watchdog.

I was using file_save_data() to write to the public file system, but quickly noticed that it was making log1.txt, log2.txt, log3.txt, etc. I want all my log messages to go into the same file. I looked at the documentation, and saw that the only flags that exist are FILE_EXISTS_REPLACE, FILE_EXISTS_RENAME, and FILE_EXISTS_ERROR. Sadly for me, no FILE_EXISTS_APPEND.

What is the drupal way to append data to a file on the file system? Or should I just use native php functions?

There is no existing way to append data to an existing file. Only modes you have listed in the question.

You will have to go for native PHP functions (a mode in fopen() or FILE_APPEND in file_put_contents()).

Some pointers:

Consider using hook_watchdog(). You can filter what you need to log to the file using the type key of the passed array.

Don't forget that there is also a module, syslog, to log these watchdog entries to syslog.

You can also use dd() function from devel module to easily log specific data to a temp file.

  dd()

  Logs any variable to a file named “drupal_debug.txt” in the site’s
  temp directory. All output from this function is appended to the log
  file, making it easy to see how the contents of a variable change as
  you modify your code.

  If you’re using Mac OS X you can use the Logging Console to monitor
  the contents of the log file.

  If you’re using a flavor of Linux you can use the command “tail -f
  drupal_debug.txt” to watch the data being logged to the file.

  dd($data, $label = NULL)


Long time of node_submit + node_save I measure time of my batch node creation and it's fairly acceptable at the beginning with, let's say 200 nodes, and totally disappointing at 1700 nodes. After some measurements I found out that the culprit is the node_submit / node_save part. For loop of 20 nodes creation it takes 5-6 seconds for each node to happen.

Where should I look for optimization? Is it some heavy module ruining my performance? Maybe it's some devel function that slows it down.

On almost empty base my call runs for 8 secs. When there's about 1600 nodes in the base I have to wait 120 secs! (loop of 20-21 nodes 5 secs each).

I found the culprit. After turning most of the modules I found out it's WORKBENCH.. Probably it has efficiency problems. Now instead of 15-20 seconds it takes 1 sec to node_save.


How to import user address profiles into Drupal Commerce? I have users with their profiles in a CSV file, state, street, phone... etc.

I tried using feeds to import this into Commerce, but it does not work. The profiles are not attached to users. I did a 2 step process with 2 feeds importers, but it isn't working, any ideas?

Migrate module is the best way to import those things.


Compression in Drupal 7 I am running Drupal (latest version 7.22 ) on Apache 2.2 and I have also installed Varnish (module and proxy). In Apache, I have disabled the mod_deflate module.
Reading around the web, it seems that the options on the performance page in Drupal (aggregate css,js) shouldn't compress the css and js files. However, browsing my site and checking the http headers, I see that I am receiving "Content-Encoding: gzip". Looking at the (default) .htaccess, I see that there are some rewrite rules in order to server gziped files to those clients that can read them. So, I guess this is where the "Content-Encoding: gzip" headers come from. Also, when I enable compression of cached pages on the performance settings page in drupal, I find that even the html of the page I am requesting (as anonymous user only) is returned compressed. My questions on the above are:

1) Do the options "Aggregate and compress CSS files." and "Aggregate JavaScript files." actually compress the aggregated files or is it just that .htaccess makes them seem like gziped? Using chrome developer tools, the files seem compressed. Checking them with the developer toolbar addon in firefox, however, (Information -> View document size) they are not reported as compressed (while the html file is always being reported as such, even when I access it as authenticated user!)

2) If they are indeed gziped, where does the compression take place? Can I control the level of compression, etc somehow?

3) I am always receiving X-Drupal-Cache "MISS". I don't care much since I have Varnish installed. Yet, since I am not hitting the cache, how come I am returned a compressed html file (that is not in the cache)?

4) Is there any chance that the Varnish module messes anything up? I am accessing the website with https so as to be sure that Varnish is bypassed, in any case.

5) If I enable mod_deflate, should I leave that part of .htaccess intact? I understand that mod_deflate doesn't allow for precompression, but what if the compression is better?

6) Also, if drupal compresses on its own the css, js and html files, what is the point of enabling mod_deflate for these files?

Here is the relevant part of my .htaccess file for reference:

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

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

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

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

A start:

1) Yes.

Note: If I really want to know what is going over the line, I use fiddler (Windows).

2) See function drupal_build_css_cache() in common.inc (line 3603). You cannot influence the level but you can influence whether it compresses or not with variable 'css_gzip_compression', see default.settings.php line 432.

BTW: You do not want to influence the compression level: for compress once, use many cases, maximum compression is always the best. Transfer time and decompressing time at the client is linear with compressed document size. So a 1-time slightly increased performance hit will save a lot of network activity and client side processing in the future.

3) -

4) -

5) Compression will be better as it will be done only once and it will be done better versus mod_deflate that will compress on each request and therefore will use a lower compression level. I don't know much about mod_deflate, but I guess that if there is already a  Content-Encoding header that tells the content is compressed, mod_deflate should not touch it. But I have had cases where I got a backup file that was compressed twice, so mod_deflate might not be that smart and should  explicitly be told to do so.

6) There is no point, but there might be for other requests, especially dynamic ones, i.e. non cacheable pages. Note that only aggregated css and js and cached pages (variable 'page_compression') are compressed by Drupal. Non cacheable pages are not compressed by Drupal.


Can I use the feeds module to import csv data to 2 different content type? I have 2 content types, account and contact. I have a .csv file which contains the data.

In the Account table we have:

name
street address
postcode
city
province
country
created
lastModified

and in the contact table we have:

initials
lastName
gender
function
officePhone
mobilePhone
otherPhone
email

The csv contains all fields from the table like this:

  “name”,“street address”,“postcode”,“city”,“province”,“country”,“initials”,“last name”,“gender”,“function”,“office phone”,“mobile phone”,“other phone”,“email”

Is it possible to use the Feeds module to import the csv, separate the data from the csv file and either append, replace or merge the data in the 2 different content types at once?

Unless anything has changed in the last couple of weeks, I don't think it's possible to set up one feed to import to multiple content types out of the box.  There's some discussion here.

That said, someone did mention the Feeds Node Helper module which apparently does allow this feature, although I'm no sure how robust it is.

  Feeds Node Helper is a collection of useful Feeds Import targets and
  Tampers. This is how book content can be imported and exported between
  Drupal sites. It provides helpers for the following:

  UUIDs
  Book parent based UUIDs
  Book Weights
  Node Types (by default Feeds just maps to 1 type, this allows multiple)

EDIT

If the module doesn't work, I don't see any reason why you couldn't simply set up two feeds that both use the same source CSV file; one for each content type.


How can I get Slick Slider to display the images? I have a "test" content type with a title, body, and a media entity field that allows for multiple images. I installed Slick Slider 2.2. I mostly followed the steps outlined here: https://www.ostraining.com/blog/drupal/how-to-use-the-slick-module-in-drupal-8/.
I configured the field to use the Slick Media formatter.

When I add a node with the "test" content type and add two images in the image field, the next/prev buttons appear but I can't see the images. See video of slider animation.
I tried this on two different content types and I also tried using layout builder and got the same result.
I don't see any console errors.
I am running:

Drupal: 8.9.3
Slick: 2.2

I accomplished what you're trying to do using Slick Carousel together with Slick Views.
You can create a content-type that you intend to be aggregated into the slideshow.  In my case a testimonial type consisting of a background image and overlying text.
You can create a views block and set its format to Slick Carousel.  You will be provided with setting options to configure the slideshow as you wish.
Filter your view by the content-type you want to comprise your slideshow, in my case testimonial.
lastly, pull your views block slideshow into another piece of content via entity reference.


Cookies change when I navigate to another page (Using jquery cookie) For example, the user can change the font size, and it is remembered in the cookies. Say I am on the product page and change the font size there and add the cookie. Everything looks fine, but when I go to the front page, the font size is back to normal. Going back to the product page, the cookie is applied. How can I make the cookies work site-wide instead of per page? Or is there something wrong with what I am doing?

How I do it is, when the user checks a checkbox:

$.cookie('font', 'x2');

And on $(document).ready() I simply check the cookie and apply the css so:

if($.cookie('font') == 'x2') {
  $(body).css('font-size', '200%');
}

Or something like that. I don't think the problem is in my code though anyway, since it works, is this some kind of Drupal behaviour or...?

Not really Drupal related, but it sounds to me like you are only setting the cookie for the current path.

Change:

$.cookie('font', 'x2');

to:

$.cookie('font', 'x2', { path: Drupal.settings.basePath });


Cannot print View title in View template How can I print the title of my view in views-view.html.twig?

I have tried both {{ title }} and {{ label }} but neither work.

You can see the title is set in the View, and the template is using {{ title }}


Single path for multiple menus I need to list nodes both in the main site navigation and within a section side navigation. Is it possible to target a specific menu for the Pathauto module to reference?

This is an example of the two menu structure.

Main Nav:
- Home
-- Page A
--- Page A Child 1
--- Page A Child 2
-- Page B

Page A Side Nav:
- Page A Child 1
- Page A Child 2

This results in Page A Child 1 and  Page A Child 2 having /Page-A-Child-1 and /Page-A-Child-2 as respective paths.

What I want is for both menus to have /Page-A/Page-A-Child-1 and /Page-A/Page-A-Child-2 as paths.

The pattern I'm using is [node:menu-link:parents:join-path]/[node:title].

You can create multiple path aliases for a single node, but you can not re-use existing path alias to point to different node.

If Child 1 and Child 2 in your example point to the same nodes, then I I am not sure if I understood your problem correctly, because you can create multiple menus to point to the same nodes. Let's say you created both child nodes associating them with Main menu checking on the Provide a menu link in node's Menu settings. Then you could just create a new menu on admin/structure/menu and add menu items for the same nodes replicating the same or creating new path aliases.

Another way is to let Pathauto generate whatever path aliases you want for the first menu, then programmatically copy its items and override the second menu items with theme_menu_tree().


How to filter the options from a select list field according to a previous select list? I'm trying to build a content type that has two selectlist fields. My problem is that the first field should filter the second field options

For example:

First field options (This field must filter the next field options):

-Red (Selected)

-Blue

-Green

Second field options would be:

-Apple

-Strawberry

-Cherry

Take a look at Conditional Fields module to define dependencies between fields based on their states and values. Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users, terms and files), the dependent fields are dynamically modified with the States API.


hook for disabling fields on add and edit node for a content type I have a content type called article where i have 6 fields.

But i need to display and hide this fields based on user group while add and edit node.

I am confused about which hook should i use.I am planning to use hook_page_alter().Please let me know wheather it is the correct hook i am using.Thanks a lot.

If I understand you right you'd be better off using the Field Permissions module:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

If you do code it yourself you're going to end up implementing most of that modules functionality, so even if you don't use it it's a great place to look for the right hooks to call etc.


Store cache's datas in files instead of database In a huge website, database's tables storing cache may become very large : is there a way to store cache in file system instead of DB ?

I'm talking about a solution that doesn't use external systems like varnish, simply an option provided by Drupal (a config for example). This doesn't seem documented and I'm not sure it exists !

Thanks !

Drupal comes with a php-file based cache backend by default: \Drupal\Core\Cache\PhpBackend, the factory is available as the cache.backend.php service.

You would configure that to use that by default with $settings['cache']['default'] = 'cache.backend.php';.

That said, I wouldn't really recommend using that. PHP files are going to fill your disk as well (without a cleanup-mechanism that the database now has) and if you have a very large site then you probably also have multiple servers and then cache invalidation becomes a problem again, clearing the cache on one server won't clear it on others unless you use a shared file system and that is again slow.

The recommended approach IMHO for a big site is to use an in-memory cache backend like Redis or Memcache (varnish is not a cache backend that is used by Drupal, it's something that sits in front of it). The big advantage of those two is that they store their data only stored in memory (configurable in case of redis) and very fast to access due to that but still easy to for multiple servers. They also have built-in purging of data and a fixed size, so they will automatically delete less-frequently used cache entries. And while not perfect, they are far better at that than the default database backend now which just deletes old cache entries and keeps a fixed amount of caches.


How to use the "Render Views filters as select list" option in an Entity Reference field? I have a content type Trait, that includes an Entity Reference field Trait Type. A trait type is categorized under a Trait Category. For my Trait content type form I  created an Entity Reference View for as follows:

As (if) you can see, I have included a contextual filter that takes Trait Category id values. I've also added a relationship for Trait Type and Trait Category.

The view works as expected, when I enter trait category id values I'm able to filter related trait types.

My difficulty comes when my I want to use this view as my datasource for a Entity  Reference field (Trait Types List) I want to add to my Trait content type form.In the field settings field for the Triat Types Entity Reference Field I've done the follow:

Now what I can't understand is:

What View Arguments is supposed to take and do I need to give it any value?
Shouldn't the option "Render Views Filter as a select List" a new select widget to my Trait content type form that would allow me to filter my Trait Type Entity Reference select widget?

Something like this perhaps:

Is my expectation wrong? How can I use this option?

1.  "Entity selection Views" helps you to deal with options list in the entity reference widget (on node add/edit form). E.g. if you want to reference some nodes that have specific term reference. Entity reference view can help you you.

As I see you want to reference "child" Trait nodes of special category to one "parent" Trait node. (At list your View shows it). In this case you don't have to use contextual filter. You can use ordinary "filter criteria" and set target category value.

2. "Render Views Filter as a select List" - it's not a widget for your content type add/edit form. But it's a widget for exposed filter in views. If you want to use this field as an exposed filter in views by default it's an autocomplete. But this option makes filter as select widget. If you read the "Render Views Filter as a select List" description, you might see that developers advice you not to use this option if you have more that 100 referenced entities. Just imagine a select widget with 100 options and query with WHERE condition. Just mind it.


Is it possible to customize site status messages? There are various types, like "Error, status" and they show up after creating content, or when triggered by a rule.

I'm wondering if it is possible to create a new type, such as "Dev" and have it's visibility limited to certain roles, like administrator.

The status type can be customised so you're covered with that one.

Assuming you're setting messages using drupal_set_message, you could check if the message should be set based on the status of the user. To make it a bit cleaner, you might want to write a module so you can set a specific permission to show this message to certain roles.


Override field value in view? I have a content type for events. There is an optional field where the user can provide a link that overrides the default link to the event.

For all of our internal events, the link should take website users to the node of the event. However, for events that are held elsewhere by third parties, the link should take the website user to whatever external link is official for that event.

I'm having difficulty creating a single link field in a view that is the value of the external link, unless there no value, in which case it falls back to the node link.

I can make a re-written field that is [override_link][path], but that always shows the path, no matter what. I only want the path when there is no override_link value.

This is in a Drupal 7 site.

The easiest way IMO to do this is to use the views field template. Here is a very detailed and helpful tutorial on DO. You can find the field template's name in the views theming tab under the advanced tab.

In terms of implementation for your use-case, the field's $output in the template would be empty if there is no link, and then you can change $output to be the link to that node (which you should be able to access with $row->nid).


Change ckeditor table dialogue defaults Quite simply the ckeditor table dialogue defaults to a table width of 500, yes the client should be told to delete that value, but I would like to alter the default table width value programmatically to 100%.

I have found other posts like this but in Drupal 8 land where do I do this?

You can achieve this in several ways with a script we can call, for example, ckeditor_settings_modifier.js containing:

CKEDITOR.on('dialogDefinition', function(ev) {
  var dialogName = ev.data.name;
  var dialogDefinition = ev.data.definition;

  if(dialogName == 'table') {
    var info = dialogDefinition.getContents('info');
    info.get('txtWidth')['default'] = '100%';
  }
});

This script should be added in one of these places through libraries:

only in the theme of your website (if you use it also for editing)
in your administration theme in order it works in normal node edit mode, and in your website theme in order it works in quick edit mode
in a custom module in which you can use for example some conditional rules that control the loading of the script.

In any choosen settings it is important to declare the dependency on the core/ckeditor.

This is the case of a module (my_module containing a js folder with ckeditor_settings_modifier.js), in my_module.libraries.yml:

ckeditor_settings_modifier:
  version: 1.x
  js:
    js/ckeditor_settings_modifier.js: {}
  dependencies:
    - core/ckeditor

in my_module.module:

/**
 * Implements hook_preprocess_page().
 */
function my_module_preprocess_page(&$variables) {
  // add ckeditor_modifier in case the user has the role of administrator
  $roles = Drupal::currentUser()->getRoles();
  if(in_array('administrator', $roles)) {
    $variables['#attached']['library'][] = 'my_module/ckeditor_settings_modifier';
  }
}

It works on Drupal 8.4.4 and CKEditor 4.8


How do I update all nodes? I have a custom module which creates a new field with a computed value, which I need to update.
How do I bulk update my nodes for a specific content type?

This is just a suggestion, its not well designed solution.

Considering that you already added your field to a Node type and you need update its value...

You can create a function that loads all nodes with specific type:

$articles = \Drupal::entityManager()->getStorage('node')->loadByProperties(array('type' => 'article'));;

And use a foreach to update your field content:

foreach ($articles as $nid => $article) {
  //Change what you need
  //Save your changes
}

Now, just run this once, on a new module install function or whatever you want.


Is there a way to send emails when someone logs in? Logins on my sites are very infrequent and are normally done by myself. I would like a way of getting email notification when someone logs in. This way I might be able to spot someone hacking into the site early on.

I am using Drupal 7.

A possible solution is to use the Rules module and create a custom rule like so:

Rules Event = After a user logs in.
Rules Action = Send an eMail.

That's really it (a kind of Rules 101 also if you want ...).

Here is a rule (in Rules import format) that should answer your question:

{ "rules_notify_about_login" : {
    "LABEL" : "Notify admin about login",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "3" : "3" } } } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "New login",
          "message" : "Some user just completed a login to [site:name], located at [site:url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

The rule will be triggered (Rules Event) right after login was completed. For any user who does not have the role that matches "role id = 3" (= Rules Condition), aka for any user who is not an administrator, it will send an appropriate eMail to the admin user of the site.

If you have the Rules UI enabled, you can just import the above rule. As an alternative just use the Rules UI to create a similar rule from scratch.

Some further refinements you may want to apply to the above sample rule:

Adapt the value (=3) of the role id to fit your needs or just omit the Rules Condition if you want to perform the Rules Action for any role.
Include relevant info about the user who performed a login (using available tokens about that user).
Adapt the eMail subject and content to fit your needs.

PS: This answer applies to D7, though for D8 it should be similar.


Resending webform submission doesn't use custom mail template I created a custom webform email template named webform-mail-1.tpl.php that is used when a user submits a webform.  The problem is, if someone modifies that submission and wants to resend that submission by email, the email uses the default template instead of the custom one ...

Does anybody have an idea as to why this happens ?  I didn't read anything about needing a separate template for emails that are sent again ...

Thanks !

Site was using two different themes and webform was submitted from the front end theme(first theme) and back end theme(second theme)
The problem was that the webform template was present in the front end theme and not in the back end theme. So that's why when the user submitted the webform once the email uses the custom template.and when the user edit the webform under the back end theme the webform custom template is not present in this theme so the webform was using the default template.
Fix : Keep the similar custom template in both themes.


Make new content [typeA] out of existing content [typeB] I have an event management site I am trying to build (which is using the COD framework) but I am trying to work my way around a functionality setup.

The basic principle is that an Event will be created, this will be published to the main page of my site and invite delegates to submit an Abstract for the Event in order to present their topic. The Abstracts will be scored internally and the selected ones will be marked to become actual presentations. The Event information will contain a Programme page, which is just a list of the presentations. Once the event has taken place, they want to be able to sell the video of the presentation.

What I wanted to achieve is outlined in steps:

Event is setup by admin, but has no programme information
Users submit an abstract (which has an entity reference to that Event)
When an abstract is chosen to be presented, the important information is copied into an 'empty' product, ie: Status is set to unavailable and price to 0, but the product display for that product becomes the Presentation
Programme is a list of all Presentations (product displays) for that Event
After the Event has finished, a price and an asset are added to the product, which is then set to available, so that it shows up in the shop

This process is already in place in my site as it is, but the client is wondering if they can effectively remove another step from this process. They are looking to automate the process so that they don't have to copy information from the Abstract, into the empty Product

My approach to this was to add a 'selected' checkbox to the Abstract content type, then create a rule which would then check every time the content was saved to see if this checkbox is set to 'approved', *then create a new product from the information already within the Abstract

My problem is I am getting stuck when it comes to where my * is, I don't even know if it's possible to copy all of the information from one content type into a new one of another. Can this be done, or am I going to have to find another way around or custom code it etc?

Kind regards

It is possible all right. In your custom module use node_load and node_save:

$abstract = node_load($abstract_id);
$event = new stdClass();
$event->type = 'event';
node_object_prepare($event);

$event->title = $abstract->title; // and so on

node_save($event);

$event_id = $event->nid;

Just wrap it in a function and expose it to the framework you are using - most of them provide good examples in their documentation.


create relation between two nodes using the relation module I am using the relation module and i don't like the way the default relation blocks work(entity collector and relation add blocks).

SO I'm trying to write my own block for creating relation. I have a form which has two text boxes, where the user selects two different end points between which the relation has to be made. he then clicks on submit and the relation has to be created.

coming to the relation module, i see that it doesn't have an API for use. Also i looked at the existing relation creating blocks(entity collector and relation add), they load entities and not nodes. Can some one explain me how i load all the entities available. Also is there a way where I can get the entity from the node id ?

Thanks.

I have a module that uses Hierarchical Select to give users a nice looking UI to create relations from.

Below is an excerpt of how I create the relation.

  $tid = 1; // A term id.
  $node = node_load(1);
  $relation_bundle = 'a_type_of_relation';

  $endpoints = array();
  $endpoints[] = array('entity_type' => 'taxonomy_term', 'entity_id' => $tid);
  $endpoints[] = array('entity_type' => 'node', 'entity_id' => $node->nid);

  $new_relation = relation_create($relation_bundle, $endpoints);

  if ($rid = relation_save($new_relation)) {
    drupal_set_message(t('Relation created'), 'status', FALSE);
  }
  else {
    drupal_set_message(t('Creating relation failed'), 'warning', FALSE);
  }

Adding more useful validation and messages is left as an exercise to reader, as that will be very context sensitive.


How to create tabbed menu consisting of views and a contact form while having unique paths for each tab? I'd like to create a tabbed menu of my support page like this:

           | FAQ | Contact us |

I'm using views accordion to create a view for my FAQ, but I'm using the contact form for my Contact form.

How can I combine them in a same menu tab while having each tab have its own path so that I can theme the current tab using a:active and for seo purposes?

I've tried quicktabs and block tabs, which work but doesn't give me separate paths. The node tabs module comes close but it doesn't seem to be able to work with a form.

I'm thinking I might need to build it programmatically using a custom module and hook_menu: How can I create a simple tab? but I'd prefer not going into that if possible

If your "Contact us" page is not the default Drupal contact page, but a webform (i.e. a node), you could use views to create tabs (see this tutorial, for example). In that case you would create a view that shows just the one webform node and configure it the way that it is displayed as a tab - and the FAQ view as default tab.

I suppose that there is also a workaround embedding the contact form instead of using a webform node.


How to securely authenticate content embeded in another site? I need to embed password protected content to a second domain with an iframe. The content itself is a view which will be displayed on a third party site via an iframe and the content is prepared with a custom page and template handing the display. The use case is to present the view on the other site without the users needing to login. From my research, Oauth or Services seem like good candidates, but I don't have much experience with both and using a service to show a single view seems like it might be an over complication. Anyway, I haven't found much in the way of good documentation on the subject so I'm hoping for a good introductory overview of how to implement this. So, what is the best way to securely authenticate the drupal content on another site. I don't want to expose user credentials in the src=url in the frame for security purposes, so I know I need to use another authorisation mechanism. I've looked at the Entity Iframe module, which seems to have some of these features but the module mainly works drupal-to-drupal, and I haven't been able to tangle apart how the module handles the consumer/provider communication.

So, from researching this, I believe that I have to configure oauth and pass the token to the URL in the iframe. What I am unclear about is how to configure oauth access to the page and how to generate the token to be supplied to the iframe.

1- build the content structure well in your first site and create a view from admin/structure/views/add that return the data needed to the second site which acts like a client consuming your first site content.

2- Download and enable Services module and enable the submodule Rest Server and submodule OAuth Authentication now you can create secured resources to be consumed by any other sites.

4- create an end point from admin/structure/services/add and choose authentication type as your case "OAuth Authentication" will fit as you need to authenticate the client "the second site consumes your data".

3- Download and enable Services views module that will help you expose any view as a resource to be consumed and managed via services and

4- From the view you have created before click the button Add and choose services, now the view will appear as a regular resource in your site under admin/structure/services/list click edit resources to see it named with your view name enable it and choose the required authentication and authorization.

Now any authenticated client client site or App can consume that resource from http://YOUR_SITE_DOMAIN/END_POINT/VIEWS_SERVICES_URL.

The last and the most important part in your requirements is to configure the authentication method and test it will I recommend below helpful tools and articles.

Chrome rest client extension to test the webservice.

Very helpful article about services module

Another helpful article


How do I set multiple attributes? If I have multiple attributes that I want to set to an element in a twig template it can get quite long since each attribute requires setAttribute(attribute name, attribute value).

Based on my IRC conversation (I don't remember who it was), it looks like it is not possible to set multiple attributes at once, like it is possible with CSS classes.

So I would like to know what would be a "pretty" way of setting multiple attributes in a twig template. I presume a loop of some kind.

If you are adding the attributes in Twig you can set multiple attributes by chaining the setAttribute calls like this:

{{ attributes.setAttribute('id', 'value').setAttribute('data-info', 'value'); }}


Send emails to users I want to send email to the users of my site, individually or to all of them  at once.
Is there any available module?

I am using Drupal 6.

Use this Mass Contact module it will match your requirement.

  The Mass Contact module allows anyone with permission to send a single
  message to multiple users of a site, using its roles functionality.

or

The Advanced User Module allows users who have "administer users" permission to send mail to selected groups of users, and that includes selection by role.


Delete hundreds of nodes by ID programmatically I am trying to remove 700 or so nodes from my Drupal 7 system (they are duplicates) and have a big list of node IDs in a text file.

Have tried using Views Bulk Operations (VBO) but it doesn't allow me to enter a list of IDs.

Also looked at using Drush documentation, but it doesn't seem to have a node-delete command? (surely a pretty standard thing?)

So now I'm thinking of writing my own Python script to do the following:

Take list of input IDs (via input file)

(note: this is just pseudo code)

# remove nodes
Foreach id in file_in_ids:
   SQL(DELETE FROM node WHERE nid={id});

# clean up all rows in tables containing col 'entity_id':
tables_with_entity_id = SQL(SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME
IN (
'entity_id'
)
AND TABLE_SCHEMA = 'my_drupal_db')

foreach table_name in tables_with_entity_id:
  foreach id in file_in_ids:
    SQL(DELETE FROM {table_name} WHERE entity_id=id)

Does this seem like a sound approach?

You want to avoid deleting directly from the database. The node system distributes its data across a number of tables. Generally you always want to use the API. The method your after is node_delete() which takes the nid as its single argument. This will handle deleting all the associated data and firing off any hooks that are attached to the event.

An alternative approach:

Download and install the "Devel" module. This then gives you access to a page at /devel/php where you can run arbitrary PHP code within Drupal.
You could write custom code to load the text file and explode the nid's into an array. Something like this:

$nids = file_get_contents("/path/to/file");
$nids = explode(",", $nids); // This will depend on how your nids are delimited. Could be line break "\n"
foreach ($nids as $n) {
  node_delete($n);
}


Copy value of field into the value of a different field How can I copy the value of one field into another during a node edit?

I'm trying to take the value of a text field and have it populate the title field.  I'm thinking I can use the Ajax framework and $form_state, but I haven't quite got it yet.  Or, is there a way to do this on submission?  The Title field is hidden so Ajax isn't required.

In case this helps, the scenario is this: user edits a node, fills in one text field and that value automatically populates the Title field in addition to the current field.

@Volker's tip gave me everything I needed and it's pretty simple as it turns out.

if (!empty($form_state['values']['some_other_field'])){
  $form['title']['#value'] = $form_state['values']['some_other_field'];
}

Set that in a hook_form_FORM_ID_alter and it works great.  The part I didn't have was the #value.


Disable block caching I just made a simlple block by using block > custom block, so I didn't make it programmatically.

I am a Drupal 8 newbie, and I look for a simple and clear solution how to disable caching for that block.

What code should I use ? In what file to put the code ? How to target that unique block ?

Thanks !

if you have a custom module let's suppose it called custom_module, your custom_module.module implement hook_preprocess_HOOK.

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function custom_module_preprocess_block(&$vars) {
  //- Change the block-id-name by your block id
  if($vars['derivative_plugin_id'] == 'block-id-name') {
    //- This stops the block being cache in drupal 8
    $vars['#cache']['max-age'] = 0;

  }

Edit :
if you don't know the exact block id you can install Block Content Machine Name module, it will give you the possibility to give a machine name to your custom block, and then implement the hook like the following:

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function custom_module_preprocess_block(&$vars) {
  //- Change the block-machine-name by your block machine name
  if (isset($vars['elements']['content']['#block_content']) &&
    $vars['elements']['content']['#block_content']->get('machine_name')->value == 'block-machine-name'
  ) {
    $vars['#cache']['max-age'] = 0;
  }
}


Unable to get titles to show up as higher priority in search than content I have a website I am working on that has a TON of content. The client has noticed that when searching for titles in the site search, it seems to prioritize the body content over the title.
So I changed the search index for titles to be fulltext with a boost of 13. With the rendered output set to a boost of 1. Then I reindexed and that didn't fix it. I did a full rebuild of tracking information. Same problem.
I found this article: https://medium.com/@easternstandard/how-to-configure-drupal-8-text-search-to-return-better-more-intuitive-search-results-fe0a78136ad7
And followed the instructions there (pretty much what I had already done) and reindexed. Same issue.
An example of this is that we have an article about the response to covid where the phrase "response to covid" is part of the title. When I search for that phrase I do not see it in any of the first-page search results. It is set to show 20 items. In fact, the article in question doesn't come up until result number 39. None of the prior articles seem to have covid in the title at all. Even searching with quotations makes no difference.
This is currently using the database search/index. I am tempted to implement Solr. But that is a whole-nother ball of wax and I am on a deadline right now.
We are running Drupal 8.9.9 and the Search API 8.x-1.18.
What can I do differently to make it value the title over the rendered content?

Make sure your view's topmost sort is set to "Search: Relevance (desc)" to sort your results from most relevant to least relevant.

Add the "Search: Relevance" field to your displayed fields while configuring your index. You'll see each result's relevance score inline - it's super helpful to see the impact of your various index adjustments. E.g. How much does boosting the title field by 8.0 affect a result's total score.


Why does email attachment fail on rescheduled rule? I have an action set component that takes a "date" param and does the following:

"Add Variable" saves a path string based on the date.
"Execute custom PHP code" saves some data to the path created above.
"Send HTML mail to all users of a role" sends an email with the above file attached.
"Schedule component evaluation" repeats the component at time +2 minutes and sends date parameter +2 minutes.

If I execute the component, the file is created and the email is sent with the attachment as intended. But when the rescheduled component executes again, the correct file is created on the server and the email is sent, but the attachment is not there.

The problem was that I needed to allow the cron user to "Send Arbitrary Files" in the Mime Mail permissions.


Accessing data on Drupal with external application I'm developing a native iOS application for a small company. The company has a career website on which they publish job offers. The contents such as job descriptions and contact person information are maintained with Drupal. Is there a way to get the plain data of the contents from an iOS application? I never used Drupal before, please help me.

Thanks a lot in advance!

Yes, you can use module Views to create content listings (http://drupal.org/project/views) with Services (https://drupal.org/project/services) and combine them to web services with the content listings using Services Views module (https://drupal.org/project/services_views).

Also, look at Drupal iOS SDK (https://github.com/kylebrowning/drupal-ios-sdk) for some basic already implemented connectors from ios to drupal. (Retrieving specific single user/piece of content, retrieving already mentioned views etc...)

I would start with downloading and enabling the modules, understanding views (https://drupal.org/node/1911062), then read the documentation for services (contained in the module)


Drupal 7 errors after upgrading from 7.12 to 7.14 I just updated my drupal version from 7.12 to 7.14 and now I get these errors when trying to update/edit a content type:

Warning: array_merge() [function.array-merge]: Argument #1 is not an array in _form_set_class() (line 4134 of /var/www/vhosts/xxx/public_html/includes/form.inc).

Warning: implode() [function.implode]: Invalid arguments passed in theme_radios() (line 2809 of /var/www/vhosts/xxx/public_html/includes/form.inc).

An illegal choice has been detected. Please contact the site administrator.

Please note that this is happening when I edit the node not the actual content type definition. But only for this one particular content type. All the other work fine still.

If it's at all helpful here are the fields for that content type:

Title - title - Node module element

Photo - field_photo_image - Image - Image

Vote - field_photo_vote - Fivestar Rating - Stars (rated while viewing)

Domain access - domain - Domain Access settings.

Description - field_photo_description - Long text - Text area (multiple rows)

Author - field_photo_author Text - Text field

Admin selected - field_photo_winner - Boolean - Single on/off checkbox

Any help would be much appreciated.

C

I ran into the same issue and found the solution here: http://drupal.org/node/1427430

Do you happen to also have the opengraph_meta module installed?
If so just edit this file:

sites/[your-site]/modules/opengraph_meta/opengraph_meta.module

search for this line:

'#attributes' => array('class' => 'opengraph-thumbs-wrapper clearfix'),

and change it to look like this one:

'#attributes' => array('class' => array('opengraph-thumbs-wrapper','clearfix')),


Define custom twig page template for specific multiple node pages by nid - page--custom.html.twig I have a page from different content type and I want to define a custom twig page template to these pages by their nid.

Eg. I have pages like node/2, node/4, node/20 and node/40 from the different content type and I want to apply page--custom.html.twig template only these specific pages by checking their ID.

Anyone know how to do this?

You can write a hook_theme_suggestions_page_alter()

/**
 * Implements hook_theme_suggestions_page_alter().
 */
function YOUR_THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    if ($node->id() == 2 || $node->id() == 4 || $node->id() == 20 || $node->id() == 40) {
      $suggestions[] = 'page__custom';
    }
  }


Variables in module using colons I think this may be related to using "tokens" when developing a module, but I am seeing this:

'og:updated_time' => array('value' => '[node:changed:custom:c]'),

The question I have is about:  [node:changed:custom:c]

What is this? What is it even called?

In my particular case, I am adjusting a module to retrieve a new value from a custom field.

'og:image' => array('value' => '[node:field_social_image]')

I have successfully used this for other custom fields, using the exact same syntax, but this one does not work.

These are the tokens, more specific a custom/dynamic tokens implemented by Drupal core (token.inc) and managed by Token module.

See: List of tokens page for more details:

  Custom format [node:changed:custom:?]   "?" is a single, unquoted PHP date formatting character. Use this token multiple times to build a full custom format.


Get delta of parent form field widget I've got some form input fields in a paragraph whose visibility need to be dynamically toggled by the value of a another field. This can be done with the states API and the HOOK_field_widget_WIDGETTYPE_form_alter hook.

My problem is that the paragraph is nested inside another paragraph, and I don't know how to get the delta of the parent widget, in order to build my selector name for the states API.

My node has a paragraph field_pagebuilder, which contains another paragraph field_row. All toggleable/dependant fields are inside the same sub-paragraph. This is the code I've got so far:

function wt_pricetable_field_widget_paragraphs_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  if ($element['#paragraph_type'] == 'pricetable_frontend') {

    $deltaSelf = $context['delta'];
    //////////////////////////////
    $deltaParent = 0; // FIXME: how to I get this?
    //////////////////////////////
    $element['subform']['field_pt_showroom']['#states'] = [
      'visible' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'single_room'],
        ],
      ],
      'required' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'single_room'],
        ],
      ],
    ];
    $element['subform']['field_pt_hiderooms']['#states'] = [
      'visible' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'multi_room'],
        ],
      ],
      'required' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'multi_room'],
        ],
      ],
    ];
    $element['subform']['field_bem_modifier']['#states'] = [
      'visible' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'multi_room'],
        ],
      ],
      'required' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'multi_room'],
        ],
      ],
    ];
  }
}

My problem is the $deltaParent - how can I retrive it?

Found it in $context['form']['#parents']. This is an array that contains the keys of the parent widget. In my case it looked like

[ 0 => 'field_pagebuilder',
  1 => ___PARENT_INDEX___,
  2 => 'subform',
]

which allowed me to generate my CSS selector for the states API:

$deltaParent = $context['form']['#parents'][1];


on('load') is not working with jQuery 3? I used to use the following function to load a video in the background (jquery 2.2.4):

function getVideo() {
    if ( $('video').length ) {
        $('video').each(function() {
            if (Modernizr.mq('(min-width: 1024px)') && $(this).children().attr('src') === undefined ) {
                var src =  $(this).children().attr("data-src");
                $(this).children().attr('src',src);
                $('video').load();
            }
        });
    }
}

After updating to 8.5.6, I must use jquery 3.2.1. So, I had to change the line $('video').load() to $('video').on('load', function(){});. However, the video is not loading anymore. I have tested the code, and each line gets executed until it comes to $('video').on('load', function(){});. I don't know why it is not loading. Is it because .on('load', function(){}) is only accessible by windowproperties? If so, then how can I load the video using document properties?

The markup in the theme of that specific block would be:
$variables['video_markup'] = '<video autoplay loop muted id="bgvid"><source data-src="'.$video_link.'" type="video/mp4"></video>';

Which roughly translates to:

<video autoplay="" loop="" muted="" id="bgvid" data-video="0"><source data-src="https://somevideo" type="video/mp4"></video>

I have been targeting this video element here. ANy suggestions will be appreciated.

Also, is there any way to force Drupal 8.5 to use Jquery 2.x? I tried this How do I use a jQuery version different from the default one used by core?, but it didn't work for me.

Edit:
@Jaypan Thanks for your answer. You are still using the .load() method in your addVideoHandler, which has been removed in Jquery3. I am not sure if it will work.

With Drupal, you don't (need to) use $.on(). It is handled through a combination of Drupal.behaviors, $.once(), and Drupal.attachBehaviors().

First you create a function using $.once() that will add your handler the same as you would with $.on(), but use $.once() to ensure that the handler is only applied a single time:

function addVideoHandler(context) {
  $(context).find(".video").once("add-video-handler").each(function() {
    $(this).load(function() {
      alert("video loaded");
    });
  });
}

Next, this function is called in Drupal.behaviors:

Drupal.behaviors.someArbitraryButUniqueKey = {
  attach: function (context) {
    addVideoHandler()
  }
};

This will be executed on page load, which will add the handler to all .video elements on the page. However, unlike other onload handlers (JS, jQuery), this is also called every time after an Ajax Call is executed, with any new loaded content passed as context. Therefore any newly loaded .video elements will have the handler applied to them - same as with $.on().

Generally, this is all you will need to do. However, if you are loading any content through Ajax in one of your own functions, you will need to pass the newly loaded content through Drupal.attachBehaviors():

$.ajax({
  url: "http://example.com/callback",
  success: function (data) {
    var targetElement = $("some_div");
    // Insert the returned HTML into the DOM, casting it as HTML.
    targetElement.html(data.response);
    // Finally pass the new content through Drupal.attachBehaviors().
    // Note - pass through the HTML, NOT a jQuery object. This can be done
    // by passing the [0]th element of the jQuery object.
    Drupal.attachBehaviors(targetElement[0]);
  }
});

This will call every Drupal.behaviors element, passing it the newly loaded content, which in turn will have the handlers attached. Using $.once() ensures that handlers are not accidentally applied multiple times, for example if someone calls Drupal.attachBehaviors() without passing a value, which in turn will pass the entire document.


arg() dependent hidden field in AJAX form Basically, I have a hidden field I set using arg().

$form['slideid'] = array(
  '#type' => 'hidden',
  '#value' => arg(2)
);

$form['fid'] = array(
    '#type' => 'managed_file',
    '#title' => t('Image'),
    '#default_value' => "",
    '#size' => 40,
    '#description' => t("Image should be less than xxxxxxxxxxxx."),
    '#upload_location' => 'public://',
    '#prefix' => '
',
    '#suffix' => '
',
);

This value is set correctly once the form loads, but after a call to a AJAX field (managed_file), the form is refreshed and I get the wrong value in arg(2).

I have found arg(1) changed when doing AJAX, which doesn't give me any solution.

Is there any alternative that can be used, or can we skip the hidden field in the AJAX re-build? Is it possible to use a managed_file element without the AJAX submit?

As suggested by @AyeshK, I checked the $form_state in the hook_form before i set the value from arg()

 $form['slideid'] = array(
  '#type' => 'hidden',
  '#value' => (!empty($form_state['input']['slideid']) ? $form_state['input']['slideid'] : arg(2))
);

This could also be done in the hook_form_submit ...

function hook_form_submit($form, &$form_state){

    if($form_state['values']['slideid'] != $form_state['input']['slideid']){
        $form_state['values']['slideid'] = (int)$form_state['input']['slideid'];
    }
   //====save the form data...

}

It looks like a crude fix, but it works for me.

Thank you for your help @AyeshK & @kiamlaluno


SuHosin configuration for Drupal 7? My web hosting provider decided to use the suhosin php extension to protect my websites.

For some Drupal 7 sites, I am now getting tons of errors and can't login:

Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 675 of /home/reseller1/example.com/includes/bootstrap.inc).
Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 678 of /home/reseller1/example.com/includes/bootstrap.inc).
Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 679 of /home/reseller1/example.com/includes/bootstrap.inc).
Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 680 of /home/reseller1/example.com/includes/bootstrap.inc).
Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 682 of /home/reseller1/example.com/includes/bootstrap.inc).
Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 684 of /home/reseller1/example.com/includes/bootstrap.inc).
Warning: ini_set() has been disabled for security reasons in include_once() (line 300 of /home/reseller1/example.com/sites/default/settings.php).
Warning: ini_set() has been disabled for security reasons in include_once() (line 301 of /home/reseller1/example.com/sites/default/settings.php).
Warning: ini_set() has been disabled for security reasons in include_once() (line 309 of /home/reseller1/example.com/sites/default/settings.php).
Warning: ini_set() has been disabled for security reasons in include_once() (line 316 of /home/reseller1/example.com/sites/default/settings.php).
Warning: ini_set() has been disabled for security reasons in drupal_settings_initialize() (line 772 of /home/reseller1/example.com/includes/bootstrap.inc).

Is there an alternative bootstrap without those ini_set statements?
Can we put them on Drupal?

I imagine you could try and override the setting in a local

php.ini

file.

For example.

/var/www/my-site/php.ini

disable_functions = system

Adding a single function instead of the list your host is using by default.

If that works, you could add other functions there, e.g

disable_functions = exec,shell_exec,popen,passthru,proc_open,system,pcntl_exec

Otherwise, you'll need to hack Drupal to remove those ini_set declarations and move them to the local php.ini file. ( not recommended )

You could also ask your webhost for help ( recommended )

Alternatively, find a new webhost.


Last form validation function is passing an error even though the first one registers the user I wrote a custom user_login form validation function that calls user_external_login_register() to register and login the user, but the last validation function for the form calls form_set_error().

The form's #validate array looks like this:

validate (Array, 4 elements)

    * 0 (String, 32 characters ) vtiger_portal_user_form_validate
    * 1 (String, 24 characters ) user_login_name_validate
    * 2 (String, 32 characters ) user_login_authenticate_validate
    * 3 (String, 25 characters ) user_login_final_validate

user_login_final_validate() is here: http://api.drupal.org/api/drupal/modules--user--user.module/function/user_login_final_validate

Here is the code for vtiger_portal_user_form_validate() and the authentication function that it calls:

function vtiger_portal_user_form_validate($form, &$form_state) {
  if (!vtiger_portal_authenticate($form_state)) {
    // Not a portal user. Let the other validation handlers run.
  } else {
    global $user;
    if($user->uid) {
      dpm($user);
    }
  }
}

/**
 * Custom user authentication function
 */
function vtiger_portal_authenticate($form_state) {
  $username = $form_state['input']['name'];
  $password = $form_state['input']['pass'];
  $testname = drupal_substr(drupal_strtolower($username),0,4);
  if ($testname == "dave") {
    user_external_login_register($username, 'vtiger_portal');
    return TRUE;
  } else {
    return FALSE;
  }
}

I'm Seeing the "Sorry, unrecognized username or password. Have you forgotten your password?" error and at the same time, being successfully logged in.  I have printed the $user object after calling user_external_login_register() and it shows that the uid is 9.

Can anyone help me figure out why I'm seeing an error from user_login_final_validate() when the user has obviously logged in successfully?

Update: I've found the root of the problem.

From the line 2121, user.module contains the following code.

// We are not limited by flood control, so try to authenticate.
// Set $form_state['uid'] as a flag for user_login_final_validate().
$form_state['uid'] = user_authenticate($form_state['values']['name'], $password);

user_login_authenticate_validate() sets $form_state['uid'] to FALSE so that later user_login_final_validate() sends it's error message.

The OP mistakenly pasted user_login_final_validate() from D6 instead of D7. In D7, you avoid that error message by simply setting $form_state['uid'] = [a number]. You do that from within your custom #validate callback. Once you have done that, user_login_final_validate() will not throw an error and your form submission proceeds and thus login proceeds.


Change drupal font color based on variables I had a content type=score
This "score" content type had "field 1", "field 2" in integer.
Can I customize the font color based on variables.

ex:
when the users fill in <50 then show red color,
When the users fill 50-70 then show orange color,
When the users fill >70 then show green color.

Any contributed modules can do that function?
Thanks

Yes, you can achieve this with jQuery.

In a custom module add the following code.

function custommodule_form_alter(&$form,$form_state,$form_id) {
  if ($form_id == "yourcontent type form") {
    $form['field_field1']['#attributes'] = array('id' => 'field1_id');
    drupal_add_js(drupal_get_path('module', 'custommodule') . '/jsfilename.js', ));
  }
}

Put this in jsfilename.js.

(function($) {
  Drupal.behaviors.custommodule = {
    attach: function (context, settings) {
      // I suppose your field1 html elemet ID=field1_id
      $('#field1_id').change(function() {
        if($('#field1_id').val() < 50) {
          $(this).css("color","yellow"); // you can add class to it and in css file style it  ex:$(this).addClass('class1');
        }
        else if($('#field1_id').val() > 50 && $('#field1_id').val() < 70) {
          $(this).css("color","red");
          $(this).css("color","yellow"); // you can add class to it and in css file style it  ex:$(this).addClass('class1');
        }
        // …
      });
    }
  }
}


how to effectively hide a field (with title) on a form Possible Duplicate:
  specify $form elements to be excluded from display?

I would like to hide a field on a form using hook_form_ID_alter. The form is owned by another module. This field cannot be unset because it contains a value.

Using CSS {display: none} for the standard field class is not good because the field should be hidden only in specific conditions (which must be determined using php).

In hook_form_ID_alter, I could add an #attribute to the field with a class value e.g. hideme and then use CSS to hide this class. But it will leave the field title (tried).

The field has #prefix set to <div class='some_class'> (in this particular case). This prefix precedes the field as well as the title when displayed in a browser. So I could analyze the prefix with regular expression and add a hideme class there. But I am not 100% sure what the #prefix will contain, so the regexp could be complex.

Perhaps there is a better way to hide a field with title on a form?

You can set the #access property for the form field to FALSE. The form field will not be shown to the users, but its value will be still be available in $form_state['values'] for the submission, and validation handlers.

Using #access is always the suggested way to avoid users can change the value of a form field, and avoid any third-party module depending on that form field starts to raise warnings, or fails to work as expected.


Using Entity Reference field, get the parent NID in referenced entity (node) I have a node that holds an entity reference field (multi value) to other nodes, all the referenced nodes of the same type.

In the referenced nodes I have a computed field that do some calculations. Also, in the parent node I have a computed field that takes calculated values from referenced nodes and do other calculations. All the values are stored in DB.

What I need is every time a referenced node is saved, also to re-save (update) the parent node, so that computed field can make the calculations using the new values from the referenced node.

Is it possible to get the NID of the parent node in the referenced node computed field, so I can add some code to launch the parent re-save?

All I can think right now is using SQL or adding a field (in referenced nodes) that will hold the parent NID when the referenced nodes are created; is it another way?

Thanks.

With the logical structure that is mentioned, it is possible that a node may have more than one parent. Wouldn't it be wiser to make a reference upwards than downwards? You would end up with an entityreference field of granularity 1. Unless there is some other reason for which to keep this structure.

There is no explanation on the specifics of this calculation that takes place. Is it in a custom module, is it rules, is it some other contrib module?

In any case, you can use an EntityFieldQuery in order to get a list of all nodes that reference the particular node. More details about how to use here. There is a particular reference for entityreference fields:

  Likewise an image field would use 'fid', 'alt', and 'title' as column names; an entity reference field would use 'target_id' and 'target_type' as column names.

Example (in CAPS the variables that you need to handle):

<?php
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'MY_CONTENT_TYPE')
  ->propertyCondition('status', 1) // published? yes
  ->fieldCondition('field_MY_ENTITYREFERENCE', 'target_id', $MY_CURRENT_NODE_ID)
  ->range(0, 10); //do not forget the semicolon at the end of the query conditions
$result = $query->execute();
if (isset($result['node'])) {
  $items_nids = array_keys($result['node']);
  $items = entity_load('node', $items_nids);
}
?>


Why do sub-menu items not appear on front page, but work on other pages? I have added a link to a Panels page in my main menu.  Beneath that link are items which link to a couple of Webform pages and a Basic page.

On the home page, the sub-items do not appear beneath the heading, but on all other pages, they show up just fine. If I look at Structure->Menus->Main menu, everything is set up correctly. I have cleared caches multiple times, to no avail. Any ideas?

Thanks in advance.

I suspect your problem could be resolved by ticking the "Show as expanded" checkbox on that menu item.

This worked for me. Thanks, Adam!


Drupal custom module code working differently for logged in users and anonymous users I have the below simple if else condition for a custom module form page in buildForm method for recommendation submission. I would like my form to be displayed to all user who visit for the first time and submits and cannot submit again from the same url. If the url is used again it should just display the thank you message(if already submitted). The below code wrks perfectly if the user is logged in. Like if the user is logged in, he comes and submit, thank you message is displayed everything is saved in DB correctly. The problem comes when anonymous user comes. The page loads as expected. But after filling up the details and submit button is clicked. It reloads and the same form is displayed again(instead of the thank yo message) and then if I submit again it displays validation errors even though the fields are there and gives the thank you message. Can anyone explain me why its behaving differently for logged in and anonymous users.

    public function buildForm(array $form, FormStateInterface $form_state)
    {
       if($this->CheckRecommendationStatus())
       {
          $form = array();
          $form['form_label'] = [
          '#type' => 'processed_text',
          '#text' => t('<h3Thank you already submitted
'),
          ];
        }
        else if($this->validateUrl())
        {
           $form = array();
           //it will have controls and submit button.if submit is clicked those values will be saved
        }
        return $form;
     }
     //This below method check the Database whether already the submission is made or not
     public function CheckRecommendationStatus()
     {
           $this->setUniqueIdentifier(htmlspecialchars($_GET["rec"]));
           $query = \Drupal::database()->select('m_tablename', 'mr');
           $query->fields('mr',array('id'));
           $query->condition('mr.column_name',$this->getUniqueIdentifier());
           $query->range(0,1);
           $results = $query->execute()->fetchAll();
           return $results;
     }

This sounds like a caching issue. Check the cache api and make sure to set the $form['#cache'] appropriately.

When the anonymous user submits the form, it's submitted fine, but when the form loads the second time Drupal doesn't know that it should not be serving the original cached form.

You can quickly confirm that it is a caching issue by set the form to not be cached like:

$form['#cache'] = [
  'max-age' => 0,
];


How to sort the content types/bundles on /node/create page I want to reorder the list of available content types on the create content page.
I have node-add-list.html.twig and entity-add-list.html.twig inside my custom theme template folder.
Twig then outputs the array of all types or bundles/content types in alphabetical order. How can I sort this a different way? And can I hard code the links I want in this file or can I output each content type individually?

You can do this in preprocess by overriding this code from node.module:

function template_preprocess_node_add_list(&$variables) {
  $variables['types'] = array();
  if (!empty($variables['content'])) {
    foreach ($variables['content'] as $type) {
      $variables['types'][$type->id()] = array(
        'type' => $type->id(),
        'add_link' => \Drupal::l($type->label(), new Url('node.add', array('node_type' => $type->id()))),
        'description' => array(
          '#markup' => $type->getDescription(),
        ),
      );
    }
  }
}

Or you can replace the foreach loop in the twig template

node-add-list.html.twig

    {% for type in types %}

{{ type.add_link }}

{{ type.description }}

    {% endfor %}

with a hard-coded list:

{{ types.article.add_link }}

{{ types.article.description }}

{{ types.page.add_link }}

{{ types.page.description }}