Can I have a GROUP BY as an expression? Without an alias I want to be able to achieve the following query.

SELECT FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(datetime)/60)*(60)) AS datetime,
ROUND(MAX(value), 2) AS value
FROM  my_values v
WHERE (datetime > '2012-12-15 00:00:00') AND (datetime < '2013-01-01 00:00:00')
GROUP BY ROUND(UNIX_TIMESTAMP(datetime)/60)
ORDER BY datetime;

You'll notice that my groupby clause is dynamic, so far in Drupal I have:

$select = db_select('my_values', 'v')
  ->condition('datetime', '2012-12-15 00:00:00', '>')
  ->condition('datetime', '2013-01-01 00:00:00', '<')
  ->groupBy('gbdatetime')
  ->orderBy('datetime', 'DESC');
$select->addExpression('FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(datetime)/60)*60)', 'datetime');
$select->addExpression('ROUND(UNIX_TIMESTAMP(datetime)/60)', 'gbdatetime');
$select->addExpression('ROUND(MAX(value), 2)', 'value');

This achieves the desired results, however It'd be great if I could do a GROUP BY ROUND(UNIX_TIMESTAMP(datetime)/60) without requiring the alias gbdatetime.

So, my question is can I have a GROUP BY as an expression?

This can be achieved like so:

$select = db_select('my_values', 'v')
  ->condition('datetime', '2012-12-15 00:00:00', '>')
  ->condition('datetime', '2013-01-01 00:00:00', '<')
  ->orderBy('datetime', 'DESC');
$select->addExpression('FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(datetime)/60)*60)', 'datetime');
$select->addExpression('ROUND(MAX(value), 2)', 'value');

$groupBy = &$select->getGroupBy();
$groupBy['gb'] = 'ROUND(UNIX_TIMESTAMP(datetime)/60)';

$result = $select->execute();

Which creates this query:

SELECT FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(datetime)/60)*60) AS datetime,
ROUND(MAX(value), 2) AS value
FROM my_values v
WHERE (datetime > '2012-12-15 00:00:00') AND (datetime < '2013-01-01 00:00:00')
GROUP BY ROUND(UNIX_TIMESTAMP(datetime)/60)
ORDER BY datetime DESC


How do I hide an empty field if my custom field formatter removes all items? I have a custom field formatter (in Drupal 8) that displays a list of taxonomy terms on a node. Some terms are not meant to be displayed, so the field formatter removes them from the items list.

Occasionally, all items are removed -- yet the HTML elements that wrap the field are still rendered. How do I hide the field completely when all items are removed?

EDIT FOR CLARITY:

I have a field with machine name field_tags that is an entity reference to multiple taxonomy terms.

To render this field, I wrote a custom formatter as a field formatter plugin in a custom module. The code is stored in the standard location in mymodule/src/Plugin/Field/FieldFormatter/TermListFormatter.php

My class extends EntityReferenceFormatterBase.

In my class, my viewElements() method strips out some items as needed and sometimes returns an empty array if no items should be rendered.

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];

    // Loop through each of the terms in this field.
    foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
      $label = $entity->label();

      // ONLY show taxonomy terms that begin with "Test".
      if (mb_substr($label, 0, 5) === 'Test') {
        $options = [
          'query' => [
            'tags' => [$entity->id()],
          ],
        ];

        // Output terms as links to /test?tags[]={tid}
        $elements[$delta] = [
          '#type' => 'link',
          '#title' => $label,
          '#url' => Url::fromRoute('view.test.page_1'),
          '#options' => $options,
        ];

        if (!empty($items[$delta]->_attributes)) {
          $elements[$delta]['#options'] += ['attributes' => []];
          $elements[$delta]['#options']['attributes'] += $items[$delta]->_attributes;
          // Unset field item attributes since they have been included in the
          // formatter output and shouldn't be rendered in the field template.
          unset($items[$delta]->_attributes);
        }

        $elements[$delta]['#cache']['tags'] = $entity->getCacheTags();
      }
    }

    // This will be an empty array if there were no terms beginning with "Test"
    return $elements;
  }

When all the terms are stripped out, the field wrapper elements are still output as follows:

How do I stop these elements from appearing when there are no terms to show?

Drupal adds the field wrapper only if the result returned by viewElements() contains at least one renderable child.

FormatterBase::view():

  public function view(FieldItemListInterface $items, $langcode = NULL) {
    ...
    $elements = $this->viewElements($items, $langcode);

    // If there are actual renderable children, use #theme => field, otherwise,
    // let access cacheability metadata pass through for correct bubbling.
    if (Element::children($elements)) {
      $entity = $items->getEntity();
      $entity_type = $entity->getEntityTypeId();
      $field_name = $this->fieldDefinition->getName();
      $info = [
        '#theme' => 'field',
        '#title' => $this->fieldDefinition->getLabel(),
        '#label_display' => $this->label,
        '#view_mode' => $this->viewMode,
        '#language' => $items->getLangcode(),
        '#field_name' => $field_name,
        '#field_type' => $this->fieldDefinition->getType(),
        '#field_translatable' => $this->fieldDefinition->isTranslatable(),
        '#entity_type' => $entity_type,
        '#bundle' => $entity->bundle(),
        '#object' => $entity,
        '#items' => $items,
        '#formatter' => $this->getPluginId(),
        '#is_multiple' => $this->fieldDefinition->getFieldStorageDefinition()->isMultiple(),
      ];

      $elements = array_merge($info, $elements);
    }

    return $elements;
  }

This means for the question if the field formatter removes all items the field is hidden.

However, field formatter and field preprocessing handle empty fields differently. If you only remove the first field item it is possible that the condition for an empty field has different results. See How to print all values of a multi-value field, except the first?


Attach image to taxonomy term? In my panel in "Taxonomy Term Template" I have shown the children terms in the current parent term page. Now I need to attach/associate an image to each term to make it look nice. I do see the option of selecting the term image field in the panel settings but that field shows the current parent term's image not of the children.

I have already added images for each term in my vocabulary.

I'm on Drupal 7.

Here is the screenshot to elaborate the scene.

You should make a view that lists the terms in your node (use contextual filters) and add the image fields you added to that term.

Create a node view that lists the node type that the categorized nodes come from.
Add the fields used to categorize the nodes.
Remove any other fields.
Add a contextual filter for the node id (Content:Nid).
Configure the contextual filter to have a default value and choose the 'id from url' option.
If you add that block to a region, it should show a list of terms associated with a node.
Now add the image field from the term, if you don't see that field you might need to add a relationship to that term field.


How can I get a list of all connected/logged in users? I would like to make a list of all logged in users accessible through the backend. The routes are created. It is only the request to retrieve the users that I would need. Is this data in the 'sessions' table? Thank you in advance for your help

You can try
// 3600s is one hour.
$uids = Drupal::database()->query('SELECT uid FROM sessions WHERE uid != 0 AND `timestamp` >=:time',[':time'=>(Drupal::time()->getCurrentTime()-3600)])->fetchCol();


How do I implement an image categorization system using Entity Browser and File Entity? I am currently using the Entity Browser module along with the File Entity module for handling image upload and selection for content editors in a Drupal 8 project.

I have several image fields on different content types and to get some structure for them I would like each image field to be mapped to a certain image category (taxonomy) so that the user can filter between categories when selecting existing images using the entity browser.

To do this I am using the File Entity reference for my image fields. I have added a taxonomy field with my custom ”image category” taxonomy on the Image File entity type. So far so good.

My first problem is that I want automatically populate the image category field with a certain value when adding a new image through the entity browser. So if I upload an image to a ”hero image” field the underlying file entity should get the category ”Hero images” automatically. I’m lost to how to hook into the upload process of the entity browser to set this based on which field it belongs to. How can this be done?

The entity browser also allows the user to select existing images. For this I'm using the view prepackaged with the File entity browser modulle and I have added a taxonomy dropdown filter to that view so that the images can be filtered by category. What I want to do is to have this view automatically set the correct filter when loaded. So when loading the view from a ”Hero Image” field the dropdown has the ”Hero Image” category preselected.

So essentially I'm missing two parts:

Automatically populating the file entity "image category" field when uploading an image based on which field the image was uploaded to
Automatically prepopulate the "image category" exposed filter in the "select existing image" view based on which field it was opened from

Can someone help here. Maybe there's a better way to go about this?

For the tagging part, forget about entity browser, that (currently) doesn't know about the context of where it is invoked and to what those files will eventually be added.

Instead, what you want to hook into is hook_node_presave(). Go through the referenced files in all your fields that you want to support (could be all image fields or a configurable list), check the image referenced there. If the image doesn't have a category yet, set it based on the field that you're currently looking. Or maybe always ensure it is categorized based on the current field. Whatever you want.

For views, that's currently not possible yet, for the same reason. Entity browser doesn't receive the context yet. There are some related issues like https://www.drupal.org/node/2656196 and https://www.drupal.org/node/2366335. Note that there are many ways to embed an entity browser and you don't always have a field, for example  with entity_embed.


Token for user being viewed I am formatting the user profile page in Drupal 8.9.2.
Are tokens available for the user being viewed (in user profile page), to display the user information?
I am using the Token and the Token Filter modules for this.
(edited: 8:44 AM 10 Sep 20)

I have solved the problem this way.
(1) I created a View to show desired user information.
(2) Then, I added a 'Contextual filter' to point to the user being viewed. (with the options "User ID > Provide default value > Type: User ID from route context")
(3) Then, I selected 'REWRITE RESULTS' and "Override the output of this field with custom text". As a result replacement tokens become available for user fields. I used that for formatting the Information according to the requirement.
Then, I placed this View block at the desired place.


Special code for .htaccess and robots.txt files My client was noticing that his site was extremely slow yesterday morning so he contacted his WiredTree host, who suggested that we add the following code in the .htaccess file:

Options +FollowSymlinks
RewriteBase /
SetEnvIfNoCase User-Agent "^SemrushBot" bad_user
SetEnvIfNoCase User-Agent "^DotBot" bad_user
SetEnvIfNoCase User-Agent "^AhrefsBot" bad_user
Deny from env=bad_user

Options +FollowSymlinks is already in the file and RewriteBase / is currently commented out and I'm not sure if I should uncomment it, not knowing what affect that would have. Then I would add the 3 set commands and the deny command below it. Is it OK to uncomment this line and add the extra commands?

It looks like the most important bit they want you to put in .htaccess is this:

SetEnvIfNoCase User-Agent "^SemrushBot" bad_user
SetEnvIfNoCase User-Agent "^DotBot" bad_user
SetEnvIfNoCase User-Agent "^AhrefsBot" bad_user
Deny from env=bad_user

They should probably go inside the <IfModule mod_rewrite.c> block in your .htaccess file, just after RewriteBase / (whether it's commented out or not).
This RewriteBase / line shouldn't cause any problems, if your drupal site is not in a subdirectory (e.g. your index.php file shouldn't be in a sub-folder of your webroot like http://domain.com/drupal/index.php)

The Options +FollowSymLinks shouldn't need to be included twice if it's already there.


Prevent ajax submit function being called when it fails validation I have a form, that when it's submitted, should be validated, and if valid, the results of that form should then appear below the form.

This works fine without AJAX:

function _form_validate($form, &$form_state) {
  if (!is_numeric($form_state['vsalues']['zip'])) {
    form_set_error('zip', 'Zip must be number');
  }
}

function _form_submit($form, &$form_state) {
    $values = $form_state['values'];
    $html = "
zip: ". $values['zip'] . "
";
    $form_state['storage'] = $html;
    $form_state['rebuild'] = TRUE;
 }

and then this gets printed out my main form in

  $form['output'] = array(
    '#markup' => (isset($form_state['storage']))?$form_state['storage']:'',
  );

If I make it an AJAX form, and change the submit function to:

function _form_submit($form, &$form_state) {
    $values = $form_state['values'];
    $html = "
zip: ". $values['zip'] . "
";
    $form_state['storage'] = $html;
    $form_state['rebuild'] = FALSE;
    return array("#markup" => $html);
}

It works fine apart from the fact the submit callback is triggered even when validation fails (e.g. passing a non-numeric value shows both a validation error yet also prints "zip: ").

What am I doing wrong? How can I stop the submit function being called?

Only thing you should have to put in your AJAX submit callback is this

  if (!form_get_errors()) {
    // Do your processing
  }
  else {
    // Return your form with errors.
   return $form;
  }


Submitting Data / Updating Data into Webform programmatically I have an existing WebForm in which I want to submit information through a Custom Page. Any idea how I can do that?

Also, there is another page where I want to update couple of fields in the WebForm through sid (submission ID) in a custom page.

Any Idea how to achieve that?

You can do this by adding following code in your custom module

  // Submit a webform
  module_load_include('inc', 'webform', 'webform.module');
  module_load_include('inc', 'webform', 'includes/webform.submissions');
  // Load node by webform id
  $node = new stdClass();
  $node = node_load($webform_nid);
  // Get next serial number
  $serial = _webform_submission_serial_next_value($webform_nid);

      $data = array(
        1 => array('Guest user'),
        2 => array('guest@example.com'),
        3 => array('Final testing of webform'),
      );

  $submission = (object) array(
    'nid' =>$webform_nid,
    'uid' => 0,
    'submitted' => REQUEST_TIME,
    'remote_addr' => ip_address(),
    'is_draft' => FALSE,
    'serial' => $serial,
    'data' => $data,
  );

  $sid = webform_submission_insert($node, $submission);


How to change taxonomy term in field with Rules? I have a field status that when user uploads a file, is populated by a taxonomy term "uploaded". Now when an administrator downloads the file I need the status field up change to taxonomy term processing. I have tried using Rules but can't get it right.

The Rule is like so:

Event->content type viewed
Condition->User has Role of Administrator
and I can't set the action.

The action data is [node:field-status], Value [node:field-status:parent:1]
But when I test it, it changes the status to "none".
The taxonomy terms in order are: uploaded, processing, admin hold, error, closed. So shouldn't the parent:1 be processing?

Am I asking to much of Drupal 7.50, or can someone point me in the right direction?

Question clarification

There is something in this question that I find bizarre: the requirement relates to "when an administrator downloads the file", but then the Rules Event mentioned is "content type viewed" (and combined with a Rules Condition "User has Role of Administrator").

Therefor I'm going to assume that "Content is viewed by a user who has the admin role" is an acceptable translation of "when an administrator downloads the file". With that in mind, read on about (a) what the reasons (multiple ...) are why it doesn't seem to work and (b) how to make this to work anyway ...

Mistake 1 - Use the correct token

The node:field-status is clearly a term reference field, which can, obviously, only have 1 possible value, which is one of these: uploaded, processing, admin hold, error, closed.

When you're using the Rules UI, in this case you should just use the token  [node:field-status], and NOT (repeat: NOT) [node:field-status:parent:1]. That explains '... when I test it, it changes the status to "none" ...' (as in the question).

Mistake 2 - Rules Condition 'Entity has field' is missing

From the Rules Conditions mentioned (only "user has role admin"), I'm about sure that there is a crucial additional Rules Condition that you would need ALSO to make this work. I.e. you need to tell the Rules module that you want to do something with the node:field-status field. I.e. you need to add a Rules Condition of "Entity has field" (related to that node:field-status field). Even though there are variations (other Rules Conditions), this "Entity has field" is what for me always seems to work when I want to do something with a field in Rules.

Using this Rules Condition is like ringing a bell for the Rules module to prepare for that, and have Rules already go retrieve the existing data about that field, so that you can (eg) test the existing value it contains (in a subsequent Rules Condition).

Mistake 3 - Rules Event 'Content is viewed' may be too late

Whatever you want to happen (via Rules), if you're using Rules Event 'Content is viewed', that you may simply be too late: the content is already being shown, so if the Rules Conditions or satisfied, what else do you want to happen. That is what 'Content is viewed' is all about.

If you didn't want to content to be visible at all (which does not seem to be the case here though), sorry, you're too late. If you did want something to happen BEFORE showing the content, then you should have used Rules Event "Drupal is initializing". Refer to 'How to specify a Rules event like "Content is 'going to be' viewed"?' for way more details on this. And if you want the user to see the result of your Rules Action(s), a page refresh is needed for that.

Possible alternative

Here is a rule (in Rules Export format) that might possible be an acceptable alternative (solution) to answer this question, using field_demo_tags as the machine name of the term reference field and which I labeled "Demo tags" (adapt to fit your own machine name of your field before trying to import this rule):

{ "rules_update_taxonomy_term_of_a_node" : {
    "LABEL" : "Update taxonomy term of a node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_demo_tags" } },
      { "data_is" : { "data" : [ "node:field-demo-tags" ], "value" : "1" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "This is a node with value \u0022[node:field_demo_tags]\u0022 for field \u0022Demo tags\u0022 ..." } },
      { "data_set" : { "data" : [ "node:field-demo-tags" ], "value" : "2" } },
      { "drupal_message" : { "message" : "Be aware: the value of the \u0022Demo tags\u0022 field just got updated to [node:field_demo_tags] (refresh the page to see the updated version ...)" } }
    ]
  }
}

Some more details about it:

Rules Event: Content is viewed
Rules Conditions:

Entity has field, for field field_demo_tags.
The term id of the current value of the term must be the one for uploaded (adapt this term id to fit your case).
Current user has role Administrator.

Rules Actions:

Show a message (to confirm we have a hit, mostly for demo/debugging purposes).
Do your thing, i.e. update the term id to the value of the term corresponding to processing (adapt this term id to fit your case).
Show a message (to confirm we did our job, and suggest a page refresh).

For short: if a node is viewed by a user who has role admin, and the node has been tagged with the term with Term Id = "1" (which could be the equivalent of uploaded in the question), then the term will be changed to the term with Term Id = "2" (which could be the equivalent of processing in the question). Additionally, an informational message will be shown similar to this:

  This is a node with value "uploaded" for field "Demo tags" ...
  Be aware: the value of the "Demo tags" field just got updated to processing (refresh the page to see the updated version ...)

Voilà, 2 mistakes corrected, and a workaround for the 3rd mistake, which is hopefully acceptable ...


Extending block configuration schema I'm using the Configuration Inspector module module, and I'm finding a missing schema error.

The configuration is for block.block.pminbox.settings.thread_count

The block itself is a plugin, created in my module. I've tried:

Adding the settings to the block annonation
Creating block.block.pminbox and adding settings as a mapping with thread_count as a property of that mapping
Creating block.block.pminbox.settings and adding thread_count in there
Adding the config to mymodule.schema.yml

Here is where I am at as of now.
Submit handler for class extending BlockBase:

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['thread_count'] = (int) $form_state->getValue('thread_count');
  }

mymodule.schema.yml:

block.settings.pminbox:
  type: block_settings
  label: 'Private message inbox block settings'
  mapping:
    thread_count:
      type: integer
      label: 'Thread count'

The rest of the schema in this file is being picked up, however, I'm still getting a 'schema undefined' error from the configuration inspector for this block.

It would really help to knowing how your data is saved (e.g. providing a snippet from your BlockBase::blockSubmit() implementation that shows this value), or what exactly you tried adding to your yml files.

However, in theory a working example that assumes, you are saving the value like this:

PmInboxBlock.php

/**
 * @Block(
 *   id = "pminbox",
 *   admin_label = @Translation("PmInbox"),
 *   category = @Translation("PmInbox"),
 * )
 */
class PmInboxBlock extends BlockBase {

  // ... Your Form definition here ...

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['thread_count'] = $form_state->getValue('thread_count');
  }

}

Then you provide the schema definition in a schema file named after your module:

mymodule.schema.yml

block.settings.pminbox:
  type: block_settings
  label: 'PmInbox Block'
  mapping:
    thread_count:
      type: string
      label: 'Thread count'


Pager labels aren't translated I have a site using Drupal 8.4.1 with all core language modules enabled, 3 active languages, and where English is the default language. The pager labels (e.g. "Last »") for my own views aren't translated, although the string "Last »" is available in the translation page. I can manually translate the pager labels by adding a translation for the whole view and then overriding the pager labels, but I think this isn't the right way to do it because the built-in views (e.g. /admin/content) are  translated just fine, without any manual override.

How can pager labels be translated without manually adding the translation?

I have seen this too. Looking thru the code, it appears that the pager templates do have translations set up properly. So in theory, UI translations should work. But they don't.

I haven't tried it but you probably could do this thru the hook_preprocess_pager__page(&$variables) function (for full views pages).  There seems to be a $variables['pager']['#tags'] array with the values for pagers. You might be able to do the UI string translation here.


How do I import entity related fields using drush migration? I am trying to do data migration from a Drupal 7 site to a Drupal 8 site using drush migration.
Example: I am trying to import users which has 5-7 fields and I tried to import fields using:

d7_field
d7_field_instance

These 2 are importing all fields in Drupal 7 (users, taxonomy, node). How can I restrict this to import only specific entity fields?

You can achieve this via a custom migration module, this way you have full control over what will be migrated, note the bold text:

  Create the migrations using drush migrate-upgrade --configure-only as discussed in Upgrade Using Drush
  Make sure you have aconfig/syncdirectory, to which the next step will write
  Export the migrations using drush config:export
  Create your custom migration module
  Copy only the YML files you want to use from the config/sync directory into the config/install directory of your new custom module, editing them to remove the uuid values and to edit the id, group, label, and other values as needed
  In the config/install directory of your new custom module, make a new migrate_plus.migration_group.your_module.yml file for your new migration group.

from official handbook: https://www.drupal.org/docs/8/upgrade/customize-migrations-when-upgrading-to-drupal-8

You can also rename the fields. Further processing can happen in hook_migrate_prepare_row(), hook_migration_plugins_alter(), or even a custom process plugin.

update

Please note that you will not be exporting configuration from a site and moving it to other site. Config export is a bad name here. Read it as generate migration template.

When you generated your template (aka, exported), you handpick those fields, entities and configuration that you want from all the available generated files, put them in a custom module, say my_custom_mig, enable it, and run it's migration.


What are the 'todos' when your database is hacked? I want to plan for the terrible nightmare of my database being stolen. I feel I am secure, and I am not holding much actual data, but... if it does get taken - what do we do, is there a standard way of drupalists to respond?

I am looking for specifics where obviously required, e.g. 'reset all passwords', but how?

Paul.

In Drupal 7, while all passwords are hashed (SHA-2 with 64-bit words) and salted, if your user's passwords have low entropy, brute-force password attacks are feasible.

Image source: xkcd, explanation.

Also note that the cartoon above assumes that an attacker tries to brute-force passwords over the web. As pointed out by @Damon in a comment:

  Readily available brute-force crackers check 200-500 million hashes per second on a single commodity PC, not 1000. That means a 44-bit password doesn't even last half a day, and a password as 99% of users will realistically have will last 1-2 seconds at most.

This means that if you experience a breech, you should force your users to reset their passwords, there's is the Force Password Change module that will invalidate all passwords and force users to set a new one.

There is also the Password Policy module that let you set a policy to force users to pick a password that is hard to crack by brute force (but it tends to enforce the type of policies the xkcd cartoon above lampoons, so I am not a big fan of it).

In addition to these modules, there is a recipe on Drupal.org to create a drush command to change passwords on accounts that are not actively used that may be used to invalidate passwords for stale accounts.

You may also condsider making your site less vulnerable to password cracking by adding Two-Factor-Authentication.

To guard against PHP injection, you may want to install the Paranoia module.

  The Paranoia module attempts to identify all the places that a user can evaluate PHP via Drupal's web interface and then block those. It reduces the potential impact of an attacker gaining elevated permission on a Drupal site.

To monitor your site and detect unauthorized changes, you may want to install the MD5 Check module.

  The MD5 Check generates a md5 checksum of all module files. If module is changed a critical security error is generated in watchdog log.

There may be other sensitive data in your database beside passwords (e.g. credit card numbers, medical records). If you're really worried about your database being stolen, you need to encrypt sensitive data stored in the database.  The Encryption module helps you defend sensitive data by means of symmetric encryption.

The the Payment Card Industry PCIComplianceGuide.org AFQ provides guidelines for what you should do if your site stores sensitive data.  It also links to guidelines for dealing with data breeches.

Depending upon your location, yoy may have to report a  data breach to affected parties. In the EU/EEA, this is mandated by the Privacy Directive. In the US there are now over 38 states that have privacy law that mandates notification. See www.privacyrights.org for more details.

Acknowledgements: Thanks to @Damon for pointing out that even 44 bits of entropy may not be good enough these days. Thanks to author of Cracking Drupal and Security Team member @greggles for bringing the Drush command to invalidate old passwords and the Parnoia module to my attention. Thanks to @Ben for making me aware of the PCI guidelines.


Create route that returns XML Feed How do I create a page that returns an XML feed?

Can you give more details ?

For example for an aggregator RSS :

In your test.routing.yml :

test.rss:
  path: '/rss'
  defaults:
    _title: 'rss'
    _controller: '\Drupal\test\Controller\RssController::content'
  requirements:
    _access_test: 'test'

And in your controller :

<?php

namespace Drupal\test\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

class RssController extends ControllerBase
{
    public function content()
    {
        $response = new Response();
        $response->setContent('<?xml> My flux </xml>');
       // kint($response);
        return $response;

    }

}

  You need the HttpFoundation\Response component.


D8, how to make node template aware of entity reference parent I have a multivalue entity reference field, referencing basic content.
The content (node) view is controlled via display modes (display modes is probably not relevant to the question)

Right now the entity reference field template is 'boilerplate' and just outputs the content in a for loop.

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

My display node template, node--[content type]--[display mode].tpl.twig
has custom markup, and granular output of field values.

However somewhere 'deep' in this template I need to alter the markup in accordance with the position this node has in the parent referencing entity.

i.e.

entity reference field:

node 1
node 2
node 3 <-- pass this list
position value somehow into the child node template, so i can change
the markup inside
node 4

I've been stepping through preprocessor variables in node_preprocess and field_preprocess, but I'm not really clear if the child node is 'aware' of its parent field, or more importantly the hierarchy of the parent field, and its position in it.

Any help or pointers much appreciated!

well, this seems to be working.

function THEME_preprocess_node(&$variables) {
$nid  = $variables['node']->id();

if ($variables['elements']['#view_mode'] === 'VIEW_MODE') {
// Get the node ID.
    $variables['nid'] = $nid;
    $parent   = $variables['elements']['#node']->_referringItem->getEntity();
    $items = $parent->get('FIELD_NAME')->getValue();

    foreach ($items as $key => $item) {
        if ($item['target_id'] == $nid) {
            $variables['tree_position'] = $key;
        }
    }
  }
}

Not sure this is the best way. So any suggestions still welcome.


Schedule change of field Rules does not allow data selection of fields without first knowing the node type actually has said field.

Rules only allows you to schedule components.

Rules action components can't have conditions to fulfill the first requirement.

How do I schedule a "Set a data value" action on a field?

I considered passing the field as a parameter to the component but it will only let me send "Entity" types and a binary value is not an "Entity" apparently.

Rules action components do not have conditions, but you can also add a component that is a rule itself, not an action set, and then schedule that.  Then you can just add the condition node: has type and then do set a data value however you like.


Setting value for a view filter How do I set a view filter so that the date of item makes it disappear WHEN the event occurs?

Right now when I edit the filter I have it Operator set to 'is greater than or equal to' and the Value set to 'today', but I want it to disappear at the exact time the event is occurring.

What do I put in 'value' for that to happen?

now worked. I also discovered +1 works for one hour before the event.


Using colorbox with media files The components I am using are:

CKEditor 3.6.6.1
Media 7.x.2.x-dev
Media Colorbox 7.x-1.0-rc4
Colorbox 7.x-2.4
Panels 7.x.3.3

The Theme I am using is: Bootstrap 7.x-2.2

I am trying to figure out how when I insert an image via the WYSIWYG editor CKEditor to have the image be smaller then be able to be opened in a colorbox. I am currently using the above modules with this process:

Create a new article
Click insert media
Click Library
Click a preloaded image I already have selected
Display as Colorbox
Click submit
Save the content

After all of that nothing happens. The image is not clickable at all (as to mean that a pointer does not render when I move my mouse over the image). What I am asking is simple. I have read that Media should handle colorbox integration now for images... how? I want to be able to insert images via the WYSIWYG but cannot seem to find instructions on this matter.

Did you customize this page: http://yoursite.com/admin/config/media/file-types/manage/image/file-display/colorbox ?

You should select a display mode for thumbnail (small image) and Colorbox (full size image).
Once you have updated this, clear caches or edit your content and save it again. Otherwise, your changes won't have any effect.


What are the database tables related to comments in Drupal 7? I received a lot of spam comments in one of my websites running on Drupal 7. I googled for a solution to delete them in bulk and came up on

DELETE FROM comment WERE status = 0

The query worked but the database size did not shrink significantly and I realized out that in addition to the 'comment' table there was another table called

 field_data_comment_body

which housed the body of the comment.

I would like to know which all tables are related to comments in Drupal 7

I know following tables.
1. comment
2. field_data_comment_body
3. field_revision_comment_body
4. node_comment_statistics

Beside that, I think, comments are also stored in any other tables installed by modules, and linked to comment modules.


Issues with regions using the Spaces Dashboard module I have been facing many issues trying to use the Spaces Dashboard module (part of the Spaces module).

I have setup a site with pressflow, OG, Context, Spaces, and Features; I got everything working well together.

I have been trying to implement the Spaces Dashboard feature, so group managers can manage their own group front page with an easy to use drag'n drop UI.

Through context, I have been able to create a default dashboard with some enabled blocks.
I have configured all spaces_dashboard settings and saved them in my default group space so every new group is shipped with those settings.
I have done some workaround in my template to get the context working with my Zen subtheme (based on #26 at http://drupal.org/node/633778).
I can now drag and drop blocks from my dashboard edition block to my theme regions.
I followed this tuto for setting up the UI (not really fully working with zen subtheme) : http://www.leveltendesign.com/answer/adding-customize-dashboard-magic-your-drupal-theme
I can currently drop blocks in ANY of the theme's regions even the disabled ones. I'm not sure of where does the problem comes from. The region settings are setup in the module config page at both site level and spaces level.
I cannot drop blocks in empty regions. ("Empty" meaning any region on the page that does not contains any block yet.)
If I move a block out of a region and there is no block anymore in the region I cannot move it back in the region. I'm not sure if this is a CSS, JS or module issue.
I found that by adding div for empty regions I can get some empty regions to work, but this is just a html trick and not a solution.

Content top

Finally, the 'save' button from the dashboard block doesn't save any modification to the dashboard in the current space nor in the global settings.

In case anyone still cares about this ...

You cannot drop blocks into empty regions, because they are empty. You can tell the dashboard settings to show all regions always, and then use CSS to hide the regions you dont want to be droppable ever via display none in CSS i think. Thats what I did.

The save button issue you would have to debug with Firebug and maybe a php profiler. You need to be sure the zen theme has allllll the html and css needed by the Gingko theme as lined out in that blog post above for the various JS actions to get processed correctly for the dashboard editor.

I followed the same tutorial for a Zen subtheme, spaces, dashboard and spaces_node and got it all working -- migrating to D7 looks like a pain in the future.


Pass node id to custom access denied panel page and/or view pane Rather than display an "access denied" page, I want to over-ride the standard 403 with a panel page that contains several views which take the original node id as a contextual filter.

I can create a view which handles contextual filters easily.
I can create a panel which over-rides the standard 403 with custom message.

However, there is no panels context that allows me to pass the original node id into the view, and the view doesn't get the "Content ID from URL" because the url passed to the view is "access-denied". PHP code in the panel confirms that when outputting $_GET['q'] and arg() using a custom content with PHP filter.

$_SERVER['REQUEST_URI'] DOES return the original path with the node ID, which I can parse, but I still don't know how I could pass that as a context to the view.

What is the best way to I pass the originally requested node id to the panel, and how do I pass that as context to the view? Alternatively, how can I directly pass it to the view, if doing through panels is not possible.

I found a solution that works.

I've just changed the default value of the view's contextual filter to PHP code and added this:

$node_path = explode('/', drupal_get_normal_path(trim($_SERVER['REQUEST_URI'], '/') ));
return $node_path[1];


Function not working in contextual filter I have a function in my custom module that return the nids for drafts in array.

function get_all_drafts(){
    $query = db_query("select bid from kom_draft");
    $res = $query->fetchAll();
    foreach($res as $bid){
        $output[] = $bid->bid;
    }
    return $output;
}

and following code is used in contextual filter nid ( php code text area )

$nids = get_all_drafts();
return implode('+',$nids);

and checked the multiple value checkbox but its not working, i checked the query and there in not value to compare.

when i use the same code on tpl file i am getting proper output that is + separated nids.

I just get it done by enabling validation criteria, I selected content validation with node content type and its working fine.


How to list most viewed nodes using Statistics module? How to list most viewed nodes using Statistics module in Drupal 6?

I'm looking for the PHP code to use in a custom theme.

I should have enabled this feature in admin panel before using the following code:

$number_of_hot = '10';
$hot_result = db_query_range("SELECT nid FROM {node_counter} ORDER BY totalcount DESC", array(), 0, $number_of_hot);
while ($hotid = db_result($hot_result)) {
$hot = node_load($hotid);
print $hot->title;
}


Order quantity increment condition for payment method I need to set order increment quantities in my Commerce 2 website. The website has two stores: retail and wholesale. Customers who are shopping in my "retail consumers" store must have increments of 6 products in their cart in order to check out (6, 12, 18, 24, etc). Customers in my "wholesale consumers" store must have at least 4 products in their cart in order to check out (4, 8, 12, 16, etc).
My plan is to add a custom Condition that can be used for the two payment gateways that will be used in the stores (one for each store). That custom Condition would allow me to designate an increment value for the product quantity for each gateway. "Make this gateway available if the cart contains an increment of 6 products".
I recently created a similar plugin for product quantity minimums in the cart, and I think I can re-use most of that code with a few adjustments. I am just not sure how to factor in the incremental requirement. It would be acceptable to hard-code the increments of 6 if that is the best/easiest way to do it; I could then create two separate condition plugins, one for 6 and one for 4.
Below is the Condition plugin code I have so far:
<?php

namespace Drupal\order_total_quantity_increments\Plugin\Commerce\Condition;

use Drupal\commerce\Plugin\Commerce\Condition\ConditionBase;
use Drupal\commerce_price\Calculator;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides the quantity increment condition for order items.
 *
 * @CommerceCondition(
 *   id = "order_total_quantity_increments",
 *   label = @Translation("Quantity Increment"),
 *   display_label = @Translation("Limit by quantity increments"),
 *   category = @Translation("Products"),
 *   entity_type = "commerce_order",
 *   weight = 10,
 * )
 */
class OrderTotalQuantityIncrements extends ConditionBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'increment' => NULL,
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    $increment = $this->configuration['increment'];

    if (isset($increment) && !isset($increment['number'])) {
      $increment = NULL;
    }

    $form['increment'] = [
      '#type' => 'number',
      '#title' => t('Increment'),
      '#default_value' => $this->configuration['increment'],
      '#min' => 1,
      '#required' => TRUE,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);

    $values = $form_state->getValue($form['#parents']);
    $this->configuration['increment'] = $values['increment'];
  }

  /**
   * {@inheritdoc}
   */
  public function evaluate(EntityInterface $entity) {
    $this->assertEntity($entity);
    /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
    $order = $entity;
    $increment = '0';
    foreach ($order->getItems() as $order_item) {
      $increment = Calculator::add($increment, $order_item->getQuantity());
    }

  }

}

I believe I have to modify the last part of the code (below) or add something after it.
  public function evaluate(EntityInterface $entity) {
    $this->assertEntity($entity);
    /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
    $order = $entity;
    $increment = '0';
    foreach ($order->getItems() as $order_item) {
      $increment = Calculator::add($increment, $order_item->getQuantity());
    }

  }

Can anyone please provide me with a direction to go in/guidance on how I should modify the code to meet my objective?

Per OP's comment, updated solution:
 public function evaluate(EntityInterface $entity) {
    $this->assertEntity($entity);
    /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
    $order = $entity;
    $increment = $this->configuration['increment'];
    $total = 0;

    foreach ($order->getItems() as $order_item) {
      $total += $order_item->getQuantity();
    }
    if ($total % $increment !== 0) {  return FALSE;  }

    return TRUE;
  }


On Rules Event Present Splash Screen To Flagged User Hello i was wondering what would be the best path to take to achieve my goal. I am working on a website. I am using Rules and Flag modules. I was hoping to set up a rule that when a member has been flagged then an event would happen that would be like a big cartoon splash YOUVE BEEN FLAGGED (with an image and maybe possibly sound)

Im sure that this could be within the scope of drupal. Could anyone suggest a possible way of doing this?

Thanks

One possible way is define your own Rules action against on that event.

Check the api: (assuming you are using D7)

http://drupalcontrib.org/api/drupal/contributions!rules!rules.api.php/function/hook_rules_action_info/7

Use jQuery to pop up an alert or whatever you like.


Create a view field that contain the sum of specific fields for a specific user I created a content type (Donation) that contains 3 fields:

a Donor Name field (user reference).
a date field (for the donation month).
the amount of the donation.

I am trying to create a view that returns a table with 2 columns:

one for Donor Name
one for the total/sum of all donation for that Donor.

My question: How can I achieve the second column (the sum of donations for the specific Donor/user) using views?

Try View Aggregation setting:

Goto Advanced tab, scroll down below and set "Use aggregation" to
'Yes'.
Filter Your View with Name field (user reference).
Now there must be "Aggregation settings" inline with your field
"the amount of the donation"
Goto "Aggregation settings" for "the amount of the donation"
field and select 'Aggregation type' to 'Sum'.

  Thats it, you are good to go now.


Generate image style from existing one instead of original image How can I make Drupal to generate image style from existing style, instead from original image. For example, original image is 3000x2000. I have a style medium (1000x700). And then I need a style thumbnail (100x100). How can I make Drupal to resize 1000x700 -> 100x100 and not 3000x2000 -> 100x100 (for optimization purposes).

Instead try to do this job you can  have the same result with create another image style and apply sequential this means first apply 1000x700 then 100x100.
I think you don't consider that  in one image style we can multi image effect.

I suggest you for better understanding image style  read this article


when i want to reinstall the modules i get this error Fatal error: Call to undefined function node_type_get_names() in /home/aukhma/public_html/modules/comment/comment.module on line 119

I got a  blank  page  when  I  would try to reinstall the node and the menu  modules.

The cause that pushed  me  to  reinstall those modules is that when I want to create a node for a new content type I can't find my new content type in the "add node" page.  So I did some research and found  a solution that said I need to rebuild the menu. I did that but got no result. I've also cleared the cache multiple times through the dash board.

Please, if any one can help find a solution I will be so happy, and thank you for the quick reply.

The content type you create is stored in your database, no reason to do what you are trying to do.
Check your db tables for that types.

These are core modules that are never meant to be uninstalled, cause these kind of functions are used by other modules and core files without even a dependency on them cause they are considered ... core.

Better try with a fresh install.


Adding a tab to the login page On the Login page, there are 3 tabs i.e. "Create new account", "Log in", and "Request new password". Are there modules out there that let us add more? If not, how can I achieve this manually?

Cheers

You can use hook_menu with type as 'MENU_LOCAL_TASK'. So that your menu path will be like 'user/your_path'.

Ex:

function my_module_menu($items) {
  $items['user/my-path] = array(
    'title' => 'Some title'
    'page callback => 'your callback',
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

If you are using views to print this page, you can set menu as Menu tab in path options.


Override User Registration Page I want to override the user registration page, but my code is not working like it used to for Drupal 6.

function mytheme_theme(&$existing, $type, $theme, $path) {
   $hooks['user_login_block'] = array(
     'template' => 'templates/user-login-block',
     'render element' => 'form',
   );
   $hooks['user_login'] = array(
     'template' => 'templates/user-login',
     'render element' => 'form',
   );
   $hooks['user_register'] = array(
     'template' => 'templates/user-register',
     'render element' => 'form',
   );

   return $hooks;
 }

Only the login block hook seems to work.

function mytheme_preprocess_user_login_block(&$vars) {
  $vars['name'] = render($vars['form']['name']);
  $vars['pass'] = render($vars['form']['pass']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

function mytheme_preprocess_user_register(&$vars) {
  exit;
}

I need this to be a preprocess function so I can change/add variables to put into the template. The second function is never called.

I got it: The theme ID should be user_register_form, not user_register. Now it works.


How to bring a third-party content? Drupal 7.
There is a service, there will send the request, it returns an xml. With the handler present in human readable form. We bring a response variable. How to display the value of this variable on the page?
I created a page with hook_menu:

function mymodule_menu() {
  $items = array();
  $items['serch'] = array(
    'title' => 'Result',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_proc'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_proc($parms){

}

In the FORM API I have not found a suitable element.
If use it hook_page_alter, I don't know how apply to the content?

$page['content']['system_main']['pager']
$page['content']
$page['content']['system_main']

or something else....

You can use the #markup property to display arbitrary data.

The function signature for your drupal_get_form callbacks must be:

function mymodule_proc($form, $form_state) {}

Concerning the response object that you want to render, I would need more information in order to help you.


How to manage exported block configuration that site users can override? Using core config management, we export configuration from developer's site instances and put than under version control. Eventually, this configuration is merged and ends up in production, where we import it thru either Drush or the UI.
Trouble is, site owners have permissions to update block configuration, and this overrides our exported configuration.

What is the intended workflow in this case?

Put more generically: how to manage exported configuration that can be overriden by users (with a core CM workflow)?

Trouble is, site owners have permissions to update block configuration, and this overrides our exported configuration.

I thinks it's a bad idea to give site owner to change something in site-configuration. Site owner should take care only about site's content and should have permission to change site's configuration(block's configuration it's a site configuration).


Hook to replace custom tags in block showing related articles I use a single drupal8 installation to serve content for multiple website's FAQ section. So I have put some custom tags like "##website_name##" in the html in article content and title.

Depending on the current domain, the tags get replaced. I have successfully replaced the tags in article content and title while displaying article page.

I have also created a block view to show related articles to the current article depending on the taxonomy of the article.

Problem is the tags I had placed in article title is not getting replaced when the related article block is replaced.

    function my_module_preprocess_views_view_unformatted(&$variables)
    {
        $rows = $variables['rows'];
        foreach ($rows as $id => $row)
        {
            $variables['rows'][$id]['content']['#row']->_entity->get('title')->value
                = replace_tags_in_content($variables['rows'][$id]['content']['#row']->_entity->get('title')->value);
        }
    }

Also tried following code:

function my_module_preprocess_block(&$variables)
{
        if ($variables['plugin_id'] == 'views_block:related_articles-block_1')
        {
            $results = $variables['content']['#view']->result;

            foreach ($results as $key => $result)
            {
                $title = $variables['content']['#view']->result[$key]->_entity->get('title');
                $variables['content']['#view']->result[$key]->_entity->get('title')->value = replace_tags_in_content($title->value);
            }
        }
}

When I inspect the title value in debugger, values are getting replaced but when the output is shown on the page the custom tags are still present.

Following the the screen shot for the view setting:

This is not easy to solve in preprocess, it is better to do this earlier when the view() of the node is executed, for example:

function mymodule_NODE_view_alter(&$build) {
    if ( isset($build['body']['0']['#text']) ) {
      $build['body']['0']['#text'] = replace_tags_in_content($build['body']['0']['#text']);
    }
}

This works, no matter if the node is used as page or in views (as content).

You might run into caching issues, when you make changes, that are not coming from the database and drupal does not know, which cache tags have to be invalidated. This would be a version of this code to address this:

function mymodule_NODE_view_alter(&$build) {
    $nocache = false;
    if ( isset($build['body']['0']['#text']) ) {
      $build['body']['0']['#text'] = replace_tags_in_content($build['body']['0']['#text'], $nocache);
    }
    if ( $nocache ) {
      $build['#cache']['max-age'] = 0;
    }
}

You have to set $nocache in the function replace_tags_in_content($string, &$nocache) to true, if you change dynamic data from outside.


Using arguments in addConstraint() for validation I implemented hook_entity_bundle_field_info_alter() to add validation to fields of a node type. I got $bundle as an argument in the hook and I need to pass it in $options argument like below:

$fields['field_tags']->addConstraint('NodeValidate', $bundle);

How can I access this argument in NodeValidateConstraintValidator? Am I passing the argument correctly?

$options provided in addConstraint can be accessed in the constructor using parent::__construct($options) in __construct() function build the options.

hook_entity_base_field_info_alter() doesn't contain a $bundle argument, as it is defined as function hook_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type). How can I validate the base field for a particular node type?

Options needs to be an array I think. You can access it on the constraint object in your validator, see ListStringItem::propertyDefinitions() and LengthValidator, which then uses it as $constraint->max.
Base fields are exactly that. Base fields. There is no bundle, they are the same for all bundles of an entity type (they can be overriden per-bundle, but then they become accessible in the bundle hook).
You shouldn't ask two different questions together :)


Alter a custom block depending on custom block type I need to alter all the blocks of custom type 'my_custom_block_type' that get displayed on my site.
In order to achieve this, i added a custom prerender in which  i filter on the block bundle :

function my_module_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  $build['#pre_render'][] = '_custom_block_custom_prerender';
}

function _custom_block_custom_prerender(array $build) {
  if ($build['content']['#block_content']) {
    $block_bundle = $build['content']['#block_content']->bundle();

    if ($build['content']['#block_content']->bundle() === 'my_custom_block_type') {
      // do your thing here
    }
  }
  return $build;
}

I think it's not the most elegant way to do this.

I tried to enhance this, but i did not manage, after several attempts, to retrieve the block type directly inside a hook_block_view_alter or a hook_block_build_alter ...

function hook_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  // things
}
function hook_block_build_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  // stuff
}

Is there a way to easily get the custom block type inside those two hooks ?

Try hook_ENTITY_TYPE_view()/hook_ENTITY_TYPE_view_alter(), that gives you the block_content $entity as an argument, just like hook_node_view().


Sorting by linked node/entity reference fields Suppose I am printing name tags for thousands of content nodes in one content type called "Attendee." Each of these nodes specifies a single "Attendee" for an event, (and their respective name tag). Suppose these attendees also needed name tags printed out for their “friends” who are attending with them. That is not a problem: These friends need their own node with the same fields to get their own name tag, so I keep them in the same content type and distinguish that they are a friend of an attendee with a simple checkbox.

When rendering the view, I need these friends of attendees to appear right after the attendee they are going with. So to link them, I used a node reference or a entity reference field. How do I get the Views module to sort the friends of attendees right after the attendee they are going with?

P.S. I am technically using the Views PDF module, but it has the basic views functions, so if it's possible with Views, it will probably be possible with this module.

Since you haven't been able to see the new fields for ordering (which is odd), you will probably have to perform a query alter on the views query and do some modifications:

<?php
function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'myviewname') {
    $view->query->somecodetoselectfields
    $view->query->somecodeforleftjoin
    $view->query->orderby[0]['field'] = "FIELDNAME";
    $view->query->orderby[0]['direction'] = "ASC";
  }
}
?>

What I usually do is just add a tag on the views query so that I can modify it using the standard Drupal query interface, which is much easier to use IMO.

<?php
function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'myviewname') {
    $query->tag[] = 'mytag';
  }
}
?>

Then

<?php
function mymodule_query_mytag_alter(QueryAlterableInterface $query) {
  $query->blablabla;
}
?>

Take a look at:

https://www.drupal.org/node/310077
https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7
https://api.drupal.org/api/views/plugins%21views_plugin_query_default.inc/class/views_plugin_query_default/7

Apologies if the solution is not straightforward enough.


Preprocess functions and template files Are there any issues I should know about using a pre/process function and, simultaneously, a template file?

For example, I have some logic I would like to apply to a field and at the same time, I would also like to customize the HTML output for that field as well.

Can I create a pre/process function and create a template file specific for that field?

Before answering YES/NO, let me make the context clear:

The .tpl.php files live near the city gates and are ready to produce code for the rest of the world. Moving towards the core of the city (our Drupal site) there is a very strong file: template.php. This file supports .tpl.php by providing new variables, changing variables, getting the HTML ready for pieces of our site and more.

Inside template.php there are 4 categories of things one can do:

write preprocess functions, like MYTHEME_preprocess_page(&$variables) or MYTHEME_preprocess_node(&$variables). With the aid of preprocess functions we can add or alter variables inside tpl.php files. Our main weapon: kpr($variables) or dpm($variables) provided by the devel module.
write theme functions like MYTHEME_links($variables) or  MYTHEME_breadcrumb($variables). Through theme functions we change the HTML output of some chunks of our site, like the breadcrumb. Main weapon: devel themer. (We check which theme function is responsible for the HTML output and override that one)
preprocess functions for theme functions. We manage to change a variable used in a theme function. For example, MYTHEME_preprocess_username(&$variables) prepares the variables for the theme_username(). We could put the code directly inside the corresponding theme functions, but then we would probably have a mess. (anyway, that's the idea behind the separation of the code here, and is not obligatory). Main weapon: kpr() or dpm()
implement hook functions. There are 4 hook functions available for template.php:

hook_css_alter
hook_js_alter
hook_page_alter
hook_form_alter

The first two change the css/js files loaded on a site (the one's we see as @import blah blah when we view the source code, and we can tell Drupal not to load a file (even if it a default module.css or anything else)

The third is used to change things around, regarding the whole page element of Drupal. So for example, we can move things around, from a node of the main content to the second block of the sidebar, etc

With the last one we can change variables inside any form in Drupal. Main methodology: call debug($form_id) to take the unique id of the form you want to play with
then target this form by if ($form_id == blabla), then call dpm($form) or debug($form) to see what's inside the specific form and alter variables, etc.

And YES, of course you can use both a preprocess function AND a specific .tpl.php
for example:

function MYTHEME_preprocess_node(&$variables){
if ($variables['type'] == 'article')
$variables['blabla'] = .. // creates a variable to be used in node.tpl.php
}

then create node--article.tpl.php and print that $blabla there


Adding a jQuery interaction with Views Accordion I have a Views Accordion displaying some books under their categories.
I want to add some jQuery interaction, so when the user clicks the triangle of each category, the content will be loaded via jQuery AJAX.
How can I include this functionality? Something like this, though I cannot see any ID identifier associated with the href which opens / closes each of the accordion bellows.

 function mymodule_views_pre_render(&$view) {
     if($view->name == "categorias"){
         drupal_add_js('jQuery(function() {
             jQuery("#categorias-page-0").click(function(e) {
              // ... AJAX stuff
              });
         });', 'inline');
     } // if
 } // function

Show image below, what I have, and when clicking on each category I would like to perform whatever jQuery actions I'd like.

You have to use $(this) with out working on id/class.

Refer to this link jQuery $(this) Selector with Examples.


views contextual filter second variable I have a view that receives two variables like my-view-url/%/%. In a menu I have created a url something like my-view-url/animals/dogs. How do I get the contextual filter to see the second variable dogs and ignore animals.

The contextual filter is set to "Content: Has taxonomy term ID (with depth)" and I convert the taxonomy term to an id.

It think it must have something to depth but I am not sure.

This option is available out of the box in view contextual filter settings. You can able to choose input to the contextual filter using checkbox setting "WHEN THE FILTER VALUE is not in the URL". Select Provide default value from URL and choose path component. In your case it is 3. See below screenshot for example.


How to render paragraphs module in twig I am creating a custom template for my theme and I am constructing a page.html.twig page. I want to call of the individual node fields into separate rows. I have been able to successfully display everything except the paragraph field.

I have tried.

{{ node.field_benefits }}
{{ node.field_benefits.value }}
{{ paragraph.field_benefits }}
{{ paragraph.field_benefits.value }}
{{ node.paragraphs.field_benefits }}

And nothing has worked. Does anyone have any idea of the correct structure to call in the paragraph module?

Or would a for function work

{% if node.field_benefits %}
{% for field_items in node.field_benefits %}
{{ field_item.value }}
{% endfor %}
{% endif %}

First add a paragraph--your_paragraph_machine_name.html.twig to the templates directory of your theme.

Accessing your paragraph fields can be done by adding twig variables in a format similar to {{ content.field_your_field }}.

If you want only the field value, that's a little trickier. For instance if you had a List (text) field and wanted to get the value from the selected option, you could do something like:

{% for item in content.field_select_list %}
  {% if item is iterable %}
    {% for key,value in item %}
      {% if not value is iterable %}
        {% if key == '#markup' %}
          {{ value }}
        {% endif %}
      {% endif %}
    {% endfor %}
  {% endif %}
{% endfor %}

You can always run a {{ dump(content) }} to see the structure and get the values you're looking for. Hope this helps!

EDIT: You can avoid all the silly nested loops. The above example should be written like:

{% set value = content.field_select_list.0['#markup'] %}
{{ value }}

For a Text (plain) field it might look something like:

{{ content.field_text.0['#context'].value }}

To get a URL value from a Link field I've seen suggestions like:

{{ content.field_link['#items'].0.value.uri }}

But it would have an "internal:/" prefix, so I've had better luck with something like this:

{{ content.field_link.0['#title'] %}


Entity metadata wrapper, get field collection in field collection I want to get (and to set after) the value of a field collection in a field collection (multidimensional field content).

This is my code :

// The node is a custom content.

// I get the list of first collections fields.
$temp = field_collection_get($node,'field_top');
// Shows the structure you can see below in the screenshot.
dpm($temp->value()[0]);

// Now, I want to get the value of field_website_informations.
// I've tried several ways but I couldn't find the right way.
// The following line returns an error.
$testage = entity_metadata_wrapper($temp->value()[0], 'field_website_informations');

Is it possible to do with the Entity API?

The screenshot :

Yes it is possible. Let's say you have a content type with a field collection named field_collection_parent, which has a field collection in it named field_collection_child, which has a field in it named field_child.

// First you need to wrap the node with entity_metadata_wrapper
$node_wrapper = entity_metadata_wrapper('node', $node);

// To get the value of field_child:
$value = $node_wrapper
           ->field_collection_parent
           ->field_collection_child
           ->field_child
           ->value();

// UPDATE: If a field accepts multiple values, treat it like an array
// The following line would get the first value of field_collection_child in the
// first field_collection_parent.
$value = $node_wrapper
           ->field_collection_parent[0]
           ->field_collection_child[0]
           ->value();

// To set/modify the value of field_child
$node_wrapper
  ->field_collection_parent
  ->field_collection_child
  ->field_child
  ->set('Some new value');

// To save the node after modifying
$node_wrapper->save();


How to promote nodes/pages into blocks? Standard Drupal comes with a "promote to front page" when creating new content. But I want know how to promote, let's say News flow to the block located to the right?

As far as I know there is no "url" for blocks so I can't really use view to assign my news flow to the blocks url. So how do I do this the easiest way?

I complete the previous answer about Drupal 8.

In Drupal 8 with Views (include in core) it's exactly the same way.

Add a 'Promote to block' checkbox field on your News content type.

Then in Views you can create a new View or you can go in the "Content" View. Then create a new "Block". Describing all Views functionalities would take a long time, but in this block you can filter all your content, particularly in the Filter Criteria sections where you can filter in order to take only News content type with only the 'Promote to block' option checked.

If needed, search for some Views tutorials. It's quite easy and very powerful.

Then call this new block instead the old one.


Gather all broken links (Link-checker) in view I just installed the Link-checker module which seems nice for my needs. But I don't see a way to gather all the nodes with broken links, for example a view or block.

Is there any way to collect all these nodes with broken links in a view/block?

Normally this would involve either a custom module, or a patch to the link-checker module, with an implementation of hook_views_data. This requires some coding skills and understanding of databases.

One option is to try the Data module, which supposedly is capable of automatically deriving the required information by looking at the table structure. I've never tried it though, so whether or not it works, or how well it works, I cannot say. From looking at the modules schema, it looks like the interesting tables are:

D7 "linkchecker_block_custom", "linkchecker_comment", "linkchecker_node", "linkchecker_link"

D6 "linkchecker_boxes", "linkchecker_comments", "linkchecker_nodes", "linkchecker_links"


How to invalidate a views cache based on custom criteria? I have a custom content type (story) with a datetime field which determines if a story shows up in a the views that list the nodes of that content type; if the datetime defined for a node is newer than the current datetime, it will not show up.

My problem is that I have to go and empty admin/config/development/performance and click Clear all caches or uncheck Cache pages for anonymous users.

I would like to keep caching pages for anonymous users, so I am looking for other options.

Any help is much appreciated.

It sounds like the problem is not views being cached, but that the entire page is being cached. If Drupal have a complete page cached, it doesn't matter if the view is cached or not. What you need to do, it to conditionally disable the page cache, or prevent Drupal caching that page in the first place.

There have been some talk about how to do the first, but this is not something I have tested or can advise.

Be warned, that messing with the Drupal caching system can give some unforeseen problems.

An alternative solution would be to empty the page cache or invalidate the cache for that particular page once a day/hour to make sure that it's relatively up to date. This is probably the route I would take in this situation.


Css files of liberary can not be load I'm trying to add Zurb Foundation framework to my theme library file. However, when I add the following code to my library, the java script file load without any probleme or difficulty but css files only can not be load.

I would be grateful to hear what is the problem with the code and what is the right way to load a css of the library?

This is my theme folder structure (Zurb Foundation folder location):

|-Theme Name
|  |-includes
|  |  |-foundation
|  |  |  |-css
|  |  |  |-js

Library file:

foundation:
  version: 6.x
  css:
    includes/foundation/css/app.css: {}
    includes/foundation/css/foundation.css: {}
    includes/foundation/css/foundation.min.css: {}
  js:
    includes/foundation/js/app.js: {}
    includes/foundation/js/foundation.js: {}
    includes/foundation/js/foundation.min.js: {}
    includes/foundation/js/jquery.js: {}
    includes/foundation/js/what-input.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once

[theme_name].info.yml file:

name: Theme Name
type: theme
core: 8.x
base theme: classy
libraries:
  - Theme Name/foundation
  - Theme Name/global

And finally, I uncheckmark Aggregate CSS and  Aggregate JavaScript files boxes in performance, flush caches and clear my browser cache.

screenshot of Source page:

As you can see the javascript files load witout any problem.

You can follow document

  You may notice the 'theme' key for css which is not present for js. This indicates the style type the css file belongs to.

  You can set CSS weights with 5 different levels of styling:

base key assigns a weight of CSS_BASE = -200
layout key assigns a weight of CSS_LAYOUT = -100
component key assigns a weight of CSS_COMPONENT = 0;
state key assigns a weight of CSS_STATE = 100
theme key assigns a weight of CSS_THEME = 200

  This is defined by the SMACSS standard. So here if you specify theme
  it means that the CSS file contains theme related styling which is
  pure look and feel. More info here. You cannot use other keys as these
  will cause strict warnings.

In your case you can use key theme

foundation:
  version: 6.x
  css:
    theme:
      includes/foundation/css/app.css: {}
      includes/foundation/css/foundation.css: {}
      includes/foundation/css/foundation.min.css: {}
  js:
    includes/foundation/js/app.js: {}
    includes/foundation/js/foundation.js: {}
    includes/foundation/js/foundation.min.js: {}
    includes/foundation/js/jquery.js: {}
    includes/foundation/js/what-input.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once


What does "Revision translation affected" indicate? In views there is a boolean field named Revision translation affected. The description for the field is "Indicates if the last edit of a translation belongs to current revision". To me it is not so clear. What exactly does it mean?

Does it indicate what language that was changed in that revision? And what happens when non-translatable fields are edited?

I found this explanation in code comments:

  If a translation has changes in a certain revision, the translation is
  considered "affected" by that revision, and will be flagged as such
  via the "revision_translation_affected" field.

http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/Entity/entity.api.php#n102


How to use ajax in field widget form? I need to store a country and a region for geographical objects. Countries and regions are stored in a taxonomy vocabulary. Moreover, some countries have regions (as child terms) but someones don't have it.

I decided to create a complex field contains tid of a country and tid of a region. If an object doesn't have a set region, then a value of the region is 0 in this case.

I want to create a field widget for it. The widget should contain a combo box with a list of countries. Moreover, if the user is selected a country having regions, then a new combo box with its regions is appeared.

I have tried to do it with ajax like it is done in forms.

That is, I have written the following.
(Here I have removed some code from the source to shorten it)

  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
  {

// come code here ....

    // TODO: Implement formElement() method.
    $element['country_id'] = [
      '#type' => 'select',
      '#title' => t('Select a country'),
      '#options' => PalomGeo::getCountryList(),
      '#default_value' => $country_id,
      '#ajax' => [
        'callback' => '::changeCountry',
      ]
    ];

    $regions = PalomGeo::getRegionList($country_id);

    if ($regions!=[]){
      $element['region_id'] = [
        '#type' => 'select',
        '#title' => t('Select a region'),
        '#options' => $regions,
        '#default_value' => $region_id,
      ];
    }

    return $element;
  }

// Some code here

  public function changeCountry(array &$form, FormStateInterface $form_state){
    return $form['region_id'];
  }

But unfortunately, it doesn't work.

The error "The specified #ajax callback is empty or not callable" is appeared.

I want to clarify is it possible to use AJAX upon creating field widgets? If yes, does it differ from using AJAX in Drupal 8 Forms?

You need to specify the class (including the full namespace) to run that method on. E.g: 'callback' => \Drupal\my_module\Plugin\Field\FieldWidget\MyWidget::changeCountry


How do I keep  tags from displaying? I have a field in a view that shows some HTML tags that, no matter what I do, keep showing up:

What's adding them? How do I get rid of them?

You have the Theme Developer module enabled, which adds <span thmr="foo"> tags to everything. Theme Developer uses a bit of brute forcing when it comes to adding those tags that can cause problems with complex themes that don't go out of their way to support it.

Disable it and they'll go away: you should only have Theme Developer enabled during development/debugging anyway.


How to set a menu link to user/edit in Drupalgap? I do not need the profile view tab and would like to link from a menu directly to user/%/edit/. In settings.js below I tried different paths, none of which worked.

// User Menu Authenticated
drupalgap.settings.menus['user_menu_authenticated'] = {
 options: menu_popup_get_default_options(),
 links: [
{
  title: 'My Account',
  path: 'user',
  path: 'user/%/edit', //not working
  path: 'user/edit', // not working
  options: {
    attributes: {
      'data-icon': 'user',
      'class': 'ui-btn ui-btn-icon-right'
    }
  }
},

Is there a (simple) way to set such a direct link?

When the settings.js file is loaded in DrupalGap, the framework isn't yet aware of who the current user is, so it is not possible to place this type of dynamic link into traditional DrupalGap menus. Instead you can use a block to simulate a dynamic menu.

http://docs.drupalgap.org/7/Menus/Menus_with_Dynamic_Links

/**
 * Implements hook_block_info().
 */
function my_module_block_info() {
  try {
    var blocks = {};
    blocks['my_module_user_menu'] = {
      delta: 'my_module_user_menu',
      module: 'my_module'
    }
    return blocks;
  }
  catch (error) { console.log('my_module_block_info - ' + error); }
}

/**
 * Implements hook_block_view().
 */
function my_module_block_view(delta, region) {
  try {
    var content = '';
    switch (delta) {
      case 'my_module_user_menu':
        var uid = Drupal.user.uid;
        var html = theme('popup', {
            content: theme('jqm_item_list', {
                items: [
                  l('View profile', 'user'),
                  l('Edit account', 'user/' + uid + '/edit'),
                  l('Logout', 'user/logout')
                ]
            }),
            attributes: {
              id: drupalgap_get_page_id() + '_my_module_user_menu'
            },
            button_attributes: {
              'data-icon': 'bars',
              'data-iconpos': 'notext',
              'class': 'ui-btn-left'
            }
        });
        return html;
        break;
    }
    return content;
  }
  catch (error) { console.log('my_module_block_view - ' + error); }
}


Clearing a Date Field value in the Edit Node form I have a content type with a date field (field_acquisition_date) and I'm using the Popup Calendar widget in the form UI. If a user...

puts a value into that field and save the node
then edits the node again
clears out the value
and saves the node a second time

the original value is still in that date field. How can the user set that field value to empty/NULL while using the edit form?

You just need to set the default value to 'No default value' in the content type of where the field is created.

Please see in the screenshot


Line item should change the price I have this problem in Drupal Commerce: a line item should change the price of my product, that is based on customizing the users (ex. product base $10 with customization $12, customization is line items).

This is possible working on Rules, but you only see final price after you add the product on cart, I should instead see the price change in ajax so the users see final process before add to cart.

I've not found solutions online. The basic scenario is like this:

You buy a shirt based  =$10
The user customizes the shirt with your name and = $12
The user customizes name and logo = $14

I am working with Kickstart 2.0

The functionality you're looking for doesn't exist at the moment. I'd describe it as wanting line item field value changes to trigger a refresh of the Add to Cart form and the injected product fields. You can follow this feature request, though I'm not sure it's likely to be addressed soon:

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


How to override checkout form validation error message? Im using D7 and Ubercart 3. But I think this is more a form question than anything else. When validating the checkout form I get a list of errors saying fields are required. And thats all fun and stuff, but I just want the error to say:

  Please complete the form by filling out the highlighted fields.

And only once off course.

You'll want to use:  theme_status_messages.

First, use drupal_get_messages to clear the queue.

Then, use drupal_set_message to add your new generic message.


How to write a drupal cron job to fetch data from a link How can I write drupal cron job that fetches data from a link and update the database ..? Im new to drupal so unable to understand the working of cron after searching alot. Any help will be appreciated ..

Create a simple Drupal 7 module, there are a lot of examples for this (i.e. here). Then hook into cron with a function mymodulename_cron() and inside the mymodule_cron function fetch your json data.

Your mymodulename_cron() will be executed each time, the drupal cron is run. This can be done from outside or from the admin/reports page. Look at /admin/reports/status for info about this.


Append html after node content in custom module in Drupal 7 I have an custom tpl.php inside of theme for some node type. It works fine but I would like my custom module to append some HTML after each such node (content of tpl.php). And I don't want to override the output from tpl.php inside of theme (just add something at the end of it).

Is there an hook for that or should I use different approach?

You can use the node view alter hook in your module to add/change your node object:

  This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete node content structure has been built.

If you have devel enabled, you can dpm($node) inside your node_view_alter function to see the node structure and then you can add to it as needed from the module.


How to display entire comments in separate page I know we can display reply form in separate page. But now I having the requirement of displaying entire comments and reply form in separate page. Is there have any way to display those in separate page.

The Talk module shows the comments for a node in a tab added to the node page.

  The talk module removes comments from the node page and puts them on a separate tab. This style of commenting is very popular on Wiki sites (usually called the "discussion" page) and on news websites where the goal is to separate user generated content from editorial content.

  When installed this module will add a tab to the set of tabs at the top of a node view page like "View | Edit | Talk" and provides a link at the bottom of the node to go to the talk page and view comments.


Node ID from hook_comment_insert I need the ID of the node the inserted comment is attached to. This is what I have tried:

function my-module_comment_insert(Drupal\Core\Entity\EntityInterface $entity)
{

   // According to https://drupal.stackexchange.com/questions/145823/how-do-i-get-the-current-node-id
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
        $nid = $node->id();
    }
    drupal_set_message("The vaue is " . print_r($nid), 'warning');
}

But... The value I get is "1", while it should be (according to node URL) "55". Or am I using drupal_set_message for debugging the wrong way?

I also tried $entity->get('entity_id')->target_id (according to:  How to get the node id the comment is attached to in hook_comment_insert?) or \Drupal::routeMatch()->getRawParameter('node'), but I always get "1" and I'm positive that the website cache has been cleared.

print_r($variable) does not return anything useful, it just outputs text (which it does successfully, so it returns boolean TRUE [which is rendered as 1 when printed]). Your drupal_set_message basically does something like echo ($string . $boolean . $string)

Use print_r($variable, true) to return the output of the print_r to the calling function, instead of rendering it.

See https://www.php.net/manual/function.print-r.php


How to apply patches? I have installed Drupal 7 in FTP server. I am trying to apply a Drupal patch.

I did see many links online but no one shows how to do it while Drupal is in FTP server of the hosting account. I think there are many ways I can do it. One way would be to get the Net Beans. I am not sure whether I need to install Net Beans in FTP server first or install to my local machine.

If you could provide some details for beginner, it would be helpful.

If you're on UNIX based system (e.g. MacOSX, various Linux distros), the patch utility is a great tool here. I typically use the command:

patch -p1 < patch-file.patch

With the -p1 option being important for installs already under a git repo.

It sounds like your use case is a bit different though. drupal.org has a good documentation page for applying patches in various environments.


Add a custom attribute to the main div of a node only on teaser view mode I want to add a custom attribute to the main div of a node only on teaser view mode.
e-g

<div class="node" tarbot="left"> </div>

I need to add tarbot attribute to the main div of a node to apply a JS function. I want to affect only teaser view mode with my Function, not Full content display.

We can use preprocess function to change OR add an attribute to our node main div.

function MYMODULE_preprocess_node(&$variables){

  // Array of aatributes which we want to pass to the node div.
  $attr_array = ['tarbot' => 'value'];

  // Condition for teaser format.
  if ($variables['teaser'] == TRUE) {

    $variables['attributes_array'] = $attr_array;
  }
}

by using this function we will get our node div in this form

<div class="node" tarbot="value"> </div>


If I using Ubercart and "PayPal Website Payments Pro", Can customer pay with credit card directly? I'm not familiar with payment gateway. I'm building shopping cart selling physical product. Currently the website using: Drupal 6, Ubercart 6.x-2.4, with PayPal free account.

My client asked me to make credit card payment as simple as possible. Some customer don't know what is PayPal? When making ckeckout, they are redirected to PayPal account. After registration, they then asked to transfer from credit card to their PayPal account. They really confused and finally they refused to buy the product.

My question is: If I using Ubercart and "PayPal Website Payments Pro", Can customer pay with credit card directly without redirected to other website?

Read here why Authorize.net is not my choice

yes. With Paypal Pro, users remain on your site and the transaction is completed underneath by Paypal. There is no visible relationship between the two for the end user.


Create role for changing user accounts and not admins I am developing a documentation site for a client. The site has the option of Who can register accounts? set to  Visitors, but administrator approval is required.
So, currently only Admin(user1) is doing the user approval procedure.

Our client has a customer services team which handles this account approval procedure currently. So, if I create a new role (say moderator) and give it permission to administer users (blocking/unblocking, changing role of a particular user), then they will also be able to modify admin users' account; and this is not expected.

Is there a way(any module or either) to restrict moderators to administer only few roles and not admins' role? Is there any other way to do this?

I am looking something similar to this sandbox project, but I want different set of permissions.

This module might be what your looking for. http://drupal.org/project/administerusersbyrole

With it you will get permissions for any role to change any other role. Here is a screen shot of it in action on the permissions page.


How do I configure SSO by SAML? At first, I am new in SAML. Could somebody tell step by step, how to configure SSO on Drupal using simplesamlphp? Or how to test by "Test configured authentication sources"?

What I have now.

Installed simpleSAMLphp Authentication module.
Add simplesamlphp library to my site (mysite/simplesamlphp).
Changed config.php
Added meta to saml20-sp-remote.php

$metadata['name'] = array(
'SingleSignOnService'  => 'url_login',
'SingleLogoutService'  => 'url_logout',
'certFingerprint'      => 'key',
);
When I go to mysite/saml_login, I am return to login page on IdP. After login I return to my site (mysite/sso/login?params) with SAMLRequest and other GET-params. But site show page not fount error. On wiki it step 2.

So what I did wrong? May be I must set same page callback to handle this GET-params?

I also try to did this by simplesaml "Test configured authentication sources", but I got the same result.

Please, help!

This is a very old question but worth solving it.

By:

  I also try to did this by simplesaml "Test configured authentication sources", but I got the same result.

It seems that @misha-from-lviv didn't configure simpleSAMLphp correctly.

  $metadata['name'] = array( 'SingleSignOnService' => 'url_login', 'SingleLogoutService' => 'url_logout', 'certFingerprint' => 'key', );

The metadata is incomplete

The process to configure the simplesamlphp is way more complex that the 5 steps described there. This Vagrant box setup simplesAMLphp (as an SP and IdP) and Drupal 7 for you and let's you start testing SAML right away.

Disclaimer: I created the box


Why is Search API only searching node titles? I have a Drupal 8 site with a custom content type called "Story". It uses the provided body field with machine name "body". Although I have set up configured Search API, it seems to only search node titles.

Here are the fields I have added under the search index:

How can Search API be configured to search other fields, including the body field? I have tried searching words that are found only in a body field, and no search results are returned.

This is probably due to a misconfiguration in your search_api view. I'm assuming you're using an exposed filter and you'll need to be sure that your Keyword Search filter is configured to also search the body field. Edit the settings for the exposed filter and make sure body is selected in the Searched fields field.

It could be helpful to configure a search_index view mode for your nodes and configure search_api to index that view mode, then you can set your exposed filter to just search on that one "field". I find that it helps to keep things running smoothly and consistently across content types that don't necessarily share fields.

Also, make sure your content is actually indexed, sometimes it's just queued and hasn't actually been indexed yet. You can do that from your index's "View" tab.


Modifying $view in hook_views_pre_render() I'm using Drupal 8.0.5, and need to force a title on a View.

I've tried various Views hooks, but will focus on hook_views_pre_render().

There's a ViewExecutable $view taken as an argument, which is not passed by reference.

I've tried:

function mymodule_views_pre_render(ViewExecutable $view) {
  $view->setTitle('foo');
  // $view->save(); // I've also tried this
}

I've gone through step-debugging to ensure it's getting called, but it seems the setTitle method does not affect the output that renders. I've also set my theme back to Seven to ensure there's not a theme issue involved.

I'm also happy to embed the View using a custom block, but I am running into the same issue there.

How does one modify a ViewExecutable object properly?

function hook_views_post_render(\Drupal\views\ViewExecutable $view) {
   if ($view->id() == 'viewid') {
    // Set the view title.
    $view->setTitle('NEW TITLE');
   }
}


What is wrong with my render code? I am trying to create a custom content pane where I would be able to specify 8 values and create 4 divs with 2 values in each one of them. For this I am extending cTools module by creating a plugin. I am already able to fetch input and store it in $conf variable. The problem is that it seems that everything I do in render function doesn't work. At first I though I had some naming problems. My module name is

  uzduotis

And here is my code for render function:

function uzduotis_render($subtype, $conf, $args, $context) {

  $block = new stdClass();
  $block->title = "4Divs";

  $html = '';
  foreach ($conf as $key => $items) {
       $html .= '
' . $items['text'] . $items['link'] . '
';
  }

  $block->content=$html;

  return $block;

  dpm($block);
}

I try to dpm my block and I get nothing, also another strange thing is that even a block title doesn't show up which I guess notifies that something is completely wrong. Can someone please point out what is wrong? If you need some additional information, please ask for it and I will update. Thank you in advance.

You cannot run any code after a return statement. By definition the return will exit the function. Try moving the dpm call to just before the return statement.

As an aside, I believe that best practices say that $block->content should be a render array and not straight up html...


Multiple nodes from a single content type? I'm trying to create a single content type that displays data across multiple pages for a client. For example:

DOG content type with fields:

List item
Name (Title)
Breed
History (Body)
Age
Weight
Height
Previous Owner Name
Previous Owner State
Previous Owner Gender

and then I would I like these pages created automatically:

/dog/<name> (overview page that includes Name, Breed, History)
/dog/<name>/details (includes age, weight, height)
/dog/<name>/owner (includes previous owner name, state, gender)

Each page would have a submenu that links to the other pages. I can create the first overview page no problem, but how would I create the the second and third pages? Would I look at the URL pattern to find content matching the name?

As fas as i understand the question your requirement is to display those content on different pages. So it is better to create a three different views displaying the required data.For example you can create first view name dog1 having field name , breed and history and a second view name dog2 having field age weight and height and so on. And also you add submenu of those two pages link.


Programmatically delete one entry from one field on one entity What's the proper way to programmatically delete one specific field entry for a multi-entry field from one specific entity? (that's specific fields and specific entities, not field types or instances and entity types)

Here's some possibilities I've looked into which don't work:

Loading the entity with entity_load(), setting the field entry to =null or =array(), then saving with field_attach_update(). It's the closest I've found but it leaves a zombie null field entry in the database which shows up as a blank row on forms until the form is saved and hook_field_is_empty() can kick in (hook_field_is_empty() is configured such that =null or =array() will flag as empty).
Loading the entity with entity_load(), unsetting the field entry by key, then saving with field_attach_update(). This seems to do nothing - it seems that Drupal interprets the entry not being there as a sign to not modify it. (strangely I also sometimes get maximum query time expiration timeouts when trying this approach)
field_attach_delete() - this is much too blunt: it kills all fields for the entity
field_purge_data() - better, but still too blunt: it kills all entries of the field, not specific entries

So to clarify, I've got code that finds (and loads) an entity which has a field that has multiple entries, and finds a specific entry on that field that needs to be removed. I want to remove that entry completely, without touching any other entries or any other fields on the entity.

If you're able to rely on the entity API module you should be able to use code similar to the following:

// Load some entity.
$entity = entity_load_single($entity_type, $id);

// Remove the field value.
unset($entity->field_FIELD_NAME[LANGUAGE_NONE][$index]);

// Reset the array to zero-based sequential keys.
$entity->field_FIELD_NAME[LANGUAGE_NONE] = array_values($entity->field_FIELD_NAME[LANGUAGE_NONE]);

// Save the entity.
entity_save($entity_type, $entity);