Firing ajax_callback on textfield after a minimum number of character Ive created a textfield with an ajax callback with 'keyup' event.

In need the callback function to be fired only after a certain number of character ...
I can control the number of character of the input in the callback function, but this is not the way I want it...

There's maybe a javascript way to avoid the callback to be fired before 5 character ?

My form field :

        $form['myitem'] = array(
          '#type' => 'textfield',
          '#size' => 6,
          '#maxlength' => 5,
          '#default_value' => '',
          '#name' => "my_name",
          '#disabled' => FALSE ,
            '#ajax' => array(
                'callback' => 'mymodule_mycallback_ajax_callback',
                'wrapper' => "mywrapper",
                'method' => 'replace',
                'event' => 'keyup',
                'progress' => array('message' => NULL),
            ),
        );

One option is to use a custom jQuery event, eg. something like "startajaxCall". Set $form['my_input']['#ajax']['event'] = 'startajaxCall' and provide some JS to trigger your custom event after an appropriate number of keys is entered.


Ubercart Marketplace - Where is the ImageField for users? Using Drupal 6

The Imagefield is configured for products.  The imagefield appears for admin but not for users.  How do I get the imagefield to appear for users who are authorized Ubercart Marketplace sellers?  Any help is appreciated!

Andre E.

It sounds like you need to check the permissions (/admin/user/permissions).

If you have field level permissions then you'll want to look for your CCK imagefield for your product images under the heading "content_permissions module." Ensure that the "view field_YOURIMAGEFIELD" permission is checked for all users.

Also if you're using imagecache on your product images there is also a permission for that as well.

Just for general knowledge the super admin user (user 1) completely bypasses the site permissions even if the super admin is assigned a role. It's a good idea to create a new user and create a new role to assign it to. Then use this user instead of 'admin.' We create a role called 'Site Architect.'

Hope that helps!


Query returns no result I want to select all the nodes from the database where a specific taxonomy term is defined (in Drupal 7).

I already know the taxonomy term (IDs). So I want to use a join to get the latest node thats created for that taxonomy.

For the moment I have this:

$query = db_select("node","n");
$query->join('taxonomy_index', 'i', 'n.nid = i.nid');
$query->fields("n",array('nid','title','created'))
        ->orderby("created","desc")
        ->range(0,1);

drupal_set_message($id);

$query->where('(i.tid = :type)', array(':type' => $id));

drupal_set_message($query);

$query->execute();

$array = array();
foreach ($query as $record) {
    $array[] = $record;
}
return $array;

This is (some of ) the output of the messages:

Id: 1

  SELECT n.nid AS nid, n.title AS title, n.created AS created FROM
  {node} n INNER JOIN {taxonomy_index} i ON n.nid = i.nid WHERE ((i.tid
  = :type)) ORDER BY created DESC LIMIT 1 OFFSET 0

If I use the following string directly in PHPMYADMIN, I have results:

  SELECT n.nid AS nid, n.title AS title, n.created AS created FROM
  drpl_node n INNER JOIN drpl_taxonomy_index i ON n.nid = i.nid WHERE
  ((i.tid = 1)) ORDER BY created DESC LIMIT 1 OFFSET 0

The result directly in Drupal returns an empty array.. What am I doing wrong?

Usually it's better if you use EntityFieldQuery instead of db_select. See EntityFieldQuery vs Db_select()

From EntityFieldQuery use page:

  The EntityFieldQuery API lets you fetch information about entities
  (nodes, users, taxonomy terms et cetera) from Drupal without actually
  building SQL queries.
  EntityFieldQuery is a class that allows retrieval of a set of entities
  based on specified conditions. It allows finding of entities based on
  entity properties, field values, and other generic entity metadata.
  The syntax is really compact and easy to follow, as well. And, best of
  all, it's core Drupal; no additional modules are necessary to use it.

In your case:

$nodeQuery = new EntityFieldQuery();
$query = $nodeQuery->entityCondition('entity_type', 'node')
  // get only nodes that are 'published'
  ->propertyCondition('status', 1)
  // replace field_food_menu with field_TAXONOMY_NAME
  // replace 2 with the taxonomy ID (tid) you're wanting
  ->fieldCondition('YOUR_TAXONOMY_FIELD_NAME', 'tid', $SEARCHED_TID)
  // SOrt by creation date.
  ->propertyOrderBy('changed', 'DESC')
  // Retrieve only last item.
  ->range(0,1)
  // USe user 1 to query all nodes, not only those that current use can access.
  ->addMetaData('account', user_load(1));

// Get a list of nids that match given criteria (because if the use of range() a list of 1 elem, at most.
$result = $query->execute();

(Code it's not tested, probably you have to tweak it a little).

I should add that this method also checks if user is allowd to access to the nodes that returns. That's the reason for the last line, it makes all nodes available, not just those the current user can access. If you want to see only nodes for that user just remove that line.


Need to find and disable an email that may be coming from a module Drupal 7 question: There is an email that goes to users that seems to be produced by a module (on a role change) that is confusing to a specific client's users. They would like me to disable that specific email, but I have not been able to figure out where to do that.

I've gone through the users and roles and configuration for the module. I've done a search on the text in the site files (the snippets of text that do not have field-specific data) and come up empty.

So, generically, I'm wondering about how to disable emails from being sent if there doesn't seem to be a setting to do so in the dashboard. I would be happy to add more information here that is about the module specifically, but it seems that it would be helpful to have some generic pointers of where to look, in case the situation comes up in other modules, as well.

If you have the Rules module enabled, go and check the rules

/admin/config/workflow/rules

It's very likely that there is a rule that is sending the emails. So just disable it.


How to update changed date for a node I am migrating content from Drupal 7 to Drupal 8. Migration works fine except the changed date for node get changed to the current time. I want to set the timestamp to the Drupal 7 timestamp. I have tried out the following but it is not working.
        $changed_date = $node->getChangedTime();
        $node->set($source['parent_field_name'], $paragraph_target);
        $node->changed->value = $changed_date;
        // print_r($changed_date);die;
        $node->save();

Not personally tested, but according this issue is a problem for already existing entities, while it should be resolved for new ones.
Also, there's a module that seems to address this issue.
So, I'd say:

try to create the node only in one step, to see if that preserve the original timestamp
if that fails, try either the patch or the module


Access menu links from a module I'm trying to display a menu in my module. I've used \Drupal::entityManager()->getStorage('menu')->load('oz-topbar-menu'); which allows me to get the title of the menu, the description, etc.

I obviously need the links of that menu, and I can't understand how to retrieve. From what I've read in the documentation I should probably use MenuLinkTreeInterface but I don't understand how to instantiate it.

I've tried \Drupal::menuTree()->load('oz-topbar-menu', $menu_parameters);. With basic menu parameters it returns a humongous amount of information; I'm guessing it must be the entire menu tree of Drupal.

I tried playing with the parameters of MenuTreeParameters (setTopLevelOnly, setRoot('oz-topbar-menu')) but it returns an empty array.

I've tried sending this as a MenuTreeParameters object with \Drupal::menuTree()->getCurrentRouteMenuTreeParameters('oz-topbar-menu'), but I still get a massive link tree.

You are probably just missing the build() call.

$menu_name = 'my-custom-menu';
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$renderable = \Drupal::menuTree()->build($tree);
print \Drupal::service('renderer')->render($renderable);

Core is the best example for these kinds of things. I pulled the above from SystemMenuBlock::build().


How to display the user registration or profile field on the search page? How can I render/display user profile or registration field on search result page (user search)?

Copy the template file YOUR_SITE/modules/search/search-result.tpl.php to your theme and modify the code inside with this:

<?php
//obtaining the username
$username = explode('(', $title);
$username = trim($username[0]);
//getting the user object
$user = user_load_by_name($username);
?>
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

  <?php
  /*
   * The following lines will print the info
   */
  print $user->field_date_of_birth[LANGUAGE_NONE][0]['value'] . "
";
  print $user->field_gender[LANGUAGE_NONE][0]['value'] . "
";
  print $user->field_your_industry[LANGUAGE_NONE][0]['value'] . "
";
  print $user->field_your_city[LANGUAGE_NONE][0]['value'] . "
";
  print $user->field_zip_code[LANGUAGE_NONE][0]['value'] . "
";
  print $user->field_countrynew[LANGUAGE_NONE][0]['value'] . "
";
  ?>

  <?php print render($title_suffix); ?>

    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

    <?php endif; ?>
    <?php if ($info): ?>

<?php print $info; ?>

    <?php endif; ?>


How to add a custom field to views block I have a view (block) created. When I modify the view block, I have only the field "block title" in the form. However they are 3 fields (block title, block description et block body) in a block of drupal (which I can create via /structure/block/add).

So my question is how can I add a custom field (like a textfield) to the form of views block?
Is it possible to add it programmatically?

Thanks in advance.

Views is used to pull in existing data/content from other nodes so that you can customise and display it either in new a page or block. There is no body field on the blocks page for a views block is because the contents of that block is controlled by the view and can change dynamically. So if you want to change the body text displayed in the view you can edit the body field of one of the  content nodes your view is collecting from.

When I want to add extra custom text to a view I usually add a random field to the view and then inside that fields settings enable rewriting to allow rewrite the fields output with custom values, if you want to go a bit deeper you can use the module Views Custom Fields as another alternative: https://www.drupal.org/project/views_customfield, but as far as I know editing the body of a views block directly from the blocks admin page is not possible without writing some custom programming.


Restrict block visibilty based on menu I want to display a block only on a particular menu-link.

For example I have a main menu link name: about us and the link: /about

If I restrict the block based on pages and give link as /about , In future the client may change the menu link as /about-us.

So instead of restricting it based on pages, is there any other module which restrict block visibility based on menu's or How can I custom code it?

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $active_trail = menu_get_active_trail();
  end($active_trail);
  $nid = 1; // change to nid of parent node you want to check
  if ($active_trail[1] && $active_trail[1]['link_path'] == 'node/'.$nid) {
    return true;
  } else {
    return false;
  }
}

You can use the above code to achieve it in Drupal 7.


How to specify image paths for Commerce feeds imports on xampp? Been banging around with Commerce feeds and think I've wrapped my head around it. One thing which has been flummoxing is how to provide the path in the CSV file to the image(s) on my xampp install.

I put the folder in xampp/htdocs/drupal/sites/default/files/poster_pics/XXX_image.jpg

Do I provide the path to the root of the site? (IE htdocs/drupal/etc?) or do I provide the entire path to the file on the local machine? (IE C:/xampp/htdocs/drupal/ rest of the path? or something more elaborate like

file:///C:/xampp/htdocs/drupal/sites/default/files/poster_pics/ANON0060.jpg

Many thanks in advance.

It's possible that something like a drupal file system paths (public://poster_pics/name.JPG). There actual path: http://example.com/sites/default/files/poster_pics/name.JPG i.e place image or file here manually.


How to display a twig template via a controller's render array I'm trying to do something you'd think was simple, but I don't find good documentation for it.

I'm trying to create a controller that displays a twig template.

I've done the following so far:

1) In my module directory, I've created a templates/ directory.  It contains a field-permission-description.html.twig file, containing mostly HTML text.  So far, I don't even have any {{ twig_variables }} in it:

Field permision text will be here.

2) I have a theme function in my MY_MODULE.module file:

/**
 * Implementation of hook_theme
 *
 * Since we have a lot to explain, we're going to use Twig to do it.
 */
function MY_MODULE_theme($existing, $type, $theme, $path) {
    return [
      'field_permission_description' => [
        'variables' => [
          'stuff' => NULL
        ]
      ]
    ];
}

3) In my controller, the function returning the render array looks like this:

  /**
   * A simple controller method to explain what this example is about.
   */
  public function description() {
    $build = [
      'description' => [
        '#theme' => 'field_permission_description',
        '#stuff' => 'some stuff',
      ]
    ];
    return $build;
  }

I clear the cache with drush, and go to the page. There's no error, even in the watchdog, but the content region of the description page is blank; the template does not render.

It's not a problem with the controller, since if I substitute something else (say, just a little HTML in a #markup key), it renders fine.

There's been a couple of answers a year or two ago, but these all have things that no longer work as of RC1.

What do I need to do to get a twig template to render the way I'm trying to do here?

The problem turns out to be a missing ' mark in the twig file itself.

It turns out that the twig was rendering, but since I had

and not

the browser refused to show the badly written HTML.

So this was user error, but a hard user error to debug.  I saw what was going on by looking at the source for the page, which made it obvious.

Hopefully this will save folks some trouble.  But in any event: the technique I use here is valid, and works if you don't do stupid things in your twig :-)


Paragraph type can't delete individual items I use Paragraph module Version: 8.x-1.5. Somehow I can't delete individual items anymore?

Is there a settings somewhere I missed?

I have this same problem and also have a link field set to unlimited. I don't see a remove button. Evidently there is a patch in progress for this specific issue. https://www.drupal.org/project/drupal/issues/1038316


Failed to load the AWSSDK I'm trying to get Drupal to work with the S3 File System module.

I downloaded the AWS SDK files and put them in the libraries folder. I don't know why I'm getting the failed to load error.

I tried using the https://github.com/aws/aws-sdk-php/releases/download/2.6.3/aws.zip as suggested. It fixed 1 of the 2 errors, but it fails to load the AWSSDK.

I tried to clear the cache, but it didn't help
I checked the admin/reports/dblog page, in the case the errors were related to file permissions on the SDK files), but nothing shows up

Check the README.txt of the S3 File System module. Contains a couple of instructions that are helpful.

  In the unlikely circumstance that the version of the SDK you
  downloaded causes errors with S3 File System, you can download this
  version instead, which is known to work: https://github.com/aws/aws-sdk-php/releases/download/2.6.3/aws.zip

  IN CASE OF TROUBLE DETECTING THE AWS SDK LIBRARY:
  Ensure that theawssdk2 folder itself, and all the files within it, can be read by your webserver. Usually this means that the user apache (or _www  on OSX) must have read permissions for the files, and read+execute permissions for all the folders in the path leading to the awssdk2 files.

The link to the aws-sdk-php on the AWS installation page will allow you to download the latest version (3.4.1).

On my case, I had to download the 2.6.3 version of the SDK that is mentioned on the README.txt.

You might want to check at admin/reports/dblog if there are any errors related to loading the SDK.

I found that sometimes the libraries info gets hard cached and that is why this module has the _s3fs_load_awssdk2_library(). Take a look of this:

  This function is a replacement for calling libraries_load('awsdsk2'). It's needed because libraries_load() caches failures to load the library, meaning that temporarily having a bad setup (e.g. nonexistent or unreadable files in the awssdk2 folder) can lead to the library being permanently unable to be loaded, even after the bad setup is repaired. This can only be remedied by clearing the full site cache.

TD;LR: sometimes you will need to refresh the libraries cache for the SDK, if that is the case, the _s3fs_load_awssdk2_library() can be invoked by going to admin/config/media/s3fs/actions and use the "Refresh file metadata cache" button option. Or also you can use the Drush command drush s3fs-refresh-cache.


403 Error on AJAX Request in add new item (collection field) I have normal content type which has 12 collection fields
each field has unlimited value
when i try to click add new item on any field it gives me ajax error

An AJAX HTTP error occurred.
HTTP Result Code: 403
Debugging information follows.
Path: /?q=system/ajax
StatusText: Forbidden
ResponseText:

I have another content type and also has collection field with unlimited value .. but it works without any problem
so please help me why some content type has error and the other doesn't have

by the way: i use D7 and i upgraded it to 7.35 but this problem was before the upgrading

i have checked all the answers in the Drupal Answers but unfortunately did it help

edit:

ResponseText:
@import url("http://example.org/modules/system/system.base.css?nlmla7");
@import url("http://example.org/modules/system/system.base-rtl.css?nlmla7");
@import url("http://example.org/modules/system/system.menus.css?nlmla7");
@import url("http://example.org/modules/system/system.menus-rtl.css?nlmla7");
@import url("http://example.org/modules/system/system.messages.css?nlmla7");
@import url("http://example.org/modules/system/system.messages-rtl.css?nlmla7");
@import url("http://example.org/modules/system/system.theme.css?nlmla7");
@import url("http://example.org/modules/system/system.theme-rtl.css?nlmla7");
@import url("http://example.org/sites/all/modules/date/date_api/date.css?nlmla7");
@import url("http://example.org/sites/all/modules/date/date_api/date-rtl.css?nlmla7");
@import url("http://example.org/sites/all/modules/date/date_popup/themes/datepicker.1.7.css?nlmla7");
@import url("http://example.org/sites/all/modules/date/date_repeat_field/date_repeat_field.css?nlmla7");
@import url("http://example.org/modules/field/theme/field.css?nlmla7");
@import url("http://example.org/modules/field/theme/field-rtl.css?nlmla7");
@import url("http://example.org/sites/all/modules/field_hidden/field_hidden.css?nlmla7");
@import url("http://example.org/modules/node/node.css?nlmla7");
@import url("http://example.org/sites/all/modules/recieve_orders/css/orders_styles.css?nlmla7");
@import url("http://example.org/modules/search/search.css?nlmla7");
@import url("http://example.org/modules/search/search-rtl.css?nlmla7");
@import url("http://example.org/modules/user/user.css?nlmla7");
@import url("http://example.org/modules/user/user-rtl.css?nlmla7");
@import url("http://example.org/sites/all/modules/views/css/views.css?nlmla7");
@import url("http://example.org/sites/all/modules/views/css/views-rtl.css?nlmla7");
@import url("http://example.org/sites/all/modules/admin_menu/admin_menu.css?nlmla7");
@import url("http://example.org/sites/all/modules/admin_menu/admin_menu-rtl.css?nlmla7");
@import url("http://example.org/sites/all/modules/admin_menu/admin_menu.uid1.css?nlmla7");
@import url("http://example.org/sites/all/modules/ctools/css/ctools.css?nlmla7");
@import url("http://example.org/sites/all/modules/adminimal_admin_menu/adminimal_admin_menu.css?nlmla7");
@import url("http://example.org/modules/shortcut/shortcut.css?nlmla7");
@import url("http://example.org/modules/shortcut/shortcut-rtl.css?nlmla7");
@import url("http://example.org/sites/all/themes/adminimal_theme/css/reset.css?nlmla7");
@import url("http://example.org/sites/all/themes/adminimal_theme/css/style.css?nlmla7");
@import url("http://example.org/sites/all/themes/adminimal_theme/css/style-rtl.css?nlmla7");
@import url("http://example.org/sites/all/themes/adminimal_theme/css/mobile.css?nlmla7");
@import url("http://example.org/sites/all/themes/adminimal_theme/css/tablet.css?nlmla7");ySite.org/sites/all/themes/adminimal_theme/css/tablet.css?nlmla7");

and there are too many custom modules in my site

but the thing which make me more conflicted is why it doesn't give error in the other content type

for what it's worth we just wrestled with this for a while on our own sites. The solution actually ended up being disabling cloudflare on 'system/ajax' URLs. If you're running CF and have this problem - try it!


Body class padding top, where is it coming from I'm using Drupal 8.4.2 lightning-8.x-2.23 and Boostrap subtheme, Admin Toolbar.
The body class has an injected class of padding-top: 40.4px; for publisher user and padding-top: 79.4px; for admins. I want to make it the same padding. Does anybody know where this style is coming from? I dont see it in any style sheet. In Drupal 7 the admin toolbar had a settings page that allowed for padding top so that it pushes the body below the toolbar.

Logged in as admin body class

<body class="toolbar-tray-open toolbar-horizontal toolbar-fixed user-logged-
in path-workbench has-glyphicons" style="padding-top: 79.4px;">

Logged in as publisher body class

<body class="toolbar-tray-open toolbar-horizontal toolbar-fixed user-logged-
in path-workbench has-glyphicons" style="padding-top: 40.4px;">

It is being done by the core toolbar module. See updateToolbarHeight in  core/modules/toolbar/js/views/ToolbarVisualView.js.

updateToolbarHeight: function updateToolbarHeight() {
  var toolbarTabOuterHeight = $('#toolbar-bar').find('.toolbar-tab').outerHeight() || 0;
  var toolbarTrayHorizontalOuterHeight = $('.is-active.toolbar-tray-horizontal').outerHeight() || 0;
  this.model.set('height', toolbarTabOuterHeight + toolbarTrayHorizontalOuterHeight);

  $('body').css({
    'padding-top': this.model.get('height')
  });

  this.triggerDisplace();
},


Attach JS to tableselect checkboxes? Using the Drupal 7 tableselect form field, is there a way to attach javascript events to the checkboxes?

I am trying to build a custom pricing table that lets you add different options, which modifies the displayed total. When checking off an option, I need to pass the value through AJAX and return a new total price. Not sure though how to attach events.

I'm pretty sure this is quite doable with the #ajax key in a renderable array. From http://drupal.org/node/752056:

<?php
/**
 * AJAX-enabled select element causes replacement of a set of checkboxes
 * based on the selection.
 */
function ajax_example_autocheckboxes($form, &$form_state) {

  $default = !empty($form_state['values']['howmany']) ? $form_state['values']['howmany'] : 1;

  $form['howmany_select'] = array(
    '#title' => t('How many checkboxes do you want?'),
    '#type' => 'select',
    '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4),
    '#default_value' => $default,
    '#ajax' => array(
      'callback' => 'ajax_example_autocheckboxes_callback',
      'wrapper' => 'checkboxes-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),

  );

  $form['checkboxes_fieldset'] = array(
    '#title' => t("Generated Checkboxes"),
    // The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'fieldset',
    '#description' => t('This is where we get automatically generated checkboxes'),
  );

  // Complete example below!

Basically, define what function is going to be triggered by what action (in this case, a checkbox toggle). With the above code, define a function such that its signature is ajax_example_autocheckboxes_callback. Voila.


Multiple Field Widget instances on the same page, validation problem I have multiple instances of the same field widget attached to different entity forms on the same page. On validating one of these forms, when I set form_set_error($field_name, '...'), every one of these widgets get highlighted. Is there a way to get around this somehow?

Check out the API page for form_set_error. This bit should help you out:

  $name The name of the form element. If the #parents property of your form element is array('foo', 'bar', 'baz') then you may set an error on 'foo' or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every element where the #parents array starts with 'foo'.

In your case you'll just want to make sure that the parent item is different for each instance of that field, then set the error with form_set_error($parent_name . '][' . $field_name, '...')


How to edit fields' display markup in a search view? Working with searchapi and views. I have a view based on a search inWondering how to edit the markup for the fields? There's a general option to strip the markup elements, but how to control the markup for individual fields?

Select the field and drop down the "Style Settings" tab, here you can select an element and create new classes for the field, label or wrapper. You can also remove the css completely


Set timestamp field default value empty I have created field type "Timestamp" in my Drupal 8 node. Field is not required. In field settings default value, there is HTML 5 datetime picker, in which you can select default date/time or leave values as on picture:

But the Drupal behavior seem to be little bit strange - when you select default date, this value is set on node save (this is correct). When you leave field blank (values as on picture) it saves field with time of form submission (it is stated in field comment, so it is not a bug)... But how to disable default value, when you just want to leave field blank as it is possible with all other fields (e.g. text, number, ...)? I do not see any settings for this in this field configuration. Also this is not logical, beucase when you leave other fields blank, they are really blank. When you leave this field type blank, it still saves value (some additional checkbox will be more logical)?

Thanks

There is backstory to this that is a little complicated.

The Timestamp field type was added back into Drupal 8.2.0 core as a "UI Field".  The field type had always been there, just as a behind-the-scenes field, and used as the base field for CreatedItem and ChangedItem for entity timestamps (which are both non-UI field types).

If this field is rendered out on with the proper widget on the edit page (see bug), then you end up using  TimestampDatetimeWidget.  This widget has a ::massageFormValues() method, which enforces the current time being used (at save) as the field value if the element is empty.

So, the behavior you are seeing is by-design.  The widget was initially intended for entity edit pages, where created and changed timestamps never have empty values after the entity is saved.  When this field was added as a UI field, it inherited the widget and its behavior.

If you really want a timestamp and don't want this behavior, you need to make a custom module and make your own widget.  You should just be able to copy TimestampDatetimeWidget into the module, rename it, update the annotation, and update the ::massageFormValues() method:

remove the else branch containing $date = new DrupalDateTime(); - this won't set the default datetime
handle unset $date variable, example: $item['value'] = !empty($date) ? $date->getTimestamp() : NULL;

That should allow you to have empty timestamps.

Personally, I would not use Timestamp fields, though.  I would use Date fields, which can have empty values or default values, and better widgets and formatters in general.


Memory leak when looping through nodes I've got code that loops through nodes in order to generate processed output.

I've previously done an entity query that provided an array of node IDs. My main loop code looks like this:

foreach ($this->nids as $nid) {
    $node = Node::load($nid);
    $nodeData = $node->toArray();
    $nodeURL = $propertyNode->toUrl()->toString();
    print "Mem usage: ".memory_get_usage(true)."\n<br>";
}

Obviously, the loop shown here is a minimal example to demonstrate the problem; as it stands, it's pretty useless as it doesn't do anything with the data it loads.

However despite this, the loop is eating memory. The debug call to memory_get_usage(true) in the loop gives a bigger number every time, until the script eventually runs out of memory if I feed it enough nodes (about 300 seems to be enough to kill it).

Obviously, I can increase the memory available, but I'm reluctant to do that because I can't seee why the loop would be leaking memory in the first place.

Can anyone please explain why this fairly basic loop is causing a memory leak, and what I can do to prevent it?

A few additional notes:

I've tried adding unset() at the end of the loop to clear the node and data variables; this doesn't have any effect (I wasn't expecting it to, but I tried it anyway).

The nodes in question have about fifty custom fields, including a couple that are paragraphs, which in turn have fields of their own.

My real code passes the node data to a processor class that reformats it for use elsewhere. It builds an array of these objects, but they aren't the cause of the memory leak, hence why I've excluded them from the example code.

I'm currently running on Drupal 8.6; haven't had a chance to look at the 8.7 release from yesterday yet.

With thanks to the comments made by various people above, I have now optimised this code so that it doesn't run out of memory.

$chunks = array_chunk($this->nids, 100);

foreach ($chunks as $chunk) {
    $nodes = Node::loadMultiple($chunk);

    foreach ($nodes as $node) {
        //do stuff with the node here...
    }
    Drupal::entityTypeManager()->getStorage('node')->resetCache([$chunk]);
    print "Mem usage: ".memory_get_usage(true)."\n<br>";
}

I couldn't simply do loadMultiple for all the nodes at once as it was still using unholy amounts of memory, but chunking it and resetting the cache after each chunk seems to work nicely.

I experimented with different sized chunks, and I found I got the best mix of performance vs memory usage with the chunk size at 100. YMMV.


Save new revision of custom entity I created a custom entity in my module and I can edit and save it just like any other entity in core. I also want to save revisions for this entity but I couldn't find any help so far. I tried this (from node module) but it doesn't work:

$entity = $this->getEntity();
$entity->new_revision = true;
$entity->save();

I have the revisions tables declared in @ContentEntityType annotation, I have the revision_id field declared in baseFieldDefinitions() but I don't know how to actually save a new revision.

For Drupal 8 most intern values like the revision flag (newRevision) is protected, which means that you aren't allowed to set them directly. There is a good reason for this, as Drupal wants to do stuff in some cases when these values are set.

Instead you need to use the ::setNewRevision method on the entity. This will throw an exception if the entity doesn't support revisions. So if you don't know what entities you are dealing with, you could do something like this.

function save_new_revisions(EntityInterface $entities) {
  foreach ($entities as $entity) {
    if ($entity->getEntityType()->isRevisionable()) {
      $entity->setNewRevision();
    }
    $entity->save();
  }
}


Connecting Panels with Views Forgive the obtuse explanation.

I have a content type, called SHOW. this show type has a title and client and supervisor and a number of other fields associated with it.

I have an employee of the company fill out the SHOW information on the website. then, this information is available to all employees - it's an intranet.

I have another content type. It's called REQUEST. The first field in this form is a relate-able auto complete list of the SHOW titles that have been created on our site. This content type has some other fields as well, none that are related to anything else.

I have a panel that displays pertinent information from a show, the stuff I want like title and some of the other fields. All is good. In panels I've overridden the node panel for this content type to do this.

Now here's my problem.

I created a view as a table to show the REQUEST content types. I want to show this view in the SHOW panel. I've managed to do this. BUT, i only want to show the view for the corresponding SHOW that I'm in the panel for. I have 3 shows (these are TV shot titles) and each show has like 6 REQUEST content types filled out for it. Again, I only want to show this view on this panel for this specific show.

I'm so lost. Can anyone help?

In your view settings, sound like you just need to (under Advanced) add a CONTEXTUAL filter of Nid and use Content ID from URL.


Adding column in Views for completed submission plus several days A have a table column using Views from Webform submission. The variable of this column is submission date [completed].

I need to create another column showing another date [completed] + 7 days.

I tried Global: Math expression
[completed]+7
but it does show the correct date but another value.

How can I display [completed]+7 in another column.

I have solved my own problem. Using Views PhP module.
Add field Global:PHP,
in the output code box:

<?php
$correctdate = $row->completed;
$correctdate1 =strtotime("+7 days", $correctdate);
$cdate = date("j/n/Y - g:i a", $correctdate1);
echo ($cdate);
?>


drush sql-sync structure tables in alias dont work It seems that the structure tables dont work on a sql sync from my live site to my dev. Using the following comman:

drush sql-sync @example.live @example.dev

The search_api_server is every time overritten, so it gets synced. So i think also my cache tables get synced. Whats wrong with my aliases?

/**
 * Dev/Local alias
 */
$aliases['dev'] = array(
  'root' => '/var/www/example_dev',
  'uri'  => 'example.dev',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'source-command-specific' => array (
    'sql-sync' => array (
      'no-cache' => TRUE,
      'structure-tables-key' => 'common',
    ),
  ),
  // No need to modify the following settings
  'command-specific' => array (
    'sql-sync' => array (
      'sanitize' => TRUE,
      'no-ordered-dump' => TRUE,
      'structure-tables' => array(
       // You can add more tables which contain data to be ignored by the database dump
        'common' => array('cache', 'cache_filter', 'cache_menu', 'cache_page', 'history', 'sessions', 'watchdog','search_api_server'),
      ),
    ),
  ),
);

/**
 * Live alias
 */
$aliases['live'] = array(
  'remote-host' => '000.000.00.00',
  'remote-user' => 'username',
  'root' => '/var/www/html/example-live',
  'uri'  => 'example.net',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
);

There are three places you can reference aliases when using sql-sync:

drush @site sql-sync @prod @dev

@site - Where the sql-sync will execute. If this is a remote site, then the other two aliases must be defined in files that reside on the remote machine.  Options from 'command-specific' will be applied to the command.

@prod - The source for the sync.  Options from 'source-command-specific' will be applied to the command.

@dev - The target for the sync.  Options from 'target-command-specific' will be applied to the command.

The alias @site is not usually used with sql-sync; most people just run drush sql-sync @prod @dev.

Drush is going to look for different 'command-specific' records depending on the position of the alias appears on the commandline.

@site - The alias that appears before the command name will have options from the 'command-specific' -> 'sql-sync' record added to the evaluated options list.

@prod - The alias that appears in the first position after the command name will have options from the 'source-command-specific' -> 'sql-sync' record used.

@dev - The alias that appears in the second position after the command name will have options from the 'target-command-specific' -> 'sql-sync' record used.

In the typical case (drush sql-sync @prod @dev), the 'command-specific' record is not used at all, the 'source-command-specific' record from @prod is used, and the 'target-command-specific' record from @dev is used.

Try using alias records more like the following set:

/**
 * Dev/Local alias
 */
$aliases['dev'] = array(
  'root' => '/var/www/example_dev',
  'uri'  => 'example.dev',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'target-command-specific' => array (
    'sql-sync' => array (
      'no-cache' => TRUE,
      'structure-tables-list' => 'cache,cache_admin_menu,cache_block,cache_bootstrap',
      ),
    ),
  ),
);

/**
 * Live alias
 */
$aliases['live'] = array(
  'remote-host' => '000.000.00.00',
  'remote-user' => 'username',
  'root' => '/var/www/html/example-live',
  'uri'  => 'example.net',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'source-command-specific' => array (
    'sql-sync' => array (
      'sanitize' => TRUE,
      'no-ordered-dump' => TRUE,
    ),
  ),
);


How to have a three column in node page I want to have a three column in node page, my page width is 940px, and one column is 300px + 20px right margin, so 3 column is 960px, but the main width is 940px, I want to 3 column in one row,  how to do that? how to modify node.tpl.php?

I don't understand why this isn't a simple case of changing your CSS? You're adding 20px to 940px so that equals 960px. You must either use CSS3 (box-sizing: border-box;) or minus your extra 20px from 940px...which would be 920px. Standard box model stuff but maybe I'm missing something in your requirements.


How to debug a Commerce value in Rules if field is not exposed? I use Drupal Commerce with Commerce Credits module to let users buy credits which later can be used to submit content.

The module has support for Rules but I can't get a very simple condition to work. The problem is that 'Entity has credits' rule always returns 0 even if my users have credits:

I tried to debug the amount of user credits but without any results:

Rules evaluation log shows me that comparison to 0 always returns true but to different values always false, independently if user has credits or no. Before that I check if entity is of type node.

Checking if entity is of type commerce_credits and using 'Entity has credits' doesn't give me any result.

Devel debug using action "Debug value" to show credits for user fails for node:author and site:current-user as no reference to credits is shown.
I tried also to get access to commerce_credits by "Fetch entity by id/property", but couldn't figure out what id/property to define.

Looking at the code of Commerce Credits module it looks like credits get saved to an entity called commerce_credits. But I can't figure out how to use this token.

Any other way to debug Rules and find the credits value related to a user?

Looks like you did pretty much everything you can do to "debug" a rule that doesn't seem to do what you want, so I can't give you any other hints to the "how to debug"-part of your questions. But... I may have a solution to get around the actual problem ...
Have a look at the issue "After updating existing content" runs before content is saved, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which IMO is not a bug, simply how the Rules module  works ...).
A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your Rules Conditions and -Actions in a Rules Component, so that after your First Rules Action you "schedule the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs).
BTW, there are also scenarios where it is sufficient to just execute the Rules Component (containing the equivalent of your "subsequent Rules Action"), instead of using the Rules Scheduler to schedule its execution.
Update: as per geraldo's comment below this answer, the actual solution to the question here seems to be as described in comment nr 8 of support issue # 2502703, and which is like so:

The problem is line 317 in commerce_credits.rules.inc. Using count($credits->credits) always returns 1. Everything works fine when changing it to:
 if ($credits->credits >= $credit_number) {


Get related node by taxonomy term? Let's say I have two content types: Page and News.   Both of them have a field called Tags which is taxonomy term.

Let's say I tag a page and a news item with the term 'celebration'.  When a user goes to the page on the front end website, the user should see related news items on the right side bar.  A news item is related to a page if they both have at least one tag in common.

I tried to set up a news item block, but i don't know how to tell it to show only news items that share at least 1 tag in common with the page.

I've used the 2.x version of Similar by Terms in the past, and it is very good, with nice views integration. A D7 version of the 2.x branch is in development at http://drupal.org/node/1270244.

The Apache Solr module can also supply a block of nodes that have similar taxonomy terms based on a Solr database: http://drupal.org/project/apachesolr. Very fast, but not trivial to set up.

Finally, here's a comparison of similar/relevant content block modules: http://drupal.org/node/323329.


error when deleting view when I try to delete a view from the views module, I receive the following error:
error_1

Trying to save a new view shows this:
error_2

Any idea how to fix this?

I also cannot delete the view manually as my phpadmin tells me that there is an error and that I have to configure session.save_path... but I cannot find any file named session.save_path on my server.

Please let me know if you ever had this errors and if you know how to fix this. I invested 50 hrs to develop new functionality and I cannot risk the website goes down for days...

Thanks in advance!!

It sounds like you've got some pretty serious problems here.

The fact that you can't use PHPMyAdmin because of the session.save_path setting (which is in php.ini by the way, it's not file name) would suggest that something on your server has changed. At a guess I'd say your web server no longer has write access to the session folder, but without seeing the full error message it's hard to say.

The fact that the you can't enable the db log module is also quite worrying. That module defines the watchdog table upon install so the fact that it's missing might suggest Drupal is having problems creating database tables.

The best advice I can give is to get a local version of the site up and running, with permissions for files/databases set up in a way you know is correct, and see if you still have problems.

If you do, then you know that the problem is somewhere else and you should start methodically disabling and uninstalling modules until you can narrow down the culprit.

If you don't, then you know the problem is with the live server configuration.


How can I have a view to load more rows on clicking a "Load more" button? We have created a view, myview, where we want to display 3 nodes (content type = basic) and add a View All button on page load. The purpose of the 'View All' button will be to show 6 more (the view is supposed to show max 9).

How can we display 3 nodes with a View All button?

What we tried, but the view did not display the view all button nor did it allow me to limit to total of 9. I also could not find an appropriate view hook to do what i am looking for.

View settings:

Change pager plugin to full
change pager plugin to mini

Looks like Views Infinite Scroll  is a good option for you:

  Views infinite scroll allows you to load and display pages of any view inline, using AJAX (this has been called infinite scrolling, load more, autopaging, endless pages and more). The pager can be triggered with the press of a button or automatically as the user scrolls to the bottom of the view's content.

Here's the pager settings:


How to add block to only user/uid and not user/uid/edit In my site the www.example/user/uid path contains the view and edit tabs. I want to add some blocks to only the view page and not edit page.

Using "user/* (Only the listed pages)" under the visibility settings of block configuration attaches the block to both pages.

How can I make it appear on only the view page.

Thanks in anticipation.

Hope this will help you,

In Drupal 7,

You can achive it by enabling PHP filter module, which allows embedded PHP code/snippets to be evaluated. GO to admin > modules and enable PHP filter.

<?php
    global $user;
    if (arg(0) == 'user' && $user->uid == arg(1) && is_numeric(arg(1)) && (arg(2) == NULL) ){
      return TRUE;
    }
    else {
      return FALSE;
    }
?>

You can also refer Extended block visibility module. This will allows PHP block visibility to be defined in code.


Taxonomy Terms More than one level and Clean Class throws error I am using clean_class and clean_id in twig. It was working with Parent Taxonomy Terms fine, but when I use Child Taxonomy Terms and try to render to Twig Template, I get this error message:

Recoverable fatal error: Object of class Drupal\Core\Field\FieldItemList could not be converted to string in Drupal\Component\Utility\Html::getClass() (line 72 of **core\lib\Drupal\Component\Utility\Html.php).**

Drupal\Component\Utility\Html::getClass(Object) (Line: 259)
__TwigTemplate_4f47122ce7aa9a8c20dea186eff4ea8b5e46cc06c44f4f280e0f32c345504034->doDisplay(Array, Array) (Line: 455)
Twig\Template->displayWithErrorHandling(Array, Array) (Line: 422)
Twig\Template->display(Array) (Line: 434)
Twig\Template->render(Array) (Line: 64)
twig_render_template('themes/custom/cpv3/templates/page--node--community-plan-update--actualizacin-del-plan-comunitario-de-boyle-heights.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('page', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 501)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 109)
__TwigTemplate_0352d110804239c4a7412c9a9a76a1e3fccf9ff4943b7c48bf7ef5beaa137b28->doDisplay(Array, Array) (Line: 455)
Twig\Template->displayWithErrorHandling(Array, Array) (Line: 422)
Twig\Template->display(Array) (Line: 434)
Twig\Template->render(Array) (Line: 64)
twig_render_template('themes/custom/cpv3/templates/html.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('html', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 147)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 148)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 156)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Line 72 in Html.php is the function regarding Clean Classes

* @param mixed $class
   *   The class name to clean. It can be a string or anything that can be cast
   *   to string.
   *
   * @return string
   *   The cleaned class name.
   */
  public static function getClass($class) {
    $class = (string) $class;
    if (!isset(static::$classes[$class])) {
      static::$classes[$class] = static::cleanCssIdentifier(mb_strtolower($class));
    }
    return static::$classes[$class];
  }

Is this a bug in Drupal Core or could it be my theme? How can I debug this?

The error message:

  Recoverable fatal error: Object of class
  Drupal\Core\Field\FieldItemList could not be converted to string

Unfortunately the field object FieldItemList can't be casted to a string, it doesn't have a magic __toString() method, but it does have a magic __get() method. So you can provide a property name, which is for most field types value, to get the field value as string:

  class FieldItemList

  Represents an entity field; that is, a list of field item objects.

  An entity field is a list of field items, each containing a set of
  properties. Note that even single-valued entity fields are represented
  as list of field items, however for easy access to the contained item
  the entity field delegates __get() and __set() calls directly to the
  first item.

Source: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21FieldItemList.php/class/FieldItemList/8.7.x


Paragraphs item doesn't load on node/add I have one content type were I cannot add Paragraph items.  I select the item, And I get the table header, but no paragraph loads, no error.

In logs I see:

  Location: .../system/ajax/

  Referrer: .../node/add/product/

  Message:

  Notice: Undefined index: #bundle in
  theme_paragraphs_field_multiple_value_form() (line 1170 of
  .../sites/all/modules/contrib/paragraphs/paragraphs.module).

Line 1170 is:

// Add the items as table rows.
foreach ($items as $key => $item) {
  $item['_weight']['#attributes']['class'] = array($order_class);
  $delta_element = drupal_render($item['_weight']);
  $cells = array(
    array('data' => '', 'class' => array('field-multiple-drag')),
    drupal_render($item),
    array('data' => $delta_element, 'class' => array('delta-order')),
  );
  $rows[] = array(
    'data' => $cells,
    'class' => array('draggable', drupal_html_class('paragraphs_item_type_' . $item['#bundle'])), // Line 1170
  );
}

This has worked, and I have other content types on which this field works.  I can not see any difference in the field or content types.

Has anyone run into this before?  I would love some direction on where to look for problems.

This seems like it can be related to the Entityqueue module. The Draggable tables widget provided by the Entityqueue module doesn't take into account that their are other entity forms (like paragraphs in your case).

There is a patch to fix this currently but it needs some work: https://www.drupal.org/node/2460503


A particular content type forces preview before save. How do I turn this off? I've set up a new content type, but for this (and none of my other custom content types), it forces a preview before the save button appears.

Is there a way I can turn this off? I've looked around and can't see an obvious option to turn it off, but maybe I'm being blind. It's really frustrating.

You can set this option easily:

Edit the content type
Click "Submission form settings"
Set "Preview before submitting" to Optional (or Disabled if you don't want previews at all).


Where is the php_error.log file in Acquia Dev Desktop? I'm having problem with a site installed with Acquia Dev Desktop, but I can't find the php_error.log file to see the errors. There is nothing inside the DevDesktop folder and I can't see anything in the Software Preference.

Where is the php_error.log file in Acquia Dev Desktop?

Just checked in my installation of DevDesktop and found that my PHP logs are located in /Applications/DevDesktop/apache/logs/error_log.

Although it says Apache logs, PHP errors get logged there as well.

You can find the log locations via 'Preferences' => 'Logs'. DevDesktop version 2 (Apr 13, 2017).


Drupal 7 Age Gateway I have a website that will need an age gateway because it contains content about alcohol.  I'm looking for an easy way to do this, without needing to create a custom module because I haven't done any and the deadline is looming.

It would need to redirect to a page gathering age information, and only allow access to the site if >= 21 years old.  Specific pages would be exempt.

If anyone knows a module that takes care of this, or has any ideas I'm open to suggestion.

Please try module Terms of Use . It won't check user age directly but the user has to sign understanding your website terms of service before registration.


view handler date not working I am creating views handler for date in hook_views_data. All other fields working fine but date. I am assigning views_handler_field_date and views_handler_filter_date in fields and filter respectively.

The problem is that when I select date field in views I get empty response as well as got bunch of errors.

I am not sure what your code looks like, but my suggestion is to use custom handler if  the core is not working. I used custom handler in almost all my projects if I get any issue in core handler. Example is:

/**
 * A handler to display dates as just the time if today, otherwise as time and date.
 *
 * @ingroup views_field_handlers
 */
class views_handler_cusom_field_date extends views_handler_field_date {

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    $form['date_format']['#options']['example_custom'] = t('My custom format');
  }

  function render($values) {
    $format = $this->options['date_format'];
    $value = $values->{$this->field_alias};
    // check for our custom format
    if ($format == 'example_custom') {
      // check to see whether value is whithin today range
      $timezone = new DateTimeZone("Australia/Melbourne");
      $date = new DateTime();
      $date->setTimezone($timezone);
      $today = strtotime($date->format('Y-m-d 00:00:00'));
      if ($value >= $today) {
        // this value is still within today
        return format_date($value, 'custom', 'g:i A');
      }
      else {
        // this value is older than today
        return format_date($value, 'custom', 'j M Y g:i A');
      }
    }
    // otherwise render the date using the normal date handler
    else {
      return parent::render($values);
    }
  }

}

And then call this custom handler in your date field

'date' => array(
           'title' => t('Date'),

           'field' => array(
              'handler'=> 'views_handler_cusom_field_date'
              'click sortable' => TRUE,
           ),


How to load jQuery UI after bootstrap js files? I'm a newbie to drupal 7, And I'm facing a conflict between jquery.ui.button.js and bootstrap/button.js because jquery ui is loaded before bootstrap.
How can I change the order and load jquery ui last?

Knowing that bootstrap files are loaded by the theme, and jQuery UI is loaded by the module (jquery_update)

There are a couple of ways in Drupal 7 to control load/execution order.  The simplest is to change the module weight in the system table to get the right order.  Unfortunately, this will not work in this case since there is a module and theme involved.  Themes always get executed after modules (so UI changes are ensured to happen and not be overwritten).

This means you will probably have to write some code in order to modify the load order.  In your [theme.module] file, you will need to implement the Drupal hook: hook_js_alter.  E.g. add a function my_theme_js_alter(&$javascript) to the theme module file.

You will probably need to install devel and use dpm to dump the javascript array.  You can then use this information to rearrange the load order as you need it.  Probably just unset the jquery_ui entry and add it to the array at the bottom.


Cannot import multiple nodes in feeds module using csv files Im trying to import these files into nodes in my drupal 7 site

i used the no header and i mapped the columns into numbers (0,1,2. ..)

but i end up only getting only 1 node.

The alert says "created 1 node, updated 19 nodes" how come?

You file shows 20 rows. From your description, I bet that the GUID has been the same for each import, and you have actually created one node 20 times. (Created once then updated 19 times.) You need to define a unique field in each record, with a corresponding unique field in your node (eg guid). Then feeds will map that field to determine which nodes to create (no nodes with matching unique field) or to update (node has a matching field).

Try using the Title field as unique instead of guid.


How can I add a class to a view list item that has a moderation state of draft I have a view that outputs a list of nodes for a menu. The view
displays the title linked to the node. The View allows published nodes or
nodes in the moderations states draft or review. How can I add a class around the titles that are in draft or review. I would like to style these differently. I am using drupal_view to print the block inside a template. Can this be done in a theme preprocess or custom module?

This can be done through the Views interface.

You can add classes based on existing Field values to entire rows in Format > Settings, or you can add classes to individual Fields (you mentioned title) under Style settings wrapper or field HTML options.

Tokens to use in all of these cases can be found in the settings of the Field according to which you want to style the rows/other fields. The settings are under Rewrite results > Override the output of this field with custom text > Replacement patterns options.

You don't have to actually keep the rewrite enabled, you just need to temporarily reveal and uncollapse to copy the tokens you need.

Then add CSS for those classes to your subtheme as usual, or through CSS editor module.
You can hide the field ("Exclude from display") but it needs to be there on the list, arranged before any other fields that may use its value for classes.


Entity references from a view with list of nodes that can be references to nodes that keeps references I have a package (node with few entity reference fields - one per content type).
Example

So on package node I can select nodes that are related (one reference per content type).

Now I have new request:
create a view with a list of all products and on each row (product) make possible to select package this product belongs to - for example: set ref_to_shirt if product in this row is a shirt.

Note that reference field is on package and there are multiple reference fields (one per content type).

List will look something like this:

Any sugestion? I was wondering if its possible to set this as VBO action with some Rules component, but for now I'm open to any solution.

Thanks

Edit: this approach is only for listing the assignments, not changing them.

--

First make sure that the product content types have a common view mode. Pick "teaser" for example.

Create two views:

Products list: the "outer view" to list all the t-shirts, pants shoes.
Packages per product: based on a contextual filter, list all package assignments of a given product. As you have different fields link the product content types with the packages you might want to start with one type. Once it works, replicate the view/view display for the other product types.

The second view now needs to be embedded into the teaser view of products. My preferred way of doing so is using panelizer to override the teaser view mode but you can also do this using the "Eva" module.

Hope this helps :)


View that filters content based on current page I'm in the middle of a Drupal 6 to 8 migration and am attempting to recreate a view.  This view would appear on pages of the content type "People" and would show the "Publications" that this person is associated with.  The "Publications" has a field of type "Entity reference" that references each of the "People" titles.

How do I configure the view block to only show Publications that have the entity reference of the current "People" page?  I figure this has something to deal with contextual filters, but I'm a bit lost on how to filter this correctly.

Thank you in advance.

Recreating Drupal 6 Views in Drupal 8 should be quite straightforward. What got you confused?

You need to create a list of all "Child" nodes (Publications) and add the Contextual filter for the Entity reference field that references the "parent". Configure that filter to use the "Provide default value", "Content ID from URL". Adjust all the other options in the filter to your specific needs.

When you add the Block to a region in your theme you also have to set the option again (in the Block settings) for the Contextual filter to use the Content ID from URL.


Drupal 7 Commerce Stock Decrease stock when reverting cancel the order I have used drupal commerce module.
I have rules to increase stock when the order process is cancelled and decrease the stock after completed the order process.

When i cancelled the order status, the stock will be increased. It is fine.
When i trying to change the order status any of pending, processing, completed from cancelled, it didn't happened anything in my stocks.

But again when i changed status to cancelled, the stock will be increased.
So i want to write rule for "decrease stock when reverting from cancel the order process"

How to create rule for this edge cases?

It can be done using hook_default_rules_configuration().
Below is my code:

<?php
/**
 * implement hook_default_rules_configuration().
*/
function phponwebsites_default_rules_configuration(){
$rules = array();
$rules_export = '{ "phponwebsites_rules_decrement_stock_revert_cancel" : {
            "LABEL" : "Stock: decrease when revert canceling the order process (cloned)",
            "PLUGIN" : "reaction rule",
            "OWNER" : "rules",
            "TAGS" : [ "stock_control" ],
            "REQUIRES" : [ "rules", "commerce_ss", "entity" ],
            "ON" : { "commerce_order_update" : [] },
            "IF" : [
              { "data_is" : { "data" : [ "commerce-order:status" ],
                  "op" : "IN",
                  "value" : { "value" : {
                      "pending" : "pending",
                      "processing" : "processing",
                      "completed" : "completed"
                    }
                  }
                }
              },
              { "data_is" : {
                  "data" : [ "commerce-order-unchanged:status" ], "value" : "canceled"
                }
              }
            ],
            "DO" : [
              { "LOOP" : {
                  "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
                  "ITEM" : { "list_item" : "Current list item" },
                  "DO" : [
                    { "commerce_ss_decrease_by_line_item" : { "commerce_line_item" : [ "list-item" ] } }
                  ]
                }
              }
            ]
          }
        }';
   $rules['phponwebsites_rules_decrement_stock_revert_cancel'] = rules_import($rules_export);
 return $rules;
}
?>


Drush site-install working with profile_name_install_tasks and forms Is there a way to add some arguments to the drush site-install command to set the value of some form fields introduced by a hook_install_tasks() in an install profile?

I tried some arguments variants on: drush site-install my_profile my_profile_form.my_settings.key=value

But to no avail.

See Drush output (for the form field 'Featureset')

WD php: Exception: Featureset field is required. in install_run_task() (line 414 of X/includes/install.core.inc). [error]

WD php: Warning: Cannot modify header information - headers already sent by (output started at X/drush/includes/output.inc:38) in drupal_send_headers() (line 1216 of X/includes/bootstrap.inc). [warning]

Exception: Featureset field is required. in install_run_task() (line 414 of X/includes/install.core.inc).

Drush command terminated abnormally due to an unrecoverable error. [error]

Drush si command has key=valueargument.
The key is in the form [form name].[parameter name] on D7 or just [parameter name] on D6.

drush site-install standard install_configure_form.site_default_country=FR

See more: http://www.drushcommands.com/drush-6x/core/site-install


Vocabulary Term Translation Edit/Delete Page Get Access Denied/ Doesn't Function Correctly I currently have a taxonomy term with multiple translations. When I visit the translate tab for the term it does list all of the languages properly.

However no matter what translation I'm attempting to edit, it takes me to the edit page for English. I found that it seems to automatically send you to the edit page of the translation that matches the user's set Site language.

If I change the site language of the admin user to Spanish no matter what edit link I click it only takes me to the Spanish translation. The admin user has access to all allowed languages so I'm not sure why it would restrict all access to the specified site default language.

Side note if I attempt to delete a specific translation it deletes all translations.
If I manually enter this path

/taxonomy/term/{taxonomy_term_id}/translations/edit/{language}

I get an access denied page.
I shouldn't ever get an access denied page because I'm an admin with all
permissions enabled.
I do believe this path should exist because looking at the routes associated with the taxonomy term entity does contain that path. Here is some of the content of the entity info produced by devel.

[links:protected] => Array
    (
        [canonical] => /taxonomy/term/{taxonomy_term}
        [delete-form] => /taxonomy/term/{taxonomy_term}/delete
        [edit-form] => /taxonomy/term/{taxonomy_term}/edit
        [create] => /taxonomy/term
        [devel-load] => /devel/taxonomy_term/{taxonomy_term}
        [devel-render] => /devel/taxonomy_term/{taxonomy_term}/render
        [devel-definition] => /devel/taxonomy_term/{taxonomy_term}/definition
        [token-devel] => /taxonomy/term/{taxonomy_term}/devel/token
        [drupal:content-translation-overview] => /taxonomy/term/{taxonomy_term}/translations
        [drupal:content-translation-add] => /taxonomy/term/{taxonomy_term}/translations/add/{source}/{target}
        [drupal:content-translation-edit] => /taxonomy/term/{taxonomy_term}/translations/edit/{language}
        [drupal:content-translation-delete] => /taxonomy/term/{taxonomy_term}/translations/delete/{language}
    )

Why can't I access the edit forms for the translations that don't match the users set site language? How can I fix this?

Just check "Content language" under "Content language detection".


How do I migrate users passwords from Drupal 6 to Drupal 7? I am trying to migrate users from a Drupal 6 to a Drupal 7 site. My problem is how to change their password from MD5 to the hash one (used by D7).
Do you have any idea?

To update the md5 password to the hashed one I needed to use user_hash_password() and concact an 'U'. Here is the script that I used to make it work.

<?php
        require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
        $res = db_query('select * from drupal.users');

        if($res) {
                foreach ($res as $result) {
                        $hashed_pass = user_hash_password($result->pass, 11);
                        if ($hashed_pass) {
                          $hashed_pass  = 'U' . $hashed_pass;
                          db_update('users')->fields(array('pass' => $hashed_pass))->condition('uid', $result->uid)->execute();
                        }
                }
        }

Then I ran

drush scr <name_of_the_script_file>

And it worked.


How to iterate through Drupal.settings in a js file when there are lots of variables? Am trying to create a health service locator using Google maps API on my Drupal 7 site. (FYI, I cant use location module or open layers, because, Create a hospital locator in drupal 7  )

OK, so now I have a form, which takes the users location, type of service (eg, hospital, pharmacy etc) and the proximity around which they wish to find the result, using Google Maps API and Google Places API I fetch the results (details about those near by places such as hospital) in JSON format from Google. The fetched data includes each place's name, address, rating, phone number, latitude, longitude etc. now I store those values in form_state['storage'] and then sends it to the JS file using the drupal_add_js() method.

The below code is sending the values,

<?php
for($i=0;$i<$length;$i++)
 {
  drupal_add_js(array('a'.$i =>array(
             'lat'=> $form_state['storage']['results'][$i]['geometry']['location']['lat'],
             'long'=> $form_state['storage']['results'][$i]['geometry']['location']['long'],
         'name'=>  $form_state['storage']['results'][$i]['name'],
         'rating'=>$form_state['storage']['results'][$i]['rating'],
         'vicinity'=>$form_state['storage']['results'][$i]['vicinity'],
         'formatted_address'=>$form_state['storage']['results'][$i]['formatted_address'],
         'international_phone_number'=>$form_state['storage']['results'][$i]['international_phone_number'],
         'website'=>$form_state['storage']['results'][$i]['website'],
)),'setting');

}
?>.

the details of first place is in a0, second place detail is in a1 etc.

FYI, each place details are in Drupal.settings.a0, Drupal.settings.a1  etc.
 I mean, I can access those variables in js file using,

Drupal.settings.a0.name and Drupal.settings.a0.website
similarly for second place, Drupal.settings.a1.name etc.

Now my problem is I need to iterate through these different places.

I can iterate through different variables of one particular place usin the below for loop,

for(var x in Drupal.settings.a0)
{
 alert(Drupal.settings.a0.x);
}

But, I cant iterate through different places, like a0, a1 etc.
I mean I cant attach a variable to drupal.settings..!

I tried tried putting all places in an array, i.e, a0,a1,a2 are in an array named arr[] (I have the total no. of places in Drupal.settings.my_vars.length) then, I iterate through this array and tried attaching arr[i] to Drupal.settings as Drupal.settings.arr[i].x but it doesn't work.

How can I do it...?? Is there any better way of achieving it...??

Thanks in advance.

You can add your module name to settings like this

$locations = array();
for($i=0; $i < $length; $i++) {
  $locations[] = array('a'.$i =>array(
    'lat'=> $form_state['storage']['results'][$i]['geometry']['location']['lat'],
    'long'=> $form_state['storage']['results'][$i]['geometry']['location']['long'],
  );
}

drupal_add_js(array('mymodule' => $locations), 'setting');

and loop is js like

for (var x in Drupal.settings.mymodule) {
  // ...
}


Facebook Comment Social Plugin - Get Comment Count on Nodes and Views I used a module 'Facebook Comment Social Plugin' to display comments on nodes, which it successfully did, however i like to know, is there a way to display comment count for the comments coming from the facebook plugin in nodes and views.

This might be late to answer, but do checkout Social Stats module.

This is a statistics module. It provides data from various social media sites. The data which is saved per node. It includes data from:

Facebook : likes count, shares count, comments count & total count.
Twitter : tweets count.
LinkedIn : share count.
Google Plus : plus one count, share count & total count
Total Share Count : total across all available social networks

It has an view integration. So, it would serve your purpose exactly.
P.S - I am the author and maintainer of the module. If you find any issues please feel free to report using the issue queue, and I'll be glad to help.


Profile 2 fields not displaying in registration form I create 2 Profiles with distinct Fields as well as assigned each one a unique role with permissions to Administer Profile2 registration paths, but all I'm getting is the default Username and E-mail fields nothing else (On both of them).

Make sure you check to "Show during user account registration" on the profile type.

Admin > Structure > Profile Types > [Type] > Edit


Entity translation not working I'm using Entity Metadata Wrapper and Entity Translation to programatically add a translation to existing nodes. This is my code, i'ts not working and I'm at loss to understand why:

$meta = entity_metadata_wrapper('node', $node);

$new_lang = 'fr';

$meta->language($new_lang);

$meta->language($new_lang)->title = 'Some French Title';

// Other fields are changed, but not shown here

$r = $meta->value();

$handler = entity_translation_get_handler('node',$r);

$translation = array(
  'entity_type' => 'node',
  'nid'         => $node->nid,
  'uid'         => $node->uid,
  'created'     => $node->created,
  'changed'     => $node->changed,
  'translate'   => 1,
  'status'      => 1,
  'language'    => $new_lang,
  'source'      => $node->language,
);

$handler->setTranslation($translation, $r);

$meta->save();

Most importantly, you should be calling $handler->saveTranslations(); after setting the translation. Your updated code should look like this:

$meta = entity_metadata_wrapper('node', $node);

$new_lang = 'fr';

$meta->language($new_lang);

// The body field is set to be translatable.
$meta->language($new_lang)->body->value = 'Some French Body';

// Other fields are changed, but not shown here

$handler = entity_translation_get_handler('node',$node);
$translations = $handler->getTranslations();

// This is a convenience way to initialize the translation data for
// the new language.
$new_translation = array(
  'language' => $new_lang,
  'source' => $translations->original
) + $translations->data[$translations->original];

$handler->setTranslation($new_translation);
$handler->saveTranslations();
$meta->save();

As a last note, the title property of a node is not translatable, unless you use the Title module. In that case, you should probably use the $meta->title_field accessor to change the value.

Good luck!


How to add logic to Webform Using webform 3 module, how to add logic to my multi-step form so that I can choose what to display on second step based on the choice from step1?

I have been successful doing this using Forms API, but then I loose the ability to do webform reporting(analytics). Is it possible to combine form (design, analytics and  validation) using "webform module" with logic using Forms API? or is there a better solution?

It appears Webforms has conditional rules which works great. Also there is a module called Webform Conditional for in page conditional statements.


How to search views with exposed filters I have a page view with exposed filters (4 checkboxes with ajax calling) which user can change.

I want to change default search, to searching only results which appears in this view.

How can I do that?

Views filter populate should help you with your issue.  What you need to do is don't expose the Title, Body, and Location in the Filter Criteria of your view.  Then add Populate filters and expose it and select Title, Body, and Location as your filters.


How to query Nodes by a referenced Term Value (via EntityFieldQuery)? I have to query my content types (firm_unit) based on different fields conditions, and for that I came to use EntityFieldQuery.

$query = new EntityFieldQuery;

$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', $type = 'firm_unit')
  ->propertyCondition('status', 1);

This is nice when I want to query conditions on direct content fields, like these:

$query->fieldCondition('field_name', 'value', $keyword, 'CONTAINS');
$query->fieldCondition('field_sector', 'value', $sector, '=');

It seems to be unable to directly access, and then query by, referenced contents, like names/titles and fields of referenced terms (it just can access their tids).

Which is then the way I may query my node contents based on term referenced values?

Should I query the tid before (is the _taxonomy_get_tid_from_term  func the proper to use?), and then query the content like this?

$my_tid = _taxonomy_get_tid_from_term ($term_to_match);<br/>
$query->fieldCondition('term_fieldname', 'tid', $my_tid);

EntityFieldQuery can not, as you have noticed JOIN tables, because it may run queries against a backend where JOIN does not make sense.

You will need bridge this gap in code, which is what your own suggestion is doing, it looks fine to me.

However, if you don't intend to run on MongoDB or some such, my personal preferance is would be to ditch EntityFieldQuery in favor of a SQL-query with db_select instead. This mostly because MySQL provides the ACID, while all the "no-sql" db's needs to break atleast one of those.


How do I delete files using the Content > Files interface? I got a ticket from our stakeholders that certain outdated PDFs are googlable, and this is causing problems with people going on old information.

Navigating to admin/content/files, I am able to find entities(?) for the files, by searching on their filename and extension (MIME type). There is also a seemingly handy column "Used In". However, when I click through the values in the "Used In" column (e.g. "2 places"), the paths are like render elements or something similiar: {Content Type} > Paragraphs (previous revision) > Column Content (previous revision) > Column Wrapper Content (previous revision) > Accordion Section (previous revision) > Accordion Section Body.

From this information, I am not able to navigate to the page where the file resides, in order to remove it.

Furthermore, one of the files is used in 0 places, and there appears to be no interface that allows me to delete it. I am able to open the PDF from the file path link in an incognito window, so I conclude that, even though a user can't discover this PDF by navigating on our site, they still might get to it through a google search.

My question is different from this similar question, How do I delete files the correct way?, because in that question, the asker already knows which node it is that contains the file they want to delete. In this case, I don't know where on the website the file is actually attached. I'm trying to get that information.

One proposed solution might be to google for the files, and find out where on our site they are from Google's search results, but I want to know how to delete these files through Drupal, so in a future case, where I can't find them through google, I still have a way to delete them.

Edit even after googling search terms for the files, I find that the top search results are direct links to the PDFs themselves. So even using google, I'm not able to determine which page or URL on our site has them on.

How do I delete these files, listed in the "Files" tab of the admin content screen?

Edit 3 So Clive's first answer "didn't work" for me, because it turns out, as Clive deduced, that the reference to the files were broken. But I was able to confirm that the code did indeed work by testing a node whose attached image I was certain of. I've deleted "Edit 2" expounding on the broken reference information I got from the code.

There are a couple of approaches; if you'd rather manage the deletion a bit more tightly, you can use the API to get a list of node (and/or other "thing") IDs that reference a particular file:

$usage = \Drupal::service('file.usage')
  ->listUsage(\Drupal\file\Entity\File::load($fid));

Then you can edit the node/etc, find the offending reference (in your example it looks like that would be within a paragraph of a previous revision), and remove it.

If you just want an interface for deleting files, there's the fledgling Delete Files module. It will even degrade gracefully for deleted files that are still referenced:

  If a file you've deleted is managed by Drupal, this module replaces it with a new empty file to head off potential problems with dangling file references.


How do you import a database through lando? I am trying to setup a site within lando and need to import the database. How do you import a database through lando?

lando db-import <path to sql or sql.gz or .zip file here> will do that for you.

db-import will drop all tables before performing the import.  it has a --no-wipe flag that can be used if you don't want to drop tables first.

More information in the documentation: https://docs.lando.dev/guides/db-import.html


Add new items to a multivalue field instead of override existing values I have an Article content type with a multi-values taxonomy reference field (field_article_countries) for the Countries vocabulary. I also have a Book content type with a multi-values taxonomy reference field (field_book_countries) for the same vocabulary.

I am trying to:

Loop through all the loaded articles one by one
Get all the field_article_countries values
Set those values to field_book_countries
Save the loaded Book node

For example, a Book node (ID 12) has field_book_countries set to none. An Article node (ID 3) has field_article_countries set to Italy; another Article node (ID 40) has field_article_countries set to Greece, Turkey, Egypt, Brazil, Spain.

I want to:

Load the first Article node
Get the value of its field_article_countries (Italy)
Load the Book node and set its value of field_book_countries to Italy
Load the other Article node
Get the values of its field_article_countries (Greece, Turkey, Egypt, Brazil, Spain)
Set the field_book_countries values for the Book node to Greece, Turkey, Egypt, Brazil, Spain, Italy
Save the Book node

The code I am using to achieve this is the following.

$articleIDs = [
  '3',
  '40'
];

// Load all the articles.
$articles = \Drupal\node\Entity\Node::loadMultiple($articleIDs);

// Loop through the loaded articles.
foreach ($articles as $article) {
  // Get the "Countries" Values.
  $countries = $article->get('field_article_countries')->getValue();

  // Set the 'countries' values to the node "book".
  $book->set('field_book_countries', $countries);
  // $book->field_book_countries[] = ['target_id' => $countries];
}

// Save the Book node.
$book-->save();

However, for some reason and during the loop, the new values of field_book_countries are overriding the existing one.

What am I doing wrong?

You need to loop through all articles, saving all countries in an temp array. When the loop finished save the countries in the book node.

For example:

$countries = [];
// Loop through loaded articles.
foreach ($articles as $article) {

    // Get the "Countries" Values.
    $countries = array_merge($countries, $article->get('field_article_countries')->getValue());
}
// Set the 'countries' values to the node "book".
$book->set('field_book_countries', $countries);
// Save Book node.
$book-->save();


Best practice for avoiding module / theme / profile name clashes? We currently have our code managed such that each site has its own theme and install profile.
These have naturally evolved in such a way that the names of these items (and their directories) tend to be the same.

For example, one site's theme and profile are both called 'dennis'

This causes problems with feature servers, and (I'm suspecting) with Aegir.

Now... it's relatively easy to rename either of these (although, for various reasons it's noticeably easier to rename the profile). Is there any sort of best practice here, ie is it normal to call the theme dennis_theme, or the profile dennis_profile? Should I apply this convention to both, or just to one?

In my office we usually have a site key that gets used for most things.

Client: Acme Company & Co
Key: acme
Site Folder: /path/to/WebServer/sites/acme
Custom Modules: acme_tweaks, acme_forms, acme_blocks, acme_settings
Theme: acme_theme
Repo: acme.git
etc...

For code that we re-use from site to site, we ensure that it's generalized and client ambiguous and then add it to some common modules that are part of our default module set - such as:

theme_tweaks
template_suggestions

Our rule is that unless it can be applied to all our client sites (at least moving forward) then it shouldn't go in theme_tweaks but in acme_tweaks etc.


"Flexible Field" for Drupal I am sorry for the vague question but I have no idea about where to start.

Please think of a scenario that, you created a video content type and you want your site visitor either upload their video files to your site, or they use the embed codes from any third party providers (youtube, vimeo etc.). For the sake of providing a clean GUI, you do not want to show both fields, but based on the choice of your user (maybe an image combo), you either show the file upload field or text area field (where they put the embed code in)

My question is, I wonder if there any elegant way to do it in Drupal without making any PHP, HTML or CSS modification?

I have done this in the past by adding a drop down that gives the user an option of selecting "embed" or "upload"  then use the Conditional fields module to show or hide the required field.


List all revison users on a node I want to list all the users who have ever contributed to the revisions of a node.

Use The Views Module To Create A Custom Block

If you're using the Views module you can create a view that will show you what you need.

Create a new view (admin/structure/views/add) and choose 'Content Revisions' as the view type.

Add the 'Node Revision: User' relationship so that you can access the username of the user that made each edit.

Add a 'Node ID' contextual filter to your new view.

When the filter value is not available you should provide a default value.  Choose the Content ID from URL.

Add the field 'User: Name' but be sure to select the relationship you created earlier as in the graphic.  You may also want to add a link to view the revision or see when the revision was created.

You can optionally sort by "Content revision: Updated date" desc to ensure the block is easy to follow.

The last step is to go to 'admin/build/block' and enable the new block for the appropriate content types.

Lastly, one of my favorite resources for views comes from NodeOne's insanely talented Johan Flak. If you're new to views check out http://nodeone.se/sv/node/20

Also, as @indrock said in his comment, you can also see the history of a node's revisions at http://your-site-url/node/%nid/revisions  This is a much simpler solution and I wish I would have seen it before I went views crazy.


Render page callback output in another region than "content" I am implementing hook_menu and I want to render the output of one page callback in a certain region, other than content.

Is there a way of doing this?

Instead of defining a page via hook_menu it is better to define a block that you can place everywhere across the site.

Is there any requirement that restricts you to using a page?

If not the following code creates a block:

/**
* Implements hook_block_info().
*/
function YOUR_MODULE_block_info() {
  $blocks = array();
  $blocks['YOUR_BLOCK_ABC'] = array(
    'info' => t('YOUR BLOCK NAME'),
  );
  return $blocks;
}

/**
* Implements hook_block_view().
*/
function YOUR_MODULE_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'YOUR_BLOCK_ABC':
      $block['subject'] = '';
      $block['content'] = _YOUR_MODULE_BLOCK_ABC_CONTENT();
      break;
  }
  return $block;
}

function _YOUR_MODULE_BLOCK_ABC_CONTENT() {
  // This is where you code you use for the page goes.
  return t('Hello world');
}

Code from http://kahthong.com/2013/06/create-your-own-custom-drupal-block-programmatically

You can restrict the block visibility in the block settings to only be shown on single pages. Maybe this might solve the problem. To access arguments from the current page you can use the arg function.

Cheers
j


Show the list of all users who edited a node in Drupal 7 Usually, I display the name of the user edited a node at last, not the ones in the middle. I want to display a list of all the users who edited a node. Is that possible by using Views or any other way? They do so here.

So you thought that part would be closed source ? No!
Check http://drupalcode.org/project/drupalorg.git/blob/refs/heads/7.x-3.x:/drupalorg_handbook/drupalorg_handbook.module which adds this functionality to book nodes. This module was built for drupal.org but it's not that difficult to get it modified for your needs!

If you want to do this in Views,

Create a view with Content Revisions in under "Show". uncheck page display,check 'make a block', and click continue and edit. You will be taken to Views UI. Now, remove existing fields and add a new relationship to Content: Author.
Add new field to user name from the just-added relationship.
Add new contextual filter to the node ID. Set the default action to take argument from URL. Then, expand click on Query settings and enable Distinct.
Give the block a title and admin name.
Place block where you want.
Enjoy!


How to add attachment in views slideshow Goal: Putting text as an attachment on views slideshow

Theme: Bootstrap

Drupal: 8

Content type: Slideshow which has two fields: image and text

Added two nodes of the content type.

Created a slideshow block using views and bootstrap carousel. Slideshow is working just fine. Slideshow just displays the image/slide field.

Below shows just the views block for slideshow.

Now, I like to put the text field as an attachment (putting the text on top of image in the slideshow) to the views block.

Views > Add > attachment > after that I am lost. I am not sure what setting to use to put the corresponding text field on each image slide.

Below shows I added the attachment in view but when I visit my site, I only see image slideshow and I do not see the text (slide-img) on the slideshow as an attachment.

Please advise.

All you need to do is to add your text field to the "Fields" section of this view. Not as an attachment. As a field.


How can I copy some content from one site to another site? I have two sites i'm working on (one in D8 8.4.5, the other in 8.5.0).
I'd like to "copy" some elements from one to the other.
For example, some nodes or some menus (with their links, of course) or some users.

How do I do that?

With configuration sync and database tables export/import?

You'll need to use Drupal Core's migration module with Drupal 8 migration (source).

  This is an Migrate source to import Data from a Drupal 8 site.

If you're not familiar with creating custom migrations, you'll need to read up on that. Also read the README file.


After forced login, return to first entered login I have situation where i redirect user programatically on condition. After condition is met:

drupal_goto('http://www.mydomain.com/user/login');

But what it does, it forgets path that was initially entered by user.

Is there a way to redirect user to login (programatically), but to remember url ?
(as it works when you try to login to admin area).

BTW, i have Login Tobbogan also installed. (Drupal 7)

Thanks!

I believe the correct way to do this is:
drupal_goto('user/login', array('query' => drupal_get_destination()));

The documentation for drupal_get_destination() states:

Prepares a 'destination' URL query parameter for use with drupal_goto().
Used to direct the user back to the referring page after completing a form. By default the current URL is returned. If a destination exists in the previous request, that destination is returned. As such, a destination can persist across multiple pages.

Update: You could try putting the URL in directly:
$path = 'path-to-redirect-to'; // or $GET['q']
drupal_goto('user/login', 'query' => array('destination' => $path)));


How do you set a one-off access checker on a route? As far as we can tell, the "Simplified custom access checker" section of the handbook is outdated. The entirety of CheckProvider seems to be service oriented and this is the provider which has the $route->setOption('_access_checks', $checks); call. In turn, AccessManager::check has a $checks = $route->getOption('_access_checks') ?: array(); call. There's nothing which would accommodate one-off checkers like the handbook page suggests:

requirements:
  _custom_access: '\Drupal\example\Controller\ExampleController::access'

and based on our debugging, this is indeed not working. What is the current way, if any, to do this?

The handbook is correct. The access is handled by services. The normal way to implement a custom access check is to define a service in mymodule.services.yml. See this example from the core book module:

  access_check.book.removable:
    class: Drupal\book\Access\BookNodeIsRemovableAccessCheck
    arguments: ['@book.manager']
    tags:
      - { name: access_check, applies_to: _access_book_removable }

And then use this in routing:

_access_book_removable: 'TRUE'

Here you can choose your own arbitrary naming schema.

As described in the handbook, if you want to simplify this, you can reuse the service access_check.custom, which is already defined in core.services.yml:

  access_check.custom:
    class: Drupal\Core\Access\CustomAccessCheck
    arguments: ['@controller_resolver', '@access_arguments_resolver_factory']
    tags:
      - { name: access_check, applies_to: _custom_access }

Then you have to use _custom_access: for the route. You can not use something like _my_module_access: as before, the key must match the tag in the service definition.

The first solution puts the complete logic of the access check in a service and makes it reusable and self-explanatory. If you only need the access code in one route and want to place the access code in the controller class the second method provides a shortcut.


Why can't I add another allowed file extension to a Drupal 7 image field? I've added the SVG file extension for image uploads via admin/structure/types/manage/image/fields/gallery_image, as you see below:

But when I go to upload an image, I'm still not allowed to upload SVG.

I definitely pressed "Save" in the admin page, and I cleared the cache, and I even see the settings as I wanted them in the database, when I inspect the field_config_instance table.  There must be some other table or cache that's not updating.  Any idea?

The Image widget internally allows (and silently enforces post Drupal 6) the use of only the png, gif, jpg and/or jpeg extensions. So, while you can remove an extension from a field, eg, I have removed gif from most of my implementations to avoid anything animated, you can't add any to this list.  I would imagine this is because it in itself displays the image after being uploaded and didn't want to break any displays in older IE browsers in the actual form (plus, who knows how image styles would work on them as well :)


Get path from router and redirect after autocomplete selection I have a form that is inflated inside a box.  In that form I have an autocomplete field.  I want to allow the user, when they select an item from the autocomplete's suggestions they are automatically redirected to the appropriate page.

My current idea is to handle this in JS.  But I don't like this as it makes it very difficult to use Drupal's routing system to route -- instead I have to hardcode things, which is bad.

class AutocompleteSearchForm extends FormBase {

  public function getFormId() {
    return 'search_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['search'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Lookup'),
      '#description' => $this->t('Search.'),
      '#placeholder' => $this->t('Search'),
      '#autocomplete_route_name' => 'block.autocomplete.callback',
      '#autocomplete_route_parameters' => array('name' => 'name'),
      '#attached' => array(
        'library' => array('module/autocomplete'),
      ),
    );
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    \Drupal::logger('module')->warning('form submitted for' . $form_state->get('search'));
  }
}

And my JS is:

(function ($) {
    $('#edit-search').on('autocompleteclose', function (event, node) {
        var entity_id = $(this).val();
        alert(entity_id);
    });
}(jQuery));

As you can see, I tried to manage this through the callback, but I don't expose a button and this doesn't submit unless the user hits the "enter" button, which isn't exactly intuitive.

Is JS the best way to handle this?  If it is, is there a good way to get access to Drupal's path/router system from JS?

Try to use $build['#attached']['drupalSettings']['vartest'] = $test; to pass $test from PHP to JS. The variable $test contains the Drupal's path/routes.

Replace $build with the variable containing the form or the render array to which the settings are attached. In a form builder or hook_form_alter(), that would be $form.


How to group by with rollup? How to get booking records from booking table? How to get GROUP BY function WITH ROLLUP?

Here is my SQL query:

SELECT * FROM booking
GROUP BY startBooking WITH ROLLUP;

How to convert above query in Drupal 7?

     $queryPrice = db_select('booking', 'b');
     $queryPrice->fields('b');
     $queryPrice->groupBy('b.startBooking');
     $resultPrice = $queryPrice->execute();

How to roll up use in above query in Drupal 7?

You can add a GROUP modifier right to the end of the string:

$queryPrice->groupBy('b.startBooking WITH ROLLUP');

With the rest of your query Drupal produces:

SELECT  b.*
FROM
{booking} b
GROUP BY b.startBooking WITH ROLLUP