How to let editors place custom forms? I have a custom form:

\Drupal\module\Form\CustomForm

I want to be able to embed this form in a basic page by adding a shortcode/variable to the basic page such as:

[form][/form]

or

form

This is very easy to achieve in WordPress but really difficult in Drupal.

How can I achieve the above?

As also WordPress is now moving towards modular content (codename Gutenberg) I'd advise you to do the same in Drupal with Paragraphs.

Then you can provide different paragraph types (image, text, CTA etc.), one of them could be a simple block reference (I don't remember if core already offers block reference fields or
if you need Block field for that) with which you let editors choose blocks to be placed wherever they want. (Paragraphs also are resortable.)

So, you already have your form, cool. Next level is to let your custom module provide a block that outputs this form. Next, In your theme add a new region "Disabled" (that never gets printed anywhere) and place your block there. Now this block will be available to choose as block reference. (I guess it's desired behavior that only blocks that are assigned to a region can be referenced.)

Bonus would be a little bit of back-end JS to only display certain blocks in the block reference select list. But that's just bonus.


Do wildcards not work with Menu Local Task? I am getting an offset error , Undefined offset: 4 in _menu_translate()

 $items['admin/content/import-dashboard/new'] = array(
    'title' => 'Import Dashboard',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('import_dashboard_new_content',"article"),
    'access arguments' => array('Import Dashboard Permission'),
    'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
    'expanded' => TRUE,
  );
    $items['admin/content/import-dashboard/new/%'] = array(
    'title' => 'Import Dashboard',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('import_dashboard_new_content',4),
    'access arguments' => array('Import Dashboard Permission'),
    'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
    'expanded' => TRUE,
  );

I simply want to default new to article, and also use wildcards to support other arguments.

I'm pretty flexible in my approach, so feel free to throw a few suggestions if it could be done better.

Can someone quickly suggest where I made my rookie mistake?

Indeed, changing to Menu Callback works when using the wildcard.

$items['admin/content/import-dashboard/new/%'] = array(
    'title' => 'Import Dashboard',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('import_dashboard_new_content',4),
    'access arguments' => array('Import Dashboard Permission'),
    'type' => MENU_CALLBACK,
    'expanded' => TRUE,
  );

Would still like to know why it fails when it a MENU_LOCAL_TASK or MENU_NORMAL_ITEM

The problem is that your menu items are local tasks, which are menu tabs, so on a given page drupal will load all the tabs for the current page.

So on the admin/content/import-dashboard/new page it loads your tab menu items:
admin/content/import-dashboard/new
admin/content/import-dashboard/new/%

but when it goes to get the second item there is no 4th param on the current page so it gets that error.

This is why when you change it to not be a MENU_LOCAL_TASK it stops the problem.

If you have a page that has menu tabs where the last part of the path is a wildcard, how could drupal know what all the possible tabs are? It can't.

This is why when you see menu tabs they are things like node/%/view, node/%/edit, etc. so you have a finite number of tabs and each has its own definition.

As a side note, yes you can use multiple menu item types, but using MENU_LOCAL_TASK | MENU_NORMAL_ITEM doesn't really make sense.
As an example MENU_IS_LOCAL_TASK | MENU_LINKS_TO_PARENT | MENU_VISIBLE_IN_BREADCRUMB is one that would make sense.

Also, I'm not sure if this is your full hook_menu() or if admin/content/import-dashboard exists somewhere else, but usually if you're doing tabs there is a parent page (in this case admin/content/import-dashboard) and a tab that is MENU_DEFAULT_LOCAL_TASK.

There is however the ability to set in your menu item:

'tab_parent' => 'admin/content/import-dashboard/new'

This allows you to set the parent page to use for tab items.
Without this it defaults to the path of the tab item minus its last path part.


How to get a list of entities available in your Drupal? Sometimes I need to create a new entity but I don't know the exact machine name of the entity to put in the entity_create() method.

Is there an easy way to check which entity types are available to create in your Drupal 7 site?

You can just invoke hook_entity_info() and check the keys:

$info = module_invoke_all('entity_info');
$all_entity_machine_names = array_keys($info);


How to get selected value in option id value in drupal form api Hi hello please help how to get dynamically selected option id value (i.e #options=>0=>'bala',1=>'kumar')

for example (1001->india,1002->usa) like that stored in select option value (india, usa like that) , but i want to fetch the id value(1001, 1002) of selected value of id value from option? that value to be store in $key variable, please help me

$query_state=db_select('state', 's');
$query_state->fields('s',array('State_code','State_name'));
$query_state->orderBy('State_name','ASC');
$state_results = $query_state->execute();
$options_state = array();

foreach($state_results as $state_record) {
  $options_state[$state_record->State_name]=t($state_record->State_code);
}

$form['state1']= array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' =>$options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

// here values are popup in select option component but corresponding value of state in city select option not visible

 $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

$query_city=db_select('city', 'c');
$query_city->fields('c',array('District_Code','District_Name','State_Code'));
$query_city->condition('State_Code',$key,'=');

$query_city->orderBy('District_Name','ASC');
$city_results = $query_city->execute();
$options_city = array();

foreach ($city_results as $city_record) {
  $options_city[$city_record->District_Code]=t($city_record->District_Name);
}

$form['city']= array(
  '#type' => 'select',
  '#title' => t('District'),
  '#options' => $options_city,
  '#prefix' => '
',
  '#suffix' => '
',
  '#required' => TRUE,
  '#states'=>array(
    'visible'=>array(
      ':input[name="state1"]' => array(
          'value' => $options_state,
      ),
    ),
  ),
);

function _ajaxfunction($form, $form_state) {
  return $form['city'];
}

Try the following code:

function YOUR_FUNCTION_THAT_DISPLAYS_FORM(&$form, &$form_state) {
  $query_state=db_select('state', 's');
  $query_state->fields('s',array('State_code','State_name'));
  $query_state->orderBy('State_name','ASC');
  $state_results = $query_state->execute();

  $options_state = array();

  // Using fetchAll() you can iterate through a result set.
  while ($state_record = $state_results->fetchAll()) {
    // You want state code as key, not state name as key.
    $options_state[$state_record->State_code]=t($state_record->State_name);
  }

  // State form element.
  $form['state1']= array(
    '#type' => 'select',
    '#title' => t('State'),
    '#options' =>$options_state,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  // City wrapper form element.
  $form['city_element_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  return $form;
}

// AJAX callback function.
function _ajaxfunction(&$form, &$form_state) {
  $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

  $query_city=db_select('city', 'c');
  $query_city->fields('c',array('District_Code','District_Name','State_Code'));
  $query_city->condition('State_Code', $key, '=');

  $query_city->orderBy('District_Name','ASC');
  $city_results = $query_city->execute();
  $options_city = array();

  while ($city_record = $city_results->fetchAll()) {
    // This is correct.
    $options_city[$city_record->District_Code]=t($city_record->District_Name);
  }

  // Render city setting.
  $form['city_element_wrapper']['city']= array(
    '#type' => 'select',
    '#title' => t('District'),
    '#options' => $options_city,
    '#required' => TRUE,
  );

  return $form['city_element_wrapper'];
}

Hope this helps you!


Redirect 'user' and 'user/uid' to 'users/name' I have been trying to redirect the default user url of '/user' to the url alias of '/users/username'.

If i go to '/user/uid' it redirects properly but if i type in '/user' the url doesn't redirect.

Using hook_preprocess_user_profile() I can print arg(0) and arg(1) with drupal_set_message() and it display that arg(1) exists as the uid on '/user'.

I have tried

function mymodule_preprocess_user_profile(&$vars) {
  global $user;
  //print_r($vars);
  if (arg(0) == 'user' && arg(1) == $user->uid){
    //drupal_set_message('0'.arg(0).'1'.arg(1));
    drupal_goto("users/$user->name");
  }
}

but this end up in an endless redirect. Is it possible to even accomplish this?

By redirecting /user you'll be redirecting the login page to a user page.  When someone goes to /user and logs in they are automatically redirected to /user/username.  Unless you have login disabled(not advised) I can't see what you want to achieve, can you explain further?

Redirects are best handled by the path redirect module

or using rules in .htacces or etc/apache2/httpd.conf


Add script on head section without module I have a google add script Which I want to integrate on the head section. How can I add the script to the head section on drupal 7 without any module and info file? Script is below:

 (function () {

        var _onload = function(){

            if (document.readyState && !/loaded|complete/.test(document.readyState)){setTimeout(_onload, 10);return}

            if (!window.__adroll_loaded){__adroll_loaded=true;setTimeout(_onload, 50);return}

            var scr = document.createElement("script");

        };
});

Add it your theme instead.

html.tpl.php would be the correct template to use.


Term reference field lists the terms for all the languages What I meant is that I have the i18n module installed and configured for content and taxonomies, this is what I need

I have a taxonomy called "Colors" I have translated all the terms of this taxonomy from spanish to english

I have a term reference field in a content type that points to the taxonomy "Colors"

While I create the the node of that content type and try to select a color, the select list shows me all the colors in english and spanish, is there a way of update that term reference select list to show only the terms for the selected language for that node?

Check the image and you will understand what I mean

If you check the image I selected in the list as language spanish, but in the color checkboxes it shows me all the terms in both languages (English & Spanish)

How to show the terms depending of the selected language while creating the node?

This is the image of the translated and original taxonomy terms in Spanish and English

Try selecting Localize. Terms are common for all languages, but their name and description may be localized as the Translation mode, after that remove the terms that you added separately for Spanish language and edit each term that are there in English and translate it to Spanish.


Show custom entity bundle field I created an module polls and entity poll using Drupal Console

I want to add default entity_type on installation.
Currently I added only one field to it field_image.

I created following files

FILENAME : field.field.poll.article.field_image.yml

langcode: en
status: true
dependencies:
  config:
    - field.storage.poll.field_image
    - polls.poll_type.article
  module:
    - image
id: poll.article.field_image
field_name: field_image
entity_type: poll
bundle: article
label: Image
description: ''
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings:
  file_directory: '[date:custom:Y]-[date:custom:m]'
  file_extensions: 'png gif jpg jpeg'
  max_filesize: ''
  max_resolution: ''
  min_resolution: ''
  alt_field: true
  title_field: false
  alt_field_required: true
  title_field_required: false
  default_image:
    uuid: null
    alt: ''
    title: ''
    width: null
    height: null
  handler: 'default:file'
  handler_settings: {  }
field_type: image

FILENAME : field.storage.poll.field_image.yml

langcode: en
status: true
dependencies:
  module:
    - file
    - image
    - polls
id: poll.field_image
field_name: field_image
entity_type: poll
type: image
settings:
  uri_scheme: public
  default_image:
    uuid: null
    alt: ''
    title: ''
    width: null
    height: null
  target_type: file
  display_field: false
  display_default: false
module: image
locked: false
cardinality: 1
translatable: true
indexes:
  target_id:
    - target_id
persist_with_no_fields: false
custom_storage: false

Field is created but it is coming as hidden in Form. How can I show it when modules get installed.

Please suggest.

--

Thanks

Configure the field in the form display, export this file

core.entity_form_display.poll.article.default.yml

and put it in the folder /config/install. Remove the uuid line from the yaml file.


How to set different themes for multiple domains I am developing a multi-domain site with same code base and single data base.
I am trying to set themes for multi domains which was previously supported by domains theme module in Drupal 7.
  Don't know how to achieve solution for this. Please help me for this.

I got an solution that my colleague suggested through a contrib module.
But, not yet used it perfectly for themes.

Steps for getting it are as follows -
1. go to

  www.github.com
  and sign up for free.
  2. Take a git clone of the
  https://github.com/agentrickard/domain.git
  in modules folder in your drupal code base.
  3. Extend the module and try it out.


Add all related content from entity reference with views I really hope someone can help me, because it's the last thing I have to do in this site, and I thought it would be more or less easy, but I can't get this to work.
Not even sure if this is the wright question, and sorry for some English.

My situation it's this one:
I have two content types: Books and Authors.
Books as a entity reference to authors.

In the node type Books, I want to display the book authors plus all their books.

As I use panels, I can do this simple or making a view.

But what I can't do, it's to display all the author's books in that node.

I can create a view with the authors and all their books, using views merge rows, to merge the books.

But if in the contextual filters I use the nid, all I get it's the same book from the node.

So I'm trying to create a attachment to display just the books titles from those authors, but honestly, I'm completely lost !

Perhaps someone could give me some examples how to achieve this.

Thanks

Click the "More" link in the contextual filter. That fieldset is collapsed by default but you'll find the option to make exclusions there. You may have to exclude the current node ID separately--not sure about that.


hook_form_FORM_ID_alter in theme file to toggle field visibility I have a boolean check box that I want to control the visibility of an entity-reference field below it.  By default, this check box is unchecked, which means the entity-reference field should not be shown.

I've tried a handful of things in my .theme file, but I can't seem to solve the problem.

use Drupal\Core\Form\FormStateInterface;

function mytheme_form_node_news_form_alter(&$form, FormStateInterface
  &$form_state, $form_id) {
    $form['field_news_top_story_image']['#states'] = [
    'visible' => [
        ':input[name="field_news_topstory"]' => ['checked' => TRUE]
    ]
];

}

node_news_form (and eventually node_news_edit_form once I figure this out) appears to be the form I want to affect.  field_news_topstory is my checkbox and field_news_top_story_image is the entity-reference field I want to hide* until field_news_topstory is checked.  *I've set this field to disabled in Manage Form Display.

Am I close?  :)

EDIT: Had my code backwards, but still not working.

After a lot of banging on this, I found the right combo.  We don't have a custom admin theme, so I ended up moving this code in to a custom module.

The important part I was missing was [value] in ':input[name="field_news_topstory[value]"]' => ['checked' => TRUE]

use Drupal\Core\Form\FormStateInterface;

function mymodule_form_node_news_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    $form['field_news_top_story_image']['#states'] = [
       'visible' => [
         ':input[name="field_news_topstory[value]"]' => ['checked' => TRUE]
       ]
   ];
}


How to insert the image field in the menu links How to insert the image field in the menu links? I've added an image field in the vocabulary I've created and uploaded image on each terms. I am able to display those images and the other fields I require using the views and I've used the taxonomy_menu to add the terms in the menu links, but one of my requirements is to display those image into the menu links. I don't think that the menu_icons module is the solution, I don't want to double up the work in uploading the image. Please bear with my English and hoping that I explained it well. Thank you.

You can try using the module Menu Minipanels. This module will allow you to use views and custom blocks inside the menu.

Or you can customize the menu display as specified here.


drupal add class to form-item if error on form to all forms I just want to add class to .form-item if there is error on form i used the following code but its not working.

function semanticUI_form_element($variables) {
  if (isset($element['#parents']) && form_get_error($element)) {
    $attributes['class'][] = array('error1');
  }
  if(form_get_error($element)){
    $attributes['class'][] = array('error1');
  }

  if (!empty($element['#required'])) {
    $element['#attributes']['class'][] = 'test';
  }
}

Any help would be appreciated.

If you copy the theme_form_element() function out of includes/form.inc and into your theme's template.php file, re-name it to match your theme, and change the initial setting of $attributes['class'] accordingly:

  if (form_get_error($variables['element'])) {
    $attributes['class'] = array('form-item', 'da-error');
  } else {
    $attributes['class'] = array('form-item');
  }

...this will put a da-error class in the overall <div> wrapping this element.


How do I add to $page_top in html.tpl.php? I wanted to add a piece of HTML at the top of all pages, right after <body>. In the #drupal IRC channel I got the recommendation to override html.tpl.php in the theme. That works fine. But isn't there some useful hook that I could use, so I don't have to copy html.tpl.php and just add a few lines?

I tried to modify $variables['page']['page_top'] in THEME_preprocess_page() and THEME_preprocess_html() but upon debugging $page_top in html.tpl.php, the changes had been discarded.

How do I do it by hook? And which way is to prefer?

Have a look at how the Drupal core toolbar module does this:

/**
 * Implements hook_page_build().
 *
 * Add admin toolbar to the page_top region automatically.
 */
function toolbar_page_build(&$page) {
  $page['page_top']['toolbar'] = array(
    '#pre_render' => array('toolbar_pre_render'),
    '#access' => user_access('access toolbar'),
    'toolbar_drawer' => array(),
  );
}

This is probably the most correct way of adding something to the page top as you can comfortably use render arrays.


How to hide specific pages from users, but not the content? I'm trying to hide a specific set of pages from anonymous users and I would like to return a 404 for them. To be more precise, the set of pages I'm trying to hide are ECK entity pages (info blocks I guess), taxonomy term pages and a few node types. But I would like to still have them visible in the pages they are part of.

To be more clear, let me give you an example : I would like to have itinerary/gallery/1 hidden from anonymous users, but I would still like for the gallery itself to be visible in the blog pages it's embedded in.

I tried using the Rabbit Hole module and it works great for taxonomy terms and the node types, but not for the ECK stuff. I tried extending the module but it doesn't seem possible the way Rabbit Hole works unless I create an extension for each of them.

I also tried pulling a hook from hook_entity_view() but the problem with it is that it also triggers when the elements are loaded in the page, not just on their own pages. Does anyone have any idea how to do this?

You could use the Rules module to get this to work, by using the "Drupal is initializing" event. That will ensure that the rule gets triggered BEFORE the actual content is shown.

The links that you want to "intercept", should be formatted in some type of regular expression, which you then use as your Rules Condition. So that you have a rule that corresponds to "before showing the actual content of something that matches a specific path ...". After you get that part to work, your Rules Action should specify the actual redirect to be performed.

Sample rule

Refer to the "Option 1" part of my answer to the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?", which contains this rule in export format:

{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

Here are some suggested tunings of the above sample, to make it work for your case also:

machine name and label.
replace the node/* by your path(s) (in the regular expression).
possibly you may want to add an extra Rules Condition to only perform the Rules Actions for selected user roles (eg: only for user who are not administrators).
replace the path in the action part of the rule by your target path, and check if you do want some type of error message to be shown (if not remove that part of the action).


Does hook_drush_exit() get called for disabled modules? I have a module that exposes a drush file that contains an implementation of hook_drush_exit(). This function gets called at each drush command, even though the module is disabled.

Is this behaviour by design, or is it a bug/misconfiguration?

Using Drush 7, I get different results -- which is to say, hook_drush_exit() is usually not called unless the module it is implemented in is enabled.

Two things to note about this:

Earlier versions of Drush may have behaved differently; I did not test older versions, and I do not remember.
In some instances, it may be possible for some hook_drush_exit() to fire, even if the module it is not enabled.  One example where this happens is the drush help command.

hook_drush_exit() will be called for all commandfiles (module.drush.inc) that are loaded.  If Drush bootstraps the Drupal site all the way to the configuration level, then it will only load commandfiles for enabled modules.  If Drush is going to bootstrap the Drupal site at least to the "BOOTSTRAP_DRUPAL_ROOT" level, but not all the way to the configuration level, then it is not possible for Drush to determine which modules are enabled, and which are disabled.  In these somewhat rare cases, Drush will go ahead and load all of the commandfiles it can find anywhere inside the Drupal root, even for modules that are not enabled.

In any event, the workaround you used is the right solution, but now you know why your hook is being called.


How do I programatically add fields to the Media module's field tables? I use the Media (ver, 2) module to manage a library of media assets.  It allows reuse of the same media in several nodes and keeps track of media use.

When reusing media (e.g.) images, I want to be able to add different captions (and maybe other metadata) to each use of the same image. I.e.: When I use the same image attached to two different nodes, I want to set the caption for each instance.

There is a great tutorial “How to Add Captions to Images in Drupal” about adding captions – but its approach is to add the caption to the image entity itself. This means that the same caption must be repeated whenever the image is reused.  I want an unique caption for each use instance.

I’ve noticed that version 2 (7.x-2.0-alpha4) of the Media  module manage some metadata (e.g. field_media_description) about each media instance use in the two tables {field_data_field_media} and {field_revision_field_media}. I’ve tried to use the already existing field field_media_description for the caption. This works, and almost does what I want.

However, I want the caption field to be a textarea (not a textfield), and I prefer not to overload some existing field with new functionality (maybe breaking the initial intent for this existing field) - so I want to add another field (field_media_caption) to these tables.

I’ve been digging about the Media module for days, trying to figure out how to add my own fields to these tables, and have not been able to figure it out.

So:
How do I programatically add additional metadata fields to the Media module's field tables?

I will also accept an alternative solution that allows me to use a different module to manage a library of reusable images and add captions fields per use-instance.

There is a sandbox module I helped with, Media Wrapper, which solves this problem by managing media via a field collection. This has the advantage of making it possible to associate any fields you like with a media file, including captions. And the metadata is all per-use rather than per-file.

As it is a sandbox module, it's not as polished as we would like but it does a reasonable job of solving this problem.

To use it, once installed you create a field collection with your media field and meta data and then configure it via field settings of the field collection to say how each field is to be used (for alt text, title, caption etc).


Custom form template So I am recently started working on front-end development, and have started messing around with making my own custom templates for modules. I have been able to get page related templates to work, but am having a problem getting form related templates to work.

This is for Drupal 7.

I have a form, like this (Its not quite this basic, but very similar and no special fields)

function mymodule_menu() {
  $items['admin/atavism/config'] = array(
    'title' => 'Configuration',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('atavism_config'),
    'access arguments' => TRUE,
  );
}

function atavism_config() {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save Configuration',
  );

  $form = theme('atavism_config_form', array('form',$form));
  return $form;
}

function atavism_theme() {
  return array(
    'atavism_config_form' => array(
      'template' => 'page--atavism-config-form',
      'path' => drupal_get_path('module','atavism') . '/theme',
    ),
  );
}

And then I created the page--atavism-config-form.tpl.php. Inside of the form, I am using;

print render($form);

I am doing the same thing for pages that are just content (normal pages with just text and markup for example, and no forms), and it's working as intended, but I am also doing the same thing for a couple of different forms I have, and I am running into two problems. Either #1, the form renders in the template, but ONLY the provided $form variables are available (so the form can't be submitted), or I get a white screen with a PHP error of 'Unsupported operand'.

It appears I may be doing something wrong with forms, but I can't figure out what. Could somebody please help me?

Adding the response I gave on Drupal.org:

The issue is that you are rendering the form with the theme() function, in the form definition. Instead, you need to identify the form as using a #theme, and let it be rendered downstream:

So remove this:

$form = theme('atavism_license_list_view', array('form' => $form));

And add this:

$form['#theme'] = 'atavism_license_list_view';

Link: https://www.drupal.org/forum/support/module-development-and-code-questions/2019-03-07/custom-template-file-for-modules#comment-13019068


Webforms module breaks MySQL database I've got 'Webform 7.x.3.20" installed on my Drupal 7 and it works perfectly, apart from it seems to have 'broken' the MySQL database. I first noticed this when I tried to use the 'Backup and Migrate' module - I got the following error:
Additional uncaught exception thrown while handling exception.

Additional uncaught exception thrown while handling exception.
Original
PDOException: SQLSTATE[HY000]: General error: 2013 Lost connection to
MySQL server during query: show table status; Array ( ) in
backup_migrate_source_db_mysql->query() (line 435 of
/home/example.com/public_html/sites/all/modules/backup_migrate/includes/sources.db.mysql.inc).
Additional
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has
gone away: INSERT INTO {watchdog} (uid, type, message, variables,
severity, link, location, referer, hostname, timestamp) 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, :db_insert_placeholder_9); Array (
[:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] =>
php [:db_insert_placeholder_2] => %type: !message in %function
(line %line of %file). [:db_insert_placeholder_3] =>
a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:112:"SQLSTATE[HY000]:
General error: 2013 Lost connection to MySQL server during query: show
table status; Array ( )
";s:9:"%function";s:39:"backup_migrate_source_db_mysql->query()";s:5:"%file";s:96:"/home/example.com/public_html/sites/all/modules/backup_migrate/includes/sources.db.mysql.inc";s:5:"%line";i:435;s:14:"severity_level";i:3;}
[:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] =>
[:db_insert_placeholder_6] =>
http://example.com/admin/config/system/backup_migrate
[:db_insert_placeholder_7] =>
http://example.com/admin/config/system/backup_migrate
[:db_insert_placeholder_8] => 82.29.92.127
[:db_insert_placeholder_9] => 1409596675 ) in dblog_watchdog()
(line 160 of
/home/example.com/public_html/modules/dblog/dblog.module).
Uncaught exception thrown in session handler.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has
gone away: SELECT 1 AS expression FROM {sessions} sessions WHERE (
(sid = :db_condition_placeholder_0) AND (ssid =
:db_condition_placeholder_1) ); Array ( [:db_condition_placeholder_0]
=> Zy8B5O3kHHKb5uIZnFFODRyXl9C_a82Ek-o9why5wNU [:db_condition_placeholder_1] => ) in _drupal_session_write() (line
209 of /home/example.com/public_html/includes/session.inc).

I then went to look on phpMyAdmin to find that if I clicked on the database itself, it showed that there were no tables and has started logging me out of phpMyAdmin almost immediately. However, if I click on the '+' to the left of database name on the left hand side, I can view all of the tables in the database and even browse them individually.
Finally, I have used mysqlcheck over SSH and found that all the tables are OK until it reaches any belonging to webforms, and then I get "Got error: 2013..." again. I know for definite it is the module because I tried removing the tables for the database, and everything goes back to normal.
Any ideas why this is happening and how this can be fixed? The webform module is excelllent and I do make good usage of it, however I'm going to have to find an alternative if this continues as I can't even update Drupal core or backup the database at the minute!

I would expect this is more related to the backup and migrate module.

The addition of the webform module's data may have pushed your setup over its limit when doing large amounts of processing like backup and migrate would be doing.

I would suggest checking your MySQL configuration's max_allowed_packet setting, it may be too low.

I would usually recommend setting it to 64M for Drupal 7 and then restarting the MySQL service and see if that resolves the issue.


Drupal add fieldset inside form and wrap all form elements under that fieldset I want to add fieldset tag inside form tag. Also i want to wrap all the form element under this fieldset. I'm using the following function to change the form design and html.

MY CODE:

function change_password_form($form, &$form_state) {
  if (user_is_anonymous()) {
    return $form; // Or drupal_access_denied()?
  }
  $form['#account'] = $GLOBALS['user'];
  $form['fieldset']['current_pass'] = array(
    '#type' => 'password',
    '#title' => t('Current password'),
    '#size' => 25,
    '#required' => TRUE,
  );
  return $form;
}

CURRENT OUTPUT :

<form action="/projects/drupal/hpedu/change-password" method="post" id="change-password-form" accept-charset="UTF-8">

  Current password *
 <input type="password" id="edit-current-pass" name="current_pass" size="25" maxlength="128" class="form-text required">

<input type="submit" id="edit-submit" name="op" value="Submit" class="form-submit">
<input type="hidden" name="form_build_id" value="form-pGcx3HehTZlOkicX1gaBrr5eBjv8iT6iccQvCN8uXTU">
<input type="hidden" name="form_token" value="1qygden7YqhLlXvjiC8-ypYDXhOKwW_brUB4BdXlKNU">
<input type="hidden" name="form_id" value="change_password_form">

</form>

EXPECTED OUTPUT :

<form action="/projects/drupal/hpedu/change-password" method="post" id="change-password-form" accept-charset="UTF-8">
<fieldset class="myclass">

  Current password *
 <input type="password" id="edit-current-pass" name="current_pass" size="25" maxlength="128" class="form-text required">

<input type="submit" id="edit-submit" name="op" value="Submit" class="form-submit">
<input type="hidden" name="form_build_id" value="form-pGcx3HehTZlOkicX1gaBrr5eBjv8iT6iccQvCN8uXTU">
<input type="hidden" name="form_token" value="1qygden7YqhLlXvjiC8-ypYDXhOKwW_brUB4BdXlKNU">
<input type="hidden" name="form_id" value="change_password_form">

</fieldset>
</form>

Any help would be greatly appreciated.

It should be something like this.

function change_password_form($form, &$form_state) {
  if (user_is_anonymous()) {
    return $form; // Or drupal_access_denied()?
  }

  $form['#account'] = $GLOBALS['user'];

  // To make the fieldset define #type as fieldset
  $form['fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Password Info'),
    '#collapsible' => TRUE, // Added
    '#collapsed' => FALSE,  // Added
  );

  $form['fieldset']['current_pass'] = array(
    '#type' => 'password',
    '#title' => t('Current password'),
    '#size' => 25,
    '#required' => TRUE,
  );

  return $form;
}


Comment reply form not working? When I click 'reply' button on the comment, a new comment form open in new Windows; but subject box does not contain 're:' or like that and my reply saves as a new comment.

How can I repair my comment system?

Regards.

you need to go to admin/structure/types/manage/article [if your content type is Article] or admin/structure/types/manage/page [if it's Basic Page]

click on comment settings and make sure you have threading checked, so the replies have an indentation.

Asfar as re: in subject box, to my knowledge, drupal does not come with that by default.


How to programmatically manage taxonomies? I'm working on a project with this requirement: there will be a couple of custom content types where many fields comes from taxonomies references.
Many of these taxonomies have plenty of terms (50+). These terms are periodically updated (added/corrected/removed) by a third party system in charge of this task, which later exposes these 'most current' terms list through a webservice.
So I don't need to force a human operator to manually check these terms lists and update D8 taxonomies accordingly, I thing that a good approach would be to periodically run a task to verify that webservice and then updated D8 with what have changed.
I've carefully read the following references:

Programmatically create term in Drupal 8?
Programmatically create a term?

Create taxonomy term programmatically on Drupal 8
http://www.drupal8.ovh/en/tutoriels/55/create-taxonomy-term-programmatically-on-drupal-8

Drupal 8 - Examples - create_taxonomy_term.php
https://gist.github.com/facine/35bb291811c146b6fc9e#file-create_taxonomy_term-php

Saving and retrieving taxonomy terms programmatically for Drupal 8
http://btmash.com/article/2016-04-26/saving-and-retrieving-taxonomy-terms-programmatically-drupal-8

The one that come closer to the project needs is the 4th one in the above list. It would suffice the requirements for now.
But I didn't quite get where this code should be typed. Does it need to be a custom module or should it go into themes/mytheme/mytheme.theme or so?
From where I stand, I think that an elegant solution is to have a routine somewhere (where?) that I could call via D8's cron so I can retrieve-then-update taxonomies periodically. But I have no clue on how I could achieve that goal.
Can someone provide any good references so I can fulfill this desire with code?

A simple way to set this up would be a cron hook.

function hook_cron

  Perform periodic actions.

  Modules that require some commands to be executed periodically can
  implement hook_cron(). The engine will then call the hook whenever a
  cron run happens, as defined by the administrator. Typical tasks
  managed by hook_cron() are database maintenance, backups,
  recalculation of settings or parameters, automated mailing, and
  retrieving remote data.

  Short-running or non-resource-intensive tasks can be executed directly
  in the hook_cron() implementation.

  Long-running tasks and tasks that could time out, such as retrieving
  remote data, sending email, and intensive file tasks, should use the
  queue API instead of executing the tasks directly. To do this, first
  define one or more queues via a \Drupal\Core\Annotation\QueueWorker
  plugin. Then, add items that need to be processed to the defined
  queues.

As mentioned a better way for D8 would be to use the queue API.

Or try the dev version of Feeds, which can do this without code:

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


Node display based on conditional view [NULL] field entry or a Rules expression I am trying to find a solution to empty user Content Listings shown on a User dashboard (landing page). Ideally I want to show a Mini-panel pane or Custom Content Pane instead of a users listing View which would other wise show an empty table and hence blank space on (in this case a Desktop browser, alternatives to be incorporated via CSS Bootstrap etc).

Should the user not have posted any content then a pane with a (vector.svg) graphic will show in place of the empty view blockspace based on the View being NULL or empty asking them to 'add some content' or maybe a vector graphic to instruct. I have looked at the Conditional View module and Rules, but nothing seems to show such options so I'm not quite sure is this my right approach.

Where and what should be my correct approach?

you will need flag module make a global user flag: user_has_content, make a rule: react on event: after saving new content of your special type, add a condition: user author is NOT flagged, inside rules action: flag it, only once your user author will be flagged, then on your view, add relationship to author & one more relationship on the new flag on author, and display content if user is flagged, make another view, display whatever you want if user is NOT flagged, this works also on D8, done.

EDIT: since you are using panels, it's easier, make 2 panes as explained, and in panels add this 2 panes, make your rules inside panels UI, display pane 1 if user is flagged, display pane 2 if user is not flagged.


Add a custom form only to a particular content type is there any way to add a form only to a particular content type so that in all nodes of my content type, say, My_Custom_Content, that form is displayed but not on any other nodes

If I'm not wrong, I think you are trying to display your custom form in the node view of a particular content type. You can do this in two ways.

The first approach is to implement hook_node_view() from the module level.

function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        if($node->type == 'your_content_type'){
            $node->content['my_form'] = array(
                '#markup' => drupal_get_form('your_form_id'),
                '#weight' => 1,
            );
        }
    }
}

The second approach is to implement hook_preprocess_node() from the theme level.

function MYTHEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    if($variables['node']->type == 'your_content_type'){
        $variables['content']['my_form'] = drupal_get_form('your_form_id');
    }
  }
}


Zero pad Drupal 7 Form API Date Control day and month HTML select element I'm using the Form API Date controls for my form, and I am wondering if there is a way to zero pad the month and day values in the HTML select elements for values less than 10 at declaration time. I am using the following render array declarations in the page callback function.

$form = array();

$form['date_from'] = array(
    '#title' => t('Date From'),
    '#type' => 'date',
);

$form['date_to'] = array(
    '#title' => t('Date To'),
    '#type' => 'date',
);

Which displays on the page as:

And creates the select element values (without zero padding):

I think you can use #date_format

  $format = 'm d Y';
  $form['date_from'] = array(
     '#type' => 'date',
     '#title' => t('select a date'),
     '#date_format' => $format,
   );

More values:
http://php.net/manual/en/function.date.php


How to use a RedirectResponse with a # (hash)? I have this code:

$event->setResponse(new RedirectResponse(base_path().'mypage#actions_clicker'));

It redirects to /mypage, but it doesn not include the #actions_clicker part. How do I make Drupal not loose the hash / # part?

Try url encoding the # fragment. so it becomes %23, e.g:

$event->setResponse(new RedirectResponse(base_path().'mypage%23actions_clicker'));

Update:

Check the browser header to see that the fragment is passed. In my local testing it was ok:

Sample code to append fragment to redirect response.

return new RedirectResponse($redirect_url . '#test', 301);

More info: https://stackoverflow.com/a/2305927/583715


CRUD operations on site from external application We have an application behind our firewall that we want to push content to a content type on our external Drupal site. Our internal application will need to create new nodes, update existing nodes, and delete existing nodes as needed. It would also have to have some kind of authentication method that would be used by the application.

What modules/process (services maybe) are best for doing this type of action on the Drupal site?
What type of custom programming will need to be done on the Drupal side to allow this?

I use a custom module to do this very thing in D7. It works like this:

The internal applications write to a transaction log (a database table) reflecting changes that will need to be added/edited/deleted on the site.
A simple API app exposes this transaction log over the Internet, with API keys.
The Drupal site reads new transaction log entries (it remembers the last log entry it synchronized) from the API then queues and makes the node changes when cron runs.

You could do something similar in D8. Or, considering Drupal 8 has a RESTful API, you could instrument your internal application to make synchronous changes to the Drupal site.


How to join the dots and reduce the dot size in scatter plot using Easychart? I am using Easychart 7.x-3.7 with Drupal 7.51. I uploaded a CSV to display a scatter chart with x-axis (1st column) and y-axis (2nd column). The size of the dots are so big. Here is a screenprint of what I have so far:

How will I reduce the size of the dots and also how will I join the dots to show it like a line?

Part of what you're asking for (= "How will I reduce the size of the dots"), is a typical example of how it is like to use a UI (= Easychart), and find out that you need some special option/facility of the Highcharts library, but which you cannot enter via the Easychart UI.

Here are some hints/directions to try to resolve that part of your question anyhow:

As you must have noticed using the Easychart UI, there is nothing (out-of-the-box) that you can use to reduce that size of those dots.
So head over to the Highcharts options reference which outlines the chart configuration options, and the methods and properties of Highcharts objects. Attention: don't get overwhelmed, there are a zillion of options ... in this case, your question boils down to plotOptions.scatter.marker.radius, which is the "radius of the point marker" (don't ask me how I know, I just do ...). It turns out that its defaults is "4". So with that your question becomes like this: How do I overwrite that default value of plotOptions.scatter.marker.radius with (eg) "1"?
To understand where we're going, first have a look at the Feature request Other chart types. It's a request about "Is it possible to use more chart types like Donut, 3d Pie, or any available HighCharts examples". So that is actually way more then just adapting the default value of "radius of the point marker". Nevertheless, comment nr 3 in that feature request contains the actual answer. The crucial part of that comment is that it contains "an example of an interface with more options than those provided by our default set". It takes some effort to digest it (what it is about), but the most important part of that sample is at the end of it, and which looks like so:

{
  "panelTitle": "Advanced Chart options",
  "pane": [
    {
      "title":"Pie/Donut",
      "options": ["plotOptions.pie.innerSize","plotOptions.pie.allowPointSelect","plotOptions.pie.depth","plotOptions.pie.cursor"]
    },
    {
      "title":"3D",
      "options": ["chart.options3d.enabled","chart.options3d.alpha","chart.options3d.beta"]
    }
  ]
}

To understand what this sample is about, have a look at the image in the next comment (nr 4), which looks like so:

As shown in the above image, by adding (near the end) those specifications about "Advanced Chart options", it is perfectly possible to add that panel with title "Advanced Chart options", and with the 2 panes titled "Pie/Donut" and "3D" (each with their related "options" also).


How to affect kernel request hostname when bootstrapping from custom PHP script I'm bootstraping from a custom PHP script using:

$autoloader = require_once 'web/autoload.php';
$request = Request::create('/');
// $_SERVER['SERVER_NAME'] = 'whatever';
// $request->server->set('SERVER_NAME', 'whatever');
$this->kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$this->kernel->boot();
$this->kernel->prepareLegacyRequest($request);

When rendering a URL from that bootstrapped Drupal, via $item->link->getUrlObject()->toString(), it has a localhost hostname:

http://localhost/sites/default/files/styles/large/public/images/pages/1.JPG?itok=gSuAsMq-

I want to change that to whatever and I've tried what is commented out in the initial block which doesn't work. I've confirmed that the $request->server->set(..., ...); does set the value though.

Any idea on how to solve this?

You need to use the HTTP_HOST instead the SERVER_NAME, also you can pass it as $server param to the Request::create()

$autoloader = require_once 'web/autoload.php';
$request = Request::create('/', 'GET', [], [], [], ["HTTP_HOST" => 'whatever']);
$this->kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$this->kernel->boot();
$this->kernel->prepareLegacyRequest($request);

Remember to add the hostname to $settings['trusted_host_patterns']


How do I render a block programmatically with the standard template? I'm using the following code to render a set of blocks programmatically:

$region_content = [];
$block_manager = \Drupal::service('plugin.manager.block');
$blocks = $this->getBlocks();
foreach ($blocks[$region_name] as $key=>$block_config) {
  $instance = $block_manager->createInstance($block_config['plugin_id'], $block_config['config']);
  $region_content[] = [
    $instance->build();
  ];
}

The contents of $block_config['config'] look like this:

[
  'provider' => 'search',
  'admin_label' => '',
  'label' => 'Search form',
  'label_display' => TRUE,
  'third_party_settings' => [
    'block_aria_landmark_roles' => [
      'role' => '',
    ],
  ],
]

The resulting $instance object seems to work correctly, and when I render $region_content I do indeed get the contents of the blocks as expected. But they are not wrapped in the block template. I thought I might have to do something like this:

$region_content[] = [
  '#theme' => 'block',
  'contents' => $instance->build(),
];

...but that doesn't work at all. How do I take this $instance object and render it using the standard block template? Or am I completely off course here?

If you want to render blocks directly from twig you can use:

Twig tweak 8.x-1.9 https://www.drupal.org/project/twig_tweak

You just need to install it.
The block should be configured on "admin/structure/block" page.
Example how to use:

Block:

{{ drupal_block('system_powered_by_block') }}

Add this code directly in the twig template file.


How do you turn off comments, by default, for a module defined content type? I have a D7 module, which defines a content type, via the appropriate hooks.

By default, comments are turned on for my content type. How do I set the default to off, inside of the code of my module? (NOT through the Drupal interface)

Thanks in advance.

These instructions will enable you to identify and set any variable you'd like in Drupal 7. Please feel free to ask for clarification.

I'd start by installing the Devel module so you can see the variable you need to set. This will allow you to inspect the array where this setting is defined.

Visit a node of the content type you're working with. You'll see a tab called "Devel". Follow it and you'll be able to see the array which defines a node of this content type. There should be a value called "Comment", and I believe it needs to be set to "1" to disable comments.

As a sidenote, the Features Overrides module does this by setting
$overrides["variable.comment_mycontenttype.value"] = '1';

But, since we're not using that module, we'll set it manually.

You should be able to define that variable inside your module code by using the variable_set() function.

That code can live inside hook_update_N(), which is executed when update.php is run. Simply add the code for your update hook inside your custom module and run update.php on your site.


Views pager in a panel page I created a view to show a nodes image field (unlimited values) and placed that views block into a panel page region. For some reason the pager doesn't show up. I googled around but cant see any others having these issues. All the associated images are shown on the page instead of the 6 i set up in views.

Well, just after posting here i went back to the problem. Turns out i only had to check off the "Display all values in the same row" in the "Multiple field settings" section of the field in the view. Pager showed up now.


How to connect panel and translated panel after 'Add translation' node? I translate the panel node by selecting Add translation. After doing this, I setup the panel title, layout etc. Press save, but I then end up with two nodes which aren't connected, ie. switching languages doesn't work. Then, going to the translation still shows the 'Add translation' link! This isn't the case for my other content types.

The only way around this at the moment is to manually couple the two translations together by entering the translated node's title in the 'SELECT TRANSLATIONS FOR' autocomplete search field.

Does anybody know how to solve this problem?

Maybe too late, but just in case you still need it: http://drupal.org/node/1994046


Order of facets block change after the research I'm new in Drupal and I have a problem when I use search ajaxified with search api and facet block.

My research works fine: When I click on the facet block that contains tags for example, my results are fine. After, my block are not anymore in the same order than before.

For instance, before I click on one tag, the order are like this (all my blocks are in the left sidebar and so in the same region):

navigation
Facet API: content type
Facet API: Tags
Saved search

After the reseach in Ajax:

navigation
Saved search
Facet API: content type
Facet API: Tags

All my Facets blocks are now at the bottom.

I followed all the instructions on Drupal.org given by the author of the module, and they worked fine, I just don't understand why my facet block are not in the same order after the ajax search. I've been trying for a couple days and cannot figure out a cause for this. Has anybody encountered this before?

Maybe I need to create another region to put only my facet block in, but I think there must be a better solution than that.

It may not be the block weights, but just in case, can you see what I mean by making sure they're distinct.

Verify the below and see if you still have the same issue:


Feed content type field with configuration value I have a config form with several config variables where i save some user preferences like «position» or «weight»

Now, at the moment of generating a content type i want to feed a select field with the «position» config formerly mentioned saved values as options for this field.

I saw i would may create a reference field as a view reference. So i guess i would do before a view printing those values, but i guess if there is a more convenient way to do this.

I prefer to do it without code, using the gui.

PS: I'm doing this with a simple config form, for customer's reasons i can not use Configuration Entity Types :-/

finally, I decided to do a custom autocomplete for the field with a validation in the form submission :-S


"is-active" class on all menu levels My main navigation menu is visually split as in the picture:

Level 1 is visualised in the upper-right corner, level 2 below.

Technology (like all the current items in level 2) is child of About.

In the screenshot, Technology has been assigned the class is-active. Is there a way to also assign it to About? In other words, I would like the entire active branch of the menu to be displayed as active.

You can achieve that by using the Menu Trail By Path module.

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

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

  blog blog/category1 blog/category1/article1

  8.x-1.x branch

  8.x-1.x branch is completely rewritten. It should be compatible with any menu.


More filter options on admin/content Is there a way to have more/advanced filters on https://example.com/admin/content using Drupal 8? Like filtering for taxonomy terms or fields for example?

Yes. Now that Views is integrated into Drupal 8, the admin/content display can be driven by a customizable View.

Make sure the Views/Views UI module is enabled in admin/modules, then navigate to admin/structure/views. You'll see a View named Content which corresponds with admin/content. You can edit that view to add various exposed filters that correspond with your own content setup (e.g. custom taxonomy filtering).


Hook to trigger when a field collection item is being deleted I have create a module and I am using the following hook implementation.

The code works on success, but how do I prevent or stop further processing when I get failed as status?

mymodulename_field_collection_item_delete($field_collection_item) {
   $itemID = entity_id('field_collection_item', $field_collection_item);
   $fc = entity_load_single('field_collection_item', $itemID );
   $pid = $fc->field_product_guid['und'][0]['value'];
   $responseAPI = json_decode(deleteProductRequestAPI($pid,"DELETE"), true);
   if($responseAPI['status']=='success'){
     drupal_set_message(t('Is successfully deleted.'));
   }else{
     drupal_set_message(t('Failed to deleted.'));
   }
   die;
}
// here curl request sending
functin deleteProductRequestAPI($pid,$method){
  // here i have written code for send request and will
  // get response in status as "success" or "failed".
}

The field Collection name is Products and the content type is Brands.

What you should do instead of an API call on delete is create a job with the QueueAPI in Drupal to create a job for processing later. In that job, pull the ID from the record (stored in the job) and do the API call. If the status failed, requeue the job.

I can’t write all the code out for you but there are plenty of QueueAPI examples for D7 out there.

https://api.drupal.org/api/drupal/modules%21system%21system.queue.inc/group/queue/7.x

and

https://rbayliss.com/blog/drupal-queue-api/

Are great starting points.

You could then create a custom Drush command that processes  these jobs as fast as you desire. Note the section in rovs post that deals with “failed” states of a job and not removing it from the queue. That is key.

This will let Drupal function normally and defer errors in the remote system to you to work through.


Using Context, can I (programiatically) move the page's menu to a different region? Using Context, can I move a node's menu to a different region?

Or more specifically, from inside hook_context_page_reaction(), can I get access to the page's render array to move items between regions?

I'm working with this below.

/**
 * Implements hook_context_page_reaction().
 */
function context_movemenu_context_page_reaction()
{

    $node = node_load(menu_get_object()->nid);
    if ($plugin = context_get_plugin('reaction', 'context_movemenu')) {
         $plugin->execute();
    }
}

and using this execute() method. I'm just dumping all incoming args to see what I can send over.

function execute() {
   dpm(func_get_args());
}

Am I approaching this from the wrong location? Ideally, this sites has most of it's configuration in context. The site owner likes that workflow.

You could place all blocks in template_preprocess_page with

$variables['page'][$region_key] = array();
$variables['page'][$region_key][]['#markup'] = $region_content;

Seeing your edit, you can check for the plugins blocks like this

$context_content_bottom = array();
  $blocks_content_bottom = array();

  // Blocks that are assigned to the region using Context
  if ($plugin = context_get_plugin('reaction', 'block')) {
    $context_content_bottom = $plugin->block_get_blocks_by_region('content_bottom');
  }

  // Blocks that are assigned to the region using the blocks interface
  if ($blocks = block_get_blocks_by_region('content_bottom')) {
    $blocks_content_bottom = $blocks;
  }

  // Merge them together
  $vars['region']['content_bottom'] = array_merge($context_content_bottom, $blocks_content_bottom);

Taken from here

but why not do it in the UI ??
just place the block several times under opposed conditions


How to add custom Jquery in drupal module? I have created a custom module in drupal 7. The module creates a form for user and store the  form's data into database. The module is working fine. But I want to add a custom jquery for the page. I searched Google and find the result for adding custom JQuery for theme not for modules. I guessed and add the following in my module's  info file

;scripts
scripts[] = js/test.js

Just alert a "hello" word while the module will load. But nothing is happened. Is this possible to add custom Jquery for a module or I am doing wrong? Please help.

There are several ways of adding JS to your module, you can check them here https://www.drupal.org/node/756722

Your attempt should work fine, just don't forget to clear the caches after editing module's .info file.

Cheers!


Autocomplete widget - save id of suggested and accepted value I'm writing a custom text field and widget module with ajax autocomplete from scratch. I want the lookup to work on one column, but I want another column's value (the looked-up item's id) to be saved as the field value in the node.

So, for example, user types for example Sams, they accept suggestion Samsung, but Drupal save its database identifier, say 145.

Conversely, when opening the node for editing, the saved value of 145 should be again looked up, converted and displayed as Samsung.

What is the key to get it working the Drupal way?

Use the Entity and Entity Reference modules to create the link between the two items, using this method means your selections will be available to other modules such as Views, Rules, etc.


fetching records from webform_submitted_data table through following source code but showing error How to display the records from the table by using the following source code?

  Notice: Undefined offset: 0 in eval() (line 20 of /var/www/module(80)
  : eval()'d code).

<?php
include_once(drupal_get_path('module', 'webform').'/includes/webform.submissions.inc');
$query = db_select('webform_submitted_data', 'u');
$query->fields('u', array('sid','nid','data'));
$query->condition('nid','159','=');
$results =$query->execute();

echo "<table>";
echo "<tr>";
echo "<th>  Profile Photo </th>";
echo "<th> Faculty  Name and Department  </th>";
echo  "</tr>";

if ($record = $results->fetchAssoc())
{
$sid = $record['sid'];
$nid = $record['nid'];
$submission = webform_get_submission($nid,$sid);
echo "<tr>";
echo $val = $submission->data[15][0];
}
?>

Try below code,

You can retrieve node webform all submissions using  webform_get_submissions which accepts an array of filters.. As per the error you mentioned in the question seems like below code is causing problem

echo $val = $submission->data[15][0];

I would suggest printing the information that you got before you try to fetch the data so that you know you are correclty accessing the array results.. print_r will assist you to see the results..

module_load_include('inc','webform','includes/webform.submissions');
$submissions = webform_get_submissions(array('nid'=> 159));

foreach ($submissions as $submission){
    foreach ($submission->data as $row=>$data){
        print '
';print_r($row);print '
';
        print '
';print_r($data);print '
';
    }
}

Extract the information you want from $row and $data ...


How do you create a variable from hook_preprocess_page() that will be available to a node template? I have this in my module "spot":

function spot_preprocess_page(&$vars) {
  $vars['social'] = 'hi';
}

Other things I set in this function come through fine. But my node--spot.tpl.php template is complaining that the variable does not exist:

  Notice: Undefined variable: social

I have cleared the cache.

What am I doing wrong?

How do you create a variable from hook_preprocess_page() that will be available to a node template?

You cannot.
The parameter passed to hook_preprocess_page() (what you define as &$vars) is not the same parameter passed to hook_preprocess_node(), which means that if you set $vars['social'] in the first, it is not passed to the latter. If you need to pass a value to the node template file, you need to set it in hook_preprocess_node(), or hook_process_node().


How to create a view block for comments with nesting and parent relationship I'm trying to display the comments on my nodes in a view rather than using drupals default comments rendering.

Is it possible to display a comment view on a node, which also renders the comments with replies, rather than rendering every comment (including replies) as a top level comment?

How would you setup views to do this?

UPDATE

I've successfully setup views, so that it renders comments and replies in the correct order.

You have to set:

Relationship -> Comment: Parent Comment
Sort Criteria -> Thread (desc)
Sort Criteria -> (Parent Comment) Comment: Post date (asc)

However the pager still counts every single comment reply as an item, so it is prone to cutting off threads in the middle and ideally I'd still like to page it.

ORIGINAL WORKINGS

What I've tried to do so far -- Show: Settings: Parent relationship

Getting the top level comments was reasonably easy, I created a view block which displays comments and then added:

Contextual filter -> Comment NID (Content ID from URL) (Shown here)

This gives a me a view block which will display comments. However all the comments are rendered as top level comments (no indented markup)

I needed the parent relationship, so I added a second relationship (comment views by default have a Comment: Content relationship),

Comment: Parent Comment

And then under Format: Show: Settings, I enabled:

Relationship: Parent Comment

Unfortunately on loading the node, this causes several PHP errors. views_plugin_row_comment_view.inc has a pre_render function and for some reason changing the Relationship: Parent Comment causes none of the CID's to load in the pre-render function and so it spits out all the horrible errors you see below. How am I setting this up wrong?

Undefined property: stdClass::$cid in views_plugin_row_comment_view->pre_render() (line 79 of ... sites\all\modules\views\modules\comment\views_plugin_row_comment_view.inc
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of C:\xampp\htdocs\basic\includes\entity.inc).
Notice: Undefined index: in template_preprocess_views_view_row_comment() (line 645 of C:\xampp\htdocs\basic\sites\all\modules\views\modules\comment.views.inc).
Notice: Trying to get property of non-object in template_preprocess_views_view_row_comment() (line 646 of C:\xampp\htdocs\basic\sites\all\modules\views\modules\comment.views.inc).
Notice: Undefined index: in template_preprocess_views_view_row_comment() (line 646 of C:\xampp\htdocs\basic\sites\all\modules\views\modules\comment.views.inc).
Notice: Trying to get property of non-object in template_preprocess_views_view_row_comment() (line 650 of C:\xampp\htdocs\basic\sites\all\modules\views\modules\comment.views.inc).
EntityMalformedException: Missing bundle property on entity of type comment. in entity_extract_ids() (line 7729 of C:\xampp\htdocs\basic\includes\common.inc).

What I've tried to do so far -- Sort: Comment Threading

I took a look at the following sandbox module and according to the issue thread it was based on https://drupal.org/node/1039494, apparently it was solved ages ago by adding in a sort criteria Comment: Thread.

I tried adding this and setting the relationship to parent comment but this also had no effect, the comments still remained in separate rows. Has anyone had success with this method?

I recommend installing the Views Threaded Comments sandbox module.

  Provides Threaded comments views plugin

I'm a developer, so I'd start there ... if you're not a developer you may not find a sandbox project as a good starting off place, your mileage may vary.


Cannot get value of Node object I'm trying to retrieve a value from a Node object. It looks like the value is there, when debugging and checking out the object. But somehow it cannot be accessed.

Trying to get the field:

// $this->entityManager is an instance of EntityTypeManagerInterface
$node = $this->entityManager->getStorage('node')->load($nodeId);

// hasField always returns FALSE
$node->hasField('field_google_hire_identifier');
// $node->get('field_google_hire_identifier'); returns unknown field error

Debugging $node->hasField, looking inside getFieldDefinition:

  public function getFieldDefinition($name) {
    if (!isset($this->fieldDefinitions)) {
      $this->getFieldDefinitions();
    }
    if (isset($this->fieldDefinitions[$name])) {
      // This code should be executed, but it is not.
      return $this->fieldDefinitions[$name];
    }
  }

The second if statement content is not executed, with my understanding it should be.

The node was created with migrate.

I disabled APC and Opcache.

The field name string contained a right to left mark.
See https://stackoverflow.com/questions/54653637/cannot-get-array-key-array-key-not-set/54655517#54655517 to find out how to remove it


Can I hide a webform? I would like to pilot a webform for a period of time and have the option to hide it vs. delete if needed. How do you hide a webform from your site?

In Drupal 8, you can archive your webform if it's closed.

To close your webform, go in the settings of your webform in the "Form" tab. You can schedule the closing too.

When it will closed, you will have the option to archive it in the "General" tab of its settings.


How to change the word "blog" for "journal" I have used string overwrites for a lot of stuff but sometimes I hit a section I cannot change. One of these is the "User's blog" button. How do I change the word "blog" for "journal"? I am impressed no one seems to have asked this question before.

There is String Overrides module.

Provides a quick and easy way to replace any text on the site.

Features
Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.


Display main menu item based on the URL I want to show main menu links in the sidebar. I have placed that menu block in sidebar region from admin side.

But based on the current URL, i need to display that particular menu item.

Item1 (item1)
  Item1_Sub1_item1 (item1/sublev1)
     Item1_Sub1_Sub2_item1 (item1/sublev1/subsublev1)
     Item1_Sub1_Sub2_item2 (item1/sublev1/subsublev2)
  Item1_Sub1_item2
     Item1_Sub1_Sub2_item1
     Item1_Sub1_Sub2_item2
Item 2
  Item2_Sub1_item1
     Item2_Sub1_Sub2_item1
     Item2_Sub1_Sub2_item2
  Item2_Sub1_item2
     Item2_Sub1_Sub2_item1
     Item2_Sub1_Sub2_item2

If the current url is / (home), then my menu should diplay all menu item
If the current URL (item1/sublev1) match to menu item (Item1_Sub1_item1) then only the parent and child of that menu should be displayed as below

Item1 (item1)
  Item1_Sub1_item1 (item1/sublev1)
     Item1_Sub1_Sub2_item1 (item1/sublev1/subsublev1)
     Item1_Sub1_Sub2_item2 (item1/sublev1/subsublev2)

If the current URL (item1/sublev1/subsublev1) match to menu item (Item1_Sub1_Sub2_item1) then only the parent and child of that menu should be displayed as below

Item1_Sub1_item1 (item1/sublev1)
  Item1_Sub1_Sub2_item1 (item1/sublev1/subsublev1)

I have overridden the menu--main.html.twig file using theme suggestion and using menu--main-sidebar.html.twig file to design the menu.

Any idea how to achieve this? My guess is,

I need to create a block programmatically to do all these operations
Display that block in my html.twig.file

If I am right, how to do that in theme? If i am wrong, what else need to do?

For info I am already using Menu_block module, but I can't place block for each URL. So i want to program it.

Yeah, I think your guess is good.

Create a block programmatically: Create a custom Block. This means to create an own module with this block.
The created block should appear (when the module is activated) in your block settings, there you can add it.
The content of your block appears where you added it.

Another option, easier but not so beautiful, could be to hook in your THEME.theme. As an example you can add the menu in the  template_preprocess_html:

function template_preprocess_html(&$variables) {
    $variables['my_own_menu'] = $my_own_menu;
}

Then you can use the variable {{ my_own_menu }} in your html.html.twig and do whatever you want to do.


Import soap webservice xml to node with Feeds? I have a soap web service which requires authentication to access its various function. I want to call one function of this web service and import that XML to node in Drupal with feeds module.

I am not finding any example of authentication from the Feeds module.

I assume you have no access to change the feed provider.

There are couple of additional contributed modules which handle different types of authentication for the feeds module.

This handles regular http authentication, which is more likely with soap:
https://www.drupal.org/project/feeds_httpfetcher_aa

and this one is for oauth which ia also possible with soap:
https://www.drupal.org/project/feeds_oauth


Views OOP approach - Let Views extend from Meta/Parent View Hej.

On my Drupal Site I have several slider, all of them have the most in common but could differ in some way.

I'd like to have a View as Meta/Parent View so that if something is changed it will be changed in the Child Views as well. But every Child View could have their own attributes or adaptions.

I know there is the Display Section in the View but if I add a View or Display and change something, it effects every view even the Master Display.

Is there something like a View OOP approach in Drupal?

When you change something on any of the different displays (other than master), there should be combobox at the top that says "for" which defaults to "All Displays" meaning that the change will apply to all displays. But you can select "This Block" or "This Page" so that the change only happens to that particular display.

Also, if you go into views settings "admin/structure/views/settings" you can set "Always show the master display" which I usually do.


Apply Modules to Previous Posts I've recently imported my articles from another database (custom format) and I'd like to apply modules (like Colorbox and other such output-related modules) to those previous posts. Is the standard behaviour to allow this sort of thing, or am I supposed to manually adjust all previous posts?

I've only ever worked with WordPress before, and their plugins work on all articles (past and new).

For colorbox to work on your new posts, you need to edit the content type(s) of your new posts

Home » Administration » Structure » Content types » YourContentType

Click on "Manage Display". Here, you can choose the format "Colorbox" for the image field (and click that modal to customize, etc). It will be applied to all nodes of that content type.

Of course, you'll first have to install the colorbox module and library.

The same principle applies to other modules.

About posts/nodes and content types:

Typically, there are only very few content types configured in Drupal - by default there are "article" and "basic page", but you can create more as you need them.

You would import your old post into drupal using one or very few different content types.

The changes need to be done for the content type, meaning they'll get applied to all nodes (posts) in that content type.

You need to look which content type to imported your nodes (posts) into. When you go to http://www.example.com/admin/content, you see a list of your nodes, and in the "Type" column the content type.

Then you go to http://example.com/admin/structure/types/manage/yourcontenttype/display and manage the display as outlined in my answer.

For the article content type, this would be:
http://example.com/admin/structure/types/manage/article/display

Of course, you need to change example.com to your url.


Unable to send email local configuration problem I'm getting strange email errors on User Registration, when a user creates an account on my website, it emails them a link to activate their account, however, its started showing errors at the top of the email as shown below. I had everything working fine, emails going out, now i get these errors and Im not sure what I have changed to cause this. I did install the Honeypot module and Captua module last night (also have User Registration Password), but Im sure I tested afterwards and it was working fine. Any ideas? I have changed the email addresses below to make them anonymous.

On 8 Feb 2016, at 13:23, Mail Delivery System  wrote:

A message that you sent was rejected by the local scanning code that checks incoming messages on this system. The following error was given:

local configuration problem

------ This is a copy of your message, including all the headers. ------

Received: from 707134 by linweb.ahost.me with local (Exim 4.80.1)
   (envelope-from )
   id 1aSlmr-0003aW-L4
   for yyy@gmail.com; Mon, 08 Feb 2016 13:23:29 +0000
To: yyy@gmail.com
Subject: Account details for testuser at zzz Club
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes
Content-Transfer-Encoding: 8Bit
X-Mailer: Drupal
Sender: xxx@icloud.com
From: xxx@icloud.com
Message-Id:
Date: Mon, 08 Feb 2016 13:23:29 +0000

testuser,

Thank you for registering at zzz Club. You may now log in and
verify your account by …..

This was resolved by setting up a 'anything@mydomain.co.uk' with my host, and setting this to my email address under Configuration/Site Information, and also under the settings for the Trigger rule I set to send an email when a user is created.


Drupal 7 Views Change the Query String I have a complex View that needs to utilize multiple contextual filters. Currently to access the filters I need to separate the values with a "/". I'm attempting to code a solution that passes arguments to a View (via URL) and it would be ideal to have the query string look like this:

http://www.example.com/query?nid=1450&tid=543

vs (the current way)

http://www.example.com/query/1450/543

so that I can better parse this. How can I get a View to accept parameters like this?

What you're actually saying is that you don't want contextual filters, contextual means that you want an argument based on the context of the site which is usually separated out by the url.

The quickest way to do what you want is this.

move your contextual filters into the filters section of views,
making sure that you expose them to visitors.
Under the more setting of each filter is where you set the filter
identifier and change the advanced options to label the filter as you
require such as "nid" then your url would be
mywebsite.com/page?nid=xxx
Then under the exposed form settings, change the setting to "expose
form as block" to yes to make the exposed filters disappear.


Drupal 7 Search results have no theme or format (no HTML) I have a Drupal 7 installation with about 10 custom types and a custom theme. I have a search form in the site's header displayed with

$block = module_invoke('search', 'block_view', 'form');
print render($block);

This code is in an include file called by my page.tpl.php, it's not actually inside a block.

If there are no search results, the search page displays (mostly) correctly and it uses the search-results.tpl.php template in my theme.

However, if there are search results, I get an unformatted page.  It's just the search results (with their associated HTML p tags, etc.) with no site HTML.  No head tag, no body tag and none of the custom theme's HTML.

By using advanced search, I have identified, specifically, that one of my custom types is causing this issue.  The confusing thing is that this type just has a title and a body text.  Other, more complicated types are not causing this issue.  When I limit it by type, I get the correct output.

How can I get the search results to show up on a regularly themed page?

EDIT

I have also tried:

echo drupal_render(drupal_get_form('search_form'));

I don't know if this will help anyone; but, just in case, here is the solution to my problem.

One of my content types (the one causing the issue) is only viewable in the public site via ajax.  As such, I had this code in my function *mytheme_node_view_alter(&$build)*

//show only output for popup
if($build['#node']->type=="blue_pop_up"){
    echo $build['#node']->body["und"][0]["safe_value"];
    die();
}

This was breaking my search results page when it found content of this type. I simply added this to the code:

//show only output for popup
    if($build['#node']->type=="blue_pop_up")
    {
        if($build["body"]["#view_mode"] != "search_result")
        {
            echo $build['#node']->body["und"][0]["safe_value"];
            die();
        }
    }


Bad request with Acquia Dev Desktop2 overriding installation I use Acquia Dev Desktop2 on Mac for php7.0.
I think that it is the previous version.
I was waiting for the upgrade to use php7.1, but there was no announcement in check for update menu.
I have no choice, so I downloaded it and overwrite install.
The bad request will be displayed on all local sites.
Phpmyadmin of all sites will be displayed correctly.
What is the solution?

What I can think of is using underscores for site addresses.

test_drupal8_mockup1.dd:8083

In order to remove the underscore, I edited vhosts.conf and restarted apache.
'But request' was not improved.

As an alternative solution, I tried to add the following setting setting to httpd.conf.

<IfVersion> = 2.4.25>
 HttpProtocolOptions unsafe
</ IfVersion>

'Bad request' message is solved.
The reason was that ServerName contained underscores.


"IMCE Uploader" module is preventing some file types from being uploaded within IMCE I have downloaded and enabled the "IMCE Uploader" module at https://drupal.org/project/imce_uploader

This module allows you to within IMCE to upload multiple files at one time and is working better than the "IMCE plupload" module which I have found has corrupted some files after uploading.

I have configured the Media browser settings at /admin/config/media/browser to include a lot of file types (including jsonp, docx and xlsx) and without having the "IMCE Uploader" module enabled they all display when trying to do an upload within IMCE.

After enabling the "IMCE Uploader" and "IMCE Uploader - Plupload" modules I have noticed that some file types like jsonp, docx and xlsx are not allowed anymore when trying to do an upload within IMCE.

Is there any way that I can allow these additional file types to be uploaded within IMCE when using the "IMCE Uploader" and "IMCE Uploader - Plupload" modules?

I am thinking that perhaps your allowed file types has changed in your IMCE profile, or IMCE Uploader has created a new profile for you and is using it by default. Check admin/config/media/imce/ and make sure the profile you are using allows those file types.


Update database to Drupal 6 to Drupal 7 I upgraded my website to D6 to D7 successful but only with the development version (not in production) and I've new datas in production since (Drupal 6). So I'm wondering the best way for update the Drupal 6 database to the Drupal 7 database.

You could migrate DB data with the Migrate module (though it's not very light module and has an individual learning curve, so if you are not a programmer, or not yet, it might be better for you to find a Drupal programmer that will help you run it). Otherwise, if the site is small (i.e has only several or about fifteen pages) I would suggest of building it from the start... In most cases it shouldn't take much time..

Blessings,


Redirecting based on parts of URL Is there a module for Drupal that would allow me to perform redirects based on parts of the URL?

For example, if the URL contains this-string-to-redirect, e.g. example.com/this-string-to-redirect/node/content, then redirect to another path.

If you want to do this yourself, quick and dirty, it would be something like this:

function yourmodule_init() {

  $foo=drupal_get_path_alias($_GET['q']);
  $bar=explode('/',$foo);

  if ($bar[0]=='this-string-to-redirect') {
    $bar[0]='redirect-me-here';
  }

  $baz=implode('/',$bar);

  drupal_goto($baz);

}

You might also want/need to throw in a weight of -1 to make sure your module runs early by putting:

function yourmodule_install() {
  db_query('UPDATE {system} SET weight = -1 WHERE name = "yourmodule"');
}

in yourmodule.install but a quick look just now shows globalredirect's weight at the default of 0 so this may be unneeded.


Page template for specific path: page--about.html.twig I have a page with the path /about that I would like to have a different page layout from the rest of the site.

I have created page.html.twig as my general page template, and page--about.html.twig as the template for this specific page. Both files are in the /templates directory of my theme. However, only the general template is getting used.

Yes, I have cleared the cache.

Appreciate any help!

James

You don't say if /about is a different content type or just a node.

If it's a node, you need to use the format:

page--node--1.html.twig

Replace 1 with the about page node id.  See the d.o. page for reference info.

If you are trying to have a template for an about content type.  You need to add code to your theme like this:

function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Add content type suggestions.
  if ($node = \Drupal::request()->attributes->get('node')) {
    array_splice($suggestions, 1, 0, 'page__node__' . $node->getType());
  }
}

See this d.o page for more info.


Multiple Values in Custom Template Field I have a custom template for a node, and a field which has the possibility of having multiple pieces of data. In this case:

There is an Author node
There are Publication nodes
Publications are being Entity Referenced on the Author node

The custom template then prints the publications to the node

<?php print render($content['field_publications']); ?>

I know that adding ['1'] displays the first publication if multiple publications are attached to the same author, however, how would I display the top 5 publications, if say, there was 10 publications by the same author?

Slice the array?

foreach(array_slice($content['field_publications'], 0, 5) as $field_publication):


How to check with the Rules module if a user has a custom picture? I'm using the Rules module, and I have a rule with these Rules Events:

After saving a new user account
After updating an existing user account

Within the Rules Conditions, I try to put "Data value is empty" -> account: (I don't found "picture", "image" or any of this)

I have: admin/config/people/accounts user images [check]

Any idea how I can check if the user has used a custom image?

Here's what I did, using a quick custom module to define and evaluate the condition that a user has uploaded a custom image to the core-provided Picture in the user account.

Module name: mymodule

This goes in mymodule.rules.inc:

/**
 * Implements hook_rules_condition_info()
 */
function mymodule_rules_condition_info() {
  return array(
    'mymodule_condition_user_has_picture' => array(
      'label' => t('User has picture'),
      'parameter' => array(
        'account' => array(
          'type' => 'user',
          'label' => t('User account')
        ),
      ),
      'group' => 'User',
    ),
  );
}

/**
 * Evaluates condition user_has_picture
 */
function mymodule_condition_user_has_picture($account) {
  if ($account->picture == NULL) {
    return false;
  } else {
    return true;
  }
}

Note that I've chosen to make the condition positive (returns TRUE if picture is found). If you want the condition to return true when the picture is NOT found, use the Negate option found in Rules.


Error when trying to migrate comments to a clean D8 site: What's wrong with my .yml file? I'm trying to migrate content from my current D7 site to a Drupal 8 installation.

I've managed to import some of the nodes, and now I want to import the comments for those nodes.

Every time I click on "run" (.../admin/structure/migrate/manage/importarComentarios/migrations/importar-comentarios/process/run) I get an error:

What am I doing wrong?

This is my migrate_plus.migration.importarComentarios.yml file:

id: importar-comentarios
label: Comments

migration_tags:
  - CSV

migration_group: importarComentarios

source:
  plugin: csv
  path: 'public://csv/exportar-comentarios-genericos.csv'
  header_row_count: 1
  delimiter: ','
  enclosure: '"'
  keys:
    - id
  column_names:
    0:
      nid: 'nid'
    1:
      created: 'created'
    2:
      body: 'body'
    3:
      autor: 'autor'
    4:
      cid: 'cid'
    5:
      titulo: 'titulo'
    6:
      mail: 'mail'

destination:
  plugin: entity:comment

process:
  entity_id: nid
  subject: title
  'comment_body/value': body
  'comment_body/format':
    plugin: default_value
    default_value: "html"
  # Migrate our custom field
  field_mail: mail
  field_nombre: autor
  status:
    plugin: default_value
    default_value: '1'
  created: created
  nombre: autor
  email: mail
  # The comment type (aka the comment's bundle).
  comment_type:
    plugin: default_value
    default_value: 'comentario'
  # The type of entity we're attaching this comment to.
  entity_type:
    plugin: default_value
    default_value: 'node'
  # The field we should attach this comment to. This is a field on your node.
  field_name:
    plugin: default_value
    default_value: 'comentarios'

migration_dependencies: {}

And this is the migration overview:

This is the overview

This is the destination

This is the process

And when clicking the source, I get:

  The website encountered an unexpected error. Please try again later.

My configuration is:

My content type is called contenido

And these are the fields of my comments

And my contenido content type has a comentarios field for comments

keys:
    - id

The yml is using a key 'id' that is not defined in the column_names. Since you have a 'nid' column, I suggest changing 'id' to 'nid'.


how to get individual classes for each menu list items I am theming my website and used the following code to print my main menu.

<?php
 $main_menu = variable_get('menu_main_links_source', 'main-menu');
 $tree = menu_tree($main_menu);
 print render($tree);
?>

Now, I need to have individual class name of each list item, so that I can call different background images using css. I would like to have class with name 'menu-497' as shown in screenshot. I couldn't figure out how this is done. Please help.
Old code which used to load individual list class is below. But this code won't load submenu, so I am not using it.

<?php print theme('links__system_main_menu', array(
  'links' => $main_menu,
  'attributes' => array(
    'id' => 'topNav',
  ),
)); ?>

It looks like you need Menu attributes module:

  You should use this module when

  You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site
  You want to give a menu item an ID so you can easily select it using jQuery
  You want to add additional classes or styles to a menu item

Alternatively, if you don't mind some coding, see theme_menu_link(). Comments in it's documentation already shows how to do it:

   function superseven_menu_link(array $variables) {
     $variables['element']['#attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];

     return theme_menu_link($variables);
   }


View with Colorbox triggered galleries How can I create a view that consists of images that trigger a gallery of images (grouped by node ID) in a colorbox?

This how you can create a Views gallery that consists of images that each trigger a Colorbox gallery (with grouped images).
This can be done with a pure views approach.
Install the Image URL Formatter module and create a basic view (filtered by the desired content type) with the following fields:

Content: Nid
Content: Images (your field with images)
Content: Images (the same field, again)

Configure the fields as follows:

Content: Nid

Check "Exclude from display"

Content: Images (the first field, which will be the visible cover image)

Formatter: Image URL
URL type: Absolute file path
Multiple field settings: display "1" value(s)
Rewrite results:

Content: Images (the second field, which consists of links to the other images)

Formatter: Image URL
URL type: Absolute file path
Multiple field settings: display "all" value(s) starting from "1"
Rewrite results:

I'm sharing this because I couldn't find any reference myself (this approach didn't do it for me).


Debugging Module Show PHP Errors I saw in a YouTube video someone had made a configuration where if there was a PHP bug in their module, upon cache rebuild it would show the error underneath the "The Website Encountered an Unexpected Error" screen.

I've been running dual screens monitoring the php error log - but would actually prefer to consolidate it into that one screen.  Where is that configuration option found?

You need add $config['system.logging']['error_level'] = 'verbose';

in file

sites/default/settings.php

or in {example}.com/admin/config/development/logging
you checked in All messages after click to Save configuration


Entity Translation for custom entity I've created a custom entity and in the next step, I would like to use the Entity Translation module to make the entity translatable.

My entity is defined like this

/**
 * Implements hook_entity_info().
 */
function MY_MODULE_entity_info() {
  $info['custom_entity'] = array(
    'label' => t('Custom Entity'),
    'base table' => 'custom_entity',
    'module' => 'MY_MODULE',
    'uri callback' => 'custom_entity_basic_uri',
    'controller class' => 'EntityCustomController',
    'fieldable' => TRUE,
    'entity keys' => array(
      'id' => 'qid',
      'label' => 'title',
    ),
    'translation' => array(
      'entity_translation' => array(
        'default settings' => array(
          'default_language' => 'de',
        ),
        'base path' => 'my-path/%custom_entity',
        'view path' => 'my-path/%custom_entity',
        'edit path' => 'admin/my-path/%custom_entity/edit',
        'translate path' => 'my-path/%custom_entity/translate',
        'path wildcard' => '%custom_entity',
      ),
    ),
    'static cache' => FALSE,
    'bundles' => array(
      'custom_entity' => array(
        'label' => 'Custom bundle',
        'admin' => array(
          'path' => 'admin/structure/custom/manage',
          'access arguments' => array('administer custom entities'),
        ),
      ),
    ),
    'view modes' => array(
      'full' => array(
        'label' => t('Full'),
        'custom settings' => FALSE,
      ),
    ),
  );
  return $info;
}

With this definition, my custom entity appears in the Entity Translation admin view (admin/config/regional/entity_translation) and I can configure it. This seems to be correct, because in the 'manage field' tab, the language selector field appears and the 'translate' tab appears also in the edit form.

The only strange thing I found is that the language selector is not rendered in the edit form in any time. If I save the translation, the source entity is overriden with the changes, but no translation is added.

I thought the problem is my Controller class, but this seems to work correctly too:

class EntityCustomController extends EntityAPIControllerExportable {
  public function create(array $values = array()) {
    $values += array(
      'created' => REQUEST_TIME,
      'type' => 'custom_entity',
      'qid' => 0,
      'bundle_type' => 'custom_entity',
      'title' => '',
    );
    return parent::create($values);
  }

  /**
   * Save Task Type.
   */
  public function save($entity, DatabaseTransaction $transaction = NULL) {
    parent::save($entity, $transaction);
  }

}

In my custom edit form, I use field_attach_form function to render all the defined themes.

And, if it helps, this is my save handler:

/**
 * Save entity by using the controller.
 */
function MY_MODULE_custom_entity_save(&$entity) {
  return entity_get_controller('custom_entity')->save($entity);
}

In my case the issue ended up being pretty simple to fix. I found that the function entity_translation_form_alter() was testing to see if my entity's edit form was suitable for alteration. My edit form failed the very first test because entity_translation_edit_form_info() was returning false.

entity_translation_edit_form_info() was returning false because my form didn't have $form_state[$entity_info['translation']['entity_translation']['edit form']] set and set to the entity I was trying to edit.

tl;dr: Make sure you set a value in your edit form's $form_state at the path you declare in the edit form element of the settings array for your entity returned by your implementation of hook_entity_info().


How to redevelop a production site? I'm working on a local version of an outdated Drupal 6 site which can not be shut down for a minute. The goal is to update the modules and give some enhancements, like adding tags, making a better menu and dynamic blocks etc with the least  possible down time for the site.

It will probably take a few weeks for me to do so. Meanwhile new content will be added to the production site as per usual.

My question is: When I finish developing the requested enhancements on local version, how should I integrate newly generated content to the development version before putting it online? I can not simply import the production database dump since this will undo my whole work. So obviously I need to import only certain tables. But how should I figure out which ones? What would you do in this situation?

It depends on what the enhancements you are making but the way I've done this same process before is to export the finished code improvements to a features module or other custom module from my dev site and use that to update the live site.

You mentioned a few examples:

"adding tags" -> you could export the improved taxonomy and then import it on the new site using a number of modules, ex. taxonomy_xml or taxonomy_csv
"making a better menu" -> the features module allows you to export your menu and import on other sites
"dynamic blocks" -> easiest to just code these in a custom module (probably the simplest kind of module to write) and enable on the new site