Entity reference field in REST I'm trying to create content with REST, everything worked correctly until we need to an entity Reference field,I add it to my content type and in want to pass entity referenced nid to it with

Part of my code :

    formValues.gender = parseInt($('input[name=optradio]:checked').val());
    var postData = {};
    postData.title = [{'value': formValues.name }];
    postData.field_enroll_email = [{'value': formValues.email}];
    postData.field_gender = [{'value': formValues.gender }];
    postData.field_phone_number = [{'value': formValues.phone }];
    postData.field_course_ref = [{'value': formValues.nid }];
    if(formValues.ac != "") {
        postData.field_academic_certificate = [{'value': formValues.ac }];
    }
    if(formValues.ec != "") {
        postData.field_english_certificate = [{'value': formValues.ec }];
    }
    postData.type = 'enroll';
    jQuery.ajax({
        url: "/entity/node",
        method: "POST",

my entity referenced machine name field is field_course_ref and I tried following method (formValues.nid contain nid of Node that I want to referenced it )

    postData.field_course_ref = [{'value': formValues.nid }];

How can I fill entity referece field with REST ?

After some research (How to POST an "entity reference" field to a node ? , REST views entity reference  issue

I found the solution, we should pass nid as target_id, final asnwer is

postData.field_course_ref = [{'target_id': formValues.nid }];

it's work correctly, I answer my question maybe be helpful for another guy later.


Contextual information on custom Access Denied page I'm trying to implement my own access denied page, and I'd like to get some information about the context of the access being denied... for example, if the user is on a specific node type page, I'd like to still display a short snippet of that node before the access denied message, so the user knows he's at least in the right part of my site.

However, I can't use menu_get_object(), as arg(0) simply returns 'access denied' in my page callback. Is there any way of passing in the path information for an access denied page? See my code below:

<?php
/**
 * Implements hook_menu().
 */
function custom_menu() {
  $items['access-denied'] = array(
    'title' => 'Access Denied',
    'page callback' => 'custom_access_denied',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}
?>

And in my page callback:

<?php
/**
 * Access Denied page.
 */
function fn_custom_access_denied() {
  global $user;
  $html = '';

  // Display access denied message and login form for anonymous users.
  if (!$user->uid) {
    $html .= '
' . t('The content you are trying to access is protected. Please log in or create an account to view the page.') . '
';
    $html .= drupal_render(drupal_get_form('user_login'));
    drupal_set_title('Login Required');
  }

  // Display access denied message for logged-in users.
  if ($user->uid) {
    $html .= '
' . t('The content you are trying to access is protected.') . '
';
    drupal_set_title('Private Content');
  }

  return $html;
}
?>

Supposing that the site is using clean URLs, I would rather use the following code:

function fn_custom_access_denied() {
  $path = drupal_get_normal_path(trim($_SERVER['REQUEST_URI'], '/'));

  if (($node = menu_get_object('node', 1, $path)) && ($node->type == 'event')) {
    drupal_set_message(t("%event is a private event.", array('%event' => $node->title));
  }

  return "";
}


How to use simple modal jquery plugin to get a dialog of table? I want to show a popup when I click on a link which is basically done by jquery plugin simple modal.
In my template.php file,

function theme_name_preprocess_page(&$variables) {
    drupal_add_js(drupal_get_path('theme', 'theme_name') .'/js/jquery.simplemodal.1.4.1.min.js');

    drupal_add_js(drupal_get_path('theme', 'theme_name') . '/js/theme_name.js');

}

function theme_name_process_views_view_field(&$vars) {
// $plus_icon is a variable defined inside this function.
 $output = "$plus_icon";
 $output .= "

";
 $vars['view']->result[$key]->field_field_flag[0]['rendered']['#markup'] = $output;
}

And in the theme_name.js file

(function($) {
    Drupal.behaviors.abc = {
('.abc-modal').click(function (e) {
                var key = $(this).attr('id').replace(/^abc-modal-(\d+)$/, "$1");
                $.post(Drupal.settings.basePath + 'queue-log', {nid : key},
                       function(data) {
                           if (data) {
                               $('#abc-modal-content-'+key).html(data.html);
                               $('#abc-modal-content-'+key).modal();
                           }
                       }, "json" );
                return false;
            });

.....
How can I get the simple modal jquery plugin working so that when I click on a link mentioned in $output variable() I get a popup displaying contents.

Here is snippet which can be helpful for you to add open the link in simple modal plugin

// Get the click action on link
$('.abc-modal').click(function() {

// Get href attribute.
  var href = jQuery(this).attr('href');

 /*  Three things here
 1. Append a div to the pop-up body
 2. Keep it hidden.
 3. load the content on the link to the div(#content is the id from where you want to load the content to the pop-up) */

      $('

').hide().appendTo('body').load(href+' #content', function(){
        }).modal({
        overlayClose: true,
        autoResize: true,
        minHeight: 600,
        minWidth:800 ,
        opacity:80,
        overlayCss: {
          backgroundColor:"black"
        }
      });
      return false;
    });


How do I programmatically render a form, other than the default form? In a preprocess function we can use this code to render the default form.

$default_form = \Drupal::config('contact.settings')->get('default_form');
$entity = \Drupal::entityManager()->getStorage('contact_form')->load($default_form);

$message = \Drupal::entityManager()
   ->getStorage('contact_message')
   ->create(array('contact_form' => $entity->id(),
));

$form = \Drupal::service('entity.form_builder')->getForm($message);

How do we render another form? I have tried $my_form = \Drupal::config('contact.settings')->get('my_form_id'); without success.

A contact form?

your_form_id is the form, you don't have to load a setting for that. If you know what contact form you want to display, just replace $default_form with your form_id and it should work.


In Drupal 7 how can I programmatically create a menu link to a view? I am trying to programmatically create a menu link to a view. The view already has a menu item but I basically need a shortcut to it in another menu location in a separate module.

You can do it using hook_menu and views_embed_view in a custom module.

function yourmodule_menu() {
    $items = array();
    $items['duplicate-view-path'] = array(
        'title' => 'View Title',
        'page callback' => 'custom_render_view',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function custom_render_view() {
  $output = views_embed_view($view_name, $display_id = 'default');
  return $output;
}


Workflow module missing content type mapping I don't see a tab or area to add a content type to a work flow. The documentation does not match what I am seeing. The tabs I see at the top are:

Primary tabs
  Edit
  States
  Transitions(active tab)
  Labels
  Permission summary

Where should I look to find the mapping area?

The recent versions of workflow module comes with workflow_field and workflow_node modules. If you want to use workflow_field, a new feature, then you have to create a workflow field in your content type and it can also be used in any entity. But if you to use it the old way then enable workflow_node module and you can assign the content type to the workflow, but it can only be used for nodes.


Preventing redirects from being cached for anonymous users I have a content type that needs to redirect only when it is tagged as "External". All of these "External" items have a field where a URL is supplied for the redirect.

During initial setup of the content type the redirection was being done in the .theme file in preprocess_html but we discovered that after the first time someone was redirected when accessing one of these nodes, it would get cached and the redirection would not longer happen.

I then built a module to do the redirection with and event subscriber and this fixed the problem when logged in as an admin but not for anonymous users.

For the third iteration, I built a module to set up middleware that implements HttpKernelInterface in order to do the redirection there.
This particular content type had a url pattern so I used that to determine when the middleware should run based on the $request->getPathInfo(); and then testing for the node type and the "External" tag being applied to it.
That solved all of the redirection problems, but other started to pop up. For example, the edit form for all of the nodes started displaying on the the title field and nothing else and views using the content type would start displaying as empty as well.

Is there a more effective way of doing this redirection and avoiding the page cache than doing it with middleware or has anyone experienced an issue like this when implementing HttpKernelInterface?

handle function being used in the middleware:

public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {

$newsPrefix = "/news";

$current_uri = $request->getPathInfo();
if(substr($current_uri, 0, strlen($newsPrefix)) === $newsPrefix){
  $path = \Drupal::service('path.alias_manager')->getPathByAlias($current_uri);

  if(preg_match('/node\/(\d+)/', $path, $matches)) {
    $node = \Drupal\node\Entity\Node::load($matches[1]);

    if (isset($node)) {

      $nodeType = $node->getType();
      if($nodeType === 'news'){

        if(isset($node->news_type_of_content) && isset($node->news_type_of_content->target_id)){
          $typeID = $node->news_type_of_content->target_id;

          if(isset($typeID)){
            $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($typeID);
            $name = $term->getName();
          }

          if(isset($name) && $name === "External" && isset($node->news_source_url->value)){

            $response = new RedirectResponse($node->news_source_url->value, 302);
            $response->send();
            exit;
          }
        }
      }
    }
  }
}
return $this->httpKernel->handle($request, $type, $catch);

}

Solution ended up being an event subscriber with a cacheable response:

<?php

namespace Drupal\news_redirect\EventSubscriber;

use Drupal\Core\Routing\TrustedRedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class NewsRedirectSubscriber implements EventSubscriberInterface {

  public function redirectMediaCoverage(GetResponseEvent $event) {

    $node = \Drupal::routeMatch()->getParameter('node');
    if (isset($node) && $node instanceof \Drupal\node\NodeInterface) {

      $nodeType = $node->getType();

      if($nodeType === 'news'){

        $typeID = $node->news_type_of_content->target_id;

        if(isset($typeID)){

          $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($typeID);
          $name = $term->getName();

        }

        if(isset($name) && $name === "Media Coverage" && isset($node->news_source_url->value)){

          $url = $node->news_source_url->value;

          if(isset($url)){

            $response_headers = [
              'Cache-Control' => 'no-cache, no-store, must-revalidate',
            ];

            $response = new TrustedRedirectResponse($url, '302', $response_headers);
            $response->addCacheableDependency($node);
            $event->setResponse($response);
          }

        }

      }

    }

  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['redirectMediaCoverage',30];
    return $events;
  }

}


JQuery Causes Seemingly Endless Loop and page load times of 1 minute + - "Warning: reference to undefined property D.cache[a][d]" The rendering of my pages on my website have slowed down drastically.  When I turn on the error console I get the image below that shows the error:

Warning: reference to undefined property D.cache[a][d]

You can see a screenshot below:

These warnings continue until the browser memory becomes bloated, the browser locks up, or the page simply takes over a minute to load!

I am at a loss for how to debug this issue b/c when I open the file cited in the warning, it is the long minified jquery script.

How can I go about fixing this issue?

This is obviously not a problem in Drupal core. This mean the the issue is in one of three places:

The theme
Custom module (developed by you)
Contrib module from Drupal.org

I can think of two approaches to go about and fix this.

Debugging

Replace the minified JS file(s) with non minified versions and start debugging.

Experiment

Try disabling modules/theme at turn until the problem disappears and try to pin point the part in the module/theme that causes the problem and from there try to find a solution.

Personally I would go for the experiment route, as this is often the fastest way to gain initial results.


How to exclude nodes from views result? I have a view with one field that shows rendered nodes, and a contextual filter (multiple values allowed) that provides the nids that should be used in the view.

Each node (with nid from the context filter) contains a node reference field with multiple values (nids of related products).

My problem is that a number of these related products, are in fact unpublished nodes. So how can I exclude these unpublished nodes from showing up in the views result? Just adding the filter Published = Yes does not work since the field in the view always is published. It is some of the rendered nodes, produced by that field, that in their turn are unpublished.

UPDATE: in a custom module I have now added this snippet:

function mymodule_views_post_execute(&$view) {
  if ($view->name === 'my_view' && $view->current_display === 'related_products') {
    foreach ($view->result as $result) {

      foreach($result->field_field_add_products as $key => $product){
        if($product['rendered']['#node']->status == 0){
          unset($result->field_field_add_products[$key]);
        }
      }
    }
  }
}

...and this does actually exclude the unwanted products. BUT they don't just leave gracefully. They leave a gap in the (repsonsive) grid that I use to show these products. How do I exclude them AND the space they occupy in my views grid?

UPDATE: this is my PHP snippet in the contextual filter:

$node = menu_get_object();
$value = null;
if(empty($node->field_lagg_till_givargrupp['und'][0]['nid'])){
    $node->field_lagg_till_givargrupp['und'][0]['nid'] = NULL;
    return FALSE;
} else {
    $groups = $node->field_lagg_till_givargrupp['und'];
    foreach($groups as $group){
        $group_nid = $group['nid']; // hämta node-id
                $value .= $group_nid.",";
    }
    return rtrim($value, ",");
}

It works well and supplies the nids wanted (the node ids for the nodes with multiple products grouped in node reference fields).

And this is a partial screenshot of the view:

I use the field Innehåll: Titel (Content: Title) to group the result by the title of each product group. The field Innehåll: Koppla givare (Content: related products) produces all the nodes present in the node reference fields. If there are 20 products entered in that multiple value field, I will have 20 rendered nodes as a result, of which some are not publised. See the resulting view below. The gaps are unpublished nodes that I succeeded in excluding with my snippet above.

So how do I rebuild the view result so that there are no gaps?

Ok, so this was in fact very simple... though it took me a great deal of time to find the solution. I removed the snippet in the custom module above and instead I added the code below in template.php. Hope it helps somebody. I found the solution here: http://agaric.com/blogs/altering-views-results

function mytheme_views_pre_render(&$view) {
if ($view->name === 'myview' && $view->current_display === 'mydisplay') {
        foreach($view->result as $index=>$val){
          $product_node = node_load($val->field_data_field_related_product_nid);
          if($product_node->status === '0'){
             unset($view->result[$index]);
          }
        }
    }
}


How do I a use a template file to theme a mulit-step form? I am creating a multi step form, and displaying that through a template file. The first step of the form displays fine, but when I go to the second step, the first step titles are also displaying.

How can I check which form fields are displayed? The form fields for the first step should not appear when the second-step form fields are shown.

The first thing to do is to save the current step to an element in your form:

$form['step'] = array
(
  '#type' => 'value',
  '#value' => $form_state['step'], // or however you are storing the step
);

Then, in the preprocess function form your template, you can turn this into a variable that can be used:

function THEME_preprocess_THEMEKEY(&$vars)
{
  $form = $vars['form'];
  // This sets up the variable
  $vars['step'] = $form['step']['#value'];
}

Now, in your template you will have a $step variable available that you can use for choosing which elements to output:

<?php if ($step == 1): ?>
  // output step 1 fields here
<?php elseif ($step == 2): ?>
  // output step 2 fields here
<?php endif; ?>


Deleting field revisions directly from the database With full recognition that this is not considered a best practice (and is generally considered a worst practice) does anyone know if it is safe to delete field revisions directly from the DB via a DELETE query assuming I can guarantee that only the latest revision is being used/referenced everywhere on the site.

I ask this question because I have a particular field that has grown so large the our update hook is taking too long. I'm looking to cheat and seeing if anyone has had experience with this.

There was a module in 7 that tried to solve this, Field SQL No Revisions. I am not sure how far along a Drupal 8 port is, but this is where you might want to start. However, that module keeps those tables empty, instead of just the 'latest' record.

Previously (7.x), I used to have hook_cron routines that would purge revision tables of any old data not being used to keep size down. We had some DBs that were huge due to that, which made backups and dev syncing take forever and be cumbersome. It really helped. You'll want to be careful and use the respective API over a database query, so the rest of Drupal is informed about what is happening and can take action (or if your site has no dependencies it might not matter, but it is always, always safer).


How to properly call dependency classes (Class not found) I'm creating a custom module that uses PHPMailer, which has been installed in the module's vendor folder via composer.

This is the error I get:

Error: Class 'PHPMailer' not found in Drupal\multisend\Service\MailerService->__construct()

PHPMailer is being used in a service class and a PHPMailer object is being created in the service classes constructor. Here is the code:

<?php

namespace Drupal\multisend\Service;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class MailerService
{
    private $mailer;
    private $config;
    private $attorney_data;

    public function __construct($attorney_data)
    {
        $this->mailer = new PHPMailer(true);
        $this->config = \Drupal::config('multisend.settings');
        $this->attorney_data = $attorney_data;
    }

    ...

I've even tried require() on the PHPMailer class but no luck. If anyone could give any suggestions, I would appreciate it greatly.

Yes this is right the onlything is never try to composer require X in a modules directory even though you can include a composer.json file in the module its self
always make sure you are in the site root. then the paths will be correct.


How to purge cached content every day via cache tag? Drupal 8 page has a day specific element which is valid for current day. I would like to add a cache tag so that it can be purged in varnish/fastly periodically. Is there a way to invalidate cache tag periodically on Drupal8?

Here is few FAQs/As:

Why can't use max-age?

max-age can be used, but it's page level header which can get quite confusing when more than one component try to set it. Cache tag is kind of self-contained to the component.

Why don't run cron?

Trying to avoid explicit cron/job to do this as it's environment specific.

Here is the code that flush cache on first hit of a day:

  public function build() {
    ...
    ...
    ...
    $this->handleCacheTag($build['#cache']['tags']);
  }

  protected function handleCacheTag(&$tags) {
    // Get the current date number.
    $current_date_number = date('z');
    $last_date_number = \Drupal::state()->get('module_name.foo.date_counter', $current_date_number);
    // If last date in settings is different from current day, invalidate
    // tags.
    if ($last_date_number < $current_date_number) {
      $invalid_tags = range($last_date_number, $current_date_number);
      array_walk($invalid_tags, function(&$invalid_tag){
        $invalid_tag = 'foo:date.' . $invalid_tag;
      });
      Cache::invalidateTags($invalid_tags);
    }
    \Drupal::state()->set('module_name.foo.date_counter', $current_date_number);
    $tags[] = 'foo:date.' . $current_date_number;
  }


How to generate custom template for views page I have created a view for content type xyz and added fields like title, body,image,designation, etc.

I want to enclosed every single field of view in html structure, so that I can see all titles in red color, all body fields in blue color, same for other fields.

what's the best approach to do this?

Edit:

Is it possible to render fields in a way like shown :

<?php print render($view['field1']); ?>

<?php print render($view['field2']); ?>

<?php print render($view['field3']); ?>

<?php print render($view['field4']); ?>

in view custom template file??

In your view, click on your field, then click on STYLE SETTINGS

Checkmark Customize Field HTML, select DIV.
Give it a class name, Ex: cool
Uncheck Add default classes, that's just extra markup that you don't need.

Then in your theme's .css file add

If your title field is a link put

.cool a{ color: red; }

If your title field is NOT link (you have link this field to the original piece of content unchecked) put

.cool { color: red; }


How to export a view in Excel format? I am using Drupal 8 and I used the Views data export module which handles XML and JSON as exporting formats.

Is there any way to export data in Excel format?

As an alternative to the module you are using, try the PHPExcel module. Some details about it (from its project page):

The PHPExcel module allows developers to export/import data to/from real Excel files.
The idea behind this module is to have a single module for handling the export or import of Excel files, instead of multiple modules handling specific cases.
The module provides no functionality as-is (the .module file is as good as empty). The phpexcel.inc file must be included to use the export or import functions in your own module.


Backup & Migrate not working because of perrmission settings? what should they be? I'm unable to use the Backup & Migrate module because it's telling me the file permissions are not set correctly. i have tried various settings in the command line using chmod. i've removed rwx from users and group but it's still not working. can someone clue me in exactly how they should be set?

the folders used are files/private/backup_migrate/scheduled and then same for manual too.

neither backup option is working. thanks in advance!

Well last time I had the same problem what I did is connect with fillezilla and right-click to the root folder of my site then change permissions to 777 filezilla will go through all your folders and sites and will change all the permissions automatically, it will take some minutes but then all your folders and files will have 777 permissions, try again to use your back-up and migrate, do not forget to clear chaches, after use backup and migrate change the permissions to your settings.php and your private folder in sites/default/private that forlder is where backpup and migrate saves the backups.

Also make sure the the database user you are using with your drupal has all the privileges.


on a multi-language site 'Entity translation' prefs don't show 'node' option I'm working on a multi-language site and would like to pre-define the language per content type (as e.g. described here in the answer) but can't get the vertical tab "nodes" to show up.

The "taxonomies" tab however does show up – so I guess sometings are actually working correctly.

i do have a couple of content types with the publishing setting "Multilingual support = Enabled" – but still none of them shows up in the Entity translation options section. What I would like to achieve is one a one-content-type-per-language setup – therefore I would like to set the default language accordingly on the Entity translation page . What am i missing? Any pointers would be appreciated.

Screenshot from the Entity translation interface:

I just recently had this problem and after 6 hours of searching for a solution I tried the following, which seems to work for me:

Without having Entity Translation installed first update Internationalization (i18n) to the latest version. Then setup the necessary submodules like "Field translation" that you need from Internationalization.

After this is all done then download and enable Entity Translation, go to Entity Translation settings under /admin/config/regional/entity_translation and enable "Content" under "Translatable Entity Types".

If you haven't configure any of your content types to be translatable with field translation (under publishing options) you won't see anything here.
So after doing this for at least one of my content types this page showed the Content tab to add the correct settings for each content type.


can't override nice menus css I made a custom stylesheet for my nice menu in sites/all/themes/mytheme/css/nice-menu-custom.css

under admin -> config -> themes -> global settings I set the path for my nice menus stylesheet as stated above.
After saving this setting, the default css from nice menus actually disapeared from the nice menu block on my site, which obviously verifies that this set up is fine.

other than that, no matter what I do, no css getting processed.

CSS compression is turned off.
My problem actually started with my nicemenu class selectors not working in my at that time sole stylesheet style.css. So figured I'm going to do overriding by the book before asking the my question. Still to no avail.
Flushed caches over and over

I think you are making it sound more complicated than it actually is. (smile)

As explained here, you may consider simply registering  your custom stylesheet in your theme's .info file:

stylesheets[all][] = nice-menu-custom.css.

Once that is done, you have the benefit that your custom style-sheet will be loaded with all other application's css and js files,  and be optimised by Drupal (when you change your dev settings to prod settings).

You understand that you can then overide any nice menu selector in your stylesheet, as long as your stylesheet loads last it should do the trick. If you want to "delete" an unwanted style, do not hack nice-menu.css, add an empty matching selector selector in your style-sheet.

THen, last but not least you can confirm your custom styles are being loaded by looking through any browser's inspector applet or script viewer, or even view source. Whatever.  In dev mode (no caching, no script compression) you should see the changes without needing to drush cc on your instance.

Hope this helps, good luck


Body field doesn't display in any view mode I inserted some articles in my Drupal 7 site, the body field  doesn't display, the manage display setting is ok, I tried to change the theme.
Even though I still to display it in edit mode.
One thing is that I imported this content type with bundle copy , it's the same Article default content type with some custom fields.

I deleted the body field and I recreate it again. that's slove my problem, while I have not yet had any contents
I didn't find a second solution


How to minify JS and CSS in D7 without using modules One of the most promising D7 module http://drupal.org/project/advagg for minification and aggregation of CSS and JS isn't ready for production sites yet.

In such a situation which is the best option?

I also checked http://drupal.org/project/core_library but it sounds overkill.

What other good options we have inside or outside drupal?

This is actually a module, but the Speedy module minifies core JS, has a stable release, and is regularly updated.


Git-like way of updating Drupal database It's easy to update Drupal on the local / remote server using Git.

However, sometimes when I make modifications in the actual module settings or any other settings on my local server – those are recorded in a database and I can't then update them easily on the remote server.

At the moment I just export the whole Drupal database and then overwrite it on the remote server.

But is there any faster / easier Git-like way of doing that?

Maybe a special module? Or a special git-like service for Drupal databases / MySQL databases?

Thank you!

The Configuration module is also a way to store configuration in files rather then the DB. You can then sync configurations by importing the configurations to a new system and pressing a button in the admin area to sync configuration with the newly updated files. there also exists  a Drush command to invoke the update.

  The configuration management module enables the ability to keep track
  of specific configurations on a Drupal site, provides the ability to
  move these configurations between different environments (local, dev,
  qa, prod), and also move configurations between completely different
  sites (migrate configurations) without the use of modules with all
  configuration being owned by the site.

I prefer this approach over Features currently, as this way Features does not attempt to take ownership of any of my files -- or rather become a dependency in my system. I believe you can later uninstall the Configuration module for example and not loose your set configuration values.


How to use number fields for drupal commerce attributes I am using Drupal 7 with Drupal Commerce (not kickstart).  My products are boxes setup in Series varying by height.

Examples:
Series 500 has 3 boxes
box 1 has dimensions of 120x20x10
box 2 has 120x20x20
box 3 has 120x20x30

Everything else about the boxes are the same, so "height" is my product attribute.  Drupal Commerce attributes by default need to be an options_select field, but I have over 1000 products of varying heights and I really didn't want to have to build and maintain a gigantic array of heights down to a thousandth of a inch (whether in the gui or in code).

My original thoughts were to build a module that has a sql table to store product heights.  Then add two fields to the product, a decimal and an options field and hide the options field.  When the user enters a decimal in the height field on the product page, on save the module will check to see if the value exists and if not insert the value into the sql table.  The options field will be setup to use an allowed values function to query the sql table to build the "heights" array so again on save after the module stores the decimal in the sql table, it will then set the value in the options field keeping the two in sync.

This would allow me to have an options field I don't have to maintain, but seemed a little hacky so wondered if there was anyone else out there that found better way (as I have googled and had no luck).

Thanks!

For the answer, I actually found a possible dup of my questions here:

support integer or float values as an attribute

but it was never answered, which is why I left mine up.  However, the question had a little more research into my problem and was able to give me insight that any field that implements hook_options_list and has an entity "property_type" defined in its hook_field_info then it can be used as an attribute.

From here I created a module that installs a new widget for the "list" modules that allows textfield input and adds the sanitized value of the textfield to the "allowed_values" on POST so that it passes validation.  From the viewmode standpoint it works like a normal list and you can use the select widget on the commerce product attribute settings to use this as an attribute.

I know the security ramifications of this could be dicey, however I am sanitizing the field input and I have only myself actually contributing content so I feel this solution works for me.


Query to save 10 fields Using Drupal 7, I created a node with the 10 fields; these fields are inserted as a table.

What query can I use insert the field values to the multiple tables, since multiple tables are the multiple fields?

Use the API: node_save().

Saving data directly to field tables is not possible, you shouldn't even consider this. There are many ways to import data into nodes, for example the Migrate or Feeds modules, if that's what you're after.


features for same content type but different structure collide in multi site I have a multi site and one content type has different fields in it than the same content type in a different site.

When I make a feature for this content type, they conflict with each other even though I have not enabled one of them in the other multi site.

Is it possible to have different features that don't conflict within a multi site if content type is the same but with different fields?

Diana,

Why not move the features into their specific site directories?
Then they dont 'see' each other in the other sites.

For example:

Feature 1 is located in sites/site1/modules/feature1

Feature 2 is located in sites/site2/modules/feature2

Then they are "unaware" of each other.

Would this work?


Where do I insert code into the header? I recently updated my Drupal 'Newsflash' theme but one of my javascripts stopped working. I contacted the writer of the js script and he suggested that my head section has lost the markup for importing the overlibmws.js file, and that I should put it back.

<script type="text/javascript" src="/files/overlib.js"></script>

Where do I go in Drupal 7 (Im guessing it is a tpl file) to insert this code into the header?

What you are looking for is html.tpl.php which by default is part of the system module. Copy the file to the location of your theme and add your code. The copy should take precedence over the default .tpl file.

Warning: Do not hack the core! I.e. if you add this change directly to the system module file it will be overwritten with the next update. In fact even adding the file to the third party theme is not a very clean solution (for the same reasons).

Consider using drupal_add_js() instead (requires custom code).


What's wrong in this insert sql? I am trying to create an entity programmatically.

My code:

//my entity
use \Drupal\my_module\Entity\my_entity;

$entity = my_entity::create(
      [
          'label' => "token",
          'type' => "bundle",
          'uuid' => $uuid,
          'user_id' => $user->id(),
          'entity_type' => $node->getType(),
          'entity_id' => $node->id(),
          'value' => 10,
          'read' => false,
          'created' => time(),
          'changed' => time()
      ]
  )->save();

However, on save, it gives me this sql error. What am I missing?

  Drupal\Core\Entity\EntityStorageException: SQLSTATE[42000]: Syntax
  error or access violation: 1064 You have an error in your SQL syntax;
  check the manual that corresponds to your MariaDB server version for
  the right syntax to use near 'read, created, changed) VALUES
  ('bundle', '4a6ca0e3-89f0-46da-8889-c42a7f45ec4a'' at line 1: INSERT
  INTO {my_table} (type, uuid, user_id, entity_type,
  entity_id, value, read, created, changed) VALUES
  (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4, :db_insert_placeholder_5,
  :db_insert_placeholder_6, :db_insert_placeholder_7,
  :db_insert_placeholder_8); Array ( [:db_insert_placeholder_0] =>
  bundle [:db_insert_placeholder_1] =>
  4a6ca0e3-89f0-46da-8889-c42a7f45ec4a [:db_insert_placeholder_2] => 2
  [:db_insert_placeholder_3] => article [:db_insert_placeholder_4] => 14
  [:db_insert_placeholder_5] => 10 [:db_insert_placeholder_6] => 0
  [:db_insert_placeholder_7] => 1493818295 [:db_insert_placeholder_8] =>
  1493818295 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save()
  (line 770 of
  core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

https://www.drupal.org/docs/develop/coding-standards/list-of-sql-reserved-words
Maybe "read" should have quotes (``) around it in order for this to work. I am uncertain why this is not done automatically.


How do I restore a site using drush? I have been learning drush and I loving it. i am having a tough time understanding how to backup and restore my site. Often I bork my site and just need to quickly restore it. These are the steps I am following and I am met with the following error:

Destination directory /Users/Nigel/Sites/sitename/ already exists.      [error]

Unable to restore files to /Users/Nigel/Sites/sitename/

cd to my Drupal installation.
Create a Drush archive dump (code and db in one)

drush ard
Grab my backup (e.g. sitename.20130221_055426.tar.gz) and place it
back into the root of my Drupal installation

drush arr sitename.20130221_055426.tar.gz

There is a similar question How do I use Drush correctly to restore a site via the arr command? , however the issue and thus the answer has to do with different db credentials, rather than the steps to restore a site.

I am obviously doing something completely wrong here. Any help would be appreciated.

Try adding --overwrite to your restore command, that will let you overwrite an existing site.


Making Panel-Col-last the first I have a 2-column panel (Regular, not stacked). I've made it responsive and it appears allright in mobile view @media screen and (max-width: 519px) {width: 100%;}.

The only problem is that my site is a Right to left one, and therefore, What you guys call "Panel-col-first" appears last in mobile view and it's seems Illogical... What is the way to change it, specifically for that particular panel?

Btw, CSS games (Float) didn't help one bit, so I'm looking for a another way, may it be customization of other files.

The control over the Panel-col's (Panel columns) can be maid manually via the relevant TPL file (each one of the natural Panels' layouts has it's own TPL).

The TPL files are stored at sites\all\modules\panels\plugins\layouts. Check there for the layout you use for your panel.

At my case, I've edited the layout "twocol". It's TPL is inside it's directory (also named "twocol").

There I've changed:

<?php print $content['left']; ?>

<?php print $content['right']; ?>

To:

<?php print $content['right']; ?>

<?php print $content['left']; ?>

After I did this flip, I still haven't seen the change in responsive mode... This is because a change had to be made in the CSS file also... The CSS change is basically comprised of a float: change, and a media screen and () change. Inspect each Panel-pane to get more info on the float and width and then make these, and any other needed changes, in the CSS file.

This manual editing seems to me to be the only way for RTLization\flipping the layouts. I hope the developers of the module would make a more "friendly" option for RTLization.

Note: Better make a backup of the edited versions of your files and store them outside the sites\all\modules\Panels folder - This could save time in case a Panels update would delete them; Even though this action is relatively short.


Using Entity Print to generate several PDFs of a Webform submission This may be too vague a question as I'm just starting to work through this. Would very much appreciate any pointers/experiences if people have done something similar.
Functionality I'm hoping for:
User completes a webform survey and upon completion they are able to download two PDFs that have differing data/results form specific sections of the webform.
A more concrete example, the webform first asks profile questions about age and job type, conditionally on that the second half of the form pulls in different questions (ie. if you answered being under 50, you get question set A, if over 50 get question set B). Once the user submits the form they could download two separate PDFs, one a summary of their profile, and the second a summary of their answers to the conditional question sets.
I've got webform and entity print running, and can see the 'view/print pdf' function added to webform submissions, and have been able to link to that PDF on the confirmation page. But I'm not sure about the best way to approach creating two separate PDFs. Views seems the best approach, but how would I link it all together? Is there another way? Like I said, apologies, this is probably too vague, just trying to avoid going down dead-end paths.
Thanks very much.

You can use the "Webform Entity Print (PDF) Attachment" module included with the Webform module to create different PDF versions of a submission.
This video includes a little more information about attachment elements.


Content Type: Is it possible to have Term reference on Parent Term instead of Vocabulary? I have many Parent Terms with child terms on a Vocabulary. I wanna use one of the parent terms on a content type as option. Is it possible to have a Term Reference field on a Parent Term instead of a Vocabulary?

Create a view that show the taxonomy terms that you want to have as options for selection (you will have to manipulate depth).

Then you create an Entity reference field on your content type that references a taxonomy term. When you add the field it will ask for Entity Selection mode. You select Views (the alternative is Simple), and then you select the view that you created above.


Add allowed file extensions in Views Send file field Using the Views Send module to send mass email.
On the email creation page I want to set my custom validation extensions for the file field provided by Views Send in combination with MimeMail (r# 267 in views_send.module).

For the file field I am trying to set the only allowed extension to be of type .docx by using the following function:

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "views_form_views_send_page") {
    if ($form_state['step'] == 'views_send_config_form') {

      $form['mail']['views_send_attachments'] = array(
        '#type' => 'file',
        '#title' => t('Attachment'),
        '#upload_validators' => array(
          'file_validate_extensions' => array('docx'),
        ),
     );
  }
}

Unfortuanetely this is not working. What am I doing wrong here?

Turns out the file behavior you're looking for is not defined for file elements, but for managed_files. It's as easy as:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_views_form_send_page_alter(&$form, &$form_state) {
  if ($form_state['step'] == 'views_send_config_form') {
    $form['mail']['views_send_attachments']['#type'] = 'managed_file';
    $form['mail']['views_send_attachments']['#upload_validators']['file_validate_extensions'][] = 'docx';
  }
}

But views_send will have to be patched to support managed_files. This still needs work in the issue queue.

Yet, as I mention in the issue, you can hack it directly in the module. It's not recommended, but we don't have a hook here and the issue above might take a while to be solved. So just change the line

$file = file_save_upload('views_send_attachments', array(), $dir);

to

$file = file_save_upload('views_send_attachments', array('file_validate_extensions' => array('docx')), $dir);


How to get the node id the comment is attached to in hook_comment_insert? How can I get the node id the comment is attached to in hook_comment_insert?

I tried the following code:

function mymodule_comment_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->bundle() == 'comment_custom' && $entity->get('entity_type')->value == 'node') {

    // Below returns empty, because "$entity->get('entity_id')->value" is empty.
    $node = Node::load($entity->get('entity_id')->value);

    // No luck with this one too.
    $node = \Drupal::routeMatch()->getParameter('node');

  }
}

the correct way to load nid is,

$entity->get('entity_id')->target_id

and not

$entity->get('entity_id')->value

In case of doubt which key to use,

try,

$entity->get('entity_id')->getValue()

and inspect the returned value.


Webform - how do I change dateformat in mail Module: Webform

The short date type is dd/mm/yy, so it appears correctly in the form (day/month/year)
But in the mail it is shown with month first. (month/day/year)

How can I change the date type in the mail?

Try go to admin/config/regional/date-time and set your site's Medium date type format.

Also, if the Medium format doesn't include at least a month, day, and year field, Webform will default to the American format of MM/DD/YYYY.

Webform uses the "medium" in e-mails and viewing submissions, though everywhere else (like a displaying the date component) it uses short for the order


Changes in the way Drupal 7 handles JavaScript and jQuery I'm currently developing a JavaScript script that runs on an administration page. I read up on the changes made in Drupal 7, namely the move from document.ready() to its own jQuery function. However, the following script doesn't work.

(function ($) {
  console.log('hello');
  $('#edit-apiusername').append('test');
})(jQuery);

console.log() is firing and I can see the output, but the simple append doesn't work. The field ID is correct.
I am not sure what I'm missing here, but I suspect it has to do with the way I'm referencing the object. Looking at Views 3 JavaScript code, I can see it's done in a similar way.

I think you misunderstood the changes.

JavaScript code should be wrapped in (function ($) { ... })(jQuery); to allow usage of $ as shortcut to jQuery. This is to allow jQuery to play nicely with other libraries. In this function, you still have to wait for the DOM to be loaded if you want to alter it. That's what wrapping your code in jQuery.ready(function(){ ... }) does.

But instead of using jQuery.ready(function(){ ... }), you should use behaviors to let Drupal's JavaScript knows that your code wants to process anything added (or removed) from the DOM.

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function(context, settings) {
      $(context).find('#edit-apiusername').append('test');
    }
  }
})(jQuery);


D7-import View break blocks PDOExeption I accidentally deleted a view in my D7 website. Good for me I had backup from yesterday, so I put that on my local drupal and exported the view.

The View is getting added successfully but when i visit a node where the view should appear it doesn't and the block panel of the website returns this:

Notice: Undefined index: kontakt-block_1 in _block_rehash() (Zeile 420 von /var/www/drupal-7.19/modules/block/block.module).
Notice: Undefined index: kontakt-block_2 in _block_rehash() (Zeile 420 von /var/www/drupal-7.19/modules/block/block.module).
Notice: Undefined index: kontakt-block_4 in _block_rehash() (Zeile 420 von /var/www/drupal-7.19/modules/block/block.module).
Notice: Undefined index: kontakt-block_6 in _block_rehash() (Zeile 420 von /var/www/drupal-7.19/modules/block/block.module).
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'rubel_zf-views-Kontakt-block_1' for key 'tmd': INSERT INTO {block} (module, delta, theme, status, weight, region, pages, cache) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array ( [:db_insert_placeholder_0] => views [:db_insert_placeholder_1] => Kontakt-block_1 [:db_insert_placeholder_2] => rubel_zf [:db_insert_placeholder_3] => 0 [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => -1 [:db_insert_placeholder_6] => [:db_insert_placeholder_7] => -1 ) in drupal_write_record() (Zeile 7194 von /var/www/drupal-7.19/includes/common.inc).

If I delete the View again the blocks panel opens without a error.

any idea how I can fix this? A lot of work was done in the meantime and the bad thing not only by me. Other employees did add content. All that well be gone ;(

First back up the live site in its current state.

On your local site running your backup database enable the database administration module

And use that to export the tables labeled 'views_views' and 'views_display' in format 'mysqldump'

On your live site, import your sql files

Then run:

mysql -u root -p drupaldb < views-views.sql
mysql -u root -p drupaldb < views-display.sql

I used this issue thread for reference.

It's worth noting that because your errors also seem to be coming from blocks (and assuming no one else has worked on them in the meantime) you might also want to do the same as above with your 'block' 'block_current_search' 'block_custom' 'block_node_type' 'block_role' tables.


Is it possible to create a Nodequeue of Nodequeues? I have a number of node queues that serve as collections of nodes. I want the user to be able to take those collections (node queues) and add them to a queue, essentially allowing the user to have a node queue of node queues. Is this possible? If not, are there ay recommendations on how I might implement something like this?

also, I'm using drupal 7

Nodequeue supports Smartqueues.

  Smartqueue API

  Nodequeue provides a robust API that allows other modules to define
  smartqueues, which are associated with external data. For example, the
  included taxonomy smartqueue creates subqueues for a given queue for
  every term in the chosen vocabulary. Nodes are then only eligible for
  subqueues whose term matches the nodes terms. This makes it very easy
  to have queues for each category without cluttering the management
  page.

If the default smartqueue's dont meet your needs you could leverage the API to write your own smartqueue that uses the queue's you've made for your users.

EDIT:

Perhaps see Smartqueue for Content Types.

  This module provides a smartqueues based on avaliable content types.
  It adds a subqueue per node of selected content type to hold an
  ordered queue for nodes of another types. Any of these types can be
  used for smartqueues as well to hold additional levels of nodes
  grouping. So you can build very complex informational structures
  powered by handy Nodequeue's features and integration.


Reverting blocks and other pseudo-exportables in an install hook We have a medium-sized Drupal 7 site whose configuration is almost entirely stored in code, in a single Features module.  In order to permit automated testing and a cleaner development workflow, I'd like to make it possible to install a new instance of the site from scratch without cloning the database.  To that end, I've created a simple install profile (based on the standard profile) which enables our themes and configuration module.  This mostly seems to work, but I've found that some feature components are not immediately reverted on the newly-installed site: specifically, blocks exported with fe_block_settings, user permissions, and variables.  All these are applied if I run drush fra -y from the command line after installing the new site, but I would like to do everything programmatically to make writing tests easier.

There is some discussion of the problem with blocks at https://www.drupal.org/node/1901116, but I've tried the fix given there (calling module_install in the hook_install implementation instead of listing a dependency in the .info file), without successs so far.  That page also doesn't address the issues I'm seeing with variables and user permissions.

Is it possible to successfully apply all of these exported feature components from an install hook, or do I need some other mechanism?

In short: the workaround is to call drupal_flush_all_caches() and drupal_static_reset() before reverting the module containing exported features again from an install task.

In detail: The main symptom observed was that blocks (exported as fe_block_settings components), were not correctly applied on the new site when they depended on a Views block display defined in the same features module.  This remained true even after adding an additional call to features_revert_module() in an installation task.  (There were also problems at one point with variables and permissions, but these were cleared up more easily by the addition of the call to features_revert_module()).

The problem with settings for views blocks is that Views caches all views loaded from the database in a static variable, making any views loaded or enabled for the first time during a single request or drush command invisible to later calls to views_block_info().  One possible (tested) workaround is the following:

views_get_all_views(TRUE);
drupal_flush_all_caches();
features_revert_module('xyz');

Supplying TRUE for the $reset parameter to views_get_all_views() forces the module to discard its static cache and re-compute the list of blocks from scratch.  This allows the revert of block settings to go through correctly.

Because I suspect this will not be the only problem caused by invalid static variable caches, I am trying the more drastic approach of resetting all static variables and clearing all caches before reverting the module:

drupal_static_reset();
drupal_flush_all_caches();
features_revert_module('xyz');

(Resetting all static variables does produce a few extra PHP warnings, which hopefully are spurious.)

The above lines are run as an installation task, and are combined with the approach described in https://www.drupal.org/node/1901116: i.e., remove the module with exported blocks from the dependencies[] list, and enable it manually in hook_install() after enabling themes for the site.  The complete implementation in the profile .install file then looks more like this, where the installation profile is named foo, the features module is named xyz and the site theme quux:

/**
 * Implements hook_install().
 */
function foo_install() {

  // ... other setup code here ...

  // Enable themes
  theme_enable(array('seven', 'quux'));
  variable_set('admin_theme', 'seven');
  variable_set('node_admin_theme', '1');
  variable_set('theme_default', 'quux');

  // Enable module containing features-exported block settings
  module_enable(array('xyz'));
}

/**
 * Implements hook_install_tasks().
 */
function foo_install_tasks(&$install_state) {
  $tasks = array(
    'foo_revert_xyz' => array(
      'display_name' => st('Apply all settings in "xyz" module'),
      'type' => 'normal',
    ),
  );
  return $tasks;
}

function foo_revert_xyz() {
  drupal_flush_all_caches();
  drupal_static_reset();
  features_revert_module('xyz');
}

Tracking this down was a real headache, so I hope the solution is useful to someone else.


Site-wide altering of access behavior in Drupal site I have a website that has 3 different types of users: anonymous, registered, elite registered. I have setup the appropriate permissions but my problem is the following: if a user does not have the appropriate permissions to see a piece of content, the content does not appear anywhere on my listings. For example, it does not appear in the results of the Search API, it does not appear in the entity reference listings or the Views.

I want the nodes to appear in various listings but when you try to access the actual node, to get a message that prompts you to register/upgrade your account.

Is this a way to configure such a behavior site-wide? Or would I have to handle the permissions on a per-item basis (e.g. setup the views or override the entity reference permission handling to show the results regardless of the permissions and redirect the Access Denied page to an "Upgrade your account" page)?

Here's one way to do it:

Set up your permissions to reference a taxonomy.
Add a hook to change the view_mode of a node you don't want a user to see.

Ours looks like this, we are using a taxonomy called 'Access Level' to control what level of access a node should be shown at (field_access_level).  Roles can be given permission against any, all or none of the various taxonomy terms, really useful for segregating products on a Drupal site.

/**
 * Implements hook_perm().
 */
function i_security_access_permission() {
  $permissions = array();
  $terms = taxonomy_get_tree(11);
  // Define permissions using taxonomy Access Level vocabulary
  foreach ($terms as $term) {
    $permissions[$term->name] = array(
      'title' => t($term->name),
      'description' => t('Access content from '. $term->name),
    );
    $permissions['Edit Role Names'] = array(
      'title' => t('Edit Role Names'),
      'description' => t('Allows users to edit role Names'),
    );
  }
  return $permissions;
}

/*
 * Implements hook_entity_view_mode_alter
 *
 * Sets the view mode to full or teaser based on user access rights
 */
function i_security_access_entity_view_mode_alter (&$view_mode, $context) {
  if (array_key_exists("field_access_level",$context['entity'])) {
    $access_tid = $context['entity']->field_access_level['und'][0]['tid'];

    $access =  taxonomy_term_load($access_tid);
    // Checks if user has access to content
    if (!user_access($access->name) && $view_mode != 'search_index') {
      $view_mode = 'teaser';
    }
  }
}

You can improve upon it by adding a test for view_mode in your node template and displaying a login button and/or your exhortation to upgrade when the node is shown in teaser mode.  Same applies for views.

Some things to note:

If you're using a taxonomy and programmatically mapping it to permissions, make sure users can't change the taxonomy terms because all of the permissions get lost
User can however, add new taxonomies and remove unwanted ones with impunity.  Especially since if you remove a term and then add it back in, the permissions you have set for your roles magically reappear (at least they have in my experience).
The && $view_mode != 'search_index' near the end is because I found this was interfering with Apache Solr indexing the site: it was only indexing teasers!  I'm not sure what other view_modes there are, so be careful with this.

I wonder if we have the makings of contrib module here?


Change default option of installation profile I've created a new installation profile name ABCD and it is showing on a "select an installation profile" Page

But it shows standard as a default option. How could i make ABCD as default.

I added hook_form_alter and hook_form_FORM_ID_alter in abcd.profile file but it's not working. As I've read in Drupal.org that bootstrap is fully loaded before reading .profile file but still form alter in not being executed in my case. Any idea ?

In your profile .info file you can add the distribution name property in the following format:

distribution:
  name: ABCD

Notice: ADD this property but leave original top level "name" property in place.

This will totally omit  the  "Choose profile" step, and your profile will be auto selected for the entire process.


How can I add or delete the front page's blocks? I am using Drupal 7, with the Stability theme. I'm trying to add featured products block to my home page but couldn't. I am able to add them to other pages, though.

How can I add or delete the front page's blocks?

1)First of all create a tpl file "page--front.tpl.php".

2)Suppose you want to place block  in sidebar second region use devel module to see the content of your page.

<?php dpm($page);
dpm($page['sidebar_second']);?>

3) Write following code after executing above code:

<?php print render($page['sidebar_second']['id_of_your_block']) ?>

for deleting/hide the front page block

1)Go to edit page at block/region setting/none


Changing numbers of render-blocking JavaScript and CSS I have a drupal 7 site.
I use the Advanced CSS/JS Aggregation module

In the past I asked this question, and tried to improve performance and "Eliminate render-blocking JavaScript and CSS in above-the-fold content" as Google Page speed test suggested.

After I got answers to the question I changed the module configuration, and set the Target Number Of CSS & JS Bundles Per Page to be 4.

For some reason, now, when I am running speedtest, I see that I have "9 blocking script resources and 5 blocking CSS resources" instead of 4 clocking for CSS and 4 blocking for script.

Why is that happening?
How can I fix it, and make the advagg configuration work?

The bundler works per region, so set it to 2 for JS as you have footer JS and header JS; 2 header + 2 footer + 2 external scripts will give you 6 for desktop and 3 for mobile, as Page Speed Insights seems to only count header JS for mobile. Moving all the JS to the footer might help eliminate all render blocking JS with mobile according to Page Speed Insights Mobile; it will also give you a better score for the Page Speed Insights desktop as more JavaScript files can be combined.

You can disable the bundler as that will give you a better score, but you will have to download a new full sized CSS/JS aggregate if any of the CSS/JS changes per page on your site; so you won't be able to fully take advantage of the browser cache and real world performance will not be as optimal as it could be if you do disable the bundler. It's about tradeoffs.

http://www.webpagetest.org/result/140619_5M_134C/ Shows a decent report as well.


Can I create nodes through drush for particular content type I have different content type in my site. For testing purpose, I want to add content to all content type form, but manually its not possible in such short term.

So, is any Drush command available to create node?

Just a note to point out a new module called Faker which can be used in conjunction with Devel Generate :

  Use the PHP Faker library to generate more meaningful sample content.

  Devel Generate is great for creating a lot of sample content in a
  hurry, but sometimes you want samples that are more meaningful, or
  closer to the content you expect users to generate. This is where
  Faker comes in.

  Faker is a PHP library that generates fake data for you

  Faker (the library) can generate real looking names, addresses,
  emails, domains and more. Faker (the module) combines the library with
  quick content creation abilities provided by Devel Generate, to give
  you the power to easily generate real looking sample content.


Autocomplete several fields with values based on the selected value of an user reference field UPDATE: the code is now cleaner and shorter. An autocomplete field triggers the ajax callback which reloads a field. The whole thing works for one field but not so well for multiple fields.

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'form_id_form') {
$form['triggering_field_id'][LANGUAGE_NONE][0]['value'] += array(
    '#autocomplete_path' => 'my_auto_path',
    '#ajax' => array(
        'callback' => 'my_ajax_callback',
            'wrapper' => 'my_ajax_wrapper',
            'method' => 'replace',
            'effect' => 'fade',
        ),
    );

    $form['dependant_field1'] += array(
        '#prefix' => '
',
    );
    $form['dependant_field2'] += array(
        '#suffix' => '
',
    );
  }
}

function my_module_menu() {
    $items = array();

    $items['my_auto_path'] = array(
        'title' => '',
        'page callback' => '_my_auto_path',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function _my_auto_path($string) {
  $string = array(':s' => $string . '%');

  if ($string) {
    $results = db_query("SELECT name FROM {users} WHERE name LIKE :s", $string);

    $items = array();
    foreach ($results as $result) {
        $items[$result->name] = $result->name;
    }
    print drupal_json_encode($items);
  }
}

function my_ajax_callback(&$form, &$form_state) {
    if (user_load_by_name($form_state['values']['triggering_field_id'][LANGUAGE_NONE][0]['value']) != FALSE) {
        $user_obj = user_load_by_name($form_state['values']['triggering_field_id'][LANGUAGE_NONE][0]['value']);
        $user_id = $user_obj->uid;
        //let's get another field from user's object:
        //$user_whatever_userfield = $user_obj->whatever;

        $form['dependant_field1'][LANGUAGE_NONE][0]['value']['#value'] = $user_id;
        //Do the same for the 2nd field but need to return both fields at the same time...
        //$form['dependant_field2'][LANGUAGE_NONE][0]['value']['#value'] = $user_whatever_userfield;
        return $form['dependant_field1'];

        //another way, with ajax commands:
        //but I can only replace the whole <input> instead of just the val() of each field.
        //$commands = array();
        //$commands[] = ajax_command_replace("#dependant_field1_id", $user_id);
        //$commands[] = ajax_command_replace("#dependant_field2_id", $user_whatever_userfield);
        //return array('#type' => 'ajax', '#commands' => $commands);
    }
}

I just found the solution to my problem: Every AJAX command runs and replaces the defined element. The trick is to predefine the values for all fields I need to update, within the callback. Then, these values remain in tact within the array of the newly rendered fields using the AJAX commands. Here is my updated callback:

function my_ajax_callback(&$form, &$form_state) {
    if (user_load_by_name($form_state['values']['triggering_field_id'][LANGUAGE_NONE][0]['value']) != FALSE) {
        $user_obj = user_load_by_name($form_state['values']['triggering_field_id'][LANGUAGE_NONE][0]['value']);
        $user_id = $user_obj->uid;
        // and another user attribute:
        $user_whatever_userfield = $user_obj->whatever;

        $form['dependant_field1'][LANGUAGE_NONE][0]['value']['#value'] = $user_id;
        $form['dependant_field2'][LANGUAGE_NONE][0]['value']['#value'] = $user_whatever_userfield;

        $commands = array();
        $commands[] = ajax_command_replace("#dependant_field1_wrapper", render($form['dependant_field1']));
        $commands[] = ajax_command_replace("#dependant_field2_wrapper", render($form['dependant_field2']));
        return array('#type' => 'ajax', '#commands' => $commands);
    }
}

Also, I changed the position of my wrapper to have a wider range, in order to include all the fields I want to ajax-update. As every AJAX command will be recreating each form element, if the form element lives within a wrapper (added in form_alter), the wrapper will also be rendered and that causes an HTML mess. So having one hidden field above & another hidden field below my fields makes life easy. The new wrapper encloses these hidden fields and leaves all other fields clean when regenerated from the callback.


How do I change taxonomy page callback for a specific vocabulary only? Following Clive's answer to this question, I would like to change taxonomy page callback and redirect users to another page just for a specific vocabulary.

function MYMODULE_taxonomy_page_callback($term) {
  if (/* Check if the vocabulary is the one we need to implement hook to */) {
    drupal_goto('somewhere');
  }
}

How can I achieve this?

Since the callback is getting the taxonomy term object as argument, you can check the value in $term->vocabulary_machine_name to get the machine name of the vocabulary, and see if it is the one you are interested in.

function MYMODULE_taxonomy_page_callback($term) {
  if ($term->vocabulary_machine_name == 'MYVOCABULARY') {
     drupal_goto('somewhere');
  }
  else {
    return taxonomy_term_page($term);
  }
}


Make session time longer on Drupal 7 I got a webform and it seems to timeout after one or two hours, I want to increase the timeout session to like 4-5 hours or more.

How do I make this possible?

In your settings.php change/add this line

ini_set('session.cookie_lifetime', desired time in seconds);

it will increase your timeout length in desired way.


How to change the value of the Submit button text when extending ConfigFormBase I need to change the value of the Submit button text when extending ConfigFormBase. What is the correct way to do it?

The submit button is defined in the base class and you can change it:

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $form['actions']['submit']['#value'] = $this->t('Save my configuration');
    ...


Using Entity metadata wrappers to change field value under hook_node_insert() I am trying to change a field value inside both hook_node_insert() and hook_node_update() using EMW. It actually changes the original $node object that is passed to these hook functions but the change doesn't get saved at the end.

function mymodule_node_insert($node) {
  if (!_is_dynamic_type($node->type))
    return;

  $messagew = entity_metadata_wrapper('message', message_create('post', array('uid' => $node->uid)));

  //copy terms
  $nodew = entity_metadata_wrapper('node', $node);
  //below loads a full taxonomy term
  $nodew->field_hidden_type = taxonomy_term_machine_name_load('event', 'hidden_type');

  $messagew->field_hidden_type = $nodew->field_hidden_type->value();//this actually works
  $messagew->save();
}

There are a few questions near to this one actually, but none of them addresses this precisely. This one for example is a very good explanation of the mechanism but its suggestion it not use.

Here, one should not use $nodew->save(), because it causes infinite loop. I also played a little with module weight, that does not help either.

I also tried to change another entity reference field. No use.

I don't want to go with field_attach_update() because it is old-fashioned.

The method you are using the save the field isn't ideal.
For setting the field values you should use the set() function provided by the EntityMetadataWrapper class.

function mymodule_node_insert($node) {
  if (!_is_dynamic_type($node->type))
    return;

  $messagew = entity_metadata_wrapper('message', message_create('post', array('uid' => $node->uid)));

  //copy terms
  $nodew = entity_metadata_wrapper('node', $node);
  //below loads a full taxonomy term
  $nodew->field_hidden_type = taxonomy_term_machine_name_load('event', 'hidden_type');

  $messagew->field_hidden_type->set($nodew->field_hidden_type->value());
  $messagew->save();
}

On a side note, I see that there is not check on the node type, or any other parameters in the implementation of  hook_node_insert. Note that it will get triggered every time a node of any content type is created.


Why am i getting a blank UI in filedepot module in drupal 7? I want to have proper file management for my site powered by drupal. I have downloaded the filedepot module, and have performed all the steps to configure it properly...but still i am not getting the user interface after i click the filedepot link on the navigation menu, its totally blank. i figured out there are many, who are getting the same problem; have tried different solutions, but no luck anywhere.

please suggest me some solution for the same, m using drupal 7, filedepot 7.x-1.1 and libraries 7.x.-1.0.

please please need help badly

I found this solution at "https://drupal.org/node/1268336"

Renaming it solved the issue for me.

"rename /sites/all/libraries/jquery.blockUI.js to /sites/all/libraries/jquery.blockui.js. It is case-sensitive, and the JS file is not being loaded after following the instructions provided."


Flexslider LI styles randomly applied I've got a css issue that I can't get my head around, and could really use some help.

I'm trying to style flexslider on a drupal 7 installation and some but not all of my list styles are being applied to the images, then it seems like the application is random.

In the flex slider on the bottom of this page:http://www.multibrand.visionmix.us/for-her-all

each LI item has a border but each li is also supposed to have a inset shadow applied to it.
Some LIs do but most don't, and I can't figure out why.

I'm using:

Flexslider 7.x-2.0-alpha3

jQuery Update 7.x-2.3+6-dev set to 1.8

Drupal 7.23

Any ideas would be very welcome

I've got it sorted out.
The images in the LIs were too bug and covering over the effect. Once I resized the images everything was fine.


How to access protected property in feed object? When I try to access protected property in feed object I am getting error (Error: Cannot access protected property Drupal\feeds\State::$messages)

Feed Object:

Anybody know How to get protected property(messages) from object?

There is no public method on the State object that returns the messages. The public methods on the object are:

progress()
setCompleted()
setMessage()
displayMessages()
logMessages()

The method displayMessages() is the closest method you can use to access the messages, the messages are then transferred to \Drupal\Core\Messenger\Messenger, which has a method called all() to return all the messages on that object.

PHP also has an API called 'Reflection', which - among more - allows you to bypass visibility settings on class properties and methods. The main purpose for this API is to retrieve doc comments for functions, classes and methods. I wouldn't recommend to use this unless if it is for debug purposes.

Note that since Feeds 8.x-3.0-alpha6 the messages are also displayed on the feed page while an import is not yet completed.

Why do you need access to the messages? Maybe you can open a feature request ticket in the Feeds issue queue to request adding a public method for retrieving the messages.


Displaying custom fields in a forum I have made some custom fields at config->account settings (manage fields) and I have put them in my registration form but I want some of them display at image I show below under the post count and generally when they create a new topic or replay.

How do I display that field? From a search I did I found that it's inside the module VIEWS. I am searching inside there to find where to add the field.

http://img848.imageshack.us/img848/7913/costumfield.png

Answer
At drupal 7 at Configuration - account settings - right top cornet manage fields you can create custom fields and put them where you like, then the most common to do is to add these feilds in your code with editing the source code just i didnt know how to do it.. i dont thing there is another way..! because i use the module author pane and the best way is too add them to author panel in the module code..

You might also want to take a look at http://drupal.org/project/author_pane. That shows author information as shown in the picture you have posted.


What if update.php fails due to code errors? I sometimes run into the issue, when my PHP code has errors. I run update.php, but it fails with a php error message. After that, Drupal seems to think that the database is up-to-date, but it isn't. Trouble is, running update.php again does not solve the problem.

For example, just now, it has failed to create the tables for a newly created entity. update.php does nothing, but all my Entity code – of course – fails with database errors.

I don't know how to recover from this situation, other than uninstalling and reinstalling the module, which means killing all content first.

You could also rerun the update after you fixed your code.

See here:
reseting the hook_update_n status of a module


How to bulk delete content of a given type? I need to delete all content of a content type. I'm allowed to select up to 50 node per deletion process. My problem is that I have 900 nodes then I need to repeat this 18 times.

Anyway to select all nodes to mass delete them?

Check the Views Bulk Operation module. This allows you to create list for exactly this purpose and gives you some other interesting functions.


Multiple aliases per node (and active trail) Our site is split down the middle for tenants and landlords. But we have content the is the same for both such as "how to report antisocial behaviour".

User would normally navigate something like "Home > Tenant > ASB" or "Home > Landlord > ASB".

Duplicating content obviously isn't good, but we aren't worried about SEO, we are worried about maintainablity and context for the user.

So, I looking for a way to provide 2 aliases for a piece of content, and have the active trail show accordingly.

I found this, which suggest that symfony should be able to handle it, but I can't find how I would make it work in Drupal.

I can add a second alias, but I always get forwarded to the last one entered.

A simple solution is to create Content Type, say 'delegated', with a single node reference field. Then, configure the reference field to point nodes of the content you want to be duplicated. Configure this field to show the referenced node as full node view (or whatever View mode you prefer).

This way:

You can create independent pages with their own title, breadcrumb, alias, metadata, etc, but same content (if they reference the same node).
Editors are able to update/create those 'delegated' node easily (they are just a node).
As reference field can be limited by a View, you can narrow the contents available to be referenced in a powerful way.

As all are nodes, you can even create admin views to see with contents are related, or any other node available operation.

The main drawback is if you have configurations in referenced nodes that you want to be in the referencer node (say metatags). This could be solved using a custom module (updating referencer metatags when referenced node is updated) or manual copy-paste (ugly).


How to show blocks by url, when nodes have multiple paths? I know that having multiple path aliases to a single node is discouraged, but it is a situation I have to deal with.

My node is accessible via /news/node-1, /baseball/news/node-1 and /basketball/news/node-1. It's the same node, just three different aliases.

I have a 3 menu blocks, only 1 of which should be shown at any given time. I've configured the Page restrictions on the blocks so that they are restricted to certain url path patterns.

The "baseball" menu is restricted to baseball/*, the "basketball" menu is restricted to basketball/* and the 3rd menu is everything else, so I've set it to show on all pages except for baseball/* and basketball/*.

However, my problem is that when I'm browsing to baseball/news/node-1, the 3rd "everything else" menu is the one being shown. My -guess- is that Drupal is looking behind the scenes and seeing that the node is also considered to be /news/node-1 and therefore the path being used to choose my menu block is choosing the 3rd "everything else" menu.

a) Is there a way to see what path Drupal is using when determining which blocks to show based on path?

b) Is there a hook I could implement so that I can directly control which block to show on each request?

c) Any other ideas how I can make sure the correct block is shown?

Try setting the baseball menu to show on baseball/* and baseball/*/*. Likewise for the basketball menu, then set the Everything Else menu not to show on all four paths.


How to handle files for Drupal in cloud when in multi-site mode? I want to run Drupal from a cloud and I am trying to figure out the design of the file system for multi-site setup.

In cloud there are multiple webservers hidden under the load balancer serving content from a single database(which is a service that handles replication on its own so no issue there) and using central storage for user/drupal data.

So far I have solved the user-added data(mostly images uploaded into a content or attached via fields) but I'm stuck on how to handle files like compiled Twig templates, config directory, services file and settings file and similar.

Once a new web server instance is created it will fetch the code from git repository. The user data is handled via stream wrapper(and cdn) so no action is needed there. But how should I handle the system(yml, php..) files? The settings.php and services.yml are global so they won't change(still - how to handle this in multisite setup?) and the rest is dynamic(ie. once the cache is flushed the twig templates are recompiled and this needs to be synced for all instances).

The more static files like the settings.php and services.yml files could be potentially stored in some "remote" storage and fetched from there(ie. a directory tree matching the installed sites with these files already present - not a git repo though, I think that would not be a good idea) or they could be dynamically generated based on data stored in special database.

But what about the rest(twig, config...). Would something like a fast cache be a good design? Redis db that would hold the current files and each instance would either fetch them manually or serve them directly? Once an instance flushes cache this would be immediately "synced" to all instances in second scenario. For first scenario there would have to be some timestamp with latest change that each instance would have to check on each page load and re-fetch the files.

Drupal has this quite specific file system tree so that's why I'm asking this in here. I'm sure many people run Drupal in the cloud and I'm curious how they solved this "issue".

This is why platform as a service solutions like platform.sh, getpantheon and others are so popular. They provide solutions to problems like this.

If you don't want to use them, then you can still learn from them. In this case, the answer is environment variables. You commit a settings.php file that reads the configuration from environment variables, e.g. which database server/solr/redis/... to connect to, configuration overrides and so on.

platform.sh also automatically generates a settings.local.php that some configuration built in, but they move more and more towards just documenting how to do it yourself as that's more flexible. See their example setups and specifically, settings.php of the 8.x-composer approach.

How to actually get those environment in place yourself is a non-drupal related question that you'll have better chances for good answers elsewhere. It also depends a lot on how you actually instrument those cloud servers.

So far, I've haven't had the need for customized services.yml files, all I do sometimes (beside having a services.local.yml, just like settings.local.php), is to dynamically load additional files, e.g. with the redis configuration. If you need that, you can either generate those files or you can implement a site specific service provider that generates the service/parameter definitions dynamically.

For twig, while they are generated PHP files, unless you do something really weird, they are based only on the static .html.twig files that you are deploying. So, you do not need to share them between your servers, you just need a deployment step that deletes the files on all servers when you deploy new code. Or, you could write a script that pre-generates them, then you less of a performance hit when re-deploying. Haven't seen a script yet for Drupal that does that, there might already be a question about that here.

The container is in cache, by default in the database, with a bit of configuration you can also have it in Redis or Memcache, see https://github.com/md-systems/redis/issues/12.

I'm not aware of any other files that need to be maintained like this. (other than public or other stream wrappers, which you apparently have already solved).


How can I call custom javascript on successful webform submissions through hook_form_alter? I have some custom js code which should be executed after successful webform's submission.

JS Code :

jQuery('document').ready(function(){
    form_submit_telium();
});

below approaches, I already tried

1.

$commands = array();
$commands[] = ajax_command_invoke(NULL, 'form_submit_telium');
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

-> It's not working, due to my webform is not submitted through ajax call.

$form['#attached']['js'] = array(
                drupal_get_path('module', 'module_name') . '/js/form_submit.js',
            );

3.

drupal_add_js("jQuery('document').ready(function(){
      form_submit_telium(); });",'inline');

Webform alter code:

function module_form_alter(&$form, &$form_state, $form_id){
    $form['#submit'][] = 'telium_form_submit';
}

function telium_form_submit(&$form, &$form_state){
    // above three approaches
}

Please let me know if you have any other approach to do the same thing.

Your 2nd option will work in that :

.Module

function hook_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "webform_client_form_id"){
        $form['#attached']['js'][] = drupal_get_path('module', 'c1') . '/c1.js';
    }
}

Js Code:

jQuery(document).ready(function(){
    jQuery( "#webform-client-form-id" ).submit(function( event ) {
      alert( "Handler for .submit() called." );
    });
});


How to better distinguish answers from questions when using the Answers module? Bare with me, I am not a programmer, and I'm using the Answers module. I would like to make the background color of the answer content type a different color to distinguish it from the question.

So that when you browse both the question and the answer(s) (which the Answers module shows below the actual question on the same page), they don't look too similar.

I know I can add the field label (of the body of each answer), but I'd like to figure this out.

Any suggestions?

Depending on your configuration, there are probably already classes supplied by default with Drupal.  Have you used Firebug to check the markup provided by Drupal by default?  (video tutorial on how to use Firebug)

If you do need to add a class, one quick way to add a class to a field is the Field Group module.  Navigate to the "Manage fields" page for the content type you wish to modify, create a new field group of type div, and then add the class and place the fields you wish to be "in" the class within it.


How to alter a custom form I am using Drupal 7 to create an registration form, there are: username, email dan password fields, but I want to make an username checking while user leave username field (ajax).
I found an module as Username Check

This module is great and working in "myweb/user/register" form, but I need to move this function to my custom form in username field too

The code:

function username_check_menu() {
  $items = array();

  $items['username_check/isunique'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'username_check_callback',
    'access arguments' => array('access content'),
    'file' => 'username_check.unique.inc',
  );

  $items['admin/config/system/username_check'] = array(
    'title' => 'Username check',
    'type' => MENU_NORMAL_ITEM,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('username_check_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'username_check.admin.inc',
  );

  return $items;
}

function username_check_form_user_register_form_alter(&$form) {

  $mode     = variable_get('username_check_mode', 'auto');

  if($mode != 'off')
  {
    _username_check_load_resources($mode);
    $form['account']['name']['#field_suffix'] = '&nbsp;';
    $form['account']['name']['#suffix'] = '

';
  }

}

/**
 * Load username_check resources.
 */
function _username_check_load_resources($mode) {
  $module_path = drupal_get_path('module', 'username_check');
  drupal_add_css($module_path . '/username_check.css');
  drupal_add_js($module_path . '/username_check.js');

  drupal_add_js(array(
    'usernameCheck' => array(
      'ajaxUrl' => url('username_check/isunique', array('absolute' => TRUE)),
      'delay'   => variable_get('username_check_delay', 1),
    ),
  ), 'setting');
}

and my form as userregis_form
How to apply this to my custom form?

you need to add a validation to your form via

    $form['#validate'][] = 'yourFunction';

  function yourFunction($form, &$form_state) {
        //to show the form values
        dpm($form_state);
        //do validation
  }


How to sync one menu item into other menus? I have a Drupal menu called Top-Nav which I use for my Top Navigation with the following 6 menu items(for example)

Home   a    b    c    d    e

Each of a, b, c, d and e have sub items.
I also have 5 other menus let's say named "menu1", "menu2", "menu3", "menu4", "menu5" that have exactly the same structure/items as a, b, c, d, e
Like "menu1" is the same as "a", "menu2" is the same as "b" ...

What I am trying to achieve is the following:
When the admin adds a new item to "a" section of Top-Nav i want to replicated that item in "menu1" programmatically, I want to sync them once the new link is added.

My suggestion is to use hook_form_FORM_ID_alter to add a custom submit handler. In that submit handler, you will get the current menu item values. Use those values to create a new menu item for the other menu.

Functions to use:

hook_form_FORM_ID_alter. Here form id will be 'menu_edit_item'
Use form['#submit'][] = "custom submit handler" in form alter.
Use menu_link_save in custom submit handler based on the values you get form the form_state.


How do I get a block configuration value in a module? I created a custom block that contains a form field.

This is my blockSubmit() method.

public function blockSubmit($form, FormStateInterface $form_state) {
    // Save our custom settings when the form is submitted.
    $this->setConfigurationValue('my_text_field', $form_state->getValue('my_text_field'));
}

Now I want to access the my_text_field value from outside the custom block class.

You can load the block configuration entity, and get the settings.

$block = \Drupal\block\Entity\Block::load($block_id);
if ($block) {
  $settings = $block->get('settings');
  $my_text_field = $settings['my_text_field'];
}

$block_id is the machine name you see in the block layout when you save the block.

Edit: Store module configuration

If you want to store configuration for modules don't use a block form, but use a configuration form. Reference https://www.drupal.org/docs/8/api/configuration-api/working-with-configuration-forms
(see comment from @Berdir)

Dump all blocks and their settings

$blocks = \Drupal\block\Entity\Block::loadMultiple();
foreach ($blocks as $key => $block) {
  $settings = $block->get('settings');
  var_dump([$key => $settings]);
}


Is there any way to force a custom block in the Custom Block Library to invalidate cache on edit update? I have created custom blocks in the Custom Block Library and placed instances of the blocks on a page in Block Layout.  The blocks get cached for anonymous users.

Editing the custom block and saving does not invalidate the cache for those instances of the blocks. Looking in the "cache_render" table I see that caches for blocks get created through the Custom Blocks Library are set to never expire as a default with no options I can see available in the admin UI.

I have to actually "Flush All Caches" using the Devel module to have the changes appear, or another way I have found is to go to the Block Layout page and click the "Save Blocks" button without changing anything.  The cahces for all the blocks will invalidate.

I don't want to give access to Devel to an average content manager or have to try to explain that they have to do a non-obvious extra step to have their block content changes appear.  Am I missing a setting in the UI that will invalidate the cache of those blocks on edit save?

I can cobble together a module that would add an extra submit handler that would invalidate the cache using \Drupal::service('cache_tags.invalidator')->invalidateTags() if I can get the cachetags for all instances of the block on save ... but I'm not sure how to get that info, and that just seems like a hack.

I'm hoping I'm just missing something.

I came across this question in the related questions sidebar on my question that seems to be the same issue with out-of-the-box core blocks:
Block cache not clearing on save?

The accepted answer from @4k4 on that question seems to confirm the issue, but doesn't hook in to the block save to invalidate the cache like I was thinking, but mentions, as one possible workaround, adding this to the theme:

function mytheme_preprocess_block(&$variables) {
  if ($variables['base_plugin_id'] == 'block_content') {
  $renderer = \Drupal::service('renderer');
  $renderer->addCacheableDependency($variables, $variables['content'}['#block_content']);
  }
}

I don't know if this is the best answer, but it's simple and straightforward and seems to work at the moment, though it's a wonder that this would need to be done at all.  It's probably less of a hack than what I was thinking.


File upload ajax and Radio Buttons not cooperating in registration form I have enabled Profile 2 and profile Profile2 Registration Path modules on my site and have a really long registration form with lots of fields. I have some radio boxes and file upload fields also. The problem is when I upload a file without having selected a valid option for my mandatory radio box. IF the radio box is empty when I hit upload, the file gets uploaded and I get the error "illegal option, contact admin". After that the error keeps repeating if I try to remove the file.

In my reports I see

  Location  http://localhost:6600/sitename/el/file/ajax/profile_customer/field_cv/und/0/form-Q8VxLye65S3tYFkcHSwO9Z58dG7Mhv6jRWRBnIst46s

  Referrer  http://localhost:6600/sitename/el/customer/register

  Message   Illegal choice in Specialty element.

The Specialty element is my radio box. If I enter an option in the radio box before uploading the document everything works as it should! Removing the file is troublefree also. I am completely baffled with this. I’ve searched and found many issues with file upload and radio boxes values connected to ajax. Seems weird that this thing isn't working. Can't be the only one with files and radio boxes in his registration form! Any ideas/pointers on how to solve this irritating issue?

If I understand you right you'll need to write a small custom module to hook into the registration form using hook_form_alter(), and add the #limit_validation_errors property to the correct radio group. This should stop the validation from running on AJAX calls, but still let it run when the form is submitted.

The code might look something like this:

function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['radio_button']['#limit_validation_errors'] = array();
}

It's quite likely that the particular radio group you're after will be buried in the nested $form array somewhere so you'll probably need to use the dpm() function (part of of the Devel module) to inspect the form and determine the correct element to alter.


How to attache multiple nodes of a node type to another node of another node type? Currently I am making a advertisement website for restaurants. Now I am putting the restaurant basic information (name, address,etc) in a node.

What I want to do is making a menu list for the restaurant,
Say each menu item is a node (with the type of 'item') while the restaurant is another node type 'restaurant'.

In database level, the relationship between node (restaurant) and menu item node type is one-to-many.

So how can I do this?

Thanks for any help!

Cheers!

Install the references module, once you done that, you can enable the node_reference submodule and attach a "Node Reference" field to your "restaurant" content type.

Next, set the "item" content-type as reference for the field and the "Number of values" setting as "Unlimited".

When creating or editing a restaurant, you should now be able to link multiple menus to the node.


Change ubercart default path My clients really really insist that the path of the cart pages will be store/* instead of cart/*

Also, an alias is not good enough. They want a totally unrelated page to appear in the path: cart

Crazy? yes. Challenging? you bet.

Rewrite all needed paths by hook_menu_alter. It is invoked  by menu_router_build().


Why is the rate widget (from the Rate module) not showing up? I'm using the Rate module, together with the entity reference module.

I have a content type let's name it "Gallery". I also created a "Photo" content type, then added a "yes/no" rate widget  to this content type. (c)

In "Gallery" I have an entity reference to "Photo".

Now I'm going to make a View like this: Show all of "Photo"s related to this "Gallery" plus rate widget related to every "Photo".

I created a view with nid as argument to get specific node, and two relation, first one is "Entity Reference: Referenced Entity", and second one is "Vote result". then I added first relation as a relation to second relation.

I added "Vote results:value" as field. So far I see the "Photos", but I couldn't get the rate widgets.

What am I missing to also get the rate widgets to show up?

From the screenprint about "edit widget" in your question it shows that you've created a "Yes / no" widget using the Rate module.

But nowhere in your question it shows for which "Node types" you've enabled your widget. Since you're using the "Yes / no" widget (located at admin/structure/rate/add?template=yesno when adding a new widget), you should indicate the desired "Node types" there for which the rating widget is to be enabled. If you didn't specify (select) any of node type, then that would explain why the rate widget is not showing up".


Touch of Flex Slider is not working I am using Flexsilder in Drupal7, and i also enabled touch FROM Admin .

But Flexslider is not working for pad using touch

Here is my link, where i am facing issue this is my link where flex slider is implemented

Anybody can help please

Maybe you should try with different images. It works perfectly on my tablet and phone (both w8.1) you just can't drag it with your mouse, maybe thats why you tought it didn't work?