Theme CSS libraries always loaded after module libraries My custom theme uses Bootstrap, which I'd obviously like to load before any module CSS libraries, but Drupal ignores any kind of ordering for themes, and Bootstrap CSS styles appear as @import in a <style> tag that always comes last, even if it's set to base.  Modules however, respect SMAACS groupings and will move CSS @imports into different style tags.

How can I get the theme CSS files to load before module CSS files?  Why is bootstrap ALWAYS at the bottom?

I've cleared the cache, disabled devel, tried aggregation on and off. Nothing makes a difference.

This is the code I am using.

/themes/custom/trent/trent.info.yml

core: 8.x
type: theme

name: "Trent"
description: "Test theme"
package: "Trent"

libraries:
  - trent/bootstrap

/themes/custom/trent/trent.libraries.yml

bootstrap:
  css:
    base:
      libraries/bootstrap/bootstrap.min.css: {}

/modules/custom/trent_news/trent_news.info.yml

name: Trent News
type: module
description: Displays news
core: 8.x
package: Trent
libraries:
  - trent_news/trent-news

/modules/custom/trent_news/trent_news.libraries.yml

trent-news:
  version: 1.x
  css:
    theme:
      css/trent_news.css: {}
      css/print.css: {}

I want bootstrap to move up higher but Drupal isn't respecting any setting; it just keeps it in that last <style> tag no matter what.  However, it does respect SMAACS ordering within that style tag, oddly enough. As I mentioned, I can change the module ordering (e.g. theme -> component) and the CSS imports will move into different <style> tags accordingly.

UPDATE:

core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php:165 overrides and ignores any SMACCS setting (or group setting in *.libraries.yml) for theme CSS.  It actually doesn't appear possible to move the import higher up before any module includes:

$options['group'] = $extension_type == 'theme' ? CSS_AGGREGATE_THEME : CSS_AGGREGATE_DEFAULT;

The proper way to modify the loading order is weight property as described here.  The lower the weight the further up your library should go.

Try something like the following in your trent/trent.libraries.yml

bootstrap:
  css:
    base:
      libraries/bootstrap/bootstrap.min.css: {weight: -50}

You might have to adjust the number to get it to desired position.

NOTE: weight is in the process of being replaced by dependencies. Work done can be seen in this issue and when ready this sort of problem will be easier to tackle.


top items rendered as  and remain clickable (give page refresh) I have a TB megamenu (8.x-1.x-dev) with a few top-level (parent) items that are not links, they should just trigger the submenu to drop down.
According to the documentation I could find, links marked as <nolink> or route:nolink will be rendered as <span> rather than <a> so styling can be retained, but they can't clicked, and submenus should still be toggled.
However, both <nolink> and route:nolink are still rendered as <a>, causing a page refresh when clicked.
I have tried adding the nolink definition as a special menu item under (A) admin/structure/menu/manage/main-menu, and in (B) the tb mega menu settings at admin/structure/tb-megamenu/main-menu, but nothing helps:

  When adding `nolink` to the Drupal menu link (A), it leaves the link empty, but you get the page refresh when you click it. Submenu does unfold.
  When adding `nolink` to the TB Megamenu link (B), it leaves the link empty, no page refresh as it now activates a css class that says `.nolink {pointer-events:none;}`, but button goes dead, and submenu does NOT unfold.

When on mobile, all menu items with children do unfold the submenu, don't trigger a page refresh; it's that behaviour I'd love to be able to have in desktop/laptop view too. (Even better if there is a switch "active link yes/no" or similar, so I can decide per button?)
Any help much appreciated :)

How are you getting those to save?
It should be route:<nolink>. Test that it works on a regular menu before trying the additional module to avoid confusion about what might be happening.


Using 2 code repos, one Acquia and one private gitlab server for Drupal code base tracking I run a few drupal 7 sites on acquia and I also have a separate gitlab server for sites that are not on Acquia. Is it possible to push to both repositories on Acquia and Gitlab?

Definitely possible and it's what I do. Acquia provides some documentation  on this. As Kevin mentioned you can do this by setting up two remotes for your local repository clone, one at GitHub/GitLab/Bitbucket, and one at Acquia Cloud.


How do I completely overwrite an array in JSON serialized data field I am storing an array as a JSON encoded serialized data field in Drupal 7 using the Serialized Field module.

If I have an array of 20 elements and try to overwrite it with an array of 10 elements, I would expect to only have 10 elements in the field. But instead I am getting the 10 elements (keys 0-9) from my new array AND THEN the higher keyed elements from the old array (10-19).

Is there a way to empty out the old previously stored array values before writing the new array values?

I have tried the following but nothing completely overwrites the field:

$node->field_test[LANGUAGE_NONE][0]['value'] = "";

$node->field_test[LANGUAGE_NONE][0]['value'] = NULL;

$node->field_test[LANGUAGE_NONE][0]['value'] = array();

$node->field_test[LANGUAGE_NONE][0]['value'] = array(NULL);

$node->field_test = array(NULL);

$node->field_test = NULL;

A colleague suggested a solution that worked.

The Field Settings has a group of settings called "Serialization Options" which includes a checkbox option for "Namespace the data". In my initial configuration that box was checked. I unchecked the box and saved the field settings and my problem was solved.

Final solution: Uncheck "Namespace the data" in the Field Settings.


How to trigger module install file ad hoc I am developing an install script for a custom module, but I can't figure out how to trigger the script once it has already been run once. I know that install scripts are by design intended to only be run once, but what do you do when you need to debug an install script?

I'm running Xdebug so I would prefer if I could trigger the script from the browser UI somehow as opposed to Drush, which will not pause for the debugger.

You can do different things depending on your use case.

If you really need to test your install script again you need to uninstall your module rather than just disabling it. You can do that by running drush dis mymodule && drush pm-uninstall mymodule followed by drush en mymodule again. As @Clive mentions if you have the Devel module installed you can also drush dre mymodule (Devel reinstall). Or disable the module at http://example.com/admin/modules and then uninstall the module at  http://example.com/admin/modules/uninstall . You should probably have a hook_uninstall function set up to clean up after your install. For example you may need to drop some tables or delete temporary files. See the link below for hook_uninstall.
If you have an update to already the installed module you should use hook_update_n instead of hook_install. Then you can visit http://example.com/update.php or run drush updb
Link below.
Lastly, you can probably change the database table that records the installation. I don't recall exactly how to do that but I don't think its preferable.

Here are the docs on writing uninstall hooks.
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_uninstall/7

Here are the docs on writing update hooks. Basically the way I do it is make sure that hook_install runs the update functions after it runs itself.
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_update_N/7

eg:

/*
 * Implements hook_install
 */
function mymodule_install() {
// do some things

// then run the updates
    mymodule_update_7000();
    mymodule_update_7001();
}

/*
 * Implements hook_install
 */
function mymodule_update_7000() {
// do some other things
}

/*
 * Implements hook_install
 */
function mymodule_update_7001() {
// do some more things
}


WSOD after migrating to another site? Troubleshooting a site migration I'm in the process of migrating from one URL to another, and I've got a WSOD. What I had done is to import the new database from the production server.

I've copied all the files from another server using SCP;
I've then SCPed the database from the other server;
I have imported the database from command line;
I have changed the settings.php to the correct information.

I have the feeling it's something simple that I haven't ruled out.

Do you have any idea?

Remember to check the PHP version. It's running on PHP 4.


How do I install dependencies for commerce using the Composer manager module I installed the composer manager module and enabled it. I have tried initializing it from using drush in the command line and failed using the command drush composer-manager-init.

I am confused on how to add the libraries intl, address, pricing and tax to my site.

Please refer to our installation instructions for Commerce 2.x here:

http://docs.drupalcommerce.org/v2/getting-started.html

Note that we recommend the Drupal console project, not drush. However, the linked Composer Manager instructions in there may help you do it via drush.


What are cloned sites in Drupal 8? When trying to export my site configurations from one Drupal 8 site to other I keep getting the following error

  The staged configuration cannot be imported, because it originates
  from a different site than this site. You can only synchronize
  configuration between cloned instances of this site.

So in this context what are cloned sites? How can I override this error to import the configurations?

Cloned site means that you copied the database instead of installing twice from scratch.

Drupal identifies two different sites as cloned sites by checking their uuid. If the uuids match, then it will assume that the sites are cloned instances.

Faulty configuration imports can lead to broken sites which we may not be able to restore. Hence to avoid this situation as discussed on https://www.drupal.org/node/2133325 a safety mechanism was introduced. And that mechanism was having a uuid for each Drupal site.

So if you know what you are doing and you are sure that you need to import the configurations, you can use the drush cget system.site command on source site and you can use drush cedit system.site on target website to change the uuid to that from the source.


views header (contextual) filter I have a node type news with a taxonomy reference (news categories). And I have a view for the news. In this view I have a contextual filter by this categories. The category comes with the url.

In this view I need a rendered entity (node type "views header") within the view header. These node type also uses the taxonomy "news category". At this point all works fine.

BUT: for every news category I need another entity within the view header.

This approaches I have:

Adding all nodes of type "views header" in the view header and filter them in the same context as the view itself. I tried if it is filtered per default with the view context filter but is does not.

The BUT here: I don't know how. How I can filter the nodes in view header. Is there a module for it which I didn't find?

Publishing the view header nodes as blocks. Adding the blocks in views template and configure the block visibility settings pages/only the listed pages. This solution works but I think there's too much overhead.

Does anyone know a more elegant solution?

I can see a couple of ways ahead.

Instead of creating a content type (a Node) just for the header, why not use the taxonomy term (an Entity) itself? Terms are fieldable, so you can add your additional content there, including image, other terms, &c. Then you can grab the term fields using the *replacement patterns from the "first row". You may need to create a Relationship to the term.
If you really want another Node I think you could use the Views Field View module. This way you can create a second View on your "Views Header" type, returning only one result, and pass the term ID from the first View's header to your second View.

Note: Using Views Field View in this manner follows a pattern known as a representative view. IE: A View on a node that is representative of all other nodes using this term. Views 3 does actually support representative views natively though it has some limitations and is generally more difficult to use. I talk about it more over here.


How do I check the value of a field if its empty? Is there a way to check, in a preprocess function, if the value of a field is empty?

I'm getting the following error.

  Call to a member function isEmpty()

function iom_preprocess_block__twitterfeed(&$variables) {
  // Get the twitter_username field from node.
  $twitterUsername = \Drupal::routeMatch()
    ->getParameter('node')
    ->get('field_twitter_username')
    ->value;

  if ($twitterUsername->isEmpty()) {
    dump("Empty");
  }
  else {
    dump("Not Empty");
  }
}

@vinhd proposition is correct, by the way you can also use the isEmpty() method from the field list interface. It can be more adapted for complex field types.
if ( $node->hasField('field_your_field') && !$node->get('field_your_field')->isEmpty() ) {
 //... do something
}


Relating content types to be used in Views filters I have two content types:

Games, which have a list of Developers that worked on it.
Developers, which don't store the games they've worked on.

I need:

a view that lists Developers that you can filter by Game, but "Exposed Filters" only let me filter on fields on the Developer, so I'm not sure how to do this.
to be able to add to a list of people that worked on the Game when editing/creating, rather than have to update each Developer's list of Games they worked on.

How can I make an exposed filter which selects Developers where the Game has that Developer?

Nikit's response about using Relationships in the view is correct, but it's not clear you've have already set up the correct 'node references' between Games and Developers.

So, rather than maintain your own lists of Developers for a Game, you need to use the References module to add a field that allows 'connections' between these content types. You might also want the Corresponding node references module to auto-update the reference field on a Developer when you edit a Game, and vice versa.

From here you can properly relate Games and Developers, so Views can use these relationships and allow you access the associated Games from your Developers view.


Extending Panels default layouts I'm making my first steps into Panels (yeah, shame on me I waited so long)... I immediately ran into a problem with the column-resize widget which did not want to obey. So I thought maybe there i a programmatic workaround for my need.

What I need is a 5-row layout:

1: 1 column
2: 3 equal columns
3: 1 column
4: 2 columns (2:1 ratio)
5: 1 column

How do I add a custom layout (with own icon, name and php template) so that Panels recognizes it?


What is wrong with my custom Entity form validation? I add

public function validateForm(array &$form, FormStateInterface $form_state) {
}

to MymoduleMyentityForm.php which starts with

namespace Drupal\association\Form;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;

Then I run the form and when I submit it, I get this error: Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "Entity validation was skipped." at /Applications/MAMP/htdocs/JdP8/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php line 770

Any idea why?
What am I doing wrong?

Documentation of ContentEntityForm::validateForm:

  Button-level validation handlers are highly discouraged for entity
  forms, as they will prevent entity validation from running. If the
  entity is going to be saved during the form submission, this method
  should be manually invoked from the button-level validation handler,
  otherwise an exception will be thrown.

Even if you don't use button-level validation this should be the cause for the exception. Did you call the parent method?

parent::validateForm($form, $form_state);

If you don't run the entity field validation in some way the exception is thrown.


Why can I only log in with firefox? I have an install of D7.9 that I can only access the admin tools with firefox. If I use IE, Chrome or Safari, I get "You Are Not Authorized to Access this Page" when I go to www.example.com/user and login.

Funny enough, if I try IE in compatibility mode it works fine, AND, if I try a different computer it works fine.

I've tried clearing all browser data, cookies, etc and it still won't jive..

Any ideas?

Login with Firefox.
While logged in on Firefox, open a separate window to www.example.com/user in Internet Explorer and try to log in.
If it fails, got back to the logged in session on Firefox and navigate to the Drupal Watchdog. See if any error appears.
Locate your PHP error logs, and see if they logged in any errors.
Edit your question and post any errors that you see.
...
Profit!

I feel this is a somewhat ambiguous error that could be being caused by almost anything, and there will be no way that anyone here is going to be able to psychically log in to to your server and figure out what exactly is causing that, without a more descriptive question. Checking what are your current watchdog/PHP errors is probably the best thing that you can do at the moment.


How to prevent duplicate entity reference items from being entered on a field? How would you prevent a user from being allowed to enter duplicate entity reference items on an entity reference field?

Using form alter, you could add an #element_validate function to the field.

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if (isset($form['field_articles'])) {
    if (empty($form['field_articles']['widget']['#element_validate'])) {
      $form['field_articles']['widget']['#element_validate'] = ['mymodule_prevent_duplicate_entity_reference'];
    }
    else {
      $form['field_articles']['widget']['#element_validate'][] = 'mymodule_prevent_duplicate_entity_reference';
    }
  }
}

Then in your custom validation function, if there are duplicate entity reference items, set a form error.

function mymodule_prevent_duplicate_entity_reference(array &$element, FormStateInterface $form_state, array &$complete_form) {

  $input = NestedArray::getValue($form_state->getValues(), $element['#parents']);

  $ids = array_filter(array_column($input, 'target_id'));

  // Check that there aren't duplicate entity_id values.
  if (count($ids) !== count(array_flip($ids))) {
    $form_state->setError($element, 'Field "' . $element['#title'] . '" doesn\'t allow duplicates.');
  }

}

If you would like to create a reusable widget, you could extend one of the entity reference widgets, for example,  EntityReferenceAutocompleteWidget:

namespace Drupal\mymodule\Plugin\Field\FieldWidget;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget;
use Drupal\Component\Utility\NestedArray;

/**
 * Plugin implementation of the 'entity_reference_autocomplete' widget.
 *
 * @FieldWidget(
 *   id = "no_duplicate_entity_reference_autocomplete",
 *   label = @Translation("Autocomplete - Disallow Duplicates"),
 *   description = @Translation("An autocomplete text field that validates against duplicates."),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class NoDuplicateEntityAutocomplete extends EntityReferenceAutocompleteWidget {

  /**
   * {@inheritdoc}
   */
  public static function afterBuild(array $element, FormStateInterface $form_state) {
    parent::afterBuild($element, $form_state);

    $class = get_class();
    $element['#element_validate'][] = [$class, 'validateNoDuplicates'];

    return $element;
  }

  /**
   * Set a form error if there are duplicate entity ids.
   */
  public static function validateNoDuplicates(array &$element, FormStateInterface $form_state, array &$complete_form) {

    $input = NestedArray::getValue($form_state->getValues(), $element['#parents']);

    $ids = array_filter(array_column($input, 'target_id'));

    // Check that there aren't duplicate entity_id values.
    if (count($ids) !== count(array_flip($ids))) {
      $form_state->setError($element, 'Field "' . $element['#title'] . '" doesn\'t allow duplicates.');
    }

  }
}


Is there anyway to show all results in a view initially, but only show 1 result after user sets an exposed filter? I need to be able to show all results of my view initially but then only show 1 result after the user selects their options form the exposed filters.

For the record, this seems like a really odd thing to want to do! How would you narrow it down to a single result if more than one matches the filter?

Anyway,  you should be able to use this hook:
https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7

If you check for the existence of filter values, you can then apply a "LIMIT 1" to the query.


Looking for solution to have specific terms have automatic tooltips whenever entered into content items I would like to have specific text automatically (or manually) insert a tooltip.

For example, let's say I want every instance on the website of:

CMS

And have the tooltip say:

"Content Management System"

For drupal to automatically add this would be nice...but not asking for that much ;)

Can I add some kind of dynamic token?

The html can be static since the CSS is bootstrap CDN:

Drupal is the best CMS in the world.

You could write custom javascript that wraps all strings you want to replace with the

here's a tutorial

// Pretending we have more than one paragraph to look through
jQuery('p').each(function(){
    traverseChildNodes(this);
});

function traverseChildNodes(node) {

    var next;

    if (node.nodeType === 1) {

        // (Element node)

        if (node = node.firstChild) {
            do {
                // Recursively call traverseChildNodes
                // on each child node
                next = node.nextSibling;
                traverseChildNodes(node);
            } while(node = next);
        }

    } else if (node.nodeType === 3) {

        // (Text node)

        if (/CMS/.test(node.data)) {
            // Do something interesting here
            alert('FOUND A MATCH!');
        }

    }

}


Remove link from title of custom content type in Drupal 7 I have created a custom content type that includes a title, body and an image. I am displaying this content type in a views slideshow which is working fine.

The problem is that the 'Title' on each slide is linked to a stand-alone page for that individual node. This is undesirable. Is it possible to remove this link, or at least change where it goes?

When viewing the content type, there is no 'edit' (or delete) link for the Title field on the 'manage fields' tab, and on the 'manage displays' tab, the title field does not appear at all, though it claims no fields are hidden. Why are we prevented from controlling the behavior of this field?

In the view configuration, click "Field: Title" and un-check "Link this field to the original piece of content".

If you can't find it, you can also add some css to that title. For example:

.view-id-case_studies h1 a{
   pointer-events: none;
   cursor: default;
}


taxonomy-term--vocabulary.tpl.php still shows tagged content I'm trying to show on my taxonomy term page only what's in taxonomy-term--myvocabulary.tpl.php, but :

If I enable the taxonomy/term/% view, what's in my template is not displayed
If I enable the term panel page, what's in my template is not displayed
If I disable that view and that panel, what's in my template is displayed, but content tagged with that term is also displayed.

EDIT: My template outputs several lists of content, uses APIs and webservices, I can't really explain here what it's made of, it's 350 lines of code :) Anyway, I'm sure the content of it is not related to solving that problem.

Q: What do I have to do to avoid processing and displaying of that tagged content ?

As I now think I know what you want, here's what I'd do: use Page Manager to override the default display, then add the rendered Entity display for Taxonomy. That should then pull in your custom template,


How to print meta property using custom meta tag module I have implemented the custom meta tag module found here:
http://www.phase2technology.com/blog/creating-custom-meta-tags-with-the-metatag-module/

The following code creates my new meta tag, the problem is that it creates a

<meta name="my_custom_metatag">

tag.

How can I make it print out a

<meta property="my_custom_metatag">

tag instead?

<?php
//
// Implements hook_metatag_info().
//
function my_metatags_metatag_info() {
  $info['groups']['my_metatags'] = array(
    'label' => t('My Custom Metatags'),
  );

  $info['tags']['my_custom_metatag'] = array(
    'label' => t('My Custom Meta Tag'),
    'description' => t('This is a custom meta tag'),
    'class' => 'DrupalTextMetaTag',
    'group' => 'my_metatags',
  );

  return $info;
}

Thanks!

Telling your custom meta tag to use the property theme formatter should do the trick.

$info['tags']['my_custom_metatag'] = array(
  'label' => t('My Custom Meta Tag'),
  'description' => t('This is a custom meta tag'),
  'class' => 'DrupalTextMetaTag',
  'group' => 'my_metatags',
  'element' => array(
    '#theme' => 'metatag_property',
  ),
);


Quickest way to get a landing page What is the quickest way to create a landing page for Drupal 7? The landing page module is currently not available for drupal 7. What sort of modules should I use?

For the content: Use an approriate content type or view.
For the URL use an URL alias to get something like www.mysite.com/landingpage .
If you want to hide some blocks on the landing page add a PHP snippet in the block configuration which queries arg() or $_GET['q'] for the URL.
If you need an other theme have a look at the ThemeKey module.
Use the Nodewords: D6 Meta Tags module to add meta tags for SEO or Facebook open graph tags.
Use the statistics or Google Analytics module to track the succses of your page.


How can I disable all the JavaScript scripts? I am trying to disable all the JavaScript on all the pages of a Drupal 8 site for anonymous users if there is a particular header in the request object.
I tried out this code.
/**
 * Implements hook_js_alter().
 */
function MODULE_js_alter(&$javascript, AttachedAssetsInterface $assets) {
  if (MODULE_get_headers()) {
    unset($javascript);
  }
}

/**
 * Implements hook_page_attachments_alter().
 */
function MODULE_page_attachments_alter(&$attachments) {
  // This is for disabling all 3rd party libraries.
  if (MODULE_get_headers()) {
    $attachments['#attached']['library'] = [];
  }
}

It does seem to work to a certain extent. It disables most of JavaScript, but I am seeing the styles are also off (which might be expected) as the CSS libraries might also be removed.
Is there a better way to do this? Maybe Drupal has an option to turn off all the JavaScript.

You don't necessarily need to turn off aggregation if you want to remove all javascript. You could for example remove the placeholder in the html template, then the (already aggregated) javascript won't be replaced in the html page:
function mymodule_preprocess_html(&$variables) {
  if (MODULE_get_headers()) {
    unset($variables['#attached']['html_response_attachment_placeholders']['scripts']);
    unset($variables['#attached']['html_response_attachment_placeholders']['scripts_bottom']);
  }
  $variables['#cache']['contexts'][] = 'headers:my-header';
}

You need a cache context for the request header. This doesn't work for the Internal Page Cache, though. So you need to uninstall this module or extend it to add the request header to the cache key.


How to change items under edit tab on user account page? I know how to remove the user tab completely from the user menu with hooks.

I want to know where I can find the template file that render the items under this tab (or where I can edit what to show under this tab) as I want to hide some parts for all users).

I have tried Home » Administration » Configuration » People » Account settings.
But it only changes items on the user account page NOT the edit tab.

If you'd like to hide fields or properties from the user account edit form, you can create a custom module implementing either hook_form_alter() or hook_form_FORM_ID_alter(). The ID of the form in question is 'user_profile_form'.


How can I trace the source of a redirect error listed in Administration -> Reports? Under Reports -> Recent log messages, I have a large number of errors such as the following:

Type: access denied
Date: November 7, 2013
User: Anonymous
Location: https://mysite.com/ja/user/en/user/register
Referrer: http://mysite.com/ja/user/en/user/register
Message: user/en/user/register
Severity: warning

I have a multilingual site (English en and Japanese ja), so I assume that somewhere there is a bad link or a module is outputting a bad link to the registration page.  How can I find out where?  The only clue I have is this entry in the recent error log.

When I visit the link (http://mysite.com/ja/user/en/user/register), I get a "The page isn't redirecting properly.  Firefox has detected that the server is redirecting the request for this address in a way that will never complete."

If you know the name of the failing redirect URI (such as user/register), the best is to scan through your database and look for redirect entries, e.g. using drush:

drush sql-dump --ordered-dump | grep "user/register"

Alternatively add dd() (from Devel) into drupal_goto() and log the backtrace of each call into the file, e.g.

dd(debug_backtrace(FALSE, 5));

and check drupal_debug.txt in your tmp folder.

Another trick include using DTrace and hook into static probes (if your PHP supports that: php -i | grep dtrace), for example (after running the script):

sudo dtrace -qn 'php*:::function-entry { printf("%Y: PHP function-entry:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }'

then you may grep it and look for specific functions such as drupal_goto, so you may append to above:

| grep -B5 drupal_goto > trace.txt

so this will log into file all calls to drupal_goto with 5 function calls before.

See also: How to generate the function stack trace of the last request made?


Error when get rest resource : The controller result claims to be providing relevant cache metadata I try to create a REST resource. I used EntityResource as base. I would like to return my fields in html.
Here is a exemple of my code :

public function get($id) {
    if (!$this->currentUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }

    $entity = \Drupal::entityTypeManager()->getStorage('node')->load($id);
    $entity_access = $entity->access('view', NULL, TRUE);
    if (!$entity_access->isAllowed()) {
      throw new AccessDeniedHttpException($entity_access->getReason() ? : $this->generateFallbackAccessDeniedMessage($entity, 'view'));
    }

    $result = array();
    $other_entity_dependency = array();
    if ($entity instanceof FieldableEntityInterface) {
      $fields = array();
      $contentType = $entity->bundle();
      if (isset($contentType) && !empty($contentType)) {
        foreach (\Drupal::entityManager()->getFieldDefinitions('node', $contentType) as $field_name => $field_definition) {
          if (!empty($field_definition->getTargetBundle())) {
            $fields[] = $field_name;
          }
        }
      }
      foreach ($fields as $field_name) {
        $field = $entity->$field_name;
        $field_access = $field->access('view', NULL, TRUE);
        if ($field_access->isAllowed()) {
           $value = \Drupal::service('renderer')->render($field->view())
           $result[$field_name]['value'] = $value;
            $result[$field_name]['label'] = $field->getFieldDefinition()->getLabel();

        }
      }
    }

    $response = new ResourceResponse($result, Response::HTTP_OK);
    $response->addCacheableDependency($entity);
    $response->addCacheableDependency($entity_access);

      return $response;
  }

The problem is that when I use a render function, I have this error :

  The controller result claims to be providing relevant cache metadata,
  but leaked metadata was detected. Please ensure you are not rendering
  content too early. Returned object class:
  Drupal\rest\ResourceResponse.

I haven't this issue when I use $field->value instead of \Drupal::service('renderer')->render($field->view()), but I would like to have the html render of fields, for file or image too (these types of fields are empty when I use $field->value).

How can I solve this problem ?

The problem is, that render() produces metadata which leaks to the outside of the controller. You can try renderPlain() if you don't care about the metadata or see this question how to provide your own render context to catch the metadata and add it to the response:

How to get cache metadata from nested render array when returning response?


drupalSettings value is undefined I am trying to call a JavaScript function when I click on a button in a form. I have multiple buttons in a for loop and I have attached the library to all those buttons. (Not sure whether this is a correct way or not)
I also need to pass some values to the JavaScript function depending on the button pressed, which I am passing using drupalSettings.
The issue is for the first button the value is passed and I can print it. For the second button, it is not passed. I guess the JavaScript is not called for the second form element.

buildForm Code:

$levels = 2;
$level_labels_array = ['chapter', 'sloka'];
for ($l = 1; $l <= $levels; $l++) {
  $levelName = strtolower($level_labels_array[$l-1]);
  $textOnButton = '';
  for ($k = 1; $k <= $l; $k++) {
    $textOnButton = $textOnButton . '&gt;';
  }
  $label = $levelName . '_next_navigation';

  $wrapper = $levelName . '_wrapper';
  $form[$label] = [
    '#type' => 'html_tag',
    '#tag' => 'input',
    '#attributes' => [
      'type' => 'button',
      'value' => $this->t($textOnButton),
      'class' => 'button',
      'name' => $this->t($label),
    ],
    '#attached' => [
      'library' => [
        'heritage_ui/heritage_ui_library',
      ],
    ],
  ];
  $form[$label]['#attached']['drupalSettings']['nav'] = $label;
  $form[$label]['#attached']['drupalSettings']['navLevel'] = $levelName;
}

JavaScript function:

(function($, Drupal, drupalSettings) {
Drupal.behaviors.navigation_levels = {
  attach: function (context, settings) {
    var navLabel = drupalSettings.nav;
    var navLevel = drupalSettings.navLevel;
    console.log(navLevel);
    // Attach a click listener to the nav button.
    var navBtn = document.getElementsByName(navLabel);
    if (navBtn.length != 0) {
        for (i = 0; i < navBtn.length; i++) {
            navBtn[i].addEventListener('click', function() {
                console.log("entered");
                var navLevelElement = document.getElementsByName(navLevel);
                if(navLevelElement.length != 0) {
                    $(navLevelElement[0]).trigger('change');
                }
                // Do something!
                console.log('Nav button clicked!');
            }, false);
        }
    }
  }
};})(jQuery, Drupal, drupalSettings);

Question edited for better clarification

I am guessing that you need to set your heritage_ui/heritage_ui_library library to have a dependency on core/drupalSettings.

Note that looking at your code, you should also add a dependency upon core/jquery.once, and spend a bit of time learning how to use $.once(). This is because Drupal.behaviors is called often, so your code will be run multiple times unnecessarily (and potentially with problems). You can read more here: https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


Drupal 7 - can't uninstall Features module i just started to mess up with Drupal 7 (and Drupal in general sense) - and i can't uninstall module named Features it gives error

PDOException: SQLSTATE[HY000]: General error: 1 no such table: menu_custom: DELETE FROM {menu_custom} WHERE (menu_name = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => features ) in features_uninstall() (line 29 of /Users/umren/projects/LAMP/sites/all/modules/features/features.install).

p.s. i'm using sqlite if it matters

You are missing the menu_custom table which is defined by the menu module. Most likely the problem is dependencies. If you install the menu module, that should fix it. If the menu module is already installed, the problem is that your database is broken.


Add Meta tags and Title on hook_menu "page callback" How to add Meta and Title tags to the document head on hook_menu "page callback"?
Drupal 7

Assuming Drupal 7...

For the title you can use drupal_set_title().

For the meta tags you can use drupal_add_html_head(). Example from geerlingguy in the comments of those docs:

$element = array(
  '#tag' => 'link', // The #tag is the html tag - <link />
  '#attributes' => array( // Set up an array of attributes inside the tag
    'href' => 'http://fonts.googleapis.com/css?family=Cardo&subset=latin',
    'rel' => 'stylesheet',
    'type' => 'text/css',
  ),
);
drupal_add_html_head($element, 'google_font_cardo');


What is the entity ID for private messages? I want to access some private messages using entity_load() but I don't know what the entity ID is to call them by.  I have the message ID (mid) but that doesn't appear to work.

I'm attempting to load an individual message like this:

      $message_entity = entity_load('privatemsg_message', array($row['mid']));

And this is how Private Message declares hook_entity_property_info().

/**
 * Implements hook_entity_property_info().
 */
function privatemsg_entity_property_info() {
  $info = array();
  // Add meta-data about the basic node properties.
  $properties = &$info['privatemsg_message']['properties'];
  $properties = array(
    'mid' => array(
      'type'  => 'integer',
      'label' => t('Private message ID'),
      'description' => t('Private message ID'),
    ),
    'thread_id' => array(
      'type'  => 'integer',
      'label' => t('Private message thread ID'),
      'description' => t('Private message thread ID'),
      'getter callback' => 'entity_property_verbatim_get',
    ),
    'author' => array(
      'type'  => 'user',
      'label' => t('Private message author'),
      'description' => t('Private message author'),
      'setter callback' => 'entity_property_verbatim_set',
    ),
    'subject' => array(
      'type'  => 'text',
      'label' => t('Private message subject'),
      'description' => t('Private message subject'),
      'setter callback' => 'entity_property_verbatim_set',
    ),
    'body' => array(
      'type'  => 'text',
      'label' => t('Private message body'),
      'description' => t('Private message body'),
      'setter callback' => 'entity_property_verbatim_set',
    ),
    'timestamp' => array(
      'type' => 'date',
      'label' => t('Private message sent date'),
      'description' => t('Private message sent date'),
    ),
  );
  return $info;
}

How do I get the entity ID for private messages?  Is that different than the message ID (mid) or thread ID (thread_id)?

It turns out mid is correct, but for whatever reason $row['mid'] was returning a string, not an int.  Type-casting the string as an int solved the problem.


What's the difference between global.css and default.css files in Omega theme? I´m still testing the Omega theme, and trying to get its templates and css files to work out for me. I´ve already read at the documentation and issues´ replies at Drupal forums.

They say:

  Think of global as the 'mobile first' template and this this is where
  most of your css will go.

Ok, so for mobile I use only global.css and for other resolutions I use all the other templates.

  The default template is for desktop resolutions where the css is
  different for that of mobile. The remaining templates are really just
  for exceptions and other values to address scaling up to wider
  resolutions.

This is what confuses me, because the other css files are narrow, normal and wide. So I think narrow should be for 7" screens, normal for 10" screens and wide for all the other, bigger screens (usually the desktop). So where fits default template?

  Try resizing your browser window to see the changes between layouts.

I´ve tried that, setting just a line of code in every css file, determinig different body background colors for each case.
global.css showed on the mobile screen.
global.css showed on the 7" tablet on portrait mode.
narrow.css showed on the 7" tablet in landscape mode.
normal.css showed on the 10" netbook.
wide.css showed on the 19" desktop screen.

The color that I´ve set at the default.css file didn´t showed. I´ve took mozilla firefox and resized the browser manually, and all the other templates showed just fine, but default settings never appeared.

I´ve asked this at Drupal community forums, but I would like to know what you think about this. Thanks!

Ok, this is really one of the confusing aspects of Omega.  Once you grasp it, though, it does make life easier.

The full explanation is found in the Omega Theme Documentation Handbook under How CSS works in Omega - "Ogres are like Onions... They have LAYERS".

global.css applies to all layouts (hence the name).  Since they apply to all layouts, this is the mobile-first sheet.

mytheme-alpha-default.css applies to all of the non-mobile layouts, which is when the grids kick in.

Then the narrow, normal, and wide sheets stack depending on which breakpoint you are on.

So if you are mobile, you just get global.css

Narrow, you get global.css + mytheme-alpha-default.css + mytheme-alpha-narrow.css

Normal, you get global.css + mytheme-alpha-default.css + mytheme-alpha-narrow.css + mytheme-alpha-normal.css

Wide, you get global.css + mytheme-alpha-default.css + mytheme-alpha-narrow.css + mytheme-alpha-normal.css + mytheme-alpha-wide.css

The best way to think about this is (in order):

How does my site need to look on mobile?  Make global.css
How do things change when the grid system kicks in?  Make mytheme-alpha-default.css
How does my site look when I am on a portrait table?  Make mytheme-alpha-narrow.css
How do things change when I am on a normal desktop?  Make mytheme-alpha-normal.css
How do things change when I am on a widescreen monitor?  Make mytheme-alpha-wide.css

In other words, don't think of this as four different layouts; think of it as a base layout that you apply changes to as you get wider.


Amazon like sort box on taxonomy page I have a taxonomy term page that lists certain nodes. I would like to include custom sort options like the one on amazon's search results page, at the top. It is a drop down with sort options, unlike the usual clicking on a table column. I have searched but found no resources on implementing this in drupal. Any ideas on how I can implement this?
Thx

The most easy way to get this taken care of is use the Views module. Set up a view that queries for nodes based on the term as an argument. This will give you what you already have, however, it will also allow you to use exposed filters to get more granular with the results based on the values of the exposed fields.

If you would like to learn more about exposed filteds and views, check out this video, which is not the best video in the world, but highlights using exposed filters in Views, which should hopefully get you on the right track.

As a summary, what your doing is replacing Drupal's built in taxonomy view pages with a view instead and allowing views to handle the querying and filtration of the data respectively.

Happy Programming!


What causes my error "Illegal choice in Sorted by element"? Drupal 7.50 commons

The following error shows dozens per minute when I run drush ws --tail,  but there are no reports of users encountering errors or features that are non-operational. Does anyone know what could be causing this? Reporting for anonymous user.

error     form  Illegal choice  in Sorted by element.

Below is a screenshot of one of the errors, for detail.

Below is a screenshot of part of the page content that might be generating the problem, from admin/reports/dblog.

The error seems to be affecting more than one group or all of our groups. Here is an example URL from another entry:
http://example.com/groups/oregon?sort_by=&sort_order=DESC&page=0,0,1

Here is the Commons Browsing Widget View Sorting Criteria:

I was able to figure out what view was being used on group pages (The Commons Browsing Widget) and see that there were three sorting criteria. One of them is the Radioactivity module.

I checked the general status report (admin/reports/status) to see that there was an issue with RadioActivity module.

I removed this sorting feature for now, but it should work now that I cleared up the issues with the module. I guess no one could have known that this was the cause. I'm keeping this up in case anyone else finds it helpful.


Views - getting Title field from other content types via entity reference I have two content types: speaker and session. Session has an entity reference field to speaker - when you create a session, you add references to one or more speakers.

I need to create a view of speakers and details from the speaker nodes, but also include the titles of the sessions that they're referenced on. I've added a relationship using the type Entity Reference: Referencing entity - A bridge to the Content entity that is referencing Content via field_speaker, and when I go to add new fields, I can see all of the fields from the session content type EXCEPT Title. The only Content: Title that's available is the one from the speaker nodes.

What do I need to do to get the Content: Title that's on the session node?

You should choose the one that says "Content: Title". In the next page you can choose the relationship you want this field's value to come from, i.e. your entity reference field.

e.g.


Destination fields not filled from custom migration process plugin I'm working on a D6 -> D8 migration, and my destination has a custom video upload field (field_video_upload) that contains three pieces of data: video, thumbnail, and poster (field_video_upload_video, field_video_upload_thumbnail, field_video_upload_poster respectively in the db). I'm attempting to migrate that data from my source table (actually a MySQL view) that has the data in a serialized format, and I'm using a custom source plugin to get the data.

  public function prepareRow(Row $row) {
    //TODO: Extract url from video_data field and video_thumb from thumbnail_data.
    $video_data = get_object_vars(unserialize($row->getSourceProperty('video_data')));
    $thumbnail_data = unserialize($row->getSourceProperty('thumbnail_data'));
    // Get the array values. Seems to be the best way to work around having an
    // array key of 0000000.
    $video_data = reset($video_data);
    $video_url = $video_data->url;
    $video_thumb = $thumbnail_data['video_thumb'];

    // Set the source properties.
    $row->setSourceProperty('video_url', $video_url);
    $row->setSourceProperty('video_thumb', $video_thumb);
  }
}

Here is the relevant portion of the migration configuration .yml file:

  field_video_upload:
    plugin: video_upload
    source:
      - video_url
      - video_thumb

and here is the custom process plugin video_upload to get the data:

namespace Drupal\migrate_mrctv\Plugin\migrate\process;

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

/**
 * This plugin gets values for the video upload field.
 *
 * @MigrateProcessPlugin(
 *   id = "video_upload"
 * )
 */
class videoUpload extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $video = array();

    list($video_url, $video_thumb)  = $value;

    $video['video'] = $video_url;
    // Use the same source thumb value for poster and thumb.
    $video['thumbnail'] = $video_thumb;
    $video['poster'] = $video_thumb;

    return $video;
  }
}

The source plugin works fine, and the data from the plugin is available in $value in videoUpload::transform(). However, none of the data is getting into this field in the node itself. The main node data is there, but no data for this field.

What do I need to change to get the data to import into my custom field?

Thanks.

UPDATE: In stepping through the Migrate code, I came across this line in Row->setDestinationProperty:

NestedArray::setValue($this->destination, explode(static::PROPERTY_SEPARATOR, $property), $value, TRUE);

and since PROPERTY_SEPARATOR = '/', I tried this in my configuration:

'field_video_upload/video': video_url
'field_video_upload/thumbnail': video_thumb
'field_video_upload/poster': video_thumb

but no difference.

UPDATE 2: Based on the answer from @heddn below, I'm using the iterator plugin as part of a pipeline, since this is a multivalue field, even though it's set to only allow one value.

  field_video_upload:
    -
      plugin: video_upload
      source:
        - video_url
        - video_thumb
    -
      plugin: iterator
      process:
        video: video
        thumbnail: thumbnail
        poster: thumbnail

and modifying my plugin:

  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $video = array();

    list($video_url, $video_thumb)  = $value;

    $video[] = array(
      'video' => $video_url,
    // Use the same source thumb value for poster and thumb.
      'thumbnail' => $video_thumb,
       'poster' => $video_thumb
    );

    return $video;
  }
}

This appears to work in that I the array from the video_upload plugin is passed as $value to the iterator plugin, but I'm still not getting values in field_video_upload.  What else am I missing?

That last part where you are doing the mapping like:

'field_video_upload/video': video_url
'field_video_upload/thumbnail': video_thumb
'field_video_upload/poster': video_thumb

is probably the closest. Is the destination field a multi-valued field? Then you'll need to follow the pattern as espoused in https://www.mtech-llc.com/blog/charlotte-leon/migration-csv-data-paragraphs

You need to create an array of data, then iterator over it and insert each record into the destination.

Namely (this is completely untested, but the idea of it should work if the destination is multi-valued):

   combination:
    plugin: get
    source:
      - video_url
      - video_thumb
  field_video_upload:
    plugin: iterator
    source: @combination
    process:
      video: video_url
      thumbnail: video_thumb
      poster: video_thumb


Commerce Quantity Volume Discount Rules I'm trying to make a drupal commerce pricing rule so that if the customer has 14 items in their cart they'll get 10% off their order. Here's what I tried:

{ "rules_overall_discount" : {
    "LABEL" : "Volume Discount",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "php",
      "inline_conditions",
      "commerce_line_item",
      "commerce_product_reference"
    ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "commerce_order_has_specific_quantity_products" : {
          "commerce_order" : [ "site:current-cart-order" ],
          "products" : "\u003C? $commerce_line_item ?\u003E",
          "operator" : "\u003C",
          "quantity" : "14"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_multiply" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : ".9",
          "component_name" : "base_price",
          "round_mode" : "1"
        }
      }
    ]
  }
}

I think the:

"products" : "\u003C? $commerce_line_item ?\u003E",

might be the problem. It's asking for SKU's but I simply want it to apply to everything.

Figured it out. Here's the rules settings. This will take 10% off your order if the total quantity of your cart is 14+

{ "rules_overall_discount" : {
    "LABEL" : "Volume Discount",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "commerce_line_item", "commerce_product_reference" ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "commerce_order_compare_total_product_quantity" : {
          "commerce_order" : [ "site:current-cart-order" ],
          "operator" : "\u003E=",
          "value" : "14"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_multiply" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : ".9",
          "component_name" : "base_price",
          "round_mode" : "1"
        }
      }
    ]
  }
}


Drupal bootstrap running from command line I am using Drupal 7 functions externally, and I followed this tutorial for using Drupal functions externally; it works perfectly.

In test.php file I have loaded/included Drupal bootstrap.

When I run the script from command line (php test.php), it gives me the following error:

  PDOException: SQLSTATE[42000] [1049] Unknown database 'default_drupal' in lock_may_be_available() (line 167 of /data/var/www/html/mcsu_sites_test01/includes/lock.inc).

How can I fix this error?

You could also try Drush. Once you've installed it, you can cd into your drupal root then run drush scr test.php. In that file, all Drupal functions will be available.


Json-Import of nodes with taxonomy terms I'm running Drupal 8.3.6 and I try to import a json stream originating from typo3. It is essentially a list of blog posts in this format:

[{
    "id": "1",
    "title": "Title",
    "bodytext": "Bodytext with html Mark-Up",
    "datetime": "1269437640",
    "keywords": "term1, term2, term3, term4,..."
},{
    "id": "2",
    "title": "Title 2",
    "bodytext": "Another Bodytext with html Mark-Up",
    "keywords": "term6, term3, term9, term7,..."
}]

I came up with a small module following these instructions, which works well for the title and bodytext:

protected function createBlog(string $json) {
    $jsonout = json_decode($json, TRUE);

    foreach ($jsonout as $blog) {

      $node = Node::create(array(
        'type' => 'blog',
        'langcode' => 'de',
        'uid' => '1',
        'status' => 1,
        'title' => $blog['title'],
        'body' => ['value' => $blog['bodytext'], 'format' => 'full_html'],
      ));

      $node->save();
    }
  }

However I'm struggling to get the terms created and referenced by the nodes. I tried something like this, but it doesn't work:

protected function createBlog(string $json) {
    $jsonout = json_decode($json, TRUE);

    foreach ($jsonout as $blog) {
      foreach ($blog['keywords'] as $tag) { // Loop through each blog entries keywords and create terms
        $term = Term::create(array(
          'name' => $tag,
          'vid' => 'tags',
        ))->save();
      }

      $node = Node::create(array(
        'type' => 'blog',
        'langcode' => 'de',
        'uid' => '1',
        'status' => 1,
        'title' => $blog['title'],
        'field_tags' => $blog['keywords'], // I would need to have the terms from above in an array to add them here, right?
        'body' => ['value' => $blog['bodytext'], 'format' => 'full_html'],
      ));

      $node->save();
    }
  }

The terms do not get created and if they would, I wouldn't know how to associate them with the nodes. Also if it would work, there would be the problem that on creation of the terms I do not check if a term already exists. This would be necessary because nodes can have the same terms.

Is it possible to achieve this with my approach? If yes, can you tell me how? I also looked in to migrate_plus but I find it quite complicated.

Any help would be appreciated!

Andi

Not knowing how the rest of your dependencies are set up, one thing I notice off the bat is that your keywords source field is a comma-separated single string, but you're treating it as an array of values in your processor. Maybe something like this:

protected function createBlog(string $json)
{
    $jsonout = json_decode($json, TRUE);

    foreach ($jsonout as $blog) {
        $newTags = explode(', ', $blog['keywords']);
        $newTagIDs = [];
        foreach ($newTags as $tag) {
            $newTagIDs[] = Term::create(array(
                'name' => $tag,
                'vid' => 'tags'
            ))->save();
        }

        $node = Node::create(array(
            'type' => 'blog',
            'langcode' => 'de',
            'uid' => '1',
            'status' => 1,
            'title' => $blog['title'],
            'field_tags' => $newTagIDs,
            'body' => ['value' => $blog['bodytext'], 'format' => 'full_html']
        ));

        $node->save();
    }
}

You're right that your approach would create multiple copies of the same term, though. The Entity Lookup plugin from the migrate_plus module might provide some help:

// $this->entityManager is a dependency-injected instance of Drupal\Core\Entity\EntityManagerInterface
$query = $this->entityManager->getStorage('taxonomy_term')
    ->getQuery()
    ->condition('name', $termNameToLookup)
    ->condition('vid', $vocabularyToLookup);
$results = $query->execute();
if (empty($results)) {
    // term doesn't exist in that vocabulary; should add it
} else {
    // the term already exists in that vocabulary; do something with it
}


Custom field not saving updates I've created a widget which has two textfields and a hidden uniqid. One of these fields is for the name of an item, the other is the number of people who can be involved in that item. These save without any problem, and they re-populate on the edit page correctly, but if I change the values, they do not update correctly.

I am not a Drupal expert, so I am uncertain how much code will be required for diagnosis. These seem to be the most relevant parts, but there is a volunteers_field_is_empty, volunteers_field_validate, volunteers_schema, and a volunteers_field_formatter_view, as well as empty volunteers_field_insert, volunteers_field_formatter_prepare_view, and volunteers_preprocess_node.

function volunteers_field_info() {
  $t = get_t();
  $fields = array();
  $fields['volunteers_item'] = array(
    'label' => $t('Volunteer item'),
    'description' => $t('A position for volunteers'),
    'default_widget' => 'volunteers_field_widget',
    'default_formatter' => 'volunteer',
    'settings' => array('length' => 255)

  );
  return $fields;
}

function volunteers_field_widget_info() {
  $t = get_t();
  return array(
    'volunteers_field_widget' => array(
      'label' => $t('Volunteers widget'),
      'field types' => array('volunteers_item'),
      'settings' => array(),
      'behaviors' => array(
        'default value' => FIELD_BEHAVIOR_NONE
      )
    )
  );
}

function volunteers_field_schema($field) {
  $schema = array();
  switch($field['type']) {
    case 'volunteers_item':
      $schema['columns'] = array(
        'position_title' => array (
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE
        ),
        'position_count' => array (
          'type' => 'int',
          'sortable' => TRUE,
          'default' => 1,
          'unsigned' => TRUE
        ),
        'unique_id' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE
        )
      );
      break;
  }
  return $schema;
}

function volunteers_field_widget_form_alter(&$element, &$form_state, $context) {
  $type = $context['field']['type'];
  $lang = $context['langcode'];
  $delta = $context['delta'];
  if($type == 'volunteers_item' && isset($context['items'][$delta])) {
    $item = $context['items'][$delta];
    $element['position_title']['#value'] = $item['position_title'];
    $element['position_count']['#value'] = $item['position_count'];
    $element['unique_id']['#value'] = $item['unique_id'];
  }
}

function volunteers_field_widget_form(&$form, &$form_state, $field, $instance,
  $lang, $items, $delta, $element) {

  $t = get_t();
  $type = $instance['widget']['type'];
  switch ($type) {
    case 'volunteer_field_widget':
    case 'volunteers_field_widget':
      $element['position_title'] = array(
        '#type' => 'textfield',
        '#length' => 255,
        '#title' => $t('Position name'),
        '#weight' => 0,
        '#delta' => $delta,
        '#size' => 'big'
      );

      $element['position_count'] = array(
        '#type' => 'textfield',
        '#weight' => 1,
        '#length' => 10,
        '#delta' => $delta + 1,
        '#title' => $t('Number of participants'),
      );

      $element['unique_id'] = array(
        '#type' => 'hidden',
      );
      break;
  }

  return $element;
}

function volunteers_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if($field['type'] == 'volunteers_item'){
    foreach($items as &$item) {
      // setting default values.
      $count = $item['position_count'];
      if(!$count) $count = 1;
      $item['position_count'] = $count;
      if(!isset($item['unique_id'])) {
        $item['unique_id'] = uniqid(rand(),1);
      }
    }
  }
}

The problem is with volunteers_field_widget_form and volunteers_field_widget_form_alter. volunteers_field_widget_form_alter was preventing updates. If I set the default_value of the relevant elements appropriately in volunteers_field_widget_form, Drupal both allows updates and displays correctly.

$element['position_title'] = array(
  '#type' => 'textfield',
  '#length' => 255,
  '#title' => $t('Position name'),
  '#default_value' => isset($items[$delta]['position_title']) ? $items[$delta]['position_title'] : null,
  '#weight' => 0,
  '#delta' => $delta,
  '#size' => 'big'
);


Custom block from module I am trying to create a custom block using a module.

I have followed the instructions on the Drupal site but my block does not appear in the list of custom blocks, or at the bottom of the Block Layout page.

So I installed the Examples for Developers module. It seemed to install and enable correctly but again, there didn't seem to be any example blocks in the Structure, Blocks Layout screen.

Thinking that there must be something wrong with my installation, I used the demon site to test the example modules: https://simplytest.me/project/examples/8.x-1.x

Again, when I enable the Block Example module I don't see any block modules in the list of custom blocks, or at the bottom of the Block Layout page.

Am I doing something wrong, or is this broken in Drupal 8.0?

In order to add a new block you need to click on the button place block then click again on the place block button base on what block you want to added it.


How to customize home page layout according to the user? I have a site with more than 2000 users. Users can log in to the site, can see the content, make it as his favorite etc. My home page (Dashboard of user) has different blocks created of views.

How can I allow users to customize the position of these blocks?

They can show/hide blocks, change the position (region) of blocks, can select which content need to show from the view results, change the sort criteria.

It would be quite hard to provide an exact answer as I don't know how you can affect the view results in your setup. In terms of the rearranging the content and even to save the settings I would suggest that you create a new 'textarea' user field which will be hidden in the front end and use a jquery plugin like this: https://github.com/troolee/gridstack.js to update the value of the field using AXAX when the onchange event fires. That way when you load the homepage you can request that user field and arrange your blocks in the order they wanted. You could use a similar approach for which content is shown and then read it back on page load and pass it to the view as an argument.


Webform 6x 3.11 - custom code to determine value of webform field I intend to pass a predetermined NodeID into a webform through URL querystring like so:

www.mysite.com/forms/my-form?nid=43

On the webform, one of the field values must be calculated by getting the Node Title based on what the nid is. I want to use a textfield, so that it can be one of the values submitted in the email. Can this be achieved?...because from what I see, the "default value" box only allows for a few tokens and no custom code. Furthermore I don't want to pass in the NodeTitle directly in the querystring for 2 reasons:

It will contain spaces and therefore will not be  URL encoded, and
I want to avoid people tampering with the querysting

Here's hoping some drupal guru can come to my rescue!  thanks in advance!

We had exactly the same issue when we were developing a custom job application online form, and we wanted to pass in the job details into the webform in question. How we solved it:

Created (job application) webform node
Created links to the webform node above in the form of /apply-online?n=17
Created custom node-856.tpl.php (856 happened to be the node of the apply online webform) to

first validate the nid as a valid job
validate that the job is published
validate that the job had not closed
format the additional fields into the webform such as title, position etc etc
stop any URL tampering

Created a custom webform validation hook to ensure that only published nodes of type 'job' were allowed to ever be submitted (to stop any form tampering)

Sample code for the validation hook:

/**
 *  Implementation of hook_form_alter()
 *  This function is used to add an extra validation function to the apply online webform
 */
function site_profile_form_webform_client_form_856_alter(&$form, &$form_state)  {
  $form['#validate'][] = 'site_profile_validate';
}

/*
 *  Implementation of hook_validate()
 *  Doesn't exactly validate the webform as that's done in another validation function
 *  This takes the nid from the job_url field and turns it into a url.
 */
function site_profile_validate($form, &$form_state) {
  global $base_url;

  $nid = $form_state['values']['submitted']['job_url'];
  $node = node_load($nid);
  $job_url = $base_url . url('node/' . $nid);
  $form_state['values']['submitted']['job_url'] = $job_url;

  //need this to stop the form losing the nid argument in the url
  if (empty($form_state['values']['submitted']['cv']['_fid']) || empty($form_state['values']['submitted']['cover_letter']['_fid']) || empty($form_state['values']['submitted']['completed_application_form']['_fid'])) {
    drupal_goto('apply-online', array('n' => $nid));
  }
}

Sample code for the node-856.tpl.php:

  // job's apply online node ID = 856, this template was made to theme this
  // particular page

  $job_nid = $_GET['n'];
  if (!is_numeric($job_nid)) {
   drupal_access_denied();
   exit;
  }
  $job_node = node_load($job_nid);
  if ($job_node->type != 'job') {
    drupal_access_denied();
    exit;
  }
<div id="node-<?php print $node->nid; ?>" class="node<?php if (!$status) { print ' node-unpublished'; } ?>">

<?php print t('Job Title'); ?>

<?php print $job_node->title; ?>

<?php print t('Vacancy Number'); ?>

<?php print $job_node->field_number[0]['value']; ?>

<?php print t('Closing Date'); ?>

<?php print $closing_date; ?>

<?php print t('Job Summary'); ?>

<?php print $job_node->teaser; ?>

Hope this helps


Multiple/Bulk Image Upload Tutorial? Plupload etc I want my users to be able to upload multiple images at once. They need to be able to upload 60 images for one gallery and doing that one at a time is just not feasible. I've been reading other posts here and doing a ton of searches. I'm told that using the Media module and plupload (I have the javascript library and the drupal integration module installed) that I can do it, but I can't figure out how to actually make it work.

Would anyone be willing to explain it below? I've seen at least one video on youtube that shows the person clicking the Select Media button which pops up a little window, and that window has a drag and drop plupload area where they drop their images. I don't see anything like that.

Install Multiupload Filefield Widget and, if you're so inclined, Multiupload Imagefield Widget.

Make sure your PHP upload limit will allow all the files to upload.


Using db_merge if key is ID type serial I would like to know if there is any option for db_merge function to do UPSERT (update or insert) operation in table if key is "id" column of serial type (autoincrementing).

I need to insert new row if "id" is not defined, or update if "id" is specified. For now I have:

db_merge('t_project_proposal_writer')
   ->key(array('id' => $state['storage']['project']['proposal_id']))
   ->fields(array( .... ))->execute();

where $state['storage']['project']['proposal_id'] is null, because is not specified and it should create row with next id value. It is not working, returning:

  Numeric value out of range: 7 ERROR: setval: value 0 is out of bounds for sequence "t_project_proposal_writer_id_seq"

It is working, when new id is manually specified, but then, how to get last inserted id of table? db_last_insert_id is not working in D7, only in D6.

No, there isn't any way to do that now (in 6 or 7). Simply put, that's not how Drupal was designed.

Inspect tables created by Drupal. See any increment here? No. It was design decision not to perform any id assignment in database, but leave it all to code. If you go against that decision, you need to implement your own solutions, using more basic db_select, if, db_update and db_insert. Or prepare your own query using db_query.


Anonymous user having user relationships I have come up with a peculiar problem. IO am using the User Relationships module for my Drupal 7 site. The issue is that i had given privileges to the anonymous user to view user profile. The anonymous user however cannot be a part of the user relationship but that user had clicked on that action and now somehow or other when i log in as an authenticated user and see the view which i have created to show me the users who are following me, i see i am followed(the name of the relationship) by an Anonymous user. How can i remove this. i also checked in the databases but i saw nothing regarding this...no request with user id 0. i also have all the correct permissions.

Any Suggestions

Regards

I ran into a very similar issue... Here's the code I used (modified to reflect the affected $user->uid as 0):

<?php
$anon_uid = 0;
$admin_uid = 1;
// The next line makes it appear as though the relationship was deleted by the original
// user in the relationship. You might want to change the value though since Anonymous
// should normally be denied access to do this. For example, to make it appear as
// though each of Anonymous's relationship was deleted by user 1, change $anon_uid
// to $admin_uid (next line ONLY)
$anon_deletedby = user_load(array('uid' => $anon_uid));
$anon_friends = user_relationships_load(array("user" => $anon_uid));
foreach ($anon_friends as $friend) {
  user_relationships_delete_relationship($friend, $anon_deletedby);
}
?>

PLEASE BE SURE TO BACK UP YOUR DATABASE AND TEST THIS IN A NON-PRODUCTION ENVIRONMENT FIRST.


How to create audit trails/order revisions? I've been working with Drupal Commerce for a few months now. As a non-profit, our organization hosts an e-commerce/e-learning site. We're a smaller organization with approx 20 staff users and <20,000 regular customers.

How do others handle creating audit trails/order revisions within Drupal Commerce? There are quite a few modules out there, but I have yet to find the right combination. Currently, we've added Line Item Revisions module and use the Order revisioning built into Drupal Commerce.

Here are some concerns I'm attempting to address:

How did the order end up in the current state (who and why)?
What was recently changed (line items, status, owner, coupons, etc. who and why also)
How do you identify who deleted records, specifically financial records? Secondly, how to you log what the deleted records originally entailed?

As a non-profit, we're audited annually and when staff can accidentally delete payments/orders/etc for money already collected or products already delivered, we lose any history of how it all happened. I'm hoping I'm not the only one who has this question and some of the more tenured users here can point me in a direction.

I'm assuming you're using Drupal 7 here but one of the most effective ways to do is to handle it the same way that Commerce Kickstart does: with the Message stack.

There is a Commerce Message module exposes some of the common events, you'll just need to create a view and tie it into your order page or figure out some other way of handling things.


How to pass a db_query as an array instead of a string? I am having a bit of trouble converting my module db_query argument to pass as an array as oppose to a string. The module is D6 and I am trying to port it D7. Here is the snippet:

$result = db_query("SELECT nfi.field_name, nfi.label
  FROM {field_config_instance()} nfi
    INNER JOIN {field_config()} nf ON nfi.field_name = nf.field_name
  WHERE nfi.type_name = '%s' AND nf.active = 1 AND nf.locked = 0", $type_name);

And here the updated version as suggested below, but I am still getting a PDOException error:

$result = db_query("SELECT nfi.field_name, nfi.label
  FROM {field_config_instance()} nfi
    INNER JOIN {field_config()} nf ON nfi.field_name = nf.field_name
  WHERE nfi.type_name = ':type_name'  AND nf.active = 1 AND nf.locked = 0", array(':type_name'=>$type_name));

The full error is as below, line 49 is the line starting "WHERE" or the entire bottom line basically:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '() nfi INNER JOIN field_config() nf ON nfi.field_name = nf.field_name ' at line 2: SELECT nfi.field_name, nfi.label FROM {field_config_instance()} nfi INNER JOIN {field_config()} nf ON nfi.field_name = nf.field_name WHERE nfi.type_name = ':type_name' AND nf.active = 1 AND nf.locked = 0; Array ( [:type_name] => page ) in cck_private_fields_get_content_private_fields() (line 49 of C:|... common.inc).

Any suggestions welcome. When I manage to finish this module I'll be submitting it to Drupal.org so everyone can use it.

There are three errors in that query:

The database tables are not field_config_instance(), and field_config(), but field_config_instance, and field_config. Parentheses have a particular meaning in SQL, and putting them after a table name causes an error message.
The field_config_instance table doesn't contain any "label" field. See the schema definition given in field_schema().

$schema['field_config_instance'] = array(
  'fields' => array(
    'id' => array(
      'type' => 'serial',
      'not null' => TRUE,
      'description' => 'The primary identifier for a field instance',
    ),
    'field_id' => array(
      'type' => 'int',
      'not null' => TRUE,
      'description' => 'The identifier of the field attached by this instance',
    ),
    'field_name' => array(
      'type' => 'varchar',
      'length' => 32,
      'not null' => TRUE,
      'default' => '',
    ),
    'entity_type' => array(
      'type' => 'varchar',
      'length' => 32,
      'not null' => TRUE,
      'default' => '',
    ),
    'bundle' => array(
      'type' => 'varchar',
      'length' => 128,
      'not null' => TRUE,
      'default' => '',
    ),
    'data' => array(
      'type' => 'blob',
      'size' => 'big',
      'not null' => TRUE,
      'serialize' => TRUE,
    ),
    'deleted' => array(
      'type' => 'int',
      'size' => 'tiny',
      'not null' => TRUE,
      'default' => 0,
    ),
  ),
  'primary key' => array('id'),
  'indexes' => array(
    // Used by field_delete_instance().
    'field_name_bundle' => array('field_name', 'entity_type', 'bundle'),
    // Used by field_read_instances().
    'deleted' => array('deleted'),
  ),
);

Drupal 7 placeholders aren't wrapped between quotes, when they are for strings.

The following query should not return any error.

SELECT nfi.field_name FROM {field_config_instance} nfi
  INNER JOIN {field_config} nf ON nfi.field_name = nf.field_name
  WHERE nfi.type_name = :type_name  AND nf.active = 1 AND nf.locked = 0


Performances with many fields per content type Drupal creates a new table for every new field in a content type.

How much this affects the performance in fetching data when the fields of an entity are 15 or more?

Is possible to store all fields in a table (with a new entity?) without drawbacks? Is worthwhile?

MySQL limits you to 61 table joins but Drupal doesn't care about this limit. Each field gets loaded individually, so every field will slow down Drupal a little bit but there is no practical limit. The impact depends on how long a round trip to the database takes. If you have Apache & MySQL on the same box and you're using sockets for communication then the impact will be minimal (read slides 60-68 from my presentation for more info). If Apache & MySQL are on different servers then the number of fields will have more of an effect. All of this can be mitigated by using something like the https://www.drupal.org/project/entitycache module.


data export import module how to keep alias drupal I found data_export_import module very useful, however. It does not import/export url aliases and block content. Why I could live without the block content, I really would like to have nice way to import/export url aliases. Which module or which approach would you recommend to handle import/export url aliases? the same for blocks.

Thank You.

The solution i did is created gradle script that import/exports url as following:

         task exportUrl(type:Exec){
            doFirst{println "exporting Urls..."}
                executable "sh"
                args "-c", "mysqldump -u ${user} -p${pass} ${db} url_alias>sites/default/files/data_export_import_${view}/url_${db}_import.sql"
         }

 task importUrl(type:Exec){
     doFirst{println "exporting Urls..."}
         executable "sh"
         args "-c", "mysql -u ${user} -p${pass} -h localhost ${db}<sites/default/files/data_export_import_${view}/url_${db}_import.sql"
  }

it works well because i can also use drush to do the node import/export in the gradle script as well.

            task exportNodes(type:Exec){
                   doFirst{println "exporting Nodes..."}
                       executable "sh"
                       args "-c", "drush dei-ex nodes --content-types=address,article,blog[other content types]"
                }

task importNodes() << {
       def dir = new File("sites/default/files/data_export_import/nodes").list().toList()
       for (fileName in dir ) {
              println "ipmorting file ${fileName}..."
                    exec {
                        executable "sh"
                        args "-c", "drush dei-im nodes --file=${fileName}"
                    }
       }
}

I hope its useful for anyone


IMCE browse server image upload button not displaying on ckeditor toolbar I just installed and enabled IMCE for drupal 7 and assigned the IMCE icon in the full html input format page, but the icon is not appearing in the ckeditor toolbar. I even set the permissions for the IMCE.

Make sure you scroll down that same page and look for file browser settings and make sure its set to IMCE. Mine was on none and after switching that, the file browser upload button showed up in the image dialog popup.


Conditionals based on taxonomy editing node.tpl.php, I want to create a conditional statement based on the node's taxonomy which will not print the submitter info and de-links the title from the node.

How would I get the value of the node's taxonomy when it passes into node.tpl.php?

I've tried $sTaxonomy = $node->taxonomy and doing a strpos($sTaxonomy, 'static') and a in_array('static', $sTaxonomy) which neither returned true (or not false). I've tried attaching 1-3 terms on the content and trying both methods without luck.

In D6, $node->taxonomy is an array of term objects keyed by the term id, eg:

  [145] => stdClass Object
    (
        [tid] => 145
        [vid] => 5
        [name] => nineohfour
        [description] =>
        [weight] => 0
    )

  [147] => stdClass Object
    (
        [tid] => 147
        [vid] => 5
        [name] => anotherterm
        [description] =>
        [weight] => 0
    )

Just put a drupal_set_message('<pre>' . print_r($node->taxonomy,true) . '</pre>'); in your template to take a closer look.  You can then go through that array with a foreach (or in_array)to find if a term is set and then act upon that.  I would do this in a _preprocess_node() hook though and set a variable to act upon in your node template instead of putting all that php logic in it.


How to translate new-added text? I use Contact and Locale modules. I wanted to change text included in e-mail so I went to modules/contact/contact.module and I replaced appropriate lines. Unfortunately, that text is not translate to my national language (of course is understanding). How can I add translation to new-added text?

You should never change code in Drupal core, change back to the original code in contact.module first.

When you have the Locale module enabled and have added your language (Configuration -> Regional and language -> Languages) you can translate strings. You will find the translate interface under Configuration -> Regional and language -> Translate interface.

Search for the English phrase first to find the string you want to translate (use exact spelling, it's case sensitive) and add your translation.


Custom edit Panel/Tab for content type In Drupal 8 I have a custom content type, and I want to add a group of fields to it that are related to tracking. Since these fields don't have to do with the content displayed, I wanted to separate these options in the UI by having them on a different tab or panel.

This is an example of what I have in mind.

What is the best way to accomplish this? Is there some hook to achieve this?

I have done a lot of searching, but I can't find anything relevant.

Field Group is a module that provides this functionality.
https://www.drupal.org/project/field_group


Add bootstrap icons next to fields in node page In my views I can do this easily using the rewrite results and writing this line

  [field_business_phone]

How can I do the same with the node page. It doesn't necessarily have to be a rewrite method but I am looking for an easy method of doing this. The end result I am looking for is something like this.

Use the preprocess function, like:

function YOUR_THEME_preprocess_field(&$variables) {
  $element = $variables['element'];

  if (isset($element['#field_name'])) {
    if($element['#field_name'] == 'field_business_phone') {
      foreach ($variables['items'] as $k => $value) {
        $variables['items'][$k]['#markup'] = '' . $variables['items'][$k]['#markup'];
      }
    }
  }
}

Or overwrite the field templates, in a file named field--field-business-phone.tpl.php, containing something like:

<?php

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field__items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field__item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>> <?php print render($item); ?>

    <?php endforeach; ?>


What are the possible exploits if settings.php is writable? I have recently had to set up Drupal on shared hosting using suPHP. This is a first for me, an install where all the files are writable by the user by default. All the Drupal documentation and the Drupal built in status report will warn you of the folly of having your settings.php writable by the web server process.

Option 1:
I can log into the shell and secure the settings.php by making it read-only to my own account (and the webserver account which is running as me).

Option 2:
I can log into the shell and make all the files and folders read only to my own account (and the webserver account which is running as me) which may have to be changed every time I want to install a module etc. This will be kind of a pain to maintain.

My question is: Is there a significant difference in the security risk between the two options? What are the specific exploits that are possible due to having the settings file writable by the webserver process vs. the other core files?

Option 2 is marginally better, but if you get p0wned, a hack script will chmod the file before it tries to append to it, which pretty much renders permission-based protection useless.

Personally, I would make up shell scripts to take care of the permissions for you.
For deployment, something like

find docroot/ private/ -type d -exec chmod 555 {} \;
find docroot/ private/ -type f -exec chmod 444 {} \;
find sites/default/files/ -type d -exec chmod 755 {} \;
find sites/default/files/ -type f -exec chmod 644 {} \;

Then, when you want to run drush or make updates

find docroot/ private/ -type d -exec chmod 755 {} \;
find docroot/ private/ -type f -exec chmod 644 {} \;

You should also read through Securing file permissions and ownership.  This article includes a different version of shell script for fixing permissions, and uses a slightly more restrictive scheme.


Allow comments only for the author of the node I'm using Drupal 8 for a personal project and I'd like to allow only the node author to post comments.

Can you please help? I'm stuck.

although the Drupal 8 version still is on dev but you can try comment_perm module.

The Comment Permissions module enables control of commenting by user
role and by node type. Additional user permissions for selected node
types are added to the user access system so you can configure
commenting with more control than Drupal core provides.

Update
another solution that I could suggest is using hook_form_alter.
in your custom module
function YOURMODULENAME_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if($form_id == "YOUR_COMMENT_TYPE_ID"){
    $node = \Drupal::request()->attributes->get('node');
    if(!is_null($node) && $node->getOwnerId() != \Drupal::currentUser()->id()) {
      $form['#access'] = false;
    }
  }

}


Simplest way to add a custom icon to a Navbar menu item The Navbar module comes with some pre-set icons for common uses. They're fixed to the menu item names.

If you want different icons, or, to add icons to custom menu items or menu items provided by 3rd party modules, what's the simplest way that makes these new icons appear on pages using both the admin and main themes?

There's an issue in the Navbar queue for 3rd party module maintainers wanting to support Navbar icons out of the box, but it's not intended for site builders.

The ideal answer would:

Work in both main and admin theme contexts without duplication (so, not just adding CSS to theme)
Not cause the icons to fall off if the wording of their menu item labels is changed - in many organisations CSS styling and site structure will be handled by different people and should be independent of each other (this currently happens to Navbar default icons)

You can try to create custom module and implement hook_navbar() - for new items and hook_navbar_alter() - for already created items. In this hooks you can set custom css classes for items and attach you custom css file.

check /navbar/navbar.api.php file.

Looks like links came from navbar_menu_navigation_links(), they already have css class navbar-icon-<item_title>. You create custom css file in you module and add in hook_init(). Example of css styles you can get from navbar/css/navbar.icons.css or even copy it to your file and change if needed or add css for new items.


Node content not available to anonymous users I'm having some trouble with viewing my nodes as an anonymous user. When not logged in as admin, I am still able to access the URL of the node, but the content (other than the title) is blank. I've spent a lot of time looking around the permissions, but I can't seem to resolve this issue. The problem exists when accessing the node directly or through a view.

The below example uses nodes with the Link field type, but I'm also having the same problem with my text and file fieldtypes.

This is what displays in a particular view as anonymous:

The same view, logged in as admin:

Hopefully an easy fix, any recommendations would be great!

Try rebuilding site content permissions. Every now again that has tripped me. In D7 you can find it @ /admin/reports/status/rebuild.


Best practice for node comparison for more than 2000 nodes I have around 250 content types for a total of 2000 nodes. What I have to do is finding a clone of each node and display those related clones below the node page in a block (just their titles).

So I'm finding clones on basis of same term reference field value.

For example, for the node with an ID of 6783, there is a field of type term reference (tags). This tag field contains 15 target IDs.

Now I will search all other 199999 nodes; if any node has exactly the same target IDs found in that particular tag field**, I will make all those titles populated below /node/6783.

I need to check on three stages: On first stage, check for all the nodes with the same target IDs; on
second stage, check for 90% cloning, meaning looking for the nodes that have 90% of the target IDs; on third stage, check for 80% cloning.

If I will search 2000 nodes, it will exceed the query execution time limit.

What would be the best approach so that it will not affect the performance of website too.

I do not know of a query execution time limit, so I will assume you meant php's max execution time.

If the clone search does not need to be instantly updated, a good approach would be to run the query on cron and cache the results, which means running a single query to fetch the data, process it, and save the results for a quicker fetching at a later time. Cron disables the execution time limit and will run indefinitely in the background.

If the site's cron runs once a day, the clone search results will be up to a day old.

Some resources to give some direction:

hook_cron - do your processing in this hook
Cache API - set and get cache data


How to make group visible, but content hidden? Using Organic Groups, I'd like to have three visibility states:

Group and group content is visible to all, including anonymous users.
Authenticated users can see the group, but not the content.

This would be the same thing as if everyone marked all the content as "private", but the group node was marked as "public."

Only members of the group can see the group and the group content.

I tried OG Visibility, but it is no longer maintained and did not work. Or at least I couldn't figure out how to get it to work.

Any suggestions?

This is on Drupal 7.

Steps:

Go to Configuration > Organic groups > OG field settings
Under Bundle, select your group content type
Under Fields, select Group visibility and click Add field
Under Fields again, select Group content visibility and click Add field

Now these settings will add two fields into your group node which are Group visibility(Public or Private) and Group content visibility(Public or Private).

If I understood your comment requirements right, to achieve requirement:

No. 1 - Set group visibility to public and content visibility to public
No. 2 - Set group visibility to public and content visibility to private
No. 3 - Set group visibility to private and content visibility to private


Link menu active on 2 pages I have a menu like this:

The sidebar on the left is the Main Menu with links. The first link is STOCKLIJST, that will link to the page stocklijst/aangeboden. As you can see in the second sidebar (this is a menu in a block that will only be visible when page starts with stocklijst/*) the link is active.

But when I click on the second link in the second sidebar the 'STOCKLIJST' in the first sidebar won't be selected anymore.

Why? : Because this is a link to the first link in the second sidebar ... .

How should I could make sure that the first link is active on multiple pages? Or is the easiest way to for this with JavaScript or PHP?

UPDATE:

I've tried the menu position and added a trigger like this:

But that doesn't do much. Something I do wrong?

I think you can achieve that by one of the  following modules

1)Menu Position

  Often times site builders want certain types of content to appear in a specific position in the navigational menu. The simplest solution, adding all of that content individually to the menu system, has performance and usability issues. (Imagine hundreds of menu items added to one spot in the menu.)

  This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

2) Menu Trail By Path

  Menu Trail By Path sets the active-trail on menu items according to the current url.

  For example if you are at yoursite.com/blog/category1/article1
  Menu Items with these paths will get the active-trail class on them and expand accordingly.

  blog

  blog/category1

  blog/category1/article1


How do I get the list of all group members? I have created one group using the Group module, then I added some members in that group. Now I want to get list of all members in the group from some custom code.

How do I get the list of all group members?

Use the Group module API.

$group->getMemberCount()


Force native taxonomy-term pages to only show  and not all content Natural state ends with an ocean of duplicated content; at least in some cases, this could be an SEO disaster.

How do I force native taxonomy-term pages to show only the H1's and not all content (all nodes) associated with the specific term?

When I searched the UI I couldn't find a way to do so. Maybe it is possible with a module.

Note: I can use views for that, but my aim is to change the naturally-created taxonomy term pages without Views.

You can override the default listing with the built-in view, see here https://drupal.stackexchange.com/a/165052/3218

To only show the title you then need to adapt the view:

go to the view's edit page (admin/structure/views/view/taxonomy_term/edit)
change the format-display from rendered entity, to fields
remove all fields and add the title field as only field


Add tab / local task to a node I've created a module called hotel_reviews.

I've created the route node/{node}/reviews using hotel_reviews.routing.yml.

hotel_reviews.content:
  path: '/node/{node}/reviews'
  defaults:
    _controller: '\Drupal\hotel_reviews\Controller\ReviewsController::content'
    _title: 'Reviews'
  requirements:
    _permission: 'access content'

I then tried to add a local task using hotel_reviews.links.task.yml.

hotel_reviews.content:
  route_name: hotel_reviews.content
  title: 'Reviews'
  base_route: node.view
  weight: 100

I can now access the content defined by my controller at node/1/reviews, however when I go to node/1 I don't see a reviews tab.

What am I doing wrong?

I've been using the following documentation so far:

D7 to D8 upgrade tutorial: Convert hook_menu() and hook_menu_alter() to Drupal 8 APIs
Providing module-defined local tasks
Structure of routes

Your base route is wrong. You need to use the route that node uses for /node/1. That's not node.view. It's entity.node.canonical.


How to print a date field value on a page? In Drupal 7, I have created a node type x,  with a date field D:M:Y. Here is an edited Devel tree array structure message for easy reading:

content >> system_main >> nodes >> 31 >> field_Mydate >> #items >> 0 >> value

Main question: How to print the particular node date field value from above extract? (page.tpl)

You should use Drupal's 'format_date' function.

Example:
format_date(strtotime($entity->field_mydate['und'][0]['value2']) ,'custom','F j, Y');


Filter the list of entities referenced by "Entity reference revisions" field I have a content type "Slider" which uses an Entity reference revisions field named "Slides" to save reference to various paragraphs that are then displayed on the frontend as a hero slider.
Everything works fine but now we have received a request of filtering out the slides by a show/hide boolean flag in the slide paragraph. Adding a boolean field to each such paragraph is straightforward but how do I filter those paragraphs based on it? I'm assuming a Drupal hook that allows a function to filter out the referenced entities by some arbitrary criterion but I've been unable to find it.
I understand that this question relates to a 3rd party module but it is quite possible that a core Drupal hook could be used in this context.
Any help will be greatly appreciated.
Thanks.

I'd recommend doing this by creating a new Field Formatter by extending the default EntityReferenceRevisionsEntityFormatter (or extending whichever formatter you're using to display the paragraphs). If you're not sure how to create a field formatter, review the Create a custom field formatter documentation on d.o.
Specifically, you'll need to override the getEntitiesToView() method, something like this:
protected function getEntitiesToView(EntityReferenceFieldItemListInterface $items, $langcode) {
  $entities = parent::getEntitiesToView($items, $langcode);
  $allowed_entities = [];

  foreach($entities as $entity) {
    // Check if your show/hide checkbox is checked.
    // Note: I can't remember if this check is sufficient by itself.
    if (!$entity->my_show_hide_field->isEmpty()) {
      $allowed_entities[] = $entity;
    }
  }

  return $allowed_entities;
}

Lastly, you'll need to configure your entity reference revisions field to use this new formatter.