Will assigning a name string to user #0 do any harm? By default, the {users}.name set for the Anonymous "user" (i.e. uid=0) is "" (empty) in Drupal 7.

This design choice is inconvenient for me in a module I'm maintaining (see issue #2099123 for background).

For instance, I need "Anonymous" to be available when there is an autocomplete form field that accepts a user name. Also, when I print out lists of users stored as serialized data in blobs, I want "Anonymous" to appear if there is a uid=0 somewhere in the list.

I've tried to use hook_username_alter(), but it has no impact on autocomplete widgets or serialized data.

I've looked for an API function to change the {users}.name field, and not found it.  I know there is a Drupal rule of thumb that say that updating another module's tables directly (i.e. without going through that module's API) is bad.

However, the solution I currently favour is to add a form to the admin interface that when clicked, does the following if the name field for uid=0 is "". (It does nothing if this field is not empty.)

$query = db_update('users')
  ->fields(array(
    'name' => 'Anonymous',
  ))
  ->condition('uid', 0)
  ->execute();

I've tested this solution, and it solves the problem.

I've verified that leaving the author field empty to assign node ownership to user #0 (as suggested by the the hint "Leave blank for Anonymous.") still works after this database update.

I understand that the value of {variable}.anonymous may not be "Anonymous", but believe I can live with that.

Question 1: Will assigning a string value to this particular field if it is empty have potential to break something on a site that installs my module?

Question 2: Is there a more Drupalishly right way to do this? (I.e. a way where I do not have to interfere with a piece of data that rightfully belongs to the user module.)

For the record: I've done it.  One issue immediately popped up during testing: If a user named "Anonymous" already existed, creation would fail (obviously).  After modifying the routine to check for existing users before updating, it worked.

Been running on several production sites for a week, and no problems so far. I'll report here if any problems occur.


How to load translated entity values in Twig for SEO purpose? How can I get access for the english values of my entity in the french version of my twig template. This is for a tracking task.

Let say I want to print the node title en english on the french version.

I was hoping I could do something like this : {{ node.languages.en.label }} but this doesn't work.

I'd rather avoid using preprocess if possible (I know how to do it with preprocess).

You can get the translated node with getTranslation():

{% if node.hastranslation('en') %}

{{ node.translation('en').title.value }}

{% else %}

No translation

{% endif %}

If you are not sure that the translation exists, check first with hasTranslation(), because a missing translation throws an exception.


What is the name of the table where view modes are stored? We have 10 view modes that we created. When we run drush @env cex sync in our local we are able to export the config files related to these view modes such as core.entity_view_mode.node.related.yml (where related is the view mode).

Is there a database table where these View modes are stored? If so, what is the name of it?

We are not using Display Suite or Panels, just the out of the box View Modes from Core. We do not plan to add those modules.

Goal:

Find out what view modes are being used programmatically.
Delete all view modes that are not being used.

Definition of not being used:

Article content type has 3 custom view modes: listing, minimum, related
Basic Page content type has an Entity reference to Article pages where the Article view mode = listing under Basic Page Default View Mode.
Custom view modes listing and minimum are not being used. However, if we consider all content types (e.g. 10 more content types) then it will be a pain to have to go through one by one.

View modes are stored in the configuration entity entity_view_mode which you can load like any other entity:

$view_mode = \Drupal::entityTypeManager()
  ->getStorage('entity_view_mode')
  ->load('node.teaser');

To load all view modes for the entity type node:

$view_modes = \Drupal::entityTypeManager()
  ->getStorage('entity_view_mode')
  ->loadByProperties(['targetEntityType' => 'node']);

View modes don't store much data other than a label for the view mode name.

How a view mode is displayed for a specific content type is stored in a different entity:

$display = \Drupal::entityTypeManager()
  ->getStorage('entity_view_display')
  ->load('node.article.teaser');

The usage depends on how you define what being used means. If you mean with not used that it is not configured in a content type, which you can query in the config entities mentioned before, this doesn't mean necessarily, that the view mode is not used anywhere. If you configure an entity to be displayed in a view mode, for example in a View or a entity reference field, and this view mode is not configured in the content type, then it fallbacks to the default view mode.


How can I redirect user, while showing them a status message? I'm working on a custom module, in which I want to redirect users, while showing them a status message. What I've tried so far only works for authenticated users but I want to redirect anonymous users. I've tried the below solutions so far. What else can I do?
\Drupal::messenger()->addStatus($config->get('mymessage');
$redirect = new \Symfony\Component\HttpFoundation\RedirectResponse($login->toString());
$redirect->send();

$request = \Drupal::request();
$session = $request->getSession();
$session->set('msg', $config->get('girisyapmesaji'));
$session->save();
\Drupal::messenger()->addStatus($session->get('msg'));
$redirect = new RedirectResponse($login->toString());
$redirect->send();

In general, never send responses from custom code. See How do I set a cookie using $response->headers->setCookie() in a form submission handler?
In this case you are sending a redirect response to the client while Drupal builds the real response containing the cookie to the session where the message gets stored. The real response never reaches the client because you've already sent them away.
If you don't have a controller to return the redirect you can use an event subscriber to set the response the Drupal kernel returns. See this code example https://drupal.stackexchange.com/a/274494/47547.
In your case you would set a status message instead of a custom cookie:
/src/EventSubscriber/MymoduleSubscriber.php
<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * mymodule event subscriber.
 */
class MymoduleSubscriber implements EventSubscriberInterface {

  /**
   * The route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Constructs event subscriber.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   */
  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
  }

  /**
   * Kernel request event handler.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   Response event.
   */
  public function onKernelRequest(GetResponseEvent $event) {
    if (!$event->isMasterRequest()) {
      return;
    }
    if (!$this->routeMatch->getRouteName() == 'entity.node.canonical') {
      return;
    }
    $request = $event->getRequest();
    if ($this->routeMatch->getRawParameter('node') == '1') {
      \Drupal::service('page_cache_kill_switch')->trigger();
      if ($some_condition) {
        \Drupal::messenger()->addStatus('My message');
        $redirect = new RedirectResponse('/foo/bar', 302);
        $event->setResponse($redirect);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      KernelEvents::REQUEST => ['onKernelRequest', 31],
    ];
  }

}

mymodule.services.yml
services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    arguments: ['@current_route_match']
    tags:
      - { name: event_subscriber }


What is the most performant method to run many UPDATE statements? What is the most performant method and best practices method to run many UPDATE statements efficiently? Currently I'm just creating a text block of many UPDATE statements separated with semicolons and passing that into a single db_query() call.

Using this method I'm currently getting this error, so I'm guessing it's not a smart way:

  PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute
  queries while other unbuffered queries are active. Consider using
  PDOStatement::fetchAll(). Alternatively, if your code is only ever
  going to run against mysql, you may enable query buffering by setting
  the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.:

Is there a better way that is as fast? I will need to run possibly hundreds of UPDATE statements.

Why must I do so many queries? For every node, I track three metrics of that node. These metrics are determined form other sources programmatically (like traffic data). For speed, I created a table that just tracks the nid, and the values of the three metrics. On a regular basis, I have to update the metrics for every node in this table. Every node in the system will have a row in this table.

I determine a forth metric from the values of the three, so each day I have to:

Update the values of metrics 1-3
Update metric 4 based on values of metrics 1-3

UPDATE statements alter data and are therefore by definition not fast. They might be relatively fast if you a small data set but the bigger you table gets, the slower an UPDATE will become, especially if it involves updating indexes and stuff.

So I doubt it would matter much if you execute them separately or in a single call. Instead, I would look into ways to "optimize" them in a more general way:

Maybe you can rewrite it so that you need to execute less queries, e.g. use a subquery to get the value. Make sure to actually profile it to be sure that it is faster. A complex query could also be slower than a number of simple ones.
Use db_transaction() to execute all queries in a single transaction. Not only will this enforce consistency (all or nothing, if you have an error in the 500. query the others changes will be reverted as well) it will also be considerably faster on many systems because (in the default configuration) MYSQL enforces a write to the file system after each transaction (and if you don't use transactions explicitly, every UPDATE/INSERT/DELETE query is considered a separate transaction).
Maybe your table structure can be optimized so that you need less queries.
If there is no way around executing hundreds of UPDATE queries, I would go for reliable instead of performant/fast. Have a look at how node access table rebuilds are done for example ( which can result in hundreds of thousands of INSERTS if you have many nodes). When one is necessary (e.g. a node access module is installed), it usually just sets a flag to inform the admin and then the actual rebuild is executed in the backend with a batch.

If you provide more details on what you are actually trying to do, I might be able to give you some actual advice as well.

EDIT:

Some more hints now that you posted what you are doing exactly.

If you don't need to keep old data, you could try if you can first calculate the metrics for a number of nodes, then delete them and then do a multi-insert. Maybe that's faster, maybe not.
Generally, I would implement what you're doing in a hook_cron(). You could process N nodes per cron run, store the highest node id and on the next run, process the next N. If a query returns less than the requested N, you reached the end of your data set and are done for the day, set a flag to today and can start by zero at the next day. If you need to process all nodes at the same time, I'd create a simple drush script that you can start through system cron, but still group the processing into groups of nodes, to avoid memory issues.
You could look into using a different backend for storing your metrics if you're on your own server and can install something. For example, there is http://oss.oetiker.ch/rrdtool/, which is specifically built for storing "time series data" (quote from the website). I have never used it though. And if you're in for big, then there are systems like Hadoop which is among others used by Facebook to process their enormous amount of daily metrics.


How to definitely stop inside a Rule and prevent any further actions in the rule from executing? I have not seen that the Rules module can do this out of the box, but how can I prevent further execution of subsequent actions in a rule?

For example, I have multiple components in a rule.
The first one has a condition and if that is TRUE, it will execute one action, but the other components following the first one, MUST NOT BE EXECUTED.

So without adding further conditions to the rest of the components in order to prevent execution, I want to jump out of the complete Rule after executing the fist component.

I guess this can be accomplished with php inside the first component?

This seems like a perfect use case the Conditional Rules module. Some more details about this module (from its project page):

  ... provides Rules plugins for conditionally altering execution flow directly inside a group of actions.

Using this module, there is no need for "PHP inside the first component" (as in your question.

Refer to my answer to "How to prevent a node being saved when using the Rules module?" for an illustration of how to use this module.


Full access to admin panel So I have an access to the site as 'content' manager (at least it says content in the username field when im into dupal panel). And they asked me to change the menu a bit. But all I can do is making a limited amount of actions by default (like adding a page or a product info, etc.). There's no link to edit block or menu. As I consumed there're different types of access cos as I've seen in documentation the real administrative panel is quite functional. Am I right? So I asked for the FTP access and I got it but all I can do is changing some style rules in css and injector-css. So as I understand I can change html only in the real admin panel, right? Can I do something without that panel just having an access to FTP? And if yes, where I can find it in root folder? Thanks in advance!

If they ask you to update menus then they should give your user role the permissions to make menu changes, whether you have access to FTP doesn't really matter in this case.


How to add value in to multiple value field (entity reference)? Im inserting into user field reference to other users. This is my code, but it is overiding all values of field, i just want too add value and keep values added before.

<?php
global $user;

$user->field_profile_access['und'][]['target_id'] = 34;
user_save($user)

?>

I think this line is wrong:

$user->field_profile_access['und'][]['target_id'] = 34;

You could try with:

$user->field_profile_access['und'][] = array('target_id' => 34);

or this:

$next = count($user->field_profile_access[LANGUAGE_NONE]);
$user->field_profile_access[LANGUAGE_NONE][$next]['target_id'] = 34;

I used LANGUAGE_NONE instead of 'und' here, but that's not the problem.

Or even better, using the Entity API. That example is for a field collection, but the idea should be useful for any entity, including nodes.


Missing updates for Media After much package dependency finagling via composer, updating PHP, updating MariaDb, etc.. (not as bad as D7 => D8 but still harder than I'd hoped) I managed to update from 8.9 => 9.0.7.  I was able to run update.php, clear cache, etc. site seemed to be working ok, no errors.  I enabled the core Media module as apparently blazy now depends on it.  Now I'm getting:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘########.media' doesn't exist: SELECT "base_table"."vid" AS "vid", "base_table"."mid" AS "mid" FROM {media} "base_table" GROUP BY base_table.vid, base_table.mid LIMIT 1 OFFSET 0; Array ( ) in Drupal\Core\Entity\EntityStorageBase->hasData() (line 583 of /var/www/sites/#####.test/docroot/core/lib/Drupal/Core/Entity/EntityStorageBase.php).```

If I try to run update php I see:

MISSING UPDATES FOR: MEDIA
The installed version of the Media module is too old to update. Update to a version prior to 9.0.0 first (missing updates: media_post_update_collection_route, media_post_update_storage_handler, media_post_update_enable_standalone_url, media_post_update_add_status_extra_filter).

MISSING UPDATES FOR: MEDIA LIBRARY
The installed version of the Media Library module is too old to update. Update to a version prior to 9.0.0 first (missing updates: media_library_post_update_display_modes, media_library_post_update_table_display, media_library_post_update_add_media_library_image_style, media_library_post_update_add_status_extra_filter, media_library_post_update_add_buttons_to_page_view, media_library_post_update_update_8001_checkbox_classes, media_library_post_update_default_administrative_list_to_table_display, media_library_post_update_add_langcode_filters).

I'd rather not take core back to an earlier version to resolve this as I'd have to also downgrade some modules, namely Solr which was not super easy to configure.
Can anyone suggest how I might go about resolving this?  Is there a way to update a core module without updating core?  I thought of just copying and pasting but obviously that wouldn't resolve my missing table issue.
Any pointers in the right direction would be immensely appreciated.

D9 modules will work on D8. You'll have to go back to a D8 core  and then go to /update.php or if you have Drush, run drush updb; otherwise, you'll have to manually do the changes to your DB that those updates execute.


Which SELinux setting prevents module upload via Admin interface? Just wondering if anyone knows which SELinux boolean(s) is/are blocking the installation of new modules via the admin (FTP) upload interface. I have VSFTPD installed, and can upload via FTP client. I just wanted to know for future reference. If I use "setenforce 0", it works fine.

I believe I have pegged the variable in question!

setsebool httpd_can_network_connect on

This allows the web server to connect to the FTP server. So, if you have set up an FTP server and account, but still can't upload modules to Drupal via the front end, try the above command!


Upgrading from d6 to d7: getting puzzling 'requirements problem' error I am trying to upgrade from d6 to d7 and I'm getting a requirements problem immediately after running upgrade.php. It seems there's some crucial information missing. For me, at least: absolutely no clue what is happening here.

I've got the Ad module (as well as ad_image, ad_flash) enabled

The error that is thrown back at me is:

  upload (Missing): Unresolved dependency, Flash Ad requires this module.
  upload (Missing): Unresolved dependency, Image Ad requires this module.

See screenshot

Before upgrading the drupal core, you must deactivate your contrib modules. I think you did not.?

Upgrade the core first. Then upgrade any contrib modules.
If you have used cck in drupal 6, you will need the cck module to do the migration.


"Node Recommendation" Module alternatives I what hoping to use the Node Recommendation module for drupal 6, but after testing it for a while I have come to realize that this particular module has to many issues.

http://drupal.org/project/noderecommendation

The idea of the module is excellent! give node recommendations based on related taxonomy terms and content types.

Are there any alternatives that are under active development and are stable enough that do something similar?

Thank you.

There are two excellent modules, both compatible with Drupal versions 6 and 7:

If you want to display similar nodes calculated by the actual node content, try Similar entries
If you want to display similar nodes calculated by some sort of taxonomy setup, try Similar By Terms

There's also Relevant Content, a module which allows you to configure the recommended nodes based on many different things, with different block configurations and stuff for dealing with CCK. I haven't used it, but I've heard it's quite good.


Feeds: removing text from a title I am using the feeds module to import an rss feed from twitter. The feed title and body starts with ": then my tweet". I wish to remover ":" from the creation of my nodes. I can remove it in the body by using a custom input format that removes it. However I can't remove it from the title.

I suppose I have two options:

While saving the nodes of my custom content type, remove the text
create a custom plugin for feeds

What do you think is the best way to do this? Should I try another way?

Update

I added hook_node_presave to deal with this. As it is called on both the insert and update.

/**
 * Implementation of hook hook_node_presave
 */
function my_module_node_presave($node) {
    if($node->type=='mytype'){
        $node->title =  _my_module_my_function($node->title);
        $node->body[$node->language][0]['value'] =  _my_module_my_function($node->body[$node->language][0]['value']);
    }
}

It works great but is this the correct place to be doing the check and removal?

I think this approach is fine for your use case, since it's so unlikely you'd intentionally begin a title or body with a colon on purpose.

I'd clean up the code a bit though for coding standards like

/**
 * Implements hook_node_presave().
 */
function my_module_node_presave($node) {
  if ($node->type == 'mytype') {
    $node->title = _my_module_my_function($node->title);
    $node->body[$node->language][0]['value'] =  _my_module_my_function($node->body[$node->language][0]['value']);
  }
}


Exclude entities currently referenced on a node with entity browser I have content type that references a custom entity and uses an entity browser widget to select them.
I want to create a view for the entity browser that excludes entities that have already been selected on the current node so that they're not selected twice.
Not sure if this can be done with default functionality or it needs a custom module

You are listing entities as your base type, but you want to filter based on the current node.
You need to introduce the information about the nodes that already reference (all) entities, and also what the current node is.
You do that by using the "backwards" Relationship, the one that goes from Entities back to the nodes that reference them. This Relatinship will be named something like Content using field_entity_reference and its Description will be Relate each Content with a field_entity_reference set to the content.
It will not be named "Content referenced from field_entity_reference", that one is the "forward" Relationship.
You can Require this Relationship because you want the results that do have a reference from a node.
Then add the Contextual filter Content: ID, make it use the Relationship, and configure
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Content
Your CT
Configure the other options as needed, but in the end:
More
Exclude
So we found all nodes that reference entities in our results, and used the Contextual filter to exclude the results related to the current node.


How can I pass parameters to allowed_values_function for a field? Tried these 3 ways... none of them work.

->setSettings(array(
    'allowed_values' => array(),
    'allowed_values_function' => '\Drupal\xrm_core\Util\DefinedValuesListUtil::getRegionValues',
    'allowed_values_function_arguments' => '["country_id", 0]',
  ))

  ->setSettings(array(
    'allowed_values' => array(),
    'allowed_values_function' => '\Drupal\xrm_core\Util\DefinedValuesListUtil::getRegionValues(1)',
  ))

  ->setSettings(array(
    'allowed_values' => array(),
    'allowed_values_function' => '\Drupal\xrm_core\Util\DefinedValuesListUtil::getRegionValues\1',
  ))

This particular feature seems totaly undocumented in existing drupal docs. Any ideas to point me in the right direction please?

It's undocumented because it's not possible with core classes.

The options.api.php file refers to that callback as follows:

  That function will be called:

  either in the context of a specific entity, which is then provided as the $entity parameter,
  or for the field generally without the context of any specific entity or entity bundle (typically, Views needing a list of values for an exposed filter), in which case the $entity parameter is NULL.

There's no mention of being able to pass arbitrary parameters along to it. Indeed if you look at the invocation in options_allowed_values

$function = $definition->getSetting('allowed_values_function');
...
$values = $function($definition, $entity, $cacheable);

You can see that there's no scope for passing extra params at all.

Hopefully you'll be able to get the required context from the entity, otherwise you'll need to find another way to make it available to your callback function.


Core Search only yielding results on specific words We've developed a lot of Drupal 7 websites, but never encountered this before (or just didn't notice). When searching the project in question (while having re-indexed the site untill the index is 100%) for a specific word like met it finds a basic page node which contains that word, perfect. Though when looking in the same node and trying the word emissiespectograaf we cannot find the same node nor any other. This goes for a lot of other words, long or short.

I'm just not getting it, it finds one word in a node but another word, which I know for sure that is in the same node, it's unable to find it. Even though the index has been built for 100%.

Found the culprit after hours of debugging, it seems that the module Features is causing major issues with resetting the Drupal static. See this issue which contains a temporary workaround patch, since this issue has not been resolved with a solid fix yet.


add serial id to content type How do I add a NUMBER field to my content type?
A NUMBER field means a serial id similar to auto incremented primary key on a DB table.
I wanna use a unique NUMBER in view related to my content.

The Serial module will be helpful for you.

  This module provides an auto-increment (serial) field.

  Unlike Drupal's built-in auto-increment node ID, which is global and shared by nodes belonging to all content types, serial fields are managed per content type (D6)/entity (D7). For example, the serial field of an Invoice instance will generate a unique sequential number (starting at 1, then 2, etc.) exclusively for Invoice instances.


Create custom form button that does not submit webform I have webform created via Webform UI, and it's multi-step webform.

In second step ('personal information') I add custom button using HOOK_form_alter with following code

'generate_pdf' => [
    '#type' => 'submit',
    '#value' => t('Generate PDF'),
    '#limit_validation_errors' => [],
    '#submit' => ['generate_pdf_template'],
]

function generate_pdf_template takes values from $form, $form_state inserts them into twig templat, creates PDF and automatically downloads it.

My issue is, that this generate_pdf button submits the form and user is not able to send form via original submit button. Can I somehow prevent submission when generate_pdf is clicked so user can download PDF and still be able to send webform with original button and webform's handlers.

Something like this may work.

#name and #submit are required.

The name makes sure the button does not get confused with other submit buttons.

The #submit value calls a custom function you have to create.

#limit_validation_errors prevents form validation, which may or may not be useful.

  $form['generate_pdf'] = [
    '#type' => 'submit',
    '#value' => $this->t('Generate PDF'),
    '#name' => 'generatepdf',
    '#submit' => ['::generatepdf'],
    '#limit_validation_errors' => array(),
  ];


Second managed_file upload field fails with "An unrecoverable error occurred" I have a form with two (ajax enabled) upload fields.

Submitting a file to the first one works, then submitting a file to the 2nd does not, giving

  An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (20 MB) that this server supports.

(the "likely exceeded" bit is wrong in this instance)

Looking at the code and the network requests it looks like the first is POSTed to a URL including the form build ID, and includes the same build ID in the POST body data. The second is posted to the same URL, however the result of uploading the first is that the form's hidden build id has changed -this is why the code in file.module rejects it and issues this error.

Thing is, I believe this has been working until recently (perhaps a recent upgrade of Drupal 7?) as I'm only getting these reports now but the code has been unchanged for at least a year.

Any suggestions?

(Drupal 7.69)

I'm the OP: This is not a full answer, but a fix:

Forcing the session to start with $_SESSION['something'] = 1; in the form build seems to cure this problem.

If you can provide better answers please do.


Anonymous user cache control We have written some custom blocks that render dynamic content; unfortunately, the caching defaults cache the first render of this block (and don't refresh for anonymous users). Cache control seems to only work for authenticated users. Are we missing something obvious? Is it possible to control anonymous caching on a block (or page) basis?

There are two different page caches.

The Internal Dynamic Page Cache works with all kind of elements like blocks and nodes and is uses the cache tags, cache contexts and cache max-age provided by these elements.

The Internal Page Cache is for complete pages for anonymous users and only uses cache tags.

You can control the page cache for anonymous users with one parameter.

Go to the perfomance configuration:

admin/config/development/performance

And configure the page cache maximum age with the time how long your information is valid. This is also important for proxies and the browser cache, because it would not help to invalidate the drupal cache, if the page is cached in other places. After that time the page expires and should be built again. According to the documentation:

  Configuring the internal page cache On the Performance page, you can
  configure how long browsers and proxies may cache pages; that setting
  is also respected by the Internal Page Cache module. There is no other
  configuration.

But this is not true. You should configure this time for proxies and browser cache, but the internal page cache does not respect the time you set there. The only reliable solution I found is to uninstall the module Internal Page Cache or set an expire time in an EventSubscriber (for example 3600 sec in the future):

/src/EventSubscriber/SetExpiresSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class SetExpiresSubscriber implements EventSubscriberInterface {

  public function onResponse(FilterResponseEvent $event) {
    $request = $event->getRequest();
    $response = $event->getResponse();
    if ($event->isMasterRequest()) {
      $request_time = $request->server->get('REQUEST_TIME');
      $expires_time = (new \Datetime)->setTimestamp($request_time + 3600);
      $response->setExpires($expires_time);
    }
  }

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

}

mymodule.services.yml

services:
  mymodule.setexpires:
    class: Drupal\mymodule\EventSubscriber\SetExpiresSubscriber
    tags:
      - { name: event_subscriber }


Can we alter a form using view data? I is possible to:

Hook on views_pre_view (which is executed before form_alter)
Query view data (execute the view query filtering according to URL parameters) and collect some data
Hook on form_alter
Replace some selects using data collected on item 2?

I'm asking because if I $view->execute() inside views_pre_view (to filter and use view data) it will internally call form_alter and generate the form before I'm able to collect the data to pre-populate my selects. And I'm not sure if it's possible to re-generate a form that was already generated.
I also tried views_pre_execute but this one is always executed after form_alter.
Cheers!

The only way I found for now was to, inside views_pre_view, deep clone the $view object using $view = unserialize(serialize($_view)), so when Drupal passes again on form_alter the form would be untouched and I can just recreate some selects.


Sorting view results using contextual filters on Drupal 8 I created a views that filter nodes according taxonomy terms passed through contextual filters.

Node 1: term1, term2, term3
Node 2: term1, term6
Node 3: term1, term7

Everything is working good, expect i would like to display the number of term tid found in the node.
When i use the parameters term1+term7 (in contextual filters), i would like a result like this :

Node title 1: match 1
Node title 2: match 1
Node title 3: match 2

and then sort results by the matching terms.
How can i make it work with Views 3 in Drupal 8?
Many thanks.

There are two parts to this question: getting the Contextual filtering to reduce the results to only the term IDs you specify in the URL, and using Aggregation for counting and sorting the results according to that count.

Contextual filter for Taxonomy term ID

Create your Views list of nodes with the Taxonomy reference field showing the tags, and configure that field to show all values in the same row
Add the Contextual filter for your Taxonomy term field or for the Field Has taxonomy term ID and configure it:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Filter to items that share any term
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term ID
[your vocabulary]
One or more IDs separated by , or +
More
Allow multiple values

Test this by entering the term ID (number) into the Views Preview field. You should see the results reduce to show nodes tagged with that term. Also test for more than one term, enter, for example, 3+5 to show nodes that are tagged with either terms 3 or 5, or 3,5 to show nodes tagged with both terms 3 and 5.

If you want to use term names instead of term ID numbers, then instead of using the taxonomy term reference field as the Contextual filter, you'll have to first add a Relationship for that field, then you will have the Taxonomy Name Contextual filter available. You configure it similarly as above, be careful about case options. You test it by entering the term names into Preview: firstTerm,secondTerm.

Count with Aggregation

Turn Aggregation on in the third column of Views settings
Click on Aggregation settings for the Taxonomy field (from step 1. above) and change the Aggregation type to Count DISTINCT.

This field will now show the count how many terms are shared.
Add the Sort criteria for your Taxonomy terms field, and set its Aggregation to Count DISTINCT and you'll probably want to sort descending. You should have no other sorting added except this. You will see the nodes sorted by the number of tags shared with the contextual filter.

Test this the same way as above, entering term IDs, or term names if that's what you're using.

In the end you'll have to test in a real page to check that the Contextual filter has been configured properly. Build and test in steps, don't first build everything and only test because if there's something wrong it will be more difficult to figure out what and you'll have to start from scratch step by step anyway.


How to unset CSS class for menus in the template.php? Lets say I have a menu block in my header region. And by default Drupal gives .active class for links that are active. I need to get rid of that .active class, because the CSS/HTML version of the theme (which I am porting to Drupal 7) doesn't have .active class and its not just .active, there are many more.

I need this because now default Drupal rules like a.active overrides my themes CSS of a simple a rule.

Please, do not recommend !important.

If you want to override a core stylesheet, add it to your theme .info file.

That way, the .active class need have no CSS rules

e.g: themename.info

stylesheets[all][] = system-menus.css

  To override a core or contributed module style sheet, it must be
  specified in your theme's .info file. Drupal overrides are cascading
  and your theme's stylesheets override any that were previously
  declared. For example, system-menus.css is located at
  "modules/system/system-menus.css". If you place a file with the same
  name in your theme's folder and add the following entry to the .info
  file, the original system-menus.css file will be ignored and your
  version will be loaded in its place.

More info here: http://drupal.org/node/263967

See also hook_css_alter for a code-based solution to remove stylesheets.


How set specific input format for specific field like in Drupal 7? I am in a need of the Drupal 7 functionality where I could select specific input format for specific field whereas in Drupal 8 this is based on permissions and I really dislike it and for a specific project I need the good old D7 behavior.

Right now I have to alter the input format's static cache during page load to achieve the goal of providing specific input format but it is very bad approach but I haven't found an easy way to do this yet.

Better yet, I need this for my custom form, not even a field but the permissions still apply so Field API has nothing to do with it but rather how the input formats and the text format element are tied together.

FYI this is my solution right now(it is ES service):

    $route_name = $this->routeMatch->getRouteName();
    $routes = [
      ...
    ];

    if (in_array($route_name, $routes)) {
      filter_formats($this->user);
      $formats = &drupal_static('filter_formats', []);
      $formats['user'][$this->user->id()] = [
        'my_format' => $formats['all']['my_format']
      ];
    }
  }

The way I recently did this on a Drupal 8 site was to use Better Formats.

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

You can force filter format per field - one option = no select box. Even for admins.

If you are using Paragraphs, you will also need this patch.


Add Field to Custom Content Type Programatically I'm trying to create a module that creates its own content types during installation. I understand that I need to use the Configuration API and the Entity API, but I'm having trouble adding Drupal-included fields to my custom type. From what I understand, I need to have a file for each field called field.field.node.content_type.field_type.yml. Am I correct in my understanding? If so, why are their two fields and where can I find the options to place in that configuration file? I have tried scouring through the API and I can't seem to find what I need.

This is the tutorial I'm following: https://www.drupal.org/docs/8/api/entity-api/creating-a-custom-content-type-in-drupal-8

My suggestion is to use the Core Configuration Manager to "automatically" generate all the options you need. See https://www.drupal.org/docs/8/configuration-management/managing-your-sites-configuration

The approach I'd use would be to create the new content types and all their fields through the UI. Then go to Configuration -> Development -> Configuration synchronization -> Export (tab) -> Single item

From there, you just need to select your various pieces of content one-by-one. For example, if you select "Content type" from the Configuration type menu and then Article (or your custom content type), you'll see the configuration you'd put in the .yml file in your custom module config/install folder. Just eliminate that first uuid: line. If you scroll down past the configuration text area, you'll see the name of the file name you need. For article, it's "node.type.article.yml"

Besides the content types, you'll also need the Field and Field storage configuration types (and probably Entity form display and Entity view display). Pay attention to the config dependencies to make sure you get all the pieces of configuration you need.

Once you get everything you need into configuration files, you can delete everything you created through the UI, install (or reinstall) your custom module and then check whether everything is as you want it. If it's not, you can make changes through the UI and export the config again to fix your custom module configuration yaml files. Or you can just edit the files directly once you see how everything is organized, especially if you're just making little changes like the label or description text for a field.

For me, this approach was much less painful than "scouring through the API", trying to find all the various keys and possible values.


Theme suggestions not working for custom templates I have a custom theme hook that I have a tpl for but my theme suggestions are not working. It appears that they are not even being looked for. I am guessing that I am missing something.

Code:

function MYMODULE_theme() {
  module_load_include('inc', 'mymodule', 'theme/mymodule.theme');
  return mymodule_theme_theme();
}

function MYMODULE_theme_theme() {
  $path = drupal_get_path('module', 'MYMODULE') . '/theme';

  return array(
    'mymodule_theme' => array(
      'variables' => array('module' => NULL, 'key' => NULL, 'body' => NULL),
      'template' => 'mymodule-theme',
      'pattern' => 'mymodule_theme__',
      'file' => 'mymodule.theme.inc',
      'mail theme' => TRUE,
      'path' => $path,
    )
  );
}

function MYMODULE_preprocess_mymodule_theme(&$vars) {
  $module = $variables['module'] ? $variables['module'] : basename(__FILE__, '.theme.inc');
  $functions = array();
  $variables['theme_hook_suggestions'][] = $functions[] = 'MYMODULE_theme__' . $module;
  if (isset($variables['key'])) {
  $variables['theme_hook_suggestions'][] = $functions[] = 'MYMODULE_theme__' . $module . '__' . $variables['key'];
  }
  foreach ($functions as $function) {
    $function = "MYMODULE_preprocess_$function";
    if (function_exists($function)) {
      $function($variables);
    }
  }
}

The theme hook suggestions are being applied as the new preprocess function works.

function MYMODULE_preprocess_MYMODULE_theme__MODULE__KEY(&$vars) {
  dpm($vars);
}

$vars gets printed.

However my MYMODULE-theme--MYMODULE--KEY.tpl.php is not being called.

The base MYMODULE-theme.tpl.php does work.
Theme debug output:

<!-- THEME DEBUG -->
<!-- CALL: theme('MYMODULE-theme') -->
<!-- FILE NAME SUGGESTIONS:
   * MYMODULE-theme--MYMODULE--KEY.tpl.php
   * MYMODULE-theme--MYMODULE.tpl.php
   x MYMODULE-theme.tpl.php
-->

Any ideas?

EDIT: I forgot the calls I have tried. Here they are:

$output = theme('MYMODULE_theme', array('body' => $body, 'key' => $key));

and I even tried:

$output = theme(array('MYMODULE_theme', 'MYMODULE_theme__MYMODULE__KEY), array('body' => $body, 'key' => $key));

Have you tried making the template name and pattern in the hook_theme implementation uppercase like this:

  'template' => 'MYMODULE-theme',
  'pattern' => 'MYMODULE_theme__',

You can also try to remove the pattern completely. It doesn't seem to be necessary at least in the example use case.

Preprocess functions for theme suggestions doesn't work in Drupal 7, and that's why you are manually calling them in your preprocess function. They are being added to the array so they are called but they are not in the correct format so that theme system could handle  them.


How to change the field type of existing fields? Here is my case.

I've created a content type with few fields (all fields had type:
'text').
I've exported this content type using feature and then used feature on PROD website for few weeks.
Recently we decided to change type of 2 fields to: 'email' and
'link' (first we deleted these 2 fields, and then created them with
new type), I've updated feature with my content type again (since we
did changes to these 2 fields).
Now when I do deploy to my website it says that it can't convert
fields form current type to new type (and I can understand that).
However I also believe it is something that everybody does, so there
must be a normal solution to this.

Here is a message from my terminal:

  WD php: FieldException: Cannot change an existing field's type. in
  field_update_field() (line 234 of
  /Users/aaa/git/drupal/http/modules/field/field.crud.inc).
  [error] Drush command terminated abnormally due to an unrecoverable
  error.
  [error] FieldException: Cannot change an existing field's type.
  in field_update_field() (line 234 of
  /Users/aaa/git/drupal/http/modules/field/field.crud.inc).

Please advise what is the good approach to solve my issue (change type of field that is used already).

A possible approach to avoid running into this commonly known challenge, is to perform a mini-migration for each of both of your fields, on your PROD website.

Here are the highlights of such approach:

For your eMail field:

Assume your existing field (with type text) has machine name field_email.
Create a new field with type eMail (instead of text), say with machine name field_email_new.

For your Link field:

Assume your existing field (with type text) has machine name field_link.
Create a new field with type eMail (instead of text), say with machine name field_link_new.

Deploy both fields field_email_new and field_link_new to your PROD site, using Features (similar to what you tried to use, but which failed). Since these are new fields, that should not cause similar problems. Obviously, at that point the values of these fields will be empty.
For each of both fields, use an approach similar to what I described in my answer to "How do I move content from one field to another?", which (only) uses modules Rules and Views Bulk Operations. You should be able to reuse the Rules Component included there, after adapting the machine names of the used fields.
To the extend that would be needed, don't forget to adapt custom Rules, Views, etc to reference the new (instead of old) machine names of both fields.
Delete the original (old) eMail field and Link field.
Double check your custom Rules, Views, etc that you (should have) modified in 'Step 5' above, to ensure you don't have any of the typically "integrity" error messages (because you forget or skipped some of them). If any such errors show up, adapt the machine names to the new ones to fix them.

Obviously, steps 5, 6 and 7 can be refined by creating a clone from your PROD site, and prepare that kind of work in some none-PROD equivalent. Possibly combined with using a Features based deployment procedure to migrate your changes from that clone to your PROD site afterwards.

Note: NO custom coding, only some (rather basic) admin stuff, using robust contributed modules (and which can be uninstalled again afterwards).


Can't set default value with hook_field_widget_form_alter() function mymodule_field_widget_form_alter(&$element, &$form_state, $context){
if ($context['field']['type'] == 'node_reference' &&
  empty($element['#default_value'])) {
$element['#default_value'] = 51113;
  }
}

the above does not work - I'm simply trying to set a default value through hook_field_widget_form_alter. The hook works - I can alter options and so forth, but not the default value. Any ideas?

solved - I noticed my default values worked on node-edit forms, so I tried raising my custom module's weight, which seemed to do the trick :-)


Views - offset when displaying all results? In a view, either set to "display all results" or "specified number of results" and set to 0, I cannot seem to be able to use the "offset". On the other hand, if I set a number of items, say 100, I can use the offset just fine (I want to hide the first item from the result set). Any ideas on what could be causing this?

I'm pretty sure that's the way it's designed.  If you set the number of things to be displayed to display all results or 0 (which is the same thing), it doesn't make sense to have an offset because you already ordered it to show every single result.

If you want to use an offset, set a specified number of results.  If you don't know what number to set, just pick an arbitrarily high number that you are unlikely to exceed.

EDIT: If you just want to hide the first item, is there some way to configure one of the filters so that the item is removed?  That is another possible approach.


How do I send a HTML email? Does anyone know how to send HTML email using the Rules module? This was a pretty common task in Drupal 7, and I think the rule was included with the Mime Mail module.
The Drupal 8 version of Mime Mail doesn't seems to integrate with the Rules module.

The Drupal 8 version of Mime Mail doesn't seems to integrate with the
Rules module.

This question and the follow-up comment seem to imply that Rules integration with Mime Mail is NEEDED in order to send HTML email with Rules. That's not true. Drupal core doesn't support HTML email, so you need an add-on module like Mime Mail if you want to send HTML email. But if you have Mime Mail installed, then you can send HTML email from ANY source, INCLUDING Rules. If you follow the Mime Mail Quick Start documentation you will get this working in just minutes.
There is also a complete example at https://www.drupal.org/docs/8/modules/d8-rules-essentials/examples/email-examples/sending-html-email showing how to send HTML email from Rules using Mime Mail.
Mime Mail integration with Rules allows Rules to use the ADDITIONAL features provided by Mime Mail which are not part of Drupal core or part of other email modules.  But this additional integration is not needed unless you want to use those Mime Mail features. For example, the ability to add attachments, or to specify a plaintext email body that is different from the HTML body. Those are Mime Mail specific features.
Mime Mail is not completely ported to D8 yet but there is a patch that ports the Rules support at https://www.drupal.org/project/mimemail/issues/2928965 If you need these additional features I suggest you contribute to that issue.


EntityMalformedException in custom module. Can anyone see what I did wrong? I'm trying to create a custom module and found out that it's causing the following error message to appear:

EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7721 of ~/includes/common.inc).

if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
  throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
}

I'm using xdebug setup with netbeans to debug the error and found out what is causing the culprit.

I found out it was a specific field I added in my module that looks like this:

$form['base']['st-volume-pricing']['add'] = array(
'#type' => 'button',
'#value' => t('Add'),
'#name' => 'add_row',
'#limit_validation_errors' => array(
  array('price'),
  array('till-amount'),
),
'#ajax' => array(
  'callback' => 'bulk_and_user_pricing_add_volume_standard_ajax_callback',
  'wrapper' => 'error-placeholder',
  'method' => 'append',
  'effect' => 'fade',
),
'#prefix' => '<td>',
'#title' => t('Click this button to add a standard volume price'),
);

My debugger basically showed the following data:

$info['entity keys']['bundle'] = "type"
$entity_type = "node"

$entity stdClass
add string  "Add"
add_row string  "Add"
price   string  "123"
till-amount string  "123"

I checked my database and couldn't find any nodes without type so that shouldn't cause any problems.

I suppose I have to define the bundle in my code somewhere but I'm not that famillair with bundles yet.

The field is added to the node edit page of a product created by the ubercart module using hook_form_FORM_ID_alter() -> hook_form_product_node_form_alter().

Does anyone have a clue as to what I should do to define the bundle?

Or in OOP terms, how can I make my field a class member of the ubercart product bundle (which is an extended class of the entity type base class)?

Please check Examples, specifically entity_example module to check how to define the bundle.

So for Drupal 7 it goes like:

/**
 * Implements hook_entity_info().
 *
 * This is the fundamental description of the entity.
 *
 * It provides a single entity with a single bundle and without revision
 * support.
 */
function entity_example_entity_info() {
  $info['entity_example_basic'] = array(
    // A human readable label to identify our entity.
    'label' => t('Example Basic Entity'),

    // The controller for our Entity, extending the Drupal core controller.
    'controller class' => 'EntityExampleBasicController',

    // The table for this entity defined in hook_schema()
    'base table' => 'entity_example_basic',

    // Returns the uri elements of an entity.
    'uri callback' => 'entity_example_basic_uri',

    // IF fieldable == FALSE, we can't attach fields.
    'fieldable' => TRUE,

    // entity_keys tells the controller what database fields are used for key
    // functions. It is not required if we don't have bundles or revisions.
    // Here we do not support a revision, so that entity key is omitted.
    'entity keys' => array(
      // The 'id' (basic_id here) is the unique id.
      'id' => 'basic_id' ,
      // Bundle will be determined by the 'bundle_type' field.
      'bundle' => 'bundle_type',
    ),
    'bundle keys' => array(
      'bundle' => 'bundle_type',
    ),

    // FALSE disables caching. Caching functionality is handled by Drupal core.
    'static cache' => TRUE,

    // Bundles are alternative groups of fields or configuration
    // associated with a base entity type.
    'bundles' => array(
      'first_example_bundle' => array(
        'label' => 'First example bundle',
        // 'admin' key is used by the Field UI to provide field and
        // display UI pages.
        'admin' => array(
          'path' => 'admin/structure/entity_example_basic/manage',
          'access arguments' => array('administer entity_example_basic entities'),
        ),
      ),
    ),
    // View modes allow entities to be displayed differently based on context.
    // As a demonstration we'll support "Tweaky", but we could have and support
    // multiple display modes.
    'view modes' => array(
      'tweaky' => array(
        'label' => t('Tweaky'),
        'custom settings' => FALSE,
      ),
    ),
  );

  return $info;
}

Or for simpler example, entity.api.php from Entity module which goes like:

function entity_crud_hook_entity_info() {
  $return = array(
    'entity_test' => array(
      'label' => t('Test Entity'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIController',
      'base table' => 'entity_test',
      'module' => 'entity_test',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'pid',
        'name' => 'name',
        'bundle' => 'type',
      ),
      'bundles' => array(),
    ),
  );
  foreach (entity_test_get_types() as $name => $info) {
    $return['entity_test']['bundles'][$name] = array(
      'label' => $info['label'],
    );
  }
  return $return;
}

The error EntityMalformedException which you're having it's saying that your bundle property is malformed on save, so Drupal core can't identify what type (bundle) is that.

Troubleshooting:

Check what's the value of bundle in entity keys section of array defined in entity information array via:

drush eval 'print_r(entity_get_info("entity_type"));'

If it's type, then that means your entity which you're trying to save, it's missing type attribute.

The common mistake is usually to load the entity via entity_load() and trying to re-save it, but remember that return value is an array of entity objects indexed by their ids.

So the simple test to verify if your entity re-saving works correctly, it would be:

drush eval '$entity = entity_load("entity_type", array(1)); entity_get_controller("entity_type")->save(reset($entity))'

where entity_type is your entity_type and 1 is your entity id.


response grid view and adaptive themes I have:

a view which displays three pictures of 300 * 200 each
it should be responsive at breaks of 300 and 600
adaptive themes

1) I installed responsive grid view. In here I need to add a wrapper – but I don't know which one or what to create. Is there already a wrapper in the adaptive theme for this?

2) Also I generated a css file at gridpack.com. This css file I added to the theme and I replaced:

.col with the views-responsive-grid label (css is in the page)
.col with .views-column (the css is in the page)
.row with .views-row (I can't see this back in the page)

It still doesn't work. Still on the big screen all images are display vertically. Is this the way it should work or there any other suggestions?

I don't know if you mean adaptive theme as the theme on drupals repository or adaptive theme as a general behavior. Either way, you don't need a module to handle it. You just need the proper media queries, regardless if they're served by AdaptiveThemes or you insert them directly into your CSS files, somewhere at the end.

Once again, displaying three elements as a grid doesnt require a grid regulation. Is just a view, could be unformatted or html list or whatever. You need to declare responsive widths in your CSS for each row of the view, like so:

  Consider using .gridimg as your row class in unformatted format for
  example

HTML

CSS

            .gridimg {
                width: 33.333333%;
                float: left;
            }

Then the media query where needed

            @media all and (max-width: 600px) {
                gridimg {
                    width: 100%;
                    float: none;
                    margin-bottom: 10px;
                }
            }

Do not display elements for the sake of your media queries, display elements for the sake of your content. Replace 600px with whatever resolution you want your rows to adjust.

Your classes could be named differently. Also the wrapper of your three generated rows should be set to 100%. Rows within should be position: relative;. They're like this by default, unless specified in a different manner.

Maybe your image element should have some css applied to them, for responsive purposes, if they're not set already:

            .gridimg img {
                width: 100%;
                height: auto;
                display: block;
            }


Looking for a way to trigger an event for testing custom event subscriber I am looking for ways to trigger an event in my local dev to check out a custom event subscriber. The actual event is triggered by Google social auth and I don't think it is possible to do that locally.

Is it possible to trigger events using devel

You can use the event_dispatcher service to trigger an event.

Use this code to trigger your event.

\Drupal::service('event_dispatcher')->dispatch(MyModuleEvents::MY_EVENT, new MyModuleEventClass());

Of course you have to replace the names with your real names.

You can run the code using drush php.

You can read more about subscribing and dispatching events here.


Receiving two subscriptions emails when run cron using rules I need to send subscriptions immediately to users upon updating content. It is sending one subscriptions email when I run cron manually. But, when I run cron using rules, it send two subscriptions emails.

I have checked and found that I get one email only when I use rule to send test email.

Subscriptions setting: Users are not subscribed to content type...they are subscribed to taxonomy terms only.

Using modules for mail setup:
1. Mail system.
2. Mimemail.
3. Subscriptions.
4. Mail templates.

How can I send one subscriptions email only to each users upon updating content?

I finally solved this. I noticed that it was rules who was getting trigger two times. This  link  help me.  I thetrigger me to disable another rule on same event condition.


How do I create and apply a configuration schema for an existing custom module? I have a custom module, already running for a longer while, but I did not take into account that the configuration would have to support translation. I have had no config/schema/module_name.schema.yml file at the time of installation.

I created the schema file, looked into implementing hook_update(). I was just about to start implementing it, but I checked the output of \Drupal::service('config.typed')->getDefinition(DrupalHooks::CONFIG_KEY); just in case. The schema file was automagically absorbed by either drush cr, or loaded by the code snippet itself.

I don't find my module listed on the admin/config/regional/config-translation page. Also, the other modules shown in that list seem to always have a Translate tab on their configuration page. My module doesn't get that either.

What am I supposed to do to make it translatable? Is there any hook I should implement, or am I missing something else?

To have the "Translate" tab listed on your module's configuration page you additionally need to provide a module_name.config_translation.yml in your module's root.

module_name.settings:
  title: 'Module Name'
  base_route_name: module_name.admin_settings
  names:
    - module_name.settings

Look for existing module_name.config_translation.yml file in core and contrib and you'll get the pattern no problem.


Quiz Module - Restart (Reload) the question of the quiz when it has been wrongly attempted four times I am trying to reload the page (or) make the user attempt the question again if he/she has made four wrong attempts.

I am using Quiz module in Drupal 7.

Is there a possibility?

Thanks

It's kind of hard to decide what to do without code samples, but the following ideas come to my mind:
First, you could try a simple PHP command in the form of header("Refresh:0");, calling that once the wrong answer count reaches 4.
My second idea is that you try to integrate some JavaScript into the module itself, attaching a click event to the buttons or whatever it your user is clicking on. The click event could keep track of how many wrong answers they've gotten, and once they hit the threshold, have the JavaScript call location.reload().


Example for $form_state[‘rebuild’] May anyone give me an example of rebuilding the form using $form_state['rebuild'] after user's input?

$form_state['rebuild'] is used extensively in multistep forms. Take a look at the more advanced examples in the Form Example in the Examples project.  It's used in AJAX forms, as a special case of multistep, so you may want to look at the AJAX example.


How do I construct the JSON data with session info for creating node? I am using Drupal 7 and the Services module 7.x-3.2. I am using Postman for Chrome (a http client) to test the API.

What I want to do is log in a user and create a node with the user using the Drupal service API.

I logged in the user with JSON POST request to http://example.com/api/user/login.

I successfully got the JSON result.

{
    "sessid": "KrZjlcY3rFr8v6iLoskcVQN9DmDWsg5yZqIjBeydEBY",
    "session_name": "SESS9fe39db36ccd7afd64e034fefa0129e1",
    "user": {
        "uid": "31",
        "name": "test_user",
        "mail": "services_user_2@example.com",
        "theme": "",
        "signature": "",
        "signature_format": "filtered_html",
        "created": "1352985941",
        "access": "1352991170",
        "login": 1352991510,
        "status": "1",
        "timezone": "",
        "language": "",
        "picture": null,
        "init": "services_user_2@example.com",
        "data": false,
        "roles": {
            "2": "authenticated user"
        },
        "rdf_mapping": {
            "rdftype": [
                "sioc:UserAccount"
            ],
            "name": {
                "predicates": [
                    "foaf:name"
                ]
            },
            "homepage": {
                "predicates": [
                    "foaf:page"
                ],
                "type": "rel"
            }
        }
    }
}

Then I tried to create an article via the API by sending the JSON POST request. (The user has the permission to create Article nodes.)

I got a 401 Unauthorized response.

I guess I need to include the session cookie information to send the POST request, to create a node.

I have the session information previously returned.

"sessid": "KrZjlcY3rFr8v6iLoskcVQN9DmDWsg5yZqIjBeydEBY",
"session_name": "SESS9fe39db36ccd7afd64e034fefa0129e1",

How can I utilize it to make a successful JSON POST request for creating a node?

{
   "title": "Just another drupal Post",
   "type": "Article"
}

notice no comma after the type:article tag so that your json works.


how to make fewer http requests I'm use YSlow to optimize my web pages it says:
This page has 34 external Javascript scripts. Try combining them into one.
This page has 5 external stylesheets. Try combining them into one.
but all I have in this page is some blocks and menus and a nivo slider which I think is the main reason of this issue!!
so I think nivo slider sends all this requests!!
How can I improve it?

There are couple of things you can do,

install labjs module: it is a JavaScript loader, used by Twitter, Vimeo, examiner.com... which loads (and executes) all scripts in parallel as fast as the browser will allow.
Enable gzip compression: It reduces the size of files sent from server to increase the speed. You have to enable it in .htaccess file, for more information visit this page.
As @2pha said Advanced CSS/JS Aggregation is very effective effort.
Install optimize_db module: it handles the issue with fast-growing table cache_form.

Anyway, gtmetrix  suggests many techniques to improve your website performance.


How to correctly specify image links in a content type? How to correctly specify img src  like  inside a content like Basic page or Blog, which does not break even when  site is accessed as   http:/example.com/drupalsite or  http://example.com/ and  while accessing as  http:/example.com/node/2 or  http://example.com/path-auto-title ?

First set $base_url in your settings.php file in sites/default/ directory.
I am sure you are using ckeditor or some other editor. In editor setting use use relative URL for images and links.
Make sure your Apache mod_rewrite or rewrite_module is enabled.


Theming forms. Form-element Please, help. Is it possible implement different templates for form-element.html.twig? For form 'user-form' one template, and for other forms second template.

As you requested, this is an example how I did using field names.

In your .theme file:

function THEME_preprocess_form_element(&$variables) {
  //This is a list of fields in contact form
  $showAfter = array('name', 'mail', 'subject[0][value]', 'message[0][value]');
  if (in_array($variables['name'], $showAfter)) {
    //If is one, I change here how to display instead using different twig file
    $variables['element']['#title_display'] = 'after';
    $variables['label_display'] = 'after';
  }
}

Now, if you want use different twig file for each field name use this...

.theme file

function THEME_theme_suggestions_form_element_alter(array &$suggestions, array $variables, $hook) {
  if (isset($variables['element']['#name'])) {
    //Name can be a string like this, 'subject[0][value]'.
    //When this happen, I just get 'subject'.
    $suggestions[] = 'form_element__' . explode("[", $variables['element']['#name'])[0];
  }
}

Then in your HTML appear something like this:

<!-- FILE NAME SUGGESTIONS:
   * form-element--subject.html.twig
   x form-element.html.twig
-->

Note:
The main problem is how you get form_id in preprocess or theme_suggestions (form_element Hook), I didn't find a way to get this information.


display question content type and a referenced node answer I have a content type - question (its used for questions)
AND content type - answer (it has a field -> nodereference to questions with select list)

How to display in a view block question title and below to each question - referenced node title of content type answer?

What i did: i'v created a view block, and filtering it by content type - question, now im displaying all question titles, but how to display answers below these question (Each answer below referenced question)

Something like:

Do you smoke cigarettes?

Yes, i do.

What's your name?

My name's Jack.

You will have to create a relationship.

Click the [+] next to Relationships in Views, and select the field that contains your node reference
Make sure your Row Style is set to fields
Select Node: Title - do not use the relationship yet.
Next, select Node title again, but this time tell it to use the relationship (the field should be listed in your field listing as (Relatioship name) Node: Title).
Filters should be set to whatever your content type for questions is called.


How add markup and prefix / suffix for computed field I want to add wrapper element to CCK computed field in a content type.

I could calculate the value of field but when I use HTML tags in Display Code section the result is not rendered properly.

for example I use this code in Display Code.

$display_output =  '
' . $entity_field_item['value'] . ' Count
';

But the result is not corrected HTML . it seems it is encoded !!

&lt;div class=&quot;row&quot;&gt; &lt;span class=&quot;suffix&quot;&gt;Count&lt;/span&gt;&lt;/div&gt;

Can you tell me what should I do to repair this problem ?

I don't know where your variable $entity_field_item comes from, but you can generally add additional markup in at least three different ways:

1. Adding #prefix and #suffix to the fields render array using a preprocess function:

function mytheme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  if ($element['#field_name'] == 'field_myfield') {
    $variables['items'][0]['#prefix'] = '
';
    $variables['items'][0]['#suffix'] = 'Count
';
  }
}

2. Adding #prefix and #suffix in hook_node_view():

$node->content['field_myfield'][0]['#prefix'] = '
';
$node->content['field_myfield'][0]['#suffix'] = 'Count
';

3. Adding a new item to the $content array:

$node->content['my_custom_output'] = array(
  '#type' => 'markup',
  '#markup' => $entity_field_item['value'],
  '#prefix' => '
',
  '#suffix' => 'Count
',
);


Missing the message status when saving Node Of the handful of content types on our site, some of them don't display the message status (ex. Article Test has been created) when the node is saved.

Where can I investigate the cause?

This message comes from node.pages.inc (never edit Drupal core) in a form submit function and I believe messages are stored in the $_SESSION['messages'] variable. I would try to get at these with a hook_form_alter() and custom validation and submit handlers to see where it might be dropping.

If you're running any custom code look specifically for interactions with the $_SESSION variable. Clobbering or unsetting it could prematurely remove these messages.

If you use the devel module you can simply use the following.

dd($_SESSION['messages']); //Logs to drupal logs
dpm($_SESSION['messages']); //Outputs debug information to screen

You can also create your own messages using drupal_set_message()

For example:

drupal_set_message(t('It worked!'), 'status');

You may also want to check that you don't have something like the Disable Messages module installed or misconfigured.


Feeds import - If title has "=" at the end, check whether duplicate content exists I have an XML to import products to Drupal Commerce site. But some products are duplicates. Duplicate products are having "=" at the end of their title, but NOT all products with "=" at the end of their title are duplicates.

What I need is, on importing XML, check whether product exists, if exist, do not import (easy), if product has "=" at the end of title, check whether product WITHOUT "=" at the end of the title exist. If exist, do not import, else import.

I am totally lost how to do that, should I write some feeds tamper module to handle such a behaviour or go completely outside the drupal and parse XML, compare it to current product database of drupal and export new XML to import to drupal? Any advice would be greatly appreciated!

Set product title as unique

First, you'll need to set the product title as unique. This way, Feeds will only import one product per title.

Is the "=" at the end important to the product title? If not, you'll need to find a way to remove that sign from the product title. This way, Feeds will treat a product title with an "=" as equal to the same product title without the "=".

Find replace Tamper plugin (D7 and D8)

If you are certain that the sign "=" is only used at the end of the product title (or meaningless if it appears anywhere else), you can use the easiest solution: Use the Tamper plugin "Find replace" to replace "=" with "". This plugin is available for both D7 and D8.

Find replace REGEX Tamper plugin (currently D7 only)

If the "=" sign can appear elsewhere in the product title and is important there, you'll need to use the "Find replace REGEX" tamper plugin. In the field "REGEX to find", enter a regex that matches strings ending with a "=":

/\=$/

And replace with an empty string.

D7 or D8?

At the moment of writing, the Tamper plugin "Find replace REGEX" has not been ported to D8 yet (see https://www.drupal.org/project/tamper/issues/2975179 for the status). If you are using D8 and the Tamper plugin "Find replace" does not suffice, you'll to create a custom module and listen to the Feeds parse event in order to apply modifications on the product titles.

Example:

namespace Drupal\mymodule\EventSubscriber;

class ProductFeedSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[FeedsEvents::PARSE][] = ['afterParse', FeedsEvents::AFTER];
    return $events;
  }

  /**
   * Act on parser result.
   */
  public function afterParse(ParseEvent $event) {
    // Check if this is the feed we want to edit.
    $feed_type_id = $event->getFeed()->getType()->id();
    if ($feed_type_id != 'myfeedtype') {
      // Not the feed type we want to edit. Abort.
      return;
    }

    /** @var \Drupal\feeds\Result\ParserResultInterface */
    $parser_result = $event->getParserResult();

    /** @var \Drupal\feeds\Feeds\Item\ItemInterface */
    foreach ($parser_result as $item) {
      // Get product title.
      $title = $item->get('title');

      // Remove "=" sign from the end if there is any.
      $title = preg_replace('/\=$', '', $title);

      // Set title back on item.
      $item->set('title', $title);
    }
  }

}

Be sure to replace "myfeedtype" in the example above with the name of the feed type that you created for importing products.

An event listener always needs to be declared in your module's 'services.yml' file:

services:
  mymodule.product_feed:
    class: Drupal\mymodule\EventSubscriber\ProductFeedSubscriber
    tags:
      - {name: event_subscriber}

In the D7 version, you would need to implement the hook hook_feeds_after_parse() to alter the parsed result.


Showing All Taxonomy Terms count based on a given contextual filter I need to create a view that shows All Taxonomy Terms count from a vocabulary based on a contextual filter given.

The contextual filter I'm to be passed are Regions and Regions are taxonomy terms as well so I pass the term name via URL and the contextual filter will then convert the term name to term id and it's working fine and it's already showing the list of Taxonomy Terms and their count (See pic 2).

My problem is that it's only showing terms that's been used, I need to show all terms even terms that hasn't been used or have 0 result on count. I already supplied 'No Result Behaviors' on the fields yet it's still not showing. Can someone help me on this one? Thanks!

You Did your jobs correctly but you have only one mistake, you should create  views according to nodes then relate it to taxonomy instead create taxonomy view then relate it to nodes.
I explain my mean by example

Nid           title         termid
1           title1       55
2           title2       43
3           title3       55
4          title4        --
5          title6       16

So when  there is not set termid view has a row result with no termid then this mean you can  put 0 value in  "No result"


Rules not marking all registrations to complete when commerce order is complete I am using the RedHen raiser profile which comes with Drupal Commerce and entity registration set up and ready to go. In my set up users can 'register for an race/run event' The process is they choose the number of 'tickets' they want. Based on this number entity registration shows that number of registration forms. User completes the registration forms, then hits the checkout process which tallies up the number of registrations for the order.

A single order can have multiple registrations.

I have a rule to mark all registrations to 'Complete' when the order is finished.

When I use the 'When an order is first paid in full' event only one registration from the order gets marked as complete.

When I use the 'Completing the checkout process' event all registrations are marked as complete.

From what I understand using 'Completing the checkout process' isn't safe because technically a user could get a failed credit card transaction and the completing the checkout process would return as true.

Below is the export of my rule using the completing the checkout process.

{ "commerce_registration_complete_upon_full_payment" : {
"LABEL" : "Set Registrations to Complete upon Full Payment",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Commerce Registration" ],
"REQUIRES" : [ "commerce_registration", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"DO" : [
  { "commerce_registration_set_state" : {
      "commerce_order" : [ "commerce-order" ],
      "registration_state" : { "value" : { "complete" : "complete" } }
    }
  }
]}}

My question is: How can I mark all registrations in the order to complete when the order is truly complete?

Have you experienced the issue with the failed card? I run an event website with entity registration and commerce and we process an average of 20 registrations a day and haven't had that problem yet.

But if you want to be certain you could utilize hook_commerce_checkout_complete, look at the order payment details and check that the order has been marked paid successfully. If so, invoke the rule or use entity query to lookup all registrations related to the order_id and mark them complete.


Drupal Node Id reflection What's the preferred way to get the current Node ID while inside a Drupal module function, without passing it in?

Adding more text, because StackOverflow won't post short questions:

Ideally, I'd like some kind of reflection function, where I can simply request the NID of the  node being served in the stack trace. Since Drupal revolves around serving nodes, it stands to reason that there should be some kind of reflection function that makes "the node I'm operating on presently, or NULL if I'm not operating on a node", available at all times.

The best discussions I've found pull the NID out of the URL. This strikes me as a backwards way of recovering the NID, and fragile, to put it mildly.

If you would like to get the current viewed nodes id you should be able to do like this:

// check so we're really viewing a node
if (arg(0) == 'node') {
  // grab the nid for the node
  $nid = arg(1);
  // you could also try to load the node to make
  // sure the supplied nid is valid
  if (node_load($nid) == FALSE) {
    // failed to load the node
  }
}

In the case of an ajax request I guess you really should supply the nid as an argument:

function <MODULE>_menu() {
  $items['sample/%1'] = array(
    'page callback' => '<MODULE>_sample',
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  };
  return $items;
}

function <MODULE>_sample($nid) {
  // use the supplied nid here
  $node = node_load($nid);
  if ($node) {
    // do something with the loaded node
  }
}

jQuery('#output').load('sample/21');


Apply a filter to a view I have some code:

 http://mysite.com/node/1/edit
 <?php echo "Hello World!"; ?>

I have a content that processes it:

 http://mysite.com/node/1
 Hello World!

I have a view that displays the code based on context:

http://mysite.com/node/1/code
[[php]]<?php echo "Hello World!"; ?>[[/php]]

How do I apply Syntax Highlighter or Geshi to the output of a view to get it looking pretty?

what if you try to call directly the Syntax Highlighter or Geshi libraries to be readed from view templates? here is an example of Geshi (http://qbnz.com/highlighter/geshi-doc.html#basic-usage) and here another with Syntax Highlighter (http://alexgorbatchev.com/SyntaxHighlighter/manual/demo/) Is only a suggestion (not tried).


composer-install of Drupal8 creates a tmp####/ folder. How to manage & clean it? I'm working with Drupal, with v8, using Composer to install & manage it.

I create a new Drupal8 project using the 'drupal-composer/drupal-project' template,

composer create-project --keep-vcs --stability dev --no-interaction drupal-composer/drupal-project:8.x-dev mysite

That installs

tree mysite  -L 1
    mysite
    ├── composer.json
    ├── composer.lock
    ├── drush
    ├── LICENSE
    ├── phpunit.xml.dist
    ├── README.md
    ├── scripts
    ├── tmp12972441691459034756
    ├── vendor
    └── web

If you look inside that 'tmp#' folder

tree mysite/tmp12972441691459034756 -L 2
    mysite/tmp12972441691459034756
    └── drupal-8.0.5
        ├── autoload.php
        ├── composer.json
        ├── composer.lock
        ├── core
        ├── example.gitignore
        ├── index.php
        ├── LICENSE.txt
        ├── modules
        ├── profiles
        ├── README.txt
        ├── robots.txt
        ├── sites
        ├── themes
        ├── update.php
        ├── vendor
        └── web.config

it looks like a complete copy of the source.

Afaict, it's used only on the first install, and doesn't ever seem to get cleaned up or deleted (by cron etc).

Do I need to keep those files around for some reason?  Or is it safe to just delete that folder?

Is there a Drupal8 maintenance task, maybe cron, that should be cleaning it out?

I've read older comments on this, and there's references to old versions' "/tmp" usage, but this is not that I guess, and this has a hash.  Anyway, I don't see the Drupal8-specific usage instructions anywhere.

You shouldn't keep the tmp folder. The scaffolding plugin should delete tmp folder after it copied the necessary files into the web folder. Not sure what went wrong on your machine.

Fixed in https://github.com/drupal-composer/drupal-scaffold/issues/33


Performance (or other) benefit to adding CSS and JS files in a .info file rather than tpl? Ive always the Zen theme and added additional CSS and JS files in the page's tpl file, rather than using the .info file. Is their any performance or other downside to my method?

Thanks

Yes, the JavaScript cannot be aggregated meaning that instead of asking for a single (few) css/js files, the browser will have to ask for more files which is slower and required more work of your web server.

Depeding on how many JS and CSS files you add in your page.tpl.php you can get a noticeable performance improvement using the .info file method. It's also a lot better should you need to use your theme as a base theme, since it allows for better alters of the JS/CSS files.


How to load my Entity in Entity form i have:

/**
 * @ContentEntityType(
 *   id = "my_entity",
 *   label = @Translation("drwywr werwer label"),
 *   bundle_label = @Translation("My entity type"),
 *   handlers = {
 *     bla...
 *     "form" = {
 *       "default" = "Drupal\my_entity\Form\MyEntityForm",
 *       "edit" = "Drupal\my_entity\Form\MyEntityForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm"
 *     },
 *     bla...
 *   },
 *   translatable = FALSE,
 *   entity_keys = { bla... },
 *   bundle_entity_type = "my_entity_type",
 *   links = {
 *     "collection" = "/admin/test/entity/collection",
 *     "canonical" = "/admin/test/entity/{my_entity}",
 *     "edit-form" = "/admin/test/entity/{my_entity}/edit",
 *     "delete-form" = "/admin/test/entity/{my_entity}/delete"
 *   }
 * )
 */

based on above, how do i load my entity in form below:

<?php

namespace Drupal\my_entity\Form;

use bla...

/**
 * Form controller for the node edit forms.
 */
class MyEntityForm extends ContentEntityForm {
 //how to load my entity type here?
}

i tried a couple way but i keep receiving:

  Error: Call to a member function getEntityTypeId() on null

mainly because the entity is not loaded (null value)

this is how i create the route:

in my_entity.routing.yml:

route_callbacks:
  - 'entity.my_entity.routes::routes'

in routes:

public function routes() {
// Build Entity Create Route - CREATE
  $route = new Route(
      (substr($type->getRoute()['path'], -1) == '/' ? $type->getRoute()['path'] . $type->id() : $type->getRoute()['path'] . '/' . $type->id()) . '/create',
      [
        '_form' => '\Drupal\my_entity\Form\MyEntityForm', //TODO : not finish
        'entity_type' => 'my_entity',
        'bundle' => $type->id(),
        '_title' => 'Create ' . $type->getRoute()['label'],
      ],
      ['_permission' => 'entity admin settings']
    );
  $route_collection->add('entity.my_entity.' . $type->id() . '_create', $route);
}

if you see in my content entity type config above, i have:

 *   links = {
 *     "collection" = "/admin/test/entity/collection",
 *     "canonical" = "/admin/test/entity/{my_entity}",
 *     "edit-form" = "/admin/test/entity/{my_entity}/edit",
 *     "delete-form" = "/admin/test/entity/{my_entity}/delete"
 *   }

which i want those: edit, delete to be able to 'link' with my form as well - how to do this?

what i'm trying to achieve is: to generate forms based on field define in my entity type

Your code currently loads the form with the _form routing definition. For classes extending ContentEntityForm, you have to use the _entity_form notation instead. Here is an example of an 'module_name.routing.yml' file:

kollektivhampel.pdf_erstellen_form:
  path: '/intranet/{my_entity}/something'
  defaults:
    _entity_form: 'my_entity.default'
    _title: 'Your page title'
  options:
    parameters:
      my_entity:
        type: my_entity
  requirements:
    _permission: 'some permission defined in your module_name.permissions.yml file'

The     _entity_form is composed of two parts: before the dot, you have the entity type id, in this example my_entity. Behind the dot, you have the name of the form, defined in the handlers section of the @ContentEntityType annotation. In this case, the second part is default, According to your question's code, this refers to \Drupal\my_entity\Form\MyEntityForm. You might not need the route_callbacks code, as a static routing directly in the yml file is probably enough.

For more details, see https://www.drupal.org/docs/8/api/routing-system/structure-of-routes.


access profile2 fields values How can I access fields values inside profile2 main profile? Only on edit main profile page? I try to hide a field on profile2 edit page based on another value. Code is from my template.php

function my_theme_form_profile2_edit_main_form_alter

and then calling

global $user;
$profile = profile2_load_by_user($user->uid, 'main');
$checkbox1 = $profile->field_checkbox_admin1['und'][0]['value'];

The problem is that profile variable is not accessible if all of the fields in profile are empty. dpm($profile) shows nothing and I get undefined variable error.

Just define the  variable already before using it

$profile ="";
global $user;
$profile = profile2_load_by_user($user->uid, 'main');
$checkbox1 = isseet($profile->field_checkbox_admin1['und'][0]['value']) ?      $profile->field_checkbox_admin1['und'][0]['value'] : "";

That is nature the profile 2 module, it doesn't create any entry for any field in the database untill it is not assigned any value actually. So it returns nothing if it is empty.

Hope it will help


What does the "Views: Filter by an entity reference view" reference method do? I was just creating a reference type and noticed that there is a reference method called Views: Filter by an entity reference view. What does this do, and how does it differ from the Default method?
I tried selecting it but received the following message:

No eligible views were found. Create a view with an Entity Reference display, or add such a display to an existing view.

I tried creating a view but couldn't see any Entity Reference display options. I also couldn't find any documentation about what this reference method (or the default one, for that matter) do.

In your Entity Reference Field settings the Default method will allow all of the entities of the type you specified to be eligible to be referenced.
If you're setting up your ER field to reference Taxonomy terms of a certain vocabulary then all of the terms from that Vocabulary will be able to be chosen inside that field.
If you want more control over which items should be eligible you can use Views to create a Display of type Entity reference.
Views module allows you to build various lists of entities. You can add filters and narrow down the list to the items you need in a specific case.
If you want a list of 10 specific Taxonomy Terms from a Vocabulary that contains 100 terms you can use Views to build it.
Usually you build Views Displays of types "Page" and "Block". But there is also the option to build "Entity reference" Display.
The "Entity reference" Display type has some special settings that other displays don't have, and they control what the list of entities should look like in the context of using that list in an ER field on a CT.
So once you create one Entity Reference Display type in Views, set it to filter the same type of items as an ER field in your Content Type, you will be able to return to your ER field settings and choose that Views Display as the field reference method.
This means that the entities offered to be chosen through the ER field when creating a new node will be only the entities from the Views you had created. If you had narrowed down the list of entities in the ER Views Display to only 3 items, then only those 3 items will be available in the ER field when creating a new node.
The Views Display must be Saved before it can appear in the ER field settings. When creating the View you choose the type of entities that will be listed, for example Taxonomy terms, and after the View has been created you can add a new Display to the Views, choose "Entity reference" from the list of the offered Views Displays (different Views Displays are shown as tabs on the Views Edit page).