Changing logo when signed in In page.tpl.php, the logo section is handled as:

<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
    <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

<?php endif; ?>

When user signs in, I want logo to change from logo.png to inner_logo.png

I can track where $logo comes from and add an if statement like <?php if($user->uid <=0) { $logo = "logo.png" } else { ... ?>

But would this be the correct practice? Is there a more practical Drupal way?

edit:

/* Override or insert variable into the pre-process_template*/
function bartik_preprocess_page(&$variables) {
    if (user_is_logged_in()) {
        $variables['logo'] = (drupal_get_path('theme', 'bartik') . '/images/inner_logo.png');
    }
}

In general, every .tpl.php has what is called a "preprocess" function.  The default one for page.tpl.php is template_preprocess_page().  This sets up the variables that are available in the template.  Other modules and themes can have their own; then don't replace each other, rather, they all run in a defined order.

So, you would add in a preprocess function for your theme's template.php like:

function MYTHEME_preprocess_page(&$variables) {
  if (user_is_logged_in()) {
    $path = drupal_get_path('theme', 'MYTHEME');

    $variables['logo'] = file_create_url($path . '/images/inner_logo.png');
  }
}

This will check to see if the user is logged in using the proper API call (program to the interface not the implementation), and then change the logo variable to a new path from within your theme.  Just make sure you clear the Drupal caches from admin/config/development/performance first so the function gets picked up.


Twig escapes tags when using raw value in template I am printing fields in a node template, but Twig is escaping my tags and ruining my day.

My .tpl looks like this:

{{ content.field_myfield.0 }}

I want to strip all tags from the original field and then "wrap" the field in a paragraph tag with the title class.  I found out how to get the raw value without tags based on this question.

However, this is the HTML that is actually output:

When you wish upon a star

What am I doing wrong?

You can use the following code below:

{{content.field_myfield.0|render|striptags|trim}}

  render:  The striptags filter strips SGML/XML tags and replaces
  adjacent whitespace by one space.  You can also provide tags which
  should not be stripped:

{{ content.field_myfield.0|striptags('<br><p>')}}

trim: The trim filter strips whitespace (or other characters) from the beginning and end of a string:

{{ '  I like Twig.  '|trim }}

{# outputs 'I like Twig.' #}

{{ '  I like Twig.'|trim('.') }}

{# outputs '  I like Twig' #}

{{ '  I like Twig.  '|trim(side='left') }}

{# outputs 'I like Twig.  ' #}

{{ '  I like Twig.  '|trim(' ', 'right') }}

{# outputs '  I like Twig.' #}

The example above used from the twig website.


How to make sure simpleSamlAuth module is working as intended? I'm working on a Drupal site which is utilizing the simpleSAMLphp_auth module. We want users to be able to log in using their Gmail accounts, so long as they have an pre-existing Drupal account to match. If it turns out they do not, I don't want them being authenticated.

As of now, when I attempt to use the federated login through Gmail, it seems to authenticate me because it doesn't complain at all about access being denied. It simply takes me back to the homepage of our Drupal website.

How can I check if I am actually being authenticated, even though the email I am testing with the federated login does not have a pre-existing Drupal account associated with it?

Also, I am using the email as the simpleSAML attribute for the users unique identifier and for their email as well.

There are hooks and config in the module UI that should aid in this. Here is an example from a Drupal 8 project I did that does just this:

/**
 * Implements hook_simplesamlphp_auth_allow_login().
 */
function MYMODULE_simplesamlphp_auth_allow_login(array $attributes) : bool {
  // Debugging purposes
  \Drupal::logger('mymodule')->log('info', 'Attributes contained: @attributes', ['@attributes' => $attributes]);

  if (empty($attributes['EMAIL_ATTRIBUTE_IDENTIFIER'])) {
    \Drupal::logger('mymodule')->log('info', 'Attribute was not present.', ['@attributes' => $attributes]);
    return FALSE;
  }

  // Run a query to see if the user exists by email address in Drupal
  $exists = // query users by email address

  return $exists;
}

Perhaps a simpler approach in your case would be hook_form_alter, adding a new submit handler and doing the email check there before anything else happens, but the hook above is the final say-so in if a user can authenticate and login or not.


Node form alter query While editing a node I've printed the dsm($form) in hook_form_alter and in the dsm array I see the following values:

....
form_id (Array, 3 elements)

    #type (String, 6 characters ) hidden
    #value (String, 14 characters ) unit_node_form
    #id (String, 19 characters ) edit-unit-node-form

.....

This node's machine name is "unit" I want to know what is the difference between #value and #id values.

I want to catch form alter of only this node while editing it.

Typically you would use a check on $form_id to make sure your hook_form_alter would only apply the specific form. A node editing form is normally only present on edit pages, so it would only apply to edit pages as the form is not displayed anywhere else.

Don't forget that hook_form_alter is called on all forms, so you need to check for the some values to not apply it to all forms. Usually this is the form_id.

To check for a specific form you would use:

/**
* Implementation of HOOK_form_alter()
*/
function MYMODULE_form_alter(&$form, $form_state, $form_id) {

  // 1.UNIT CONTENT TYPE FORM
  if ($form_id == 'unit_node_form') {

  }

}

This can be helpful if you modify multiple forms in one module.
If you prefer not to do that you should maybe use hook_form_FORM_ID_alter() to modify only a specific form.

Checking the form api $form_id is defined as:

  String representing the name of the form itself. Typically this is the name of the function that generated the form.

The question this throws up now is:

Is $form_id defined from

$form['form_id']['#value']

or from

$form['#form_id']

Both of which give the same results.
So unfortunately I can not directly give you an answer, other than that the form will only display on edit pages, so using $form_id seems to be standard proceedure.


Change appearance of search form I want to change the appearance of the Drupal 7 search form.  I used this code in my preprocess-html.inc file for my Omega subtheme.  It didn't work.  How do I assign html classes to divs within the Drupal 7 preprocess-html.inc file?

Here's what I put in that didn't work:

<?php

function mythemename_form_search_block_form_alter(&$variables) {
  // custom functionality here

}

?>

            <input type="text" class="form-control" placeholder="Search for...">

            <button class="btn btn-default" type="button">Go!</button>

To clarify, how do I add this bootstrap html code to the template file? I need to add these classes to the search form.

To design the search block form you can override the existing search-block-form.tpl.php in the theme's template folder.

<?php

$variables['form']['search_block_form']['#attributes']['placeholder'] = "Search for...";
$variables['form']['search_block_form']['#attributes']['class'] = "form-control";

?>

        <?php if (empty($variables['form']['#block']->subject)): ?>
          <button class="btn btn-default" type="button"><?php print t('Go!');?></button>
        <?php endif; ?>
        <?php print $search_form; ?>


Use of tmp folder in drupal All of our Drupal installations have a /tmp folder at the root of the installation (ie, in parallel with the core files).

What does Drupal use the temporary directory for?

Your temporary directory holds files before they actually move to the appropriate position in your files directory.

Not sure but I think one the example can be the time we upload a file in a content type it first goes to tmp directory before you actually save the node. Also you might have image cache working if file type is image so the file must exist on server before it crops or scale, so tmp is that directory.

Also the tmp folder is always need to be in drupal root directory, the place is configurable from settings.


Exposed filter autocomplete has TID with taxonomy term I created a view from taxonomy terms of different country names. I added an exposed filter to allow the user to enter the country, but when the user selects the country, it automatically adds the taxonomy ID after the name.

I've tried various things, from hooks to jQuery, I can't seem to figure out how to remove the TID. Please advise.

One solution can be custom javascript to remove the number from the result: like

(function($, Drupal, drupalSettings){
'use strict';

 Drupal.behaviors.my_module = {
   attach: function(context) {

  // Remove TID's onload.
  Drupal.my_module.remove_tid();

  // Remove TID's onchange.
  jQuery('body').find('#YOUR_FILTER_EXPOSED_ID').find('.form-autocomplete').on('autocompleteclose', function() {
    Drupal.my_module.remove_tid();
  });
}
};

Drupal.my_module = {
  remove_tid: function () {
    let field_autocomplete = jQuery('body').find('.form-autocomplete');
    let autocomplete_tid_stripped = field_autocomplete.val().split(' ')[0];
    field_autocomplete.val(autocomplete_tid_stripped);
  },
};

})(jQuery, Drupal, drupalSettings);

Another solution could be using views_autocomplete_filter module, add a relation to your taxonomy term and instead of entity filter and a filter on  terms name, so there will not id there. a little slower but works.


Can no longer access administration pages - Warning/Error Today, I logged in as administrator to my Drupal 7 site. I was using overlay, viewing "People", and everything was working fine. Then I clicked on "Reports".

All of a sudden, I had a white screen, and can no longer access any of the administration pages of my site. When clicking back to the home screen, I get multiple instances of this error:

Warning: require_once(C:\inetp): failed to open stream: No such file or directory in module_load_include() (line 330 of C:\inetpub\wwwroot\includes\module.inc).

I was using the administration pages just fine a couple days ago. I'm not sure what could of happened. The only thing recent was I updated Views - but this was quite a little while back - and again, had no problems after that up until now.

Can someone help?
Thanks!

go to your settings.php and add this code below

error_reporting(-1);  // Have PHP complain about absolutely everything
$conf['error_level'] = 2;  // Show all messages on your screen, 2 = ERROR_REPORTING_DISPLAY_ALL.
ini_set('display_errors', TRUE);  // These lines just give you content on WSOD pages.
ini_set('display_startup_errors', TRUE);

follow these steps Blank pages or "white screen of death" (WSOD)


Use multiple URL arguments to prepopulate multiple entity reference fields I have multiple nodes of type 'schools'

I also have a contact form that i'd like to provide on a per school basis.

I.e. The user views a school page and can use an entityform embedded or linked to that particular schools page to generate a pdf letter to mail to the school. This letter will be pre-populated with the School name, School address, Head Mistress and other fields from the 'schools' content type that it came from.

I have set up 'entity reference' and 'entityreference prepopulate' as per this tutorial and have made some  headway.

However I can so far only successfully pass one item from the node to my form using url arguments ... how can I pass multiple arguments ~5-6 elegantly to prepopulate my entity form?

I am open to alternative approaches, it would be nice to have the form embedded on the schools page...rather than linked (via the block in the above example)

You can follow the same approach given in the example.

You will need to rewrite the link from

http://example.com/contactform?field_name=12345

to

http://example.com/contactform?field_name=12345&field_name_second=4567&field_name_third=890

This should do the trick for you.

If you want it to look more elegant, then you can just pass the entity id of the referring object and then write some code to pre-populate the values based on the given entity.


how to send notification to seller when payment is received I want the system to send an email notification
to the author of the product when the payment
is received on their product. I have tried to run
the module mp_tokens this scenario but I do not
find the token [order-seller-email] there. please
help how to create a token for this issue

Assuming author of product is also seller, You can do this with a rule using loop and author:mail. Try importing this rule and see how it works

{ "rules_e_mail_seller_checkout_notification" : {
"LABEL" : "E-mail seller checkout notification",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "uc_cart" ],
"ON" : [ "uc_checkout_complete" ],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "order:products" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "mail" : {
            "to" : "[list-item:node:author:mail]\u000D\u000A",
            "subject" : "OrderID: [list-item:order-id] Product: [list-item:title]",
            "message" : "Order: [list-item:order-id]\u000D\u000ANid: [list-item:nid]\u000D\u000ATitle: [list-item:title]\u000D\u000AQty: [list-item:qty]\u000D\u000APrice: [list-item:cost]\u000D\u000ASeller: [list-item:node:author]",
            "language" : [ "" ]
          }
        }
      ]
    }
  }
]

}
}

source - https://www.drupal.org/node/1830962


How to pass the query string used to access a page in a link in a views content pane? On a views content pane that shows a list of taxonomy terms, is there any way to simply rewrite all the term links such that the query string in the URL with which the page was accessed is appended?

I'm using Drupal 7 with Views 3 and Panels 3. I have a views content pane displayed in Panels shows a list of countries.  Clicking a country goes to the country's term page (countries are taxonomy terms), which shows all of the users registered in that country (again via Panels overriding the taxonomy term pages).  These term pages (also made with views and contextual filters) accept query strings for exposed filters such as `?friendship=1'.

What I would like to do is link to the location-based search from other pages on the site and pass values to the term page view via the query string.  However, since I don't know what country the user will want to search, I have to link to the Panel that shows the list of countries.  However, since the views content pane displayed in this panel shows terms by aggregation, the query string is not passed when a user clicks one of the links.

If I understand the question, you need to tell views to pass the url path to the content pane (views > pane settings > use panel path).


Can a javascript variable be made configurable? I defined a variable in my .js file and want the user/client to change that as per his needs. Is it somehow possible to use that value in forms in drupal?

Too vague of a question, bring some examples of code.

It might go in a custom module (thus doing differently) or just using JavaScript where you can surely alter values of a variable.


Getting current node ID for use in VBO operation I have a view of nodes and I'm using VBO and rules to apply taxonomy terms to the nodes. What I want to do is:

Get the current node's ID (that is, the node with the view block in it).
Get the value of a term reference field from that node.
Apply that value to the term reference field of my VBO selected nodes.

But I'm having problems making menu_get_object work, or any other method of getting the current node's information.

I'm using the "Execute custom PHP" rules action. Here's what my code looks like:

$tagID = 'initialized';

$nodeVBO = $node;  // Storing the $node object sent from VBO

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;
  $nodeID = $nid;
  gets_tag_tid($nodeID);
}

function gets_tag_tid(&$nodeID) {
  global $tagID;
  $node = node_load($nid = $nodeID);
  // Get tag tid from node nid
  foreach ($node->field_tags[$node->language] as $item) {
    global $tagID;
    $tagID = $item['tid'];
  }
}

$nodeVBO->field_tags['und'][0]['tid'] = $tagID;

node_save($nodeVBO);

Sorry for the awkward code, it's adapted from another part of my module.

I get nothing out of the "if" or the gets_tag_tid functions. I have tried echoing the values and reforming the script various ways.

I have never written an operation or an action before so I'm not sure what I can and can't do. I think the problem might be that when VBO performs the operation it changes the URL to /batch?op=start or something like that.

Can anyone point out what I'm doing wrong or show me a better way?

Thank you

EDIT: I have tried reducing the code to the following:

$VBOnode = $node;
$nid = 'initialized';

$node = menu_get_object();
$nid = $node->nid;

$VBOnode->body['und'][0]['value'] = $nid;

node_save($VBOnode);

I was trying to print the nid to see if it was even being retrieved. Nothing is printed in the body field though (not even 'initialized'). To me this indicates that the script is calling menu_get_object(), getting nothing back because the current page is a batch page, thus $node (and subsequently $nid) are set to null values.

Does anyone know of a way to make the VBO operation execute on the node page without switching to the batch page and redirecting back? Or any other alternative solution that I could try? Thank you

You can patch VBO module - to get optional disable batch.
https://drupal.org/node/1902104

It is working - i get normal token current page url, not batch url.

I need to get current NID - where VBO function runs.

when you will get result - please write it, maybe here.


How to save a checkbox config_object in the schema files? We have a custom module with the following files. It is mainly used to store a list of content types that this configuration applies to. When saving the configuration, we get the following code.

How do we properly set the mymodule.schema.yml file to save the checkboxes?

Error Message. We also get the error message if we select Basic Page from the configuration.

  The website encountered an unexpected error. Please try again
  later.InvalidArgumentException:
  The configuration property mymodule_enabled_content_types.article
  doesn't exist. in Drupal\Core\Config\Schema\ArrayElement->get()
  (line 76 of core\lib\Drupal\Core\Config\Schema\ArrayElement.php).
  Drupal\Core\Config\StorableConfigBase->castValue('mymodule_enabled_content_types.article
  ', 'article ') (Line: 211)

mymodule/config/schema/mymodule.schema.yml

mymodule.settings:
  type: config_object
  label: 'My Module settings'
  mapping:
    mymodule_enabled_content_types:
      type: string
      label: 'Enabled Content types'

mymodule/config/install/mymodule.settings.yml

mymodule_enabled_content_types: ''

mymoduleForm.php

...
public function buildForm(array $form, FormStateInterface $form_state) {
  $config->$this->config('mymodule.settings');
  // Get all Content Types.
  $types = \Drupal::entityTypeManager()
    ->getStorage('node_type')
    ->loadMultiple();

  foreach($types as $type) {
    $content_types[$type->id()] = $type->label();
  }
  $form['mymodule_enabled_content_types'] = [
    '#type' => 'checkboxes',
    '#title' => $this->t('Enabled Content Types'),
    '#description' => $this->t('Define what content types will be enabled.'),
    '#default_value' => $config->get('mymodule_custom_variable'),
    '#options' => $content_types,
  ];
}

public function submitForm(array &$form, FormStateInterface $form_state) {
    // Retrieve the configuration
    $this->configFactory->getEditable('mymodule.settings')
      ->set('mymodule_enabled_content_types', $form_state->getValue('mymodule_enabled_content_types'))
      ->save();

    parent::submitForm($form, $form_state);
  }
}
...

You are creating your checkbox options as an associative array of node type (bundle) IDs as keys and their labels as values.

When this form is submitted, checked checkboxes submit as key => key. So the stored information (I suppose 'rss_url' in your question is intended to being 'mymodule_enabled_content_types') is similar to:

mymodule_enabled_content_types:
  article: article
  page: page
  custom: custom

As the keys of the submitted values are unknown before submission, and the values clearly are strings, this is a sequence of strings (compare https://www.drupal.org/docs/8/api/configuration-api/configuration-schemametadata#properties). The correct schema definition is:

mymodule.settings:
  type: config_object
  label: 'My Module settings'
  mapping:
    mymodule_enabled_content_types:
      type: sequence
      label: 'Enabled Content types'
      sequence:
        type: string

After changing your schema definition and rebuilding your caches, your form submit handler should work just fine and the configuration being saved using its correct data types.


Lightest way to control a field's markup So far I have used Display Suite to control the output of entities. This especially applied to node's fields which by default receive multiple wrappers (like field-items, field-item, zebras and such) which I don't need. Correct me if I'm wrong, but I would say that installing Display Suite only for that purpose is a big overhead. If you agree on that, what would then be the lightest way to get exactly the markup I want?

Yes I think Display Suite is quite an overhead just to control field markup. You could obviously overwrite the templates manually, but for a quicker solution there's the excellent Fences module

Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.
Best of all, Fences provides leaner markup than Drupal 7 core! And can get rid of the extraneous classes too!

The difference in markup is huge. From

Foobar field:&nbsp;

Leaner markup means better front-end performance.

to

Foobar field

Leaner markup means better front-end performance.


Filter nodes matching user account field [list (text)] using different field names but same key There is a field of type list (text) [field_list_user] on user accounts and a field of type list (text) [field_list_node] on nodes. Both fields have exactly the same keys but different labels [and field names]. Any content of the site can be authored by users.

Is it possible to create a block with nodes for a currently logged-in user filtered like: value (key) of field_list_user = field_list_node?

I don't think there is module to do a filter that compare 2 arbitrary value but you can add a php filter using Views PHP module

Then, you can create a PHP filter in your view.
Someone write an example that is quite similar to what you need : https://drupal.stackexchange.com/a/44100/36824


Adding a block to markup I have created several content types and using views I have created blocks that take the uid as an argument and displays content that that author has created. So far so good.

What I want to do now is create a module that displays all these blocks in a given area,

I have the HTML ready and I can create a page that passes the markup back to drupal and display that, what I would like to do is populate those areas with the given block.

so for example. If I have a page called:

www.example.com/displayMyContent/58 (where 58 is the user ID)

the HTMl of the page would be online these lines:

<?php
$uid = args(2);
$markup = "

 ". drupal_call_to_render_block("MyVideosBlock", $uid). "
";

?>

what would be the function to insert the given block into the given section and how would I pass the $uid to the block so that only the authors content would be displayed?

Also there are reasons why i am not using the blcok functions in admin mainly because there will be other blocks added on the page and I need control of where the blocks will be placed

I think you may be able to do this by using the global $user variable.

1 create the hooks block_info and block_view
create hook_theme()
define a theme to be able to pass variables to template.
create the template

in your block_view do something along the lines of this:

switch($delta){
    case 'myvideoblock':
            global $user;
            $view = views_get_view('YOURVIEW');
            $view->set_display('YOURDISPLAY');
            $view->set_arguments($user->uid);
            $result = $view->execute;
            $your_variable = $result->result;
            $block['content'] = theme('videoblock', array('your_variable' => $your_variable));
}

You should poke around in the $result->result object to get to your content though.

Hope this helps


infinit redirection loop with lightbox2 module I have a redirection with drupal_goto() function like that :

drupal_goto($url, array('fragment' =>  'lightbox='.  $lb_path, 'alias' => TRUE));

this link, after redirection, automatically open a lightbox, but the lightbox itselef still open another lightbox and so on ... (infinit redirection and opened lighboxes)

the lightbox is a content of node, and the idea is to redirect users from google search if it index a content of a lightbox. here my code in hook_node_view :

function MYMODULE_node_view($node, $view_mode, $langcode){
    if(strpos(request_uri(), "/lb/") !== FALSE && strpos(request_uri(), "lightbox") === FALSE){
         // the "/lb/" in path is only for lightbox content
         // my code here to get the right $url of the node containing the lightbox link.
         drupal_goto($url, array('fragment' =>  'lightbox='.  $lb_path, 'alias' => TRUE));
     }
}

But unfortunately I get an infinit loop !
Maybe the if statement was my fault...
Is there other alternative ? check for example if a lightbox is already open. But I don't think that would be possible in that php function!
Any other help will be appreciated :)

Thanks in advance.

Fragments are not sent to the server as part of a GET request.  That's why you aren't detecting them.  You could try adding a query parameter, so the request would look like this...

http://www...com/node/5/?lightbox=yes#lightbox=<whatever>


Administer block permission let the user to see admin theme name I gave the site admin role permission to administer blocks, but the problem is in admin/structure/block page, there is a tab that shows the admin theme name (Rubik).

he can click on Rubik but doesn't have permission to see the page.
what I want is to hide the tab.

other issue is in admin_menu module under structure > blocks there is a Rubik item too, which shouldn't be there too since the user doesn't have the permission to edit admin theme blocks.

So I'm wondering why does rubik block page link shows up!

I have had such a issue in the recent past, the only solution to this is the "Block Access" Module.


How do I change the current language in a Kernel test? I'm writing a test for something that returns a Url from an entity. This should be language-aware, so the test needs to change the current language.
I started off writing a Kernel test for this, because they're faster, but I can't figure out how to make the test code change the current language:
  public static $modules = [
    'system',
    'user',
    'language',
    'content_translation',
    [SNIP]
  ];

  protected function setUp() {
    parent::setUp();

    $this->installConfig(['language']);
    $this->installEntitySchema('configurable_language');

    $this->languages['de'] = ConfigurableLanguage::createFromLangcode('de');
    $this->languages['de']->save();

    $config = $this->config('language.negotiation');
    $config->set('url.prefixes', [
      'en' => 'en',
      'de' => 'de',
    ])->save();

    \Drupal::service('kernel')->rebuildContainer();
    \Drupal::service('router.builder')->rebuild();
    $this->languageManager = $this->container->get('language_manager');
    $this->languageManager->reset();

    [SNIP]
  }

  public function testCurrentLanguageChange() {
    // Change the site's current language.
    dump(\Drupal::languageManager()->getCurrentLanguage());

    \Drupal::service('language.default')->set($this->languages['de']);

    dump(\Drupal::languageManager()->getCurrentLanguage());
  }

}

In the test code above, both dump() calls output the 'English' language object.

Looks like I needed to call:
    \Drupal::languageManager()->reset();

No, wait, that doesn't seem to be the whole story.... ARGH.
EDIT:
For the entity to be treated as translatable and so return the right URL, I also needed to set the bundle as translatable:
    $this->entityTypeManager->getStorage('language_content_settings')->create([
      'target_entity_type_id' => 'node',
      'target_bundle' => 'page',
    ])->save();
    $this->container->get('content_translation.manager')->setEnabled('node', 'page', TRUE);


Updating drupal/core using composer: "[RuntimeException] Could not delete web/core" (using Lando) Trying to update Drupal 8 core.
composer require drupal/core:~8.9.2 --no-update

This works fine.
composer -vvv update

It fails with the following:
  - Updating drupal/core (8.8.5 => 8.9.2):     Update failed (Could not delete web/core: )
Would you like to try reinstalling the package instead [yes]? yes
  - Removing drupal/core (8.8.5)

[RuntimeException]
Could not delete web/core:

What's the easiest and/or correct way to resolve this?
(This has happened to me before but can't remember what I did to fix it)

OK - so composer does not have read/write access to the folder. I've also seen some people mentioning composer timeouts being the problem.
In my case I am using Lando for my dev environment ands listed web/core as one of the excludes:
excludes:
  - web/core

This meant the core files were not available to the container. If I remove core from the excludes then it works fine.


How can I sort Labels in config entity list builder? I have a very simple config entity with a few fields. In the list builder I want to sort the label field by creation date rather than by alphabetical order.

I originally thought this should be fairly easy, but it's proving way more difficult than I expected.

Can anybody point me in the right direction?

To answer my own question I guess.

Config entities list builder extends the ConfigEntityListBuilder class,
which comes with a few built in methods, among which

  /**
   * Loads entity IDs using a pager sorted by the entity id.
   *
   * @return array
   *   An array of entity IDs.
   */
  protected function getEntityIds() {
    $query = $this->getStorage()->getQuery()
      ->sort($this->entityType->getKey('id'));

    // Only add the pager if a limit is specified.
    if ($this->limit) {
      $query->pager($this->limit);
    }
    return $query->execute();
  }

To sort, in whichever you ones desires, the display list itself all that needs to be done is overwrite the function in the child class.

In my case it was something like this:

protected function getEntityIds() {
  $query = $this
    ->getStorage()
    ->getQuery()
    ->sort('notification_creation_date', 'DESC');

  // Only add the pager if a limit is specified.
  if ($this->limit) {
    $query->pager($this->limit);
  }
  return $query->execute();
}


How can I limit query results in hook_views_pre_execute? I am developing a Drupal 8 website where I have a block view displayed for certain content types that shows related information from other content types. I need to dynamically limit query results based on the moderation state of the node being visited (as opposed to the content in the view). My plan was to grab the node's moderation state from the page context and use that to limit the results of the view. However, the setLimit function seems to have no effect on query results:
function myModule_views_pre_execute(ViewExecutable $view) {
  // Only for my_view view.
  if ($view->id() == 'my_view') {
    $list_node = Drupal::request()->attributes->get('node');
    if($list_node->moderation_state->value == "approved"){

    }else{
      dpm("node is not approved, setting limit to 0");
      $view->query->setLimit(0);
    }
  }

UPDATE
I played around with trying different things in different hooks, inspecting the actual query generated via the view editing interface, as this exposes the "LIMIT #" expression. I learned 2 main things from that process:

Things can and will edit the query in other hooks. I found that putting the setLimit in hook_views_query_alter got overridden by some other module, and by the time hook_views_pre_execute came around, it would be changed from what I set it to earlier. However setting it in pre_execute is working fine.
Amazingly, calling setLimit(0) removes the LIMIT expression from the query entirely! However, any other value seems to work fine.

Is this expected behavior? Does Drupal prohibit setting the limit for a query to 0? Or should I be logging an issue somewhere?

No idea why setLimit(0) doesn't work as expected, but an alternative is to act as though you had limited the results to 0. When you add a contextual filter to a view, one of the options for When the filter value is NOT available is to Display contents of "No results found". This seems to be handled by ArgumentPluginBase::defaultEmpty(), which looks like
public function defaultEmpty() {
  // We return with no query; this will force the empty text.
  $this->view->built = TRUE;
  $this->view->executed = TRUE;
  $this->view->result = [];
  return FALSE;
}

If you drop this snippet into hook_views_query_alter() it appears to work exactly the same! I'd wager that you could drop it into any of the views hooks, actually, and it would have the same effect.
EDIT: Whoops, forgot to say you'd want to replace $this->view with $view if you're inside of the hooks.


Reward for daily login with rules I want to reward my users with 1 point for login every 24h.

Event: User has logged in

Condition: ??

Action: Reward points (I have a component)

I don't know how to reward once every 24 hours. how to?

Try using User Points modules to manage the points, which has a very good API to integrate with custom modules.

Read this also User Points Contributed modules


dpm() does not display any results on screen I have the same problem as file_scan_directory() takes about 10 seconds to execute. I just tried the dpm(func_get_args()) suggestion, and unfortunately it doesn't show anything to me.

I've cleared all the caches, and run the cron tasks. What am I missing?

Make sure you have print $messages; in your page.tpl.phptemplate file. By default, devel (dpm) is configured to print it's content in the message area of the site. So if your template for some reason does not render the contents of $messages, you won't see anything.


Landing page extension without 404 error I have a problem concerning a landing page and 404 errors.

Context : I have a content type "news", with auto url /news/my-news-title. I have created programmatically a kind of homepage for news, with /news as URL

What's wrong : My problem is that if I have a link like /news/aiejaziejfnjdfnj (it doesn't exist), I don't have a 404 error and this is my /news landing page which is shown.
What I wish, with you help, is to have a 404 error when I have a non existant URL.

I'm going to show you what I have done, and hope sincerely you'll have an idea of what i'm doing wrong. In a custom module, I have :

function mymodule_menu(){
    $items = array();
    $items['news'] = array(
       'title' => "Les news",
       'page callback' => 'landing_page',
       'access arguments' => array('access content'),
    );
    return $items;
}
function landing_page(){
    return "nothing";
}

Then, I have a template page--news.tpl.php in which I have write things manually without showing $content (the "nothing").

So, why /news/aizejziej is accepted and is showing /news ? Is it function landing_page() which is doing something bad by always returning something ?

Thanks in advance for your help/ideas :)

Edit : Is it possible to create a node with /news as alias, and then theme it with page--node--[node-id].tpl.php (or kind of) ? I'll didn't have my bad hook_menu and landing_page thing...

Like @Clive said, Drupal will try to resolve that path if it can. Just put a check in your page callback to see if there's an extra argument. If there is and it's valid the menu router will handle it. Otherwise it will fall back to your defined path, where if it finds something after /news, it will return drupal_not_found(). The 'return' is important, otherwise you might see the page render twice.

function MYMODULE_menu(){
    $items = array();
    $items['news'] = array(
       'title' => "Les news",
       'page callback' => 'landing_page',
       'access arguments' => array('access content'),
    );
    return $items;
}

function landing_page(){
    if (arg(1)) {
        return drupal_not_found();
    }

    return 'something';
}


Theming breadcrumb.html.twig In my theme I need to print the breadcrumbs using two different UL class names so they can be styled differently. For mobile device the breadcrumbs appear at the top with the UL

For large device the breadcrumbs appear in the left sidebar with the UL

They both also have different LI an A class names. But I only have one template file to work with called breadcrumb.html.twig, and its themed for the topnav.

In my top region I print out the breadcrumbs with this and it the style looks good:

{{ drupal_block('breadcrumbs') }}

And for the sidebar I print out the breadcrumb again using this:

{{ drupal_block('breadcrumbs') }}

But Its using the same style as the first nav. How can I theme it differently using different class names? Can I create a theme preprocess hook and use 2 templates. breadcrumb-1.html.twig and breadcrumb-2.html.twig. THen print it like this {{ drupal_block('breadcrumbs-1') }} and {{ drupal_block('breadcrumbs-2') }}

I edited this because its not clear what I want. I mainly want to know if I can created and use two different templates for breadcrumb.html.twig. In Twig debug FILE NAME SUGGESTIONS, it does not give any suggestions for this template which means I can only use one in my theme. I think what I will do is add two different ul class names in my template then print the breadcrumb in each one,  then add style by targeting the two different ul class names.

One quick option is to add some html markup that wraps the region (if you've disabled the default Drupal theme markup) in your page twig template where you call {{ drupal_block('breadcrumbs') }}.

For instance,

{{ drupal_block('breadcrumbs') }}

and

{{ drupal_block('breadcrumbs') }}

Alternatively, if your theme is setup to render blocks assigned to regions in Drupal's Structure > Block Layout, you could:

install/enable the Block Class module (as of Feb 23, it's in an alpha release for D8)
place two Breadcrumb blocks, one per region
assign your topnav and leftnav classes in the block config screen

For both use cases, you'll need to change your css to target:

.topnav ul
.topnav ul li
.leftnav ul
.leftnav ul li


Permission to control revisions without giving full content access in D6 I want users belonging to my 'editor' role to be able to create/revert etc revisions. To do this, as far as I can tell, I have to check the 'administer nodes' option in admin/user/permissions

However this seems to give editors the ability to create any content type (seems to override the specific content type permissions). I want editors to be able to create only certain content type (under node/add).

Is there a way to enable the node revision setting but restrict the content types that can be created?

Drupal 6.

You should try using the Workbench module.

  Workbench provides overall improvements for managing content that
  Drupal does not provide out of the box. Workbench gives us three
  important solutions:


Teasers/summaries don't show when body begins with picture I have a blog content type which uses a WYSIWYG editor and allows media to be inserted.  Usually things work out fine, and the blog page shows a list of nice trimmed teasers and/or summaries.  But when the blog post begins with a picture, the teasers and/or summaries don't show up on the blog page.  Instead, there is just a --- where the text would normally be.

I tried deleting the  tags around the image, but it didn't help.

Any advice? (We have to continue using the WYSIWYG editor/media insert, so that part can't change, unfortunately.)

Try this How to Add a WYSIWYG Editor to a "Text with Summary" Field if it works for you.


Get the value of a form element returned from an ajax callback function I have a select element and submit button in my form :

$form = array();

$form['myid_template'] = array(
    '#type' => 'fieldset',
    '#title' => t('Select Template'),
    '#suffix' => '

',
);

$form['myid_template']['template_options'] = array(
    '#type' => 'select',
    '#options' => array(
         1 => t("Student"),
         2 => t("Employee"),
     ),
     '#default_value' => 1,
     '#title' => t('Select'),
     '#ajax' => array(
         'callback' => 'myid_select_template',
         'wrapper' => 'myid_dynamic_input_information',
     ),
);

 $form['submit'] = array(
     '#type' => 'submit',
     '#value' => 'Save',
     '#ajax' => array(
         'event' => 'click',
         'callback' => 'myid_user_page_form_ajax_submit',
     ),
 );

My select form element calls an ajax function myid_select_template that adds a field and updates the form.

function myid_select_template($form, $form_state){
      $form = array();
      $form['form']= array(
          '#type' => 'fieldset',
          '#title' => t("Employee's Information"),
      );

      $form['form']['template2_field1'] = array(
          '#title' => t('GSIS No.'),
          '#type' => 'textfield',
          '#description' => "Government Service Insurance System number.",
          '#attributes' => array(
              'id' => $template . '_field1' ,
          ),
      );
      return $form;
}

My problem is, after myid_select_template is called, whenever I click the submit button , I cant access $form['form']['template2_field1'] from myid_user_page_form_ajax_submit callback function.

function myid_user_page_form_ajax_submit($form, &$form_state) {
    dsm($form);
    dsm($form_state);
}

I did try to display my $form and $form_state variables but I cant find the value of $form['form']['template2_field1'] in it. What should I do? Does it have connection in rebuilding the form? Do I have to rebuild the form to update the $form_statevariable? If yes, how?

I too not sure why the name attribute is not adding to the field. but you can bring by explicitly defining the name in the field.

 $form['form']['template2_field1'] = array(
      '#title' => t('GSIS No.'),
      '#type' => 'textfield',
      '#name' => 'template2_field1',
      '#description' => "Government Service Insurance System number.",
      '#attributes' => array(
          'id' => $template . '_field1' ,
      ),
  );


MailManager override "from" email I use MailManager to send emails to end users for notifications. I would like to override the email address shown to the end user, using a "fake" address shown and not the real mail account used to send the email. I use the following code, however, in my gmail receiving account I don't see the noreply@mymailserver.com but the real email account used.

$params['message'] = $message;
$params['subject'] = $title;
$key = 'send_email';
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$result = $mailManager->mail($module, $key, $targetEmail, $langcode,
                    $params, 'noreply@mymailserver.com', $send);

Is there a way to define a custom address to be shown to the end user? Am I missing something?

You can use hook_mail_alter to customize the From:

MODULE_NAME_mail_alter($key, &$message, $params) {

  switch ($key) {
    case 'my_email_key':
      $message['headers']['From'] = 'My Email Name <my_email@address.com>';
      break;
  }
}


drush xmlsitemap-regenerate domain is incorrect Whenever I run:

drush xmlsitemap-regenerate

on our live server, the domains in the sitemap all refer to:

http://default

Only when I generate the sitemap from the Drupal admin backend, do I get the correct sitemap.xml with the correct domain setup.

I need to have the drush command working correctly, as we're using it with a Capistrano deploy script.

Can I somehow pass the domain name to the drush command?

Did you set your default base URL under the 'Advanced' fieldset. in admin/config/search/xmlsitemap (D7 version) ?


Is there any way to check user activation link has been sent I have created user by profile-2 module with some certain roles,Initially user is in block state,there is one user manager that approved this user and send activation link by email.so how to check activation link already sent or not. if link already sent then need not send again.
For this Is there any module or custom code.
Please help me if anybody knows this.

Use Mail Logger  module. It simply logs all outgoing emails into a database table.
You can view the logged emails by going to the Reports -> Outgoing Mail log entries page.


How to find the right data selector in Rules Components? In Drupal 7, I have set up a rule to automatically close blog comments after two weeks. That works well.

Now, I am trying to have a block displayed on the blog entries when comments are closed. For this, I am using the Rules block visibility module.

I have set up the rule component as per the strict instructions of the module's "readme.txt" file. Without any condition, the export of the component gives this:

{ "rules_set_comments_closed_blocks_after_blog_entry" : {
    "LABEL" : "Display Comments Closed block on blog entries",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

The problem I have is with the condition. I cannot find the right data selector in the Data Compare section.

If, on the other hand, I create a rule to display a system message on the site when comments are closed, I do find the data selector item "node:comment" and comparing its value to "NOT 2" (meaning not open) makes the message display only on blog entries with closed comments.

The above exported component works, but on all blog entries whether the comments are closed or not. I just need to add the condition to differentiate nodes with closed comments from those with open comments.

I have tried "entity" has field, entity is of type, etc. But, in components, the list of data selector is still very limited. In fact they are limited to site or current user items.

How can I expand the list of data selectors so that I find my "node:comment" (or similar) selector?

Any help on this is greatly appreciated. :)

Head over to the settings of your Rules Component, and specify "Node" as an extra parameter (on top of the 3 you already have in place). You can find "Node" within group "Entity".

After doing so, try again to add "Node" as your data selector, more specifically "Node:comment" (for which you want to test if its value is "0"). This time (after you added that extra parm) it should show up as a data selector.

Here is a sample Rules Component (in export format) that does something similar (it has an extra condition for "uid=1", which is probably not what you want).

{ "rules_block_visibility_hide_block_for_user_1" : {
    "LABEL" : "Hide block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false },
      "node" : { "label" : "Node", "type" : "node" }
    },
    "IF" : [
      { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } },
      { "data_is" : { "data" : [ "node:comment" ], "value" : "0" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

If you just import the above Rules Component, it already has that "Node" as an extra parameter.

Note: if you get unexpected errors (after enhancing your Rules Component as suggested above), then enable Rules debugging (so see the Rules debugging log). You can do this via /admin/config/workflow/rules/settings


Clean way to programmatically add attributes to a view field entity label link I have a View that lists entities. One of the fields is the entity label field, which is set to output a link to the entity itself. I would like to add attributes to the <a> tag to grab later with a jQuery plugin.

I can use template_preprocess_views_view_field() and hook_views_pre_render() to get the rendered markup and alter it there, but it's very dirty and not something I'll consider. I could also create a specific theme suggestion and field template and do it that way, but I don't want to rely on something that's potentially editable or changeable. It needs to be as generic as possible.

Is there a clean solution for this?

Generate the scaffolding of a Views field plugin with Drupal Console

drupal generate:plugin:views:field

and put the link in the render() method generated by the command above:

  public function render(ResultRow $values) {
    if ($entity = $values->_entity) {
      return [
        '#type' => 'link',
        '#title' => $entity->label(),
        '#url' => $entity->toUrl(),
        '#attributes' => [
          'class' => ['foo'],
        ],
      ];
    }
  }

After clearing the cache you'll find the new field plugin when adding a field to the FIELDS list.


Search for node to reference I have a content type that has a reference field to another content type, call it "associated".

When editing the content, I'd like the user to be able to search for the "associated" entity to link to, for example using a view with a exposed filter.

Is there any combination of modules that will allow me to do this?

So i'm basically after a select widget that bring up a popup or something similar.

Thanks,

The closest thing I know of, is the relation and relation select module combo. Relation select hasn't seen any development for quite a while, but you might be able to get where you want. It allows you to setup a view with exposed filters can be be used to selecting the node you want to reference.

This is Drupal 7 only.


How do you get the nid from an entity id? I've got a field collection attached to a node. Given the entity ID of a given instance of that collection, how do I obtain the nid to which it's associated?

When using entity_load, the nid for some reason is a protected property, so I can't access it. I must be missing something.

Update: using node_load on this entity ID returns false.

It's important to understand that if all you have is the id of any entity, then there is no way to load a specific entity with that id. Since entity_id's are not unique across entity-types, it is necessary to know both the entity type, and the entity id.

See Developers need an $entity->entity_type property for a discussion on changing this for D7, as well as info about how this will be likely be handled in D8.

On the other hand, as pointed out in a different answer, if you already know that the entity id is a node id, then you can call an entity specific load function like node_load($nid). Since most entities will have such a load function to support named arguments, such a "shortcut" function will be almost universally available.

Examples: node_load(), taxonomy_term_load(), commerce_product_load().


Commerce: programmatically create new product with my ID I have database of products and I want to export it to Drupal Commerce database with my Ids being saved:

$product = commerce_product_new('product');
$product->product_id = '100500';
$product->title = 'my title';
commerce_product_save($product);

But it always returns STATUS_UPDATE because in sites/all/modules/commerce/modules/product/includes/commerce_product.controller.inc in line 80 there is:

// Determine if we will be inserting a new product.
$product->is_new = empty($product->product_id);

It always clears "is_new" when "product_id" is filled.

If I change that string like:

$product->is_new = !empty($product->is_new) || empty($product->product_id);

Everything works fine.

Is it a Commerce bug or I do something wrong?

I don't see this as a bug, as we do want to prevent arbitrary IDs from being set in general. If you're doing it intentionally, though, I think your best bet would be to implement an override in a custom entity controller that extends the core functionality and changes the behavior of the is_new check like you've done.


Using a Drop Down and available Dates in a Content Type I am running an event that spans a week.  During the event different vendors are able to have shows that run a few hours each.  What I would like to do is create a form for the vendors to fill out with their name, a description of the event and when it is happening.  I was originally using the date field, but it allows them to choose any date which has become a problem.

What I would like to do is have the actual days show up as a drop down with "Thursday, Friday, Saturday and the values of "3/1/2013", another one for Hour and a last one for minutes.

I figured out how to handle the views to display the information I want.  But what I can't figure out is a way to load this information onto a calendar.  I assume I have to combine all that information into a single database date field, but I can't for the life of me figure out how.

Any suggestions would be very much appreciated.  I am using Drupal 7 and, while getting better am still relatively new at Drupal.

Thank you.

You can use Date module. Read more here: http://drupal.org/node/262062

If you are already using that, then you probably need to change, widget type of the field to Popup-Calender or Select List


Mapping regular SQL to Drupal's Database API - using 'exists'? I have the following SQL that I'm trying to translate using Drupal's Database API:

select nid,biblio_type from biblio where not exists
    (select * from biblio_types where biblio_type = tid);

What would the translation be?  Currently I have this which is not working:

$sub_query = db_select('biblio_types','bt');
$sub_query->fields('bt',array('tid'))
         ->condition('biblio_type','tid','=');
$query = db_select('biblio','b');
$query->fields('b',array('biblio_type'))
      ->notExists($sub_query);
$result = $query->execute();

EDIT #1: Changed exists to notExists.

EDIT #2:

After changing exists to notExists and replacing the condition statement in the subquery with where per Clive's instructions, this is the SQL that is placed in $result->queryString:

SELECT b.biblio_type AS biblio_type
FROM
biblio b
WHERE  ( NOT EXISTS  (SELECT bt.tid AS tid
FROM
biblio_types bt
WHERE  (b.biblio_type = bt.tid) ))

...which is what I expect.  If I place this statement verbatim in MySQL Query Browser I get the exact results I want.  It returns exactly 9 rows of data.  Perfect!

I think you'll need to use a where() for the condition in the subquery, PDO will most likely quote the 'tid' and mess it up.

$sub_query->where('bt.biblio_type = b.tid');

You can cast a SelectQuery to a string to view it's SQL equivalent at any time, it helps a lot with debugging the more complex queries.

print (string) $query;


call_user_func() and external functions problem I'm trying to create some logic in order to have my code better organized, so I am creating a module and trying to separate functions in different files according to it's content type.

For example, I have a module called my_module and I'm creating two content_types content_type1 and content_type2

So I created this structure:

my_module.install
my_module.module
my_module.content_type1.inc
my_module.content_type2.inc

This logic inside install:

function my_module_install() {
  // During installation, the t() function is unavailable, so we use get_t()
  // to store the name of the translation function.
  $t = get_t();

  //List of objects to be created
  $nodes = array('content_type1','content_type2');

  //Create all the content-types from the array
  foreach ($nodes as &$node_name) {
    error_log('Create: '.$node_name, 0);
    call_user_func('_'.$node_name.'_create_node',$node_name);
  }

  unset($node_name);
}

And this logic inside each file ( content_types )

function _content_type1_create_node($node_name='type1') {}

function _content_type2_create_node($node_name='type2') {}

Since I added this lines to the my_module.info:

files[] = my_module.content_type1.inc
files[] = my_module.content_type2.inc

I was expecting to have all the logic working as it should but

//content_type1_create_node()
call_user_func('_' . $node_name . '_create_node', $node_name);

It cannot find the callback and I think it's because the callback.

Am I over engineering, or doing it wrong?

Your functions are in files that haven't yet been included, try changing your code to this:

foreach ($nodes as &$node_name) {
  module_load_include('inc', 'my_module', 'my_module.' . $node_name);

  $func = '_'.$node_name.'_create_node';
  if (function_exists($func)) {
    call_user_func($func, $node_name);
  }
}

I've never been able to get the files[] key in the .info file to work, I don't think it's used for arbitrary files but rather those that will form part of Drupal's code registry (using hook_hook_info() or something like that), but I haven't delved too deeply so it's worth checking yourself.

To answer your final question, yes I think you're over-engineering this a bit :)

It would make sense to do this if your module is going to become generic (so more content types can be catered for) but if it's really just 2 content types I'd put the code inside the .module file to be honest.

Obviously if you think these files will end up having a lot of code it makes sense to separate them, but if not I don't think you're really getting much benefit for doing so.


how to create template of user register, login and forget password in drupal 8? How to create template of user register, login and forget password in drupal 8 can we create template same as we created earlier in drupal7 ?

I want to open these forms in popup on clicking links

Yes it same as drupal 7.

For example:

We are using page--user--register.tpl.php for registration page template in D7. In D8 changed to twig extension page--user--register.html.twig.

You can enable debug mode in D8 so you can easily see the twig file need to use in your case. You can refer Drupal 8 custom page template to see how to enable debug mode.

Some links how to override the template files.

https://www.drupal.org/node/2521876

https://www.drupal.org/docs/8/theming/twig/working-with-twig-templates

https://www.drupal.org/node/2668886


How to sort a view on a Drupal Commerce product image field? I have several Drupal Commerce views. I want to sort on whether the image is "interesting", which means not equal to no-image-available.png.

I have added "Indexed Commerce Product: Image » The image file." as a relationship but it's still not showing up in the sortable fields.

I remember there was something like "enforce" relationship but this is not showing up where I was expecting it:

One way to solve this is to store a sortable value in an extra field.

Computed field can be a good choice. There is a quite lengthy article here. See "Additional Values for Sorting".

I also want to quote the "Downsides" mentioned in this article:

  Since the stored value computed field is only computed when the node
  is saved, your nodes need to be re-saved to allow for code changes. If
  you change the content type’s field, you may need to re-save all nodes
  of that type. If you have thousands of nodes, this can be troublesome.
  However, several modules (which are outside the scope of this post)
  can help, as can simple one-off scripts.


EntityQuery with joins I am trying to get user data by UUID in my custom module and I don't know how to join on users_field_data table to get user fields (email, username, etc.).

My request for the users table works but I don't know how to join.

$query = \Drupal::entityQuery('user')
          ->condition('uuid', $uuid)
          ->execute();
$result = User::loadMultiple($query);
dpm($result);

How can I execute a join with the users table?

The easiest way to load a field from any entity when querying is to use the entityTypeManager:

$users = \Drupal::entityTypeManager()->getStorage("user")
        ->loadByProperties(['uuid' => $uuid]); // or any other properties.

foreach ($users as $user) {
    var_dump($user->field_customfield->getValue());
}

see:  working-with-the-entity-api

Be careful to not use \Drupal::entityManager, since it is deprecated.


Only allow 1 submission from an email address in webform I am taking some users information using webform, which is their name and email address.

I need to only allow one submission per email address, restricting the form by IP or cookie in the webform settings is not sufficient in this case.

Is this possible?

Edit the email field in the webform and check both the "mandatory" and "unique" options.

In this case, it would accept entries only for unique mail id's


Changing the From Address with the Printer, email, and PDF versions module I'm using the Printer, email, and PDF versions module. On all my 'resource' nodes (resource content type) I have a link now that says 'Send by Email'. Great. But when it sends the email it's sending it with a'from' address as MY email (the site admin). I'd rather it be the email of the person who's sending the resource. There is an email field on that form they have to fill out to send the resource to someone else.

Anyone know how to make the email they use for THEIR email in the form be the 'from' email to whomever they are sending this resource?

It's in Administration » Configuration » User interface » Printer, email and PDF versions, as the Use Reply-To Header option.


Invalidating Paragraph Cache I'm working on a paragraph type that will need to display on a very limited number of pages but has some specific functionality where the preprocess function will need to run each time.

In my preprocess function, I've tried various iterations of the following:

$variables['elements']['#cache']['max-age'] = '0';
$variables['elements']['#cache']['contexts'][] = 'url.path';
$variables['elements']['#cache']['contexts'][] = 'url.query_args:r';
$variables['elements']['#cache'] = ['tags' => ['my_paragraph']];
Cache::invalidateTags(['my_paragraph']);
\Drupal::service('page_cache_kill_switch')->trigger();

However, the preprocess function runs once after a cache clear and then doesn't run again.

What am I doing incorrectly here? How can I get this to run each time?

You've got a logic error in your PHP. You're doing the following and setting some variables:

$variables['elements']['#cache']['max-age'] = '0';
$variables['elements']['#cache']['contexts'][] = 'url.path';
$variables['elements']['#cache']['contexts'][] = 'url.query_args:r';

But then in the next line you're redeclaring $variables['elements']['#cache'] as a new array of  ['tags' => ['my_paragraph']]; So everything you were doing previously in the
$variables['elements']['#cache'] is now gone

So your max-age declaration doesn't exist now. Try with just these 2 items and that should be all you need. The first to tell drupal not to cache the paragraph. The 2nd to disable anonymous page caching as setting max-age 0 doesnt disable the page cache:

$variables['elements']['#cache']['max-age'] = '0';
\Drupal::service('page_cache_kill_switch')->trigger();


Using Automatic Entity Label how to add number if title is already used (unique) I have setup auto entity label with tokens. All works great.
Lets say I have a title
e.g. tokens
[firstname] [lastname]

Displayed as:
Tom Cruise

But if there are multiple identical titles named "Tom Cruise".
e.g.

node 65: Tom Cruise
node 90: Tom Cruise
node 23: Tom Cruise

What I want is it to validate, the title is not unique therefore add number on the end.

node 65: Tom Cruise
node 90: Tom Cruise 1
node 23: Tom Cruise 2

Or something like that. I have been using nid / serial field to make them unique but that isn't what I need.

You can add node id to the label. It will make labels unique anyway.
For example

[node:field_first_name] [node:field_last_name] #[node:nid]

Please note, that there is an issue in module that prevents [node:nid] token from working.
https://www.drupal.org/project/auto_entitylabel/issues/2920695

But there is simple patch available in this issue to fix this. So this should be resolved soon I hope. Until that you need to apply patch manually.
https://www.drupal.org/files/issues/2018-11-11/auto_entitylabel-support_entity_id-2920695-31.patch


How to redirect the user after login I have created a custom form for login page. When a user logs in, I want to redirect the user to some other page, different from user/<user_name>.

How can I perform such redirect?

You can use the Rules module.

  Example use cases

  Build flexible content publishing workflows changes Send customized
  mails to notify your users about important Create custom redirections,
  system messages, breadcrumbs, ... And many more...

To use that go to admin/config/workflow/rules/reaction/import and import this
it will redirect user to admin/dashboard path after user logged in :

{ "rules_redirect_after_login" : {
    "LABEL" : "redirect after login",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "DO" : [ { "redirect" : { "url" : "admin\/dashboard" } } ]
  }
}

You may also build a custom module and use  hook_user_login and do something on the lines of :

function hook_user_login(&$edit, $account) {
     $_GET['destination'] = 'node/25';
 }


How do I insert multi image with restFul service? I have a little issue I try to add to my node with RESTful service on Drupal 7 multiple fids for a image gallery and I can't finish the process, I try

'field_gallery[und][0][]' => array(
  'fid:2381',
  'fid:2375',
),

and I don't know where I do it wrong. This is a request with php curl.

<div class="image-widget-data"><input type="file" class="form-file" size="22" name="files[field_gallery_und_0][]" id="edit-field-gallery-und-0-upload" multiple="multiple">
  <input type="submit" class="form-submit ajax-processed" value="Upload" name="field_gallery_und_0_upload_button" id="edit-field-gallery-und-0-upload-button">
  <input type="hidden" value="0" name="field_gallery[und][0][_weight]">
  <input type="hidden" value="0" name="field_gallery[und][0][fid]">
  <input type="hidden" value="1" name="field_gallery[und][0][display]">
</div>

I think what you really want is to end up with something more like:

'field_gallery[und][0]' => 2381,
'field_gallery[und][1]' => 2375,

The second level of array indexing is the field position. So the first file id goes into [0] and the second into [1].


Display comment count of referencing nodes I have two content types, Forum and Discussion (urelated to the core forum module). The content type Discussion has a node reference to the Forum it belongs named field_forum.
I would like to create a views list which show nodes of Forum with no. of comments of nodes Discussion referencing to it.

Apparently, not a problem:

Just create a view of Forum with a reference "Entity Reference: Referencing entity" (A bridge to the Content entity that is referencing Content via field_forum) and then add a "Content: Comment count" field using this reference, set aggregation to on and set aggregation type for this field as sum.

However, my problem is that, even if I DO NOT check the option "Require this relationship" when I create the relationship, still adding comment count field make forums without any discussion to be excluded from the view, while I want all forum to be there, with or without discussions.

If I remove the "Comment count" field, all forums are visible. Strange enough, using the same techniques for counting the discussions works without problems.

This MAY be related to #1349080 but unfortunately it works with or without the patch in #231 (that solves similar problems in other contests).

Solved using the following workaround (patched #231 of #1349080 required):
add a second level relation discussion->comments and then use the aggregation with count distinct operator over the id field of the comments.


{Date_Repeat} Every day of the week doesn't work This question is in regards with Date module (date_repeat)

I am setting the frequency date to "every" "weeks" until a certain time with the following advanced setting:

Day of the week: Every Saturday

but the result doesn't respect my advanced setting and it will repeat the date every "seven days" regardless the length of the month

How do I fix this?

I am using Node Repeat for this purpose.

Is there any chance that in your time zone there's a Daylight Saving Time change on Saturday, November 6 ? Like for exemple in Los Angeles.
Because this would explain the shift of one hour you get after the 5th of November (remember, remember :) ).

  Inspiration: OMG Ponies!!! (Aka Humanity: Epic Fail), Jon Skeet -
  Stack Overflow Dev Days London 2009, video and transcript.


drupal_render($form) not rendering a form I wonder if anyone has found a solution to the problem I'm seeing.  I've built a very simple "beginner's form" in drupal.

function simple_nameform() {
    $form = array(
        '#method'           => 'post',
        '#prefix'           => '
',
        '#suffix'           => '
',
        'your_name'         => array(
            '#title'        => t('Your Name'),
            '#type'         => 'textfield',
            '#description'  => t('Please enter your name')
        ),
        'submit'            => array(
            '#type'         => 'submit',
            '#value'        => t('submit')
        )
    );
    return $form;
}

I've put this form in a module, with info, I've enabled the block in admin.  When I'm on the main page render I run the commands

Send to a Friend

    <?php
        $output = drupal_get_form('simple_nameform');
        drupal_render($output);
    ?>

<?php // debug purposes only
          print_r($output);
    ?>

The form does not appear to render from the "drupal_render" line, however, the $output variable is most definitely full of something that looks very much like it might be a drupal form.

(it's a huge array filled with my form elements.  at parts it even manages to render some of the elements to page correctly).

Anyone with an idea of what I've missed?

Try:

<?php print render(drupal_get_form('simple_nameform')); ?>


Printing PHP variable in form element in buildForm function I have a php variable like this

$opensslOut = preg_replace('/\n\r{0,1}/', '<br>', $str);

I need to print its value on a form element. I used the following code

$form['openssl'] = [
      '#title' => t('OpenSSL'),
      '#markup' => t('$opensslOut'),
    ];

But didn't worked? I am a newbie in Drupal, Please help me to figure out a solution.

It's just a silly error '#markup' => t('$opensslOut') needs to be without the '' because $opensslOut is a variable and not a string.

So use

'#markup' => t($opensslOut)


how to create shell command 'd' as equivalent to 'drush'? Typing "drush" over and over again, I find it is quite time consuming.  How can I shorten the command so I can just type "d"?

I am using Mac OS X.

If you are using Drush-5 (recommended), then see examples/example.bashrc for a bunch of very useful ways to enhance your experience in your shell when using Drush.  Installation instructions are in the file.  One of the things it does is create an alias 'dr' for Drush; if you wanted this to be 'd' on your system, it would be easy enough to make that change.


Css class for Custom Content type fields I'm using seven theme for creating a basic pages. In that created more content types including title and body as shown in figure.

The page appear like this.

Is it possible to add css class/styles for arranging beautiful manner. Like add custom css class for channel and language ..... How can I do this please? Thanks!

You can use the Display Suite module to control the wrappers of each field or add classes:

Drupal adds a lot of classes already, so you can probably look at the existing markup that Drupal is outputting and style it based on the classes that are already there.


How to get a week range as a Views filter - Thursday to Wednesday I need to return nodes that have a date within a date range of Thursday to Wednesday. I have tried many different combinations, but none do the trick all the time.

The closest I can get is to set the Date From to:
"Last Thursday"
and the Date to, to:
"Wednesday"

This works whenever the day isn't Thursday. As a demo:
Today is Saturday 24th. The Filter would return everything from Thursday 22nd through to Wednesday 28th. Perfect!
However on Thursday 22nd, it returns everything from Thursday 15th through to Wednesday 28th. A whole extra week of content I don't want!

Any ideas on how to combat this in Views?

I guess that date filter with is between option filter could be a possibility if you alter the query used by your View, using a custom php builded by you to calculate values (to use and send inside query) according the current day. see this article http://www.appnovation.com/using-hook-views-query-alter about how to use query_alter hook to alter the queries used by your view.


How do I create linked nodes without user intervention? Suppose I have a cooking website where users can create Recipe nodes for Food nodes. For example, you might have a Cake node of type Food, and users should see an Add Recipe button on that page which takes them node/add/recipe except that the newly created Recipe node will have a reference to the parent Cake page.
I've added a Content type Entity Reference to to the Recipe node, which works fine. For programmatically generating the link I'm a bit lost though. I initially looked at using the Rules but it's still in alpha, and from the description it looks like I'd probably want to use the Rules Link module as well, but it doesn't have a version for 8.x at all.
Then I started looking at hook_ENTITY_TYPE_create, which is my current best guess for how to achieve the desired behaviour, but that still leaves me with some questions about what the best approach is;

How / Where do I capture the node reference when all I'm given is the EntityInterface type?
What is a mechanism for passing information about the reference/parent node to hook_ENTITY_TYPE_create so that I can even know which reference to store?
How do I create links or buttons on the parent Food node that cause such information to be passed on to the hook?
Lastly, is this even the best approach, or am I missing a way that doesn't involve writing code?

I don't think I need any hand-holding or code, but I'd be very grateful for some pointers in the right direction for each of the above points from a veteran.

A solution that doesn't go deep into the code is to use the Prepopulate module.
It enables you to prepopulate form fields through the link to the form page:

http://www.example.com/node/add/recipe?edit[field_entity_reference][widget][0][target_id]=123

You'll probably want to construct the links automatically, it can be done with Views. You create a Block Display that contructs the link using the Food information it's been placed on, through a contextual filter. When the Block is placed on Food pages the link leads to new recipe form that has the food where you just left from already filled in.
You can find more info about how to construct the link with the help of Views in this answer: Add Prepopulate links to Node pages part of the answer.


Selecting an entity reference once I am working on this project, parking management system. I have the admin populating the parking slots available in the building. Then an anonymous user visits the site, puts their details and those of their car, and then in drop down selects a parking slot. The parking slots are an entity reference fetched from what the admin populated. How do I make the system dynamically populate this dropdown so that the user only sees the empty slots? Like after they book slot A, I want it to disappear so that the next person booking does not see it in the dropdown list of available slots. This is to avoid two or more people booking the same slot. The image below shows the drop down am talking about.

I guess the Parking slot 1, Parking slot 2, etc. are nodes or fieldable entities. Most likely those nodes (or entities) have a boolean field which indicates if the parking slot is reserved already. For the sake of this example,
I call it field_reserved.

In this case you need to implement in a custom module a hook_form_alter().
I am going to write a pseudo code.

function mymodule_form_alter($form, $form_state) {

  // Check if the form id is the id of your form.

  // Use entity query that selects the node ids  of the nodes that are reserved.

  //Store the result in some array (let's say reserved_slots array).

  // With a foreach loop, check each select option id against the reserved_slots array of ids.

  //If such option exists, unset it.
}

Hopefully this gives you some guidance.
If you need a complete snippet, you will have to provide more data about your setup, like machine name of the fields, etc.


How can i import plain password that are not encrypted during a user migration? I am able to migrate all the datas of users account including the password but it doesn’t work due to encryption and hash in drupal 8.

My password are not MD5. They are not encrypted, in csv file they are like normal plain text.

I’ve seen here :
https://www.drupal.org/docs/8/api/migrate-api/migrate-destination-entityuser

  If the incoming passwords are not plain or are not MD5 hashed you'll
  have to deal with this in your migration

My password are plain so i guess it should work.

Here is what i’ve tried but the password are imported but not encrypted :

destination:
  plugin: 'entity:user'
  plaintext_passwords: true

In the documentation, it is explained how to import MD5 password but not plain password.

What should i use for the configuration ?

EDIT :

I’ve tried this :

pass:
    -
      plugin: callback
      callable: 'Drupal\Core\Password\PhpassHashedPassword::hash'
      source: passwebservice

And

pass:
    -
      plugin: callback
      callable:
        - 'Drupal\Core\Password\PhpassHashedPassword'
        - hash
      source: passwebservice

Error :

  Error: Using $this when not in object context in
  Drupal\Core\Password\PhpassHashedPassword::hash()  [error] (line 215
  of
  Core/Password/PhpassHashedPassword.php)
  0 [internal function]: Drupal\Core\Password\PhpassHashedPassword::hash('9BQmM1')
  1 core/modules/migrate/src/Plugin/migrate/process/Callback.php(54):
  call_user_func('Drupal\Core\Pas...', '9BQmM1')

When i check hash()

public function hash($password) {
    return $this->crypt('sha512', $password, $this->generateSalt());
  }

I can't invoke method this way ($this does not exist in class context) so how can I do ? Is it possible in configuration file ?

You can use Ivan Jaros' code in two ways:

As you said, preprocess your passwords to convert them to hashes.  This can be done via a Drush script that can be run from the command line.  Drush scripts are just snippets of PhP code that run in the Drupal context.  Run by  the command:

drush @site-alias scr [path to php snippet]

The alternative is to override you CVS Source class and use the preparerow method to hash the password.

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $password = $row->getSourceProperty('password');
    $hash = \Drupal::service('password')->hash($password);
    $row->setSourceProperty('password', $hash);
  }

As pointed out in the comments, you can also use a process plug-in to do this.  The callback plugin only uses static classes and AFIAK the hash method requires access to the context information that is not available via static methods.

Here's some quick untested code to create your own process plug-in to hash a plain text password.

<?php

namespace Drupal\my_mode\Plugin\migrate\process;

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

/**
 * Converts a plain password to an hash.
 *
 * Example:
 *
 * @code
 * process:
 *   password:
 *     plugin: my_module_hash_password
 *     source: field_password
 * @endcode
 *
 * @see \Drupal\migrate\Plugin\MigrateProcessInterface
 *
 * @MigrateProcessPlugin(
 *   id = "my_module_hash_password"
 * )
 */
class HashPassword extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $hash = \Drupal::service('password')->hash($value);
    return $hash;
  }

}


Completely removing cache I've set $settings['cache']['bins']['render'] = 'cache.backend.null; and $settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null; in local.settings.php, but I’m having a hard time dumping variables out to a page from a hook that runs once early on (hook_entity_bundle_field_info_alter()). If I do a simple var_dump (or dpm, etc.)  from here, variables will show up when running drush cr in the console, but not when hitting a new page in the browser afterwards. Does anyone know how I can set up debugging so I'm able to look at these variables in the browser?

What you did only uses the null backend render cache bins.

Field definitions are cached in the discovery bin, you either have to set that to null as well, but that will make your site very slow. You can also simply truncate cache_discovery manually in the database and then do another request in the browser.


Drupal 7 - theme default node view I would like to know the recommended way to re-theme the default node view for a certain content type.

E.g. http://dev.mysite/en/node/6547, now shows a 'list' of content fields. We would like to change this to a more clean layout.

Would using a node.tpl.php in the theme folder and then create a node--[TYPE].tpl.php for the specific node type solve this problem in the correct way?

Regards,
Wouter

Using .tpl.php files would indeed give you more control over the HTML Drupal will create in the end.
Also using a module like Display Suite (DS - drupal.org/project/ds) will give you more control over the fields in a certain display so that some settings about that field on that display are stored in database instead of in code.


How do I embed an Ionic webapp? I am building a partially decoupled Drupal 8 site.  Drupal hosts all the content, but I also built mobile apps and a webapp in Ionic.  The mobile apps are working fine, and now I want to host the webapp on my Drupal site.
I want my Ionic app to take over all the paths from /webapp/*, and these should all redirect to Ionic's index.html and then be passed the relevant argument from the URL.
Before I made the Ionic app, I had a React app, which I embedded into Drupal as follows.
This is the code I am using.
MY_MODULE/src/Controller/PageController.php
  public function reactApp() {
    return [
      '#markup' => '

',
      '#attached' => [
        'library' => [
          'MY_THEME/react_app',
        ],
      ],
    ];
  }

MY_MODULE/MY_MODULE.routing.yml
MY_MODULE.myreactapp:
  path: '/webapp/{react_route}'
  defaults:
    _controller: '\Drupal\MY_MODULE\Controller\PageController::reactApp'
    _title: 'React App'
  react_route: ''
  requirements:
    _permission: 'access content'

MY_THEME.libraries.yml
react_app:
  version: VERSION
  js:
    js/dist/main.min.js: {minified: true}

This worked great for embedding a simple react app and giving it all the routes at /webapp/*.
However, a webapp built in Ionic generates an index.html that looks like this.
<!doctype html>

  <meta charset="utf-8"/>
  <title>Ionic App</title>
  <base href="/"/>
  <meta name="color-scheme" content="light dark"/>
  <meta name="viewport"
        content="viewport-fit=cover,width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
  <meta name="format-detection" content="telephone=no"/>
  <meta name="msapplication-tap-highlight" content="no"/>
  <link rel="manifest" href="/manifest.json"/>
  <link rel="shortcut icon" type="image/png" href="/assets/icon/favicon.png"/>
  <meta name="apple-mobile-web-app-capable" content="yes"/>
  <meta name="apple-mobile-web-app-title" content="Ionic App"/>
  <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
  <link href="/static/css/4.21302a68.chunk.css" rel="stylesheet">
  <link href="/static/css/main.1d86f075.chunk.css" rel="stylesheet">

What I want to do

Put all the ionic build assets in a subdirectory (/webapp) inside my Drupal site (done).
Tell Drupal to redirect all requests to (/webapp) to Ionic's index.html. (how do I do this?)

I thought of using a theme hook, but I don't know how to add all the scripts and css in Ionic's index.html to the twig template.
If possible, I don't want to hard-code the Ionic script assets inside Drupal because the names will change every time the app is built, which will be often.

The problem probably is you have two .htaccess files rewriting URLs to index.php (Drupal) or index.html (Ionic). I think you need to adjust Drupal's rewrite rule because it is in the top level:
  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

For example by adding this condition:
RewriteCond %{REQUEST_URI} !^/webapp


Special characters in form element #title I am trying to write a custom form for my own search facet. In the form, the labels of the elements are dinamically generated based on the indexed values, and they can contain special Hungarian characters, which are not displayed correctly. This is my code:

  $form['facets'][$current_property] = array(
    '#type' => 'select',
    '#title' => $current_property,
    '#multiple' => TRUE,
    '#options' => $myoptions,
    '#default_value' => $widget->buildDefaultValue($element),
    '#attributes' => array('class' => array('facetapi-multiselect', $form_state['facetapi_multiselect']['facet_class'])),
    '#post_render' => array('_facetapi_multiselect_modified_disable_options'),
    );

So, for example, if $current_property is Belső memória/tárhely, then Bels? memória/tárhely is displayed in the search facet.

Can you suggest any ways how to do this correctly?
Thank you very much in advance.

Based on the version of drupal you are using, you can use one of functions below :

decode_entities($text) for Drupal 7

or

Html::decodeEntities($text) for Drupal 8

so in case of using drupal 7, Your code will looks like this:

$form['facets'][$current_property] = array(
  '#type' => 'select',
  '#title' => decode_entities($current_property),
  '#multiple' => TRUE,
  '#options' => $myoptions,
  '#default_value' => $widget->buildDefaultValue($element),
  '#attributes' => array('class' => array('facetapi-multiselect',
    $form_state['facetapi_multiselect']['facet_class'])),
  '#post_render' => array('_facetapi_multiselect_modified_disable_options'),
);


Bypassing internal cache via query parameter I'm attempting to bypass drupal's internal page cache and dynamic cache when a given url parameter is in a URL (as an anonymous user). The page in question is a view, and occasionally, when a user clicks a link to load that view, the URL has the associated query param. I've tried a number of different ways to add the cache context like below:

$vars['#cache']['contexts'][] = 'url.query_args:dynamic_trials';

I've added this in a hook_preprocess_node, I've added it in a preprocess on the view itself I've added it in a function tibco_views_utils_views_pre_view with a call to

view->element['#cache']['contexts'][] = 'url.query_args:dynamic_trials';

None of these have worked. I noticed this on one of the drupal docs pages:

Note the Internal Page Cache assumes that all pages served to anonymous users will be identical, regardless of the implementation of cache contexts. If you want to use cache contexts to vary the content served to anonymous users, this module must be disabled, and the performance impact that entails incurred

Is this true? There's no way to do what I'm trying to do above without disabling the internal page cache entirely?

The Internal Page Cache is designed to serve database content requested by a URL (the entire URL including query string). It works as long as you don't have any dynamic component, for example time based, or client request data not included in URL or session cookie, like request headers or custom cookies.

The Dynamic Page cache works on a different level. It doesn't depend on the URL directly but on the matched route. Any code using contextual data from the request or the matched route has to declare these dependencies as cache metadata.

Your problem is custom code in a Views hook. The old style Views hooks have a very narrow scope while at the same time you can access the entire View. So not all code snippets you find are good practice. Better use the Views plugin system for custom code.

For the caching part the easiest way would be to use the code of the Views caching plugins already in core which you control through the advanced settings of the View. If you only have anonymous traffic already cached by the Internal Page Cache you could disable caching of the View without impacting performance. Either through the none caching plugin or the time-based plugin which gives you finer control.


Save and Retrieve Admin Settings from the database I created a config form in the admin/config page. (Just a link field that needs to be saved for later retrieval) Im confused as to how to save and retrieve the form data.

When creating a custom form in a block I have been successful using:

variable_get('link_title', '')

However when creating a custom form it seems to require a different way. I attempted to save the data in hook_form_submit. However Im not sure how to retrieve when you return to the form at a later date.

function read_more_news_admin_form($form, &$form_state) {
        $form = array();
        $form['link_container'] = array(
            '#type' => 'container',
            '#attributes' => array('class' => array('some-class')),
            '#tree' => TRUE,
        );
        $form['link_container']['link'] = array(
            '#type' => 'link_field',
            '#field_name' => 'link_field',
            '#language' => 'und',
            '#field_parents' => array(),
            '#delta' => 0,
            '#default_value' => array(
                'title' => variable_get('link_title', ''),
                'url' => variable_get('link_url', ''),
            ),
        );
        return system_settings_form($form);
    }

    function read_more_news_form_submit($form_id, $form_values) {
      drupal_write_record('readmorelink', $form_state['values']);
    }

I don't know how system_settings_form will handle form elements of which the parent element has the tree property set. So it is best to go with a submit handler and do it yourself.

function read_more_news_admin_form($form, &$form_state) {
  $form = array();
  $form['link_container'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('some-class')),
    '#tree' => TRUE,
  );
  $form['link_container']['link'] = array(
    '#type' => 'link_field',
    '#field_name' => 'link_field',
    '#language' => 'und',
    '#field_parents' => array(),
    '#delta' => 0,
    '#default_value' => array(
      'title' => variable_get('link_title', ''),
      'url' => variable_get('link_url', ''),
    ),
  );
  $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
  return $form;
}

function read_more_news_admin_form_submit(&$form, &$form_state) {
  variable_set('link_title', $form_state['values']['link_container']['link']['title']);
  variable_set('link_url', $form_state['values']['link_container']['link']['url']);
  //drupal_write_record('readmorelink', $form_state['values']);
}


Drupal commerce taxonomy I have made taxonomy categories for products, and block where is category link list, but how I can make target url for these categories and when user go to category link there is page and all products in that category is listed?

You create a link to the taxonomy display page. This page will show all the nodes (product display types) that are tagged with the taxonomy term (category). How you display the taxonomy page is up to you. There are many modules which can give you more flexibility to the taxonomy display pages.


How to extend flood control in a custom module? I would like to use Drupal's flood control capability in another module. I have a resource I'm protecting with a password.

Can I simply call flood_register_event() and otherwise use the variables as used in the code for user_login_final_validate()?

Am I on the right track at all, or how do I use flood control?

You need to do 3 things when you validate your password entry form:

Use flood_is_allowed() to check that the user hasn't already breached their flood limit and set a form error with form_set_error() if they have.
Use flood_register_event() to log failed attempts on incorrect password errors.
Use flood_clear_event() when the user enters the correct password.

You can also decide whether to do it based on uid, ipaddress, both of those, or something else entirely.

You can see the example of the user module in user_login_authenticate_validate() and user_login_final_validate(). That example may or may not be more complex than you need in your specific case.


db_select condition with subquery causes PDOexception I want to build a relative simple select query with a subquery in its condition. What I want to achieve is to get the list of users updated after a given timestamp.

The working SQL-Query which I want to build as dynamic query is:

SELECT uid
FROM `users`
WHERE `vid` > (
  SELECT vid
  FROM `user_revision`
  WHERE `timestamp` > 1379494886
  ORDER BY `timestamp` ASC
  LIMIT 1
);

I've written the following code to build above query with Drupal's Database API:

$subquery = db_select('user_revision', 'ur')
  ->fields('ur', array('vid'))
  ->where('ur.timestamp > 1379494886')
  ->orderBy('ur.timestamp', 'ASC')
  ->range(0, 1);

$query = db_select('users', 'u')
  ->fields('u', array('uid'))
  ->condition('u.vid', $subquery, '>');

$result = $query->execute()->fetchAssoc();

But, I'm getting the following PDOexception error:

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in
      your SQL syntax; check the manual that corresponds to your MySQL server version for the right
      syntax to use near 'SELECT ur.vid AS vid FROM user_revision ur WHERE (ur.timestamp >
      137949488' at line 1: SELECT u.uid AS uid FROM {users} u WHERE (u.vid > SELECT ur.vid AS vid
      FROM {user_revision} ur WHERE (ur.timestamp > 1379494886) ORDER BY ur.timestamp ASC LIMIT 1
      OFFSET 0) ; Array ( ) in MYMODULE_page_callback() (line 22 of
      /path/to/the/module/includes/page_callback_file.inc).

What am I doing wrong building the subquery?

Thanks to @Clive's comment, I checked the documentation about the subqueries on https://drupal.org/node/310086 and I noticed the note about:

  Note: Currently it is only possible to use subselect conditions with the IN operator because with the other operators the sub-query is not wrapped in parentheses and so results in a syntax error. See #1267508: Subselects don't work in DBTNG conditions, except when used as value for IN.

I've changed my code to use IN instead of > and it worked like a charm. Here's the working code for future reference if someone falls into the same situation:

$subquery = db_select('user_revision', 'ur')
  ->fields('ur', array('vid'))
  ->where('ur.timestamp > 1379494886')
  ->orderBy('ur.timestamp', 'ASC');

$query = db_select('users', 'u')
  ->fields('u', array('uid', 'vid'))
  ->condition('u.vid', $subquery, 'IN');

$result = $query->execute()->fetchAll();


Prevent SQL injection One of the security principles is sanitize string and variables passed from client to server; SQL injection is one of the way to hack a website. in plain PHP there are some functions to prevent SQL injection:

mysql_real_escape_string()
stripslashes()

What is Drupal 8 strategy to prevent SQL injection? How can I clean up client data post in my Controller to protect my site from SQL injection?

Drupal 8 (like Drupal 7) uses PDO to communicate with databases.

With PDO, the DB API makes use of prepared statements, specifically to avoid SQL injection attacks.

Practically, this means that you should use the database API methods. If you use the select, update, delete methods directly, you have a better chance of avoiding SQL injection as everything will be parameterised.

If you use query, you need to be more careful, as the API can only protect you so much. For example, if you do this:

$sql = "SELECT uid FROM users WHERE name = '$_GET[name]'";
\Drupal::database->query($sql);

Then you deserve what you get :) You should always use this instead:

$sql = "SELECT uid FROM users WHERE name = :name";
\Drupal::database->query($sql, [':name' => $_GET['name']]);

Aside: In reality, you'll only see the 2 functions you mentioned being used in very old, practically obsolete code these days. The MySQL extension has been removed now, and stripslashes was traditionally used with magic quotes, which were deprecated in PHP 5.3. SQL injection is still very much a problem, but those 2 perhaps aren't the best to use for comparison in this day and age.