7 - How to Add Custom Error Class to Radio Button and Checklist Fields I created a field with Radio buttons and when it fails to validate, there is no red highlight around it.

There is only an error message at the top.

How can I add a custom CSS class to any radio button fields upon a failed validation?

I am already altering this form with hook_form_alter(); and have a custom validation function, so I am willing to work on a custom module for this but just need some help being pointed in the right direction.

I would ideally like to add a ".error" class or something to this div and customize it in my CSS to also give it a red border.

How can this be acheived?

Out of the box webforms created with Drupal core and the Webform module do not have in line error messaging and indicators for each form field.

You can either:

add custom hooks and javascript to get inline validation, or
install client-side validation module and associated javascript library to get validation/messaging for all standard form elements.  See https://www.drupal.org/project/clientside_validation


How can I alter node markup from a custom module (not theme)? In a custom D8 module (not a theme or sub-theme) what is the best way to alter all nodes of a specific content type by prepending them with simple markup?
I'm trying this approach with no success ...
custom/custom.module:
<?php
/**
 * @file
 * Custom module hook implementations.
 */
/**
 * Implements hook_theme().
 */
function custom_theme() {
  return [
    'custom_article_node' => [
      'template' => 'custom-article-node',
      'variables' => [],
    ],
  ];
}

custom/templates/custom-article-node.html.twig:
<i>This is a Custom Article node.</i>
{{ content }}

I'm not sure how to pass the node to the template, or to test what content type it is ... and I'm not sure if this theme hook is even executing.
(I know how to override templates in the theme layer, but in this case I need to do it in a custom module.)

This did the trick:
custom.module:
<?php

/**
 * @file
 * Custom module hook implementations.
 */

/**
 * Implements hook_theme().
 */
function custom_theme() {
  return [
    'node__custom_article' => [
      'template' => 'node--custom-article',
      'base hook' => 'node',
    ],
  ];
}

Credit where it's due:
https://www.drupal.org/forum/support/module-development-and-code-questions/2015-06-03/drupal-8-override-template-with#comment-12461953


Custom views sort handler There is a content type has a Field Collection type field(multi value), this Field Collection has a date field, I want to sort the node according to the max date value in this Field Collection field(multi value) in views, how to custom this views sort handler.

Use aggregate and set the option for distinct results. Aggregate is similar to GROUP BY in SQL so be careful what fields you include. If you really need to do it with custom code set a tag for your view's query in advanced settings and then use this tag to alter your query by implementing hook_query_alter or hook_query_TAG_alter in a custom module
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_query_TAG_alter/7


Get a list of all the modules in code base This is more of a developer question.

I need a list of all the modules that are present in my code base. I am not looking for enabled or install modules. I am just looking for all the modules(code) present in my code base.

Use the following command in the terminal at the root of your site.

grep -hr '^name =.*' . | sort

This is the non drush way and also helps me identify the duplicate code for a single module if any.


How to reformat HTML output of format? I have looked for days and cannot find an example of what I need to do. I wish to reformat the HTML output ckeditor uses for blockquote.

CKEditor output for quote:

Content

I wish it to output to something like:

Content

If I am able to do this, it has a lot of potential uses for every format provided in many sites for me. Does anyone know how to do this?

*Edit: My preference is to do this in PHP within a module if possible rather than JavaScript.

You could do this easily with jQuery, check the .wrap() method:

$('blockquote').wrap('

');

The wrap() method will wrap elements into another element.

If you want to do it as custom CKEditor plugin I would look at an existing plugin that does something similar and modify it to get the markup you want. I found a Drupal module with a custom plugin that add a wrapper element to blockquote: https://www.drupal.org/project/ckeditor_blockquote_attribution


Drupal 8 - What is the format for viewsreference arguments? I am using a views reference field inside a paragraph on a node. I know that I may add optional arguments but how should I format the arguments? Two things I would like to do are:
 - Limit the number of results returned in the view to 3
 - Display only results with a certain taxonomy term

Here is a screenshot of the arguments field in the paragraphs UI.

I'm see code ViewsReferenceFieldFormatter.php.

The argument field is treated as follows:

if (preg_match('/\//', $argument)) {
  $arguments = explode('/', $argument);
}

Hence argument have next format: tid/nid/custom_id


Composer killed when installing a module I am actually running Drupal on a LAMP (XUbuntu 20-04 with 4 GB RAM in VirtualBox)
At the beginning of the installation I had no problem with installing dependencies using composer
But since yesterday every composer command gets killed like in the following code (entity print installation):

igpde@igpde-VirtualBox:/var/www/html/d8igpde2$ composer require dompdf/dompdf
Using version ^0.8.6 for dompdf/dompdf
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Killed

I thought it could be a memory problem but in the php 7.4 client installation:

I read -1 should mean no limit

; Maximum amount of memory a script may consume (128MB)
; http://php.net/memory-limit
memory_limit = -1

Any Id how I could solve this problem?

Thanks in advance for you suggestions

Running with the vvv flag:

igpde@igpde-VirtualBox:/var/www/html/d8igpde2$ composer -vvv require dompdf/dompdf | tee composer.log
Reading ./composer.json
Loading config file ./composer.json
Checked CA file /etc/ssl/certs/ca-certificates.crt: valid
Executing command (/var/www/html/d8igpde2): git branch --no-color --no-abbrev -v
Executing command (/var/www/html/d8igpde2): git describe --exact-match --tags
Executing command (CWD): git --version
Executing command (/var/www/html/d8igpde2): git log --pretty="%H" -n1 HEAD --no-show-signature
Executing command (/var/www/html/d8igpde2): hg branch
Executing command (/var/www/html/d8igpde2): fossil branch list
Executing command (/var/www/html/d8igpde2): fossil tag list
Executing command (/var/www/html/d8igpde2): svn info --xml
Failed to initialize global composer: Composer could not find the config file: /home/igpde/.config/composer/composer.json
To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section
Reading /var/www/html/d8igpde2/vendor/composer/installed.json
Loading plugin Drupal\Composer\Plugin\ProjectMessage\MessagePlugin
Loading plugin Drupal\Composer\Plugin\Scaffold\Plugin
Loading plugin Drupal\Console\Composer\Plugin\Extender
Loading plugin Composer\Installers\Plugin
Running 1.10.9 (2020-07-16 12:57:00) with PHP 7.4.3 on Linux / 5.4.0-42-generic
Downloading https://packages.drupal.org/8/packages.json
Writing /home/igpde/.cache/composer/repo/https---packages.drupal.org-8/packages.json into cache
Downloading https://repo.packagist.org/packages.json
Writing /home/igpde/.cache/composer/repo/https---repo.packagist.org/packages.json into cache
Reading /home/igpde/.cache/composer/repo/https---packages.drupal.org-8/drupal-provider-2020-3.json from cache
Reading /home/igpde/.cache/composer/repo/https---packages.drupal.org-8/drupal-provider-2020-2.json from cache
Reading /home/igpde/.cache/composer/repo/https---packages.drupal.org-8/drupal-provider-2020-1.json from cache
...............................................
Reading /home/igpde/.cache/composer/repo/https---repo.packagist.org/provider-sabberworm$php-css-parser.json from cache
Killed

the preceding output is very long
It waits a lot of time before declaring Killed. looks like a time out!
except for the last reading every Reading ... happens fast

You ran out of memory. This happens all the time with Composer.
Composer is a huge memory hog, especially when used with Drupal because of all the external interdependencies. And Drupal's requirements continue to grow with every new release, so the memory needed to use Composer with Drupal continues to grow. 4Gb of available memory should be enough, currently, but 2Gb is not enough in my experience. I find this problem can be avoided if you configure your system with sufficient swap space (2x physical memory is usually sufficient). This is for a development system of course - you won't be using Composer to install modules like that on a production system, you should be using a .lock file instead, so Composer's memory requirement will be much smaller.


Price is 0 then show "On Request" text I have to show "On request" if price is 0, I have used Commerce Extra Price Formatters and it allow us to do so,but I need currency converter block also and if I go through Commerce Extra Price Formatters then it will not convert currency, So if there is any other alternative to show text without using any module then pls suggest..

Add this to your (template) .tpl.php file

<?php

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;

$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
$field_value = $wrapper->field_price->value();

if ($field_value == 0) {
  print 'On Request';
  } else {
  print $field_value;
  }
}

?>

Not sure if the machine name of price is field_price.

If the machine name is just price then use $field_value = $wrapper->price->value(); instead.


Uninstalled modules still in system table? Right now I,m facing problem with high resource usage of my Drupal 6 website, I can't find the solution to solve the issue, when I checked the system table, uninstalled modules still in system table, Is this normal or not uninstalled properly.

Drupal adds an entry in system table for each module present in the filesystem, even if it has never been enabled. This is the same for Drupal 6 and 7. In Drupal 8 the system table has been removed.

So, if you want to get rid of entries in system table for uninstalled modules, remove them from the filesystem once they're uninstalled.

See _system_rebuild_module_data() for details in Drupal7. In drupal 6 this function was called module_rebuild_cache().


Membership entity commerce join form I'm using Membership entity commerce (7.x-1.0-alpha2) for my website.
On the join page, I'd like to reorder the membership types : I got "one month", "three months" and "one year", but they don't show up in the desired order... Plus I would like to customize this form (hide description and term length). I've been trying to change different things in the module's code with no luck.
Any ideas ?

First off, don't edit the module's code directly. Make a custom module that will hold your changes.

Secondly, you can use HOOK_form_alter to make changes to the form.


Search Engine returning multiple 404s, Redirect 404 urls based on node id in the url I am using Drupal 7. Many of my url paths (up to 6,000) have moved to new url paths with no 301 redirect so they are returning lots of 404s on google. i have paths like /articles/bla/bla-bla/12345 which moved to /articles/bla-new/something/12345

Since the old path which now returns a 404 has the node id in the url at the end, i want to redirect a path like this "/articles/bla/bla-bla/12345" to node/12345 once the system detects a 404

Any suggestions for using .htaccess redirect rules or other module to achieve this?

I've tried this: RewriteRule ^articles/*/+ node/+ [R=301,L] but it doesnt look right.

I need some help. thank you in anticipation

Try

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^articles/.*/.*/(.*)$ /node/$1 [R=301,L]

of not worked use your absolute URL

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^articles/.*/.*/(.*)$ http://www.yourdomin.com/node/$1 [R=301,L]


How to add content in custom menu block? I have own menu type "Footer menu". When I add new content, "Footer menu" is not display in Menu setings. Where is the problem?

It's in the Content Type's settings screen under "Menu settings", you have to tick the Footer Menu to make it available for selection.


Keeping track of date when user profile has been updated I couldn't find a module or feature in D7 that keeps track of the date/time when a user updates their profile (any of the fields).
I'm not using profile2 and I'm not planning to switch to that, otherwise I could probably do it with the node revision.

Is there another way of doing it other than adding a "last_update" date field to the user and then using a hook_user_update() or hook_user_presave()?

I used the Rules module for this. There is a condition like "User Profile Updated" or something like this which you can use. You have then the changed and the unchanged values as tokens available for example to e-mail somebody about the changes.


Filter a view with content from two different content types I am creating an RSS feed that outputs all posts from two views: one is the men's blog, and the other is the women's. I found out that, when I specify my filters, I need to select both custom content types, leaving me with no results as if one cancels out the other. How do I add these two together, so I get all posts in the feed?

I noticed in contextual filters there is "month + year." I need something like this for two content types.

Are you creating two separate filters?  For example in your filter list, does it say:

Content: Type (= MensBlog)
Content: Type (= WomensBlog)

This essentially becomes an AND filter, which means it's looking for a content type that is both MensBlog AND WomensBlog.
You could instead change this to have the data in one filter.  Remove one of the filters and click to edit the other one.  On this screen, make sure the "Is one of" radio box is selected under Operator and then select MensBlog and WomensBlog.  This filter will be an or filter, rather


Would changing the permissions implemented by a module require a new version of the module? I have created a module, and I have to change the permissions implemented (and used) from the module. Should I create a new major version (e.g. passing from 7.x-1 to 7.x-2), or is it fine to create a minor version (e.g. passing from 7.x-1.3 to 7.x-1.4)?

I am talking of a module for which there is already an official release, not of a module that has only a development snapshot.

If it changes significant behaviour from previous version I recommend changing the major version. Even if its just a single adjustment like permissions. Wrong or missing permissions may cause huge problems on a site running your module.


Cannot move a site to the local server I am a complete newbie to Drupal, although I have many years of PHP development and even more years as a system administrator. My task is to move a few Drupal sites from CentOS 5.x/Drupal 6.x to Centos 6.x and Drupal 7.x

My plan is to move all sites to Centos 6.x and then upgrade to 7.x (if possible).

I downloaded the first drupal site using rsync and then I exported the relevant database with mysqldump.

I imported the database and created the appropriate mysql user with the same permissions as in the production server.

Important: In my local server I use the domain "testsite.local"
The production domain is "testsite.com".

Now, the problem: When I enter testsite.local in my browser, all I see is the Drupal page saying that I have not created a first page!

I am almost sure that this is a configuration problem, but I cannot pin-point it. Can you help me?

You need to configure Drupal to connect to your new database.
Also, make sure you have copied all the dot-files (.htaccess) as well. You will realize using a version control system is faster than rsync (although rsync is much faster than copying all files again and again).

Site migration instructions are nicely said in this drupal.org article. It's a lengthy one, so I'm quoting the part that you probably need to fix your site from current state.

  Make changes to the “Database settings” section of the settings.php
  file, to ensure that they are pointing to the new database, with the
  right user (which may be different that the one you used on the old
  computer) and the right password. You may also have to adjust the
  “base URL” if you are moving between a sub-domain and a domain level.
  If you are moving the site to a new domain, or to localhost, also
  check that "$cookie_domain" is not set to your old domain.


Registration database - Wiki I am looking for a good theme or module in which users can set up their own profiles on the page. I want them to fill out a form, so that their profile answers my questions, and I want to be able to approve their page first. Also, I would like to be able to grant other people admin rights to just some of the (geographic) profile pages; so that they may approve them. Is this possible?

In addition, I would need the answers from the forms to be transferred to a database so that people can find the profiles with specific answers. Also the profiles (after checking specific tags should be placed on the pages of these tags, when approved.

All quite complex and I am not sure if Drupal can help?

Everything you mentioned in the post is achievable by Drupal.

But not with just one module or a theme. Each functionality has its own module

1) Theme
There are lots of themes available in drupal download section which you can go through and decide on the theme that matches your requirement or you could build one on your own.

2) The profile page with in the Drupal has option to add the required fields. But if you want to extent it you can go for http://drupal.org/project/profile2

3) These additional two modules can show the percentage of the profile completed and if the profile needs to be completed. http://drupal.org/project/pcp and http://drupal.org/project/complete_profile

4) User approval is in build in Drupal.

5) To achieve the admin type you are looking there are two options one is organic groups and make each geographic location a group and give group admins the right to admin the members of that group. Another option would be to create a user role per geographic location and have the user select the role during the registration process using the autoassign role module and the use http://drupal.org/project/administerusersbyrole module to assign admin rights per role.

6) Once you use profile2 each profile is a content with in drupal and you can do all the searching that is default to drupal or you could also create views with exposed filter to do the searching on specific fields.

7) You could add a tag field to the profile and create a view to display the profiles with the tags as the argument to the view page.


Is there a required format for table name prefix? I know that in MySQL installations it must end in an underscore like prefix_ but I want to know if that is also the required format for Postgres and SQLite.

There is no requirement for the prefix to end in an underscore for any type of database but it can be beneficial for readability.

It is just a string of characters that Drupal prepends to table names in queries so it can contain any characters that are legal to use in table names in your chosen type of database.

Database prefixes are also not necessary at all unless you are using a single database for multiple purposes, for example you have all your drupal tables prefixed with drupal_ and then have other non-drupal tables without a prefix or with a different prefix.

That way you can easily tell which tables are for what.

This is usually only necessary if your hosting provider limits the number of databases you are allowed or sometimes in some more advanced Drupal configurations.

The way Drupal uses it is that if you use one of the db functions like db_select(), db_insert(), db_update(), db_delete() it automatically appends any prefix value you have configured.

When using db_query() it will also do this for any table name wrapped in braces, eg:

db_query("SELECT * FROM {node}");


Best practice to have a 'category' fields where admin can choose wich voices the user can choose I have a content type that needs a 'category' field; this can both be a taxonomy vocabulary or a text field (with the select widget), it doesn't really matter. (I won't have more then 5-6 voices at once.)

However, those voices may change over time, and normal users should be able to choose only few values when creating a new node.

What is the best practice to achieve this?

My idea is to use a taxonomy vocabulary, where only administrators can insert new voices, but I will need some kind of attribute (e.g., a boolean) that I can use in a module in order to filter them in hook_form_alter(). Could this be a Drupal-ish way to achieve that?

You could use a Node Reference field where your 'Voices' are nodes that only administrators can make, that way you can restrict the maximum number of 'Voices' allowed in the Node Reference field settings, and you could turn 'Voices' off by un-publishing them, or if you need the boolean value for the Node output you could just add a Checkbox text field on the 'Voices' node and use the Custom Formatters module to render the Node Reference field out as you wish.


how to insert simple gmaps in a block How can I insert a simple google map in a block?

I have a contact page with a contact-form (that one can fill in and send),
and I want to add to this page a google map.

thanks alot in advance!

There are many ways you can do this.

Go to maps.google.com, type in the address, get the link, then click the customize and preview embedded view. A popup should appear. Select the map size you want. Copy the html code and go to structure -> blocks -> add block, paste your code and select full html filter. And add your block to where you want it
Download the gmaps module and use it. By default is has a block created called location map

  The GMap module provides an interface to the Google Maps API within
  Drupal. It integrates with the Location module to provide users a
  clickable map for entering latitude and longitude, as well as to
  display maps of Drupal nodes and users. GMap can be used to create
  interactive maps with various map markers and content in map bubbles,
  taking advantage of Drupal's other content management features. The
  module also provides a Views display plugin which allows users to
  display the results of a view on a Google map.


Module for enforcing mandatory minimum number of tags in content type field? The built-in tag field functionality allows definition of a maximum number of tags, but not a minimum number.

Is there a contrib module to enforce a minimum?

You should be able to use Field Validation.

  This module adds an extra tab to each field instance, allowing you to
  specify validation rules for your field instances.

Just create your term/entity reference field and set up a validation rule using the Number of Selections rule.

Leave the maximum number of fields empty, and enter the minimum you require as the minimum required values.


Drush: "Unknown engine type outputformat" module conflict I've been searching in all forums for the answer, I had a problem with drush everything i did showed this message "Unknown engine type outputformat [error]"

I updated drush and still got that message since it took me so long to find the answer I'll post it here for other people with the problem
its the first answer.

The solutions is one of 3 things:

1.- Update drush

2.- Clear drush cache

3.- If you have the module "module_missing_message_fixer" the best solutions is to disable the module make the changes on drush and enable it when you are done, for some reason that module stops drush from working.

I hope this helps someone else.


Node with picture left and text right I have a content type with image and body fields. I am trying to edit the css so that the picture is on the left and the body/text is on the right with all the text staying in a column on the right rather than wrapping around the bottom of the picture. I attached a picture. I want what is show on the bottom. What is shown on the top is what I currently have. I don't want to use a module such as Panels or Display Suite.

Thanks for you input!

This appears to be about primarily about the CSS, and the right answer depends on how the html is structured.

Have you tried any resources like Learn CSS Positioning in Ten Steps?

If there are already some containers, you can float both the containers left and give them specific widths (probably).  Or you could use absolute positioning.  Do you have to account for the picture potentially NOT being there?

My best suggestion is to use Firebug or Inspector or similar to try out a couple things based on your DOM


Add help text to radio button when it's disabled I have two radio button groups that have a dependency.

When Button 1 is clicked, Buttons 4 and 5 should be disabled and vice versa. If Button 2 is clicked Button 4 and 5 are active and Button 3 is disabled.

How can I add help text to the disabled buttons that states the buttons are disabled because of your selection in Group A (Organization).

Here is the javascript that handles the buttons.

$(document).on('click', function () {
    // Organization and Data Classification dependency
    if($('#edit-field-organization-und-0').is(':checked')){

        $('#edit-field-data-classification-und-public').attr('disabled',false);
        $('#edit-field-data-classification-und-internal').attr('disabled',false);
        $('#edit-field-data-classification-und-confidential').attr('disabled',false);

        $('#edit-field-data-classification-und-btn1').attr('disabled',true);
        $('#edit-field-data-classification-und-btn1').removeAttr('checked');
        $('#edit-field-data-classification-und-btn2').attr('disabled',true);
        $('#edit-field-data-classification-und-btn2').removeAttr('checked');

    }
    else{
        $('#edit-field-data-classification-und-public').attr('disabled',true);
        $('#edit-field-data-classification-und-public').removeAttr('checked');
        $('#edit-field-data-classification-und-internal').attr('disabled',true);
        $('#edit-field-data-classification-und-internal').removeAttr('checked');
        $('#edit-field-data-classification-und-confidential').attr('disabled',true);
        $('#edit-field-data-classification-und-confidential').removeAttr('checked');

        $('#edit-field-data-classification-und-btn1').attr('disabled',false);
        $('#edit-field-data-classification-und-btn2').attr('disabled',false);

    }

}

enter code here

I would suggest you might want to think about using the Conditional Fields module and having two separate fields for the change in Group B.

But for this specific question-- not knowing your HTML structure exactly -- you'd likely just be adjusting the HTML of the label. And that would then be more of a JS design question than a drupal one (unless you are building a modue around the idea) ... how to do that best depends on how re-usable you'd want it. In straight up JS: I'd likely store a hashed array of the label text, then have arrays of the option b input radio button ids -- one for option a1, the other for option a2. And then have a function that works on the appropriate array, passing in whether it should be enabled for not: foreach optionba1; change state, unselect anything checked, change text (return to original or add new text).


Why doesn't the batch process start? I've created a class that extend the 'FormBase' class to create a form where I can upload a XLSX file to import into custom DB table.

To process the import I would use the 'Drupal batch process' to show to the user the progress of import.

These are the methods I wrote.

    class CommissionerImportUmpiresListForm extends FormBase {

      public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
        $form_file = $form_state->getValue('my_file', 0);
        if (isset($form_file[0]) && !empty($form_file[0])) {
          $f = File::load($form_file[0]);
          $f->setPermanent();
          $f->save();
          $this->setSheetData($this->commissioner_read_file($f->getFileURI()));
          $orig = $this->getSheetData();
          $clean = array_shift($orig);
          $this->setSheetData($orig);
          $operations = [];
          $c = count($this->getSheetData());
          foreach ($this->getSheetData() as $row) {
            $operations[] = [
              ['Drupal\commissioner\Form\CommissionerImportUmpiresListForm', 'batch_run'],
              [$row, $c],
            ];
          }

          $batch = [
            'title' => t('Importing the umpires list...'),
            'operations' => $operations,
            'finished' => ['Drupal\commissioner\Form\CommissionerImportUmpiresListForm', 'batch_finished'],
            'init_message' => t('Importing is starting.'),
            'progress_message' => t('Processed @current out of @total.'),
            'error_message' => t('Importing has encountered an error.'),
          ];
          batch_set($batch);
          batch_process('admin/config/content/umpire_list');
        }
      }

      private function commissioner_read_file($file) {
        $sheetData = [];

        try {
          $real_path = \Drupal::service('file_system')->realpath($file);
          $inputFileType = IOFactory::identify($real_path);
          $reader = IOFactory::createReader($inputFileType);
          $spreadsheet = $reader->load($real_path);
          $sheetData = $spreadsheet->getActiveSheet()->toArray(NULL, TRUE, TRUE, TRUE);
        }
        catch (Exception $catch) {
          \Drupal::messenger()->addMessage($catch->getMessage(), \Drupal\Core\Messenger\MessengerInterface::TYPE_ERROR);
        }

        return $sheetData;
      }

      public static function batch_run($row, $count, &$context) {
        if (empty($context['sandbox'])) {
          $context['sandbox']['progress'] = 0;
          $context['sandbox']['max'] = $count;
        }

        $context['sandbox']['progress']++;
        $context['sandbox']['current_umpire'] = $row;

        // Do something with the row.
        $result = \Drupal ::database()
          ->insert('mytable')
          ->fields([
            'cognome' => $row['A'],
            'nome' => $row['B'],
            'categoria' => $row['Z'],
            'qualifica' => $row['AA'],
            'livello' => $row['AB'],
            'comitato' => $row['AC'],
            'email' => $row['T'],
            'cell' => $row['S'],
          ])->execute();

        $context['results'][] = $row;
      }

      public static function batch_finished($success, $results, $operations, $elapsed) {
        if ($success) {
          $message = \Drupal::translation()
            ->formatPlural(count($results), 'One umpire imported.', '@count umpires imported.');
        }
        else {
          $message = t('Finished with an error.');
        }

        \Drupal::messenger()->addMessage($message, \Drupal\Core\Messenger\MessengerInterface::TYPE_STATUS);
      }
    }

I tried executing the form, but after the initial XLSX reader, that created the array with the rows in the file, the batch process doesn't start.

What's wrong? Why doesn't the batch process start?

Check out the example on Batch operations. And remove batch_process() from your code. Since you are starting the batch in a form submit handler batch_process() is interrupting that. Just batch_set() and Form API takes care of the rest.

// Only needed if not inside a form _submit handler.
// Setting redirect in batch_process.
batch_process('node/1');


How secure are variable_get and variable_set? I have a custom module that saves variables with FTP usernames and passwords. Is variable_get secure? Ie. Can it be accessed outside of the module.

Is variable_set equally secure?

Obviously they are being saved to the database and are only as secure as the DB but I'm assuming the DB is secure.

I suggest not storing this information with a variable_set or system_settings_form which will put it in the variable store (which is the database by default, and can be cached wherever caching is happening such as memcache).

Instead, I suggest using the $conf array in settings.php for the information. The benefit is that settings.php is a file you are already using to store credentials for the database and already protecting from prying eyes.

The beauty of this system is you can still use variable_get to load the value from $conf which is easy, handy, etc.

For more details read the settings.php file itself which has a lot of commented out code examples and documentation.


Cck date field save not working properly I am saving a date field and when i print the value as
print_r($node->mydate[0]['value']); it is printing only year 2012. This problem is only for one field. If i adds a new date type field in that content type that works perfectly.I checked all actions and in my custom code but still not found anything wrong with that. If i update timestamp value with my sql query using db_query that still have problem. I can't delete my field because of my previous content. Please help.

Check that the granularity on the field isn't set to year only. You can edit this by going to admin/structure/types/manage/[CONTENT TYPE]/fields and selecting "edit" on the appropriate field.


Geofield From another field showing only after saving from form I am programmatically creating nodes with a Field Collection that contain a geocoded field, the field where i take the data from for the geocoding is a computed field (i have already applied this patch: https://www.drupal.org/node/1679926 ). The problem is that the map from the field appears only after i open the node and save it from the interface, the nodes i have created through node_save() in my code won't show the map until i save them again from drupal interface.
I have tried the geocoder patch in the first comment of this discussion How to programmatically iterate over nodes, load into form, and save the form? but it didn't work (the geofield patch doesn't work because it's for 7.x-1.x version), i have also tried saving them all with bulk operations but it doesn't work

Is there any way to solve this? I was thinking about saving nodes as it was done through form submission in my code but i don't know if it's possible, also i don't want to go as far as having to use selenium or something similar to do a bulk form submission

Geofield runs geofield_field_presave() before saving the data, and calculates various values for the field. Use the devel tab, and check whether the 'geom' array of the geofield is populated and the others are empty. That was my case, and I am using geofield_compute_values() to calculate these data, but afterwards I repopulate the 'geom' array again, because I think it converts it into WKB.
You can take a look at my code. There might be other, better solutions too.


How do I get the Unix timestamp? I want to use format_date(), but it requires a Unix timestamp and my dates are ISO.

Is there a drupal way to convert ISO date to Unix timestamp? If I use strtotime, I lose my timezone offset.

You shouldn't use format_date() anymore.  You should create a DrupalDateTime object, and then use the format() method.

$date = \Drupal\Core\Datetime\DrupalDateTime::createFromFormat('c', $my_iso_8601_date);
$my_rfc2822_string = $date->format('r');


Triage / decision tree / simple guided entry / expert system for Drupal 8? Is there a Drupal 8 module or technique for asking a series of screening questions of visitors, and then spitting out a computed response? This might be called a guided interview, expert system, intake triage, or decision tree.

Specifically, we have client eligibility guidelines. I'd like a visitor to be able to put in their zip code, household size, and income to determine if they meet those guidelines. Ideally they get the result on the same page without hitting submit.

I have located this: https://bdsworks.org/triage-text-doc which is not for Drupal 8. I also read this previous result: Module for decision tree / guided entry. Hierarchical select looked promising, but I don't think it's quite the same thing I'm trying to do.

I also checked out the webform module, but it looks like the conditional logic isn't really aimed at this use. E.g., when testing against a specific value, there's no ability to test for presence in a list of multiple entries (like one of dozens of zip codes) or a range of numeric values.

Maybe this isn't as common a need as I thought?

This is not a common need of most websites. But, the building blocks exist within the Drupal API to create such business logic at the end of a webform or custom form.


Automatic filter by user country ip I want filter products views by user country ip. Can i use maybe rules for automatic sort, or some module? If this is not possible, as it may be possible to automatically filter on the field by the country?

yes you can do this by using some of the contributed modules example is shown down
https://www.drupal.org/node/522240

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

http://www.appnovation.com/blog/proximity-search-using-views-drupal

read this this will help you to find out


Path issues using composer for Commerce install on shared hosting On a shared server with Composer installed the template for installing Drupal 8 or Drupal commerce creates a project directory and puts the site in a web directory within the project.

On a shared host with a structure like:

/var/www/example.com

with home private tmp ssl web

How do you use composer to install 3 or more Dupal sites like this?

example.com
example.com/mystore
example.com/dev

If you run the composer install from the web directory /var/www/example.com/web the install paths are:

example.com/projectname/web
example.com/mystore/web
example.com/dev/web

and projectname, mystore and dev are not a protected directory.

Running composer from /var/www/example.com does not work

Went back and installed the drupal 8 tar.gz (without composer or drush) for the 3 directories I wanted and ran composer from each directory to update and then installed commerce.

After installing the tar.gz

ran: composer config repositories.drupal composer https://packages.drupal.org/8

then: composer require "drupal/commerce 2.x-dev"


Editable Fields, Custom Submit function is not being called? I'm using editable fields, so I can edit the fields on node display page (e.g. at node/123). I want to add a submit function, so that I can add other process every time the user edit the field. My problem is my custom submit function is not being called.

Below is the code I'm using:

function apws_extras_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'editablefields_form_node_field_apws_batch_completed_field':
      if ($form['type']['#value'] == 'apws_batch') {
        $form['#validate'][] = 'apws_extras_batch_completed_form_validate';
        $form['#submit'][] = 'apws_extras_batch_completed_form_submit';
      }
      break;
  }
}

function apws_extras_batch_completed_form_validate(&$form, &$form_state){
  // Check if this field is set.
  // Code for validation here.
}

function apws_extras_batch_completed_form_submit(&$form, &$form_state) {
  drupal_set_message('Submit is working');
}

You can try this:

function apws_extras_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
case 'editablefields_form_node_field_apws_batch_completed_field':
      if ($form['type']['#value'] == 'apws_batch') {
        $form['#validate'][] = 'apws_extras_batch_completed_form_validate';
        //$form['#submit'][] = 'apws_extras_batch_completed_form_submit';
        $form['actions']['submit']['#submit'][] = 'apws_extras_batch_completed_form_submit';
      }
      break;
  }
}

function apws_extras_batch_completed_form_validate(&$form, &$form_state){
  // Check if this field is set.
  // Code for validation here.
}

function apws_extras_batch_completed_form_submit(&$form, &$form_state) {
  drupal_set_message('Submit is working');
}


Sort Filter updates both block and page within single view I had this working, but can't seem to figure out what I did. I have a view that contains a block and a page. I have embedded the block into the page and exposed sort criteria on both. I want to be able to sort either the block by clicking on the title and have it update the block table and the page or click the sort criteria drop down on the page to update the block table and the page. How do I do this?

The default setting is that it will apply to all displays- make sure you choose only the specific one you want.


Is there a way to temporarily disable multilanguage selector links when a page doesn't have a translation? Currently when a basic page doesn't have a translation and you click on a different language in the multilanguage switcher it shows you the page in the same language. This causes a lot of duplicate content on the website which is bad for SEO.

How can I make sure the multilanguage switcher link to a different language shows up when the article is actually translated and disable the link when it isn't? Is there a way to configure this?

You could implement hook_preprocess_block in your theme.
Hope this helps you.

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function bartik_preprocess_block(&$variables) {

  if ($variables['plugin_id'] == 'language_block:language_interface') {
    // Gets current node object from the current path.
    $node = \Drupal::routeMatch()->getParameter('node');

    // Gets all the translation languages, returns an array.
    $languages = $node->getTranslationLanguages();
    // Gets the number of languages.
    $number_of_languages = count($languages);

    if ($number_of_languages == 1) {
      // Basically, clears out the content render array.
     $variables['content'] = array();
    }
  }
}


Disable rewrite of html_tag? In my module

    function hook_page_attachments(array &$page) {

      $og_image = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'property' => 'og:image',
          'content' =>   'http://example.com/pic.php?id=839813.jpg&size=300',
        ),
      );

      $page['#attached']['html_head'][] =  [$og_image, 'og:image'];
}

On the page the results look like this

<meta property="og:image" content="http://example.com/pic.php?id=839813.jpg&amp;size=300" />

The & is replaced for html use. Can I avoid that or added meta tags in another way?

I build a workaround. I created a custom path in drupal that redirect to the external image url like /image/{img-id} . If anyone find an answer on the main question please post.


Help me to understand what element_child() does Can anybody help me understand what element_child is doing?

It is called as element_children($form) where form contains keys like "cancel", "submit" and "#redirect".

This snippet from common.inc

/**
 * Check if the key is a child.
 */
function element_child($key) {
  return !isset($key[0]) || $key[0] != '#';
}

/**
 * Get keys of a structured array tree element that are not properties (i.e., do not begin with '#').
 */
function element_children($element) {
  return array_filter(array_keys((array) $element), 'element_child');
}

Suppose you have an array as the following (it's an array as accepted from the form API):

  $form['example_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Testing text'),
    '#default_value' => '',
    '#size' => 45,
    '#maxlength' => 45,
    '#required' => TRUE,
    '#description' => t('This is an example form demonstrating forms usage in the installer profiles tasks. Enter any text to see what happens.'),
  );

  $form['continue'] = array(
    '#type' => 'submit',
    '#value' => t('Continue'),
  );

  $form['errors'] = array();
  $form['#action'] = $url;
  $form['#redirect'] = FALSE;

If you execute element_children($form) will return an array containing the following indexes:

example_text
continue
errors

When $key is a string $key[0] is the first character of that string. The value of !isset($key[0]) || $key[0] != '#' is TRUE when the string $key is empty, or when the first character of that string is not #; array_filter() returns an array containing the keys and values for which the function referred as second argument returns TRUE.

The reason to do this is that, in the array used by the form API, keys starting with # are considered properties of that form field (or of the form), while keys that don't start with # are considered child of that form field; in the example code I used, '#redirect' is a property of the form, while 'example_text' is a form field that is child of the form.


db_query and condition in custom field on my website, i have articles. All of them have custom field named event date. I want to select 50 nodes of type article with event date value "2016-07-29 16:25:00". How to do this?

I tried following code, but it looks like query cannot find any custom field column.

$nids = db_select('node', 'n')
->fields('n', array('nid'))
->fields('n', array('type'))
->fields('n', array('field_event_date'))
->condition('n.type', 'article')
->condition('n.field_event_date', "2016-07-29 16:25:00")
->range(0, 50)
->execute()
->fetchCol();

You cannot find any custom fields because fields created using the field API are not stored in the node table, but in a different table. In code, you should use the EntityFieldQuery class.

  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'article')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_event_date', 'value', '2016-07-29 16:25:00')
    ->fieldOrderBy('field_event_date', 'value', 'ASC')
                    ->execute();

  $nodes = node_load_multiple(array_keys($entities['node']));


Access table form field's data from submitForm I'm building a custom form and it display well. My form has a table type field which I can't manage to access from the submitForm method.

public function buildForm(array $form, FormStateInterface $form_state)
{
    $form['name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Name'),
        '#required' => true,
    ];

    $form['template_components_list'] = [
        '#type' => 'table',
        '#caption' => $this
        ->t('My table.'),
        '#tree' => TRUE,
        '#header' => array(
            $this
            ->t('row_name'),
            $this
            ->t('description'),
            $this
            ->t('actions'),
        ),
    ];

    $form['template_components_list'][0]['row_name'] = array(
        '#plain_text' => 'Test1',
    );

    $form['template_components_list'][1]['row_name'] = array(
        '#plain_text' => 'Test2',
    );

    $form['actions'] = [
                '#type' => 'actions',
            ];
    // Add a submit button that handles the submission of the form.
    $form['actions']['submit'] = [
                '#type' => 'submit',
                '#value' => $this->t('Submit'),
            ];

    return $form;
}

I'm then trying to access the values in submitForm from multiple ways (some creating errors but I want to show I tried them)

public function submitForm(array &$form, FormStateInterface $form_state)
{
    \Drupal::logger('some_channel_name')->warning('
' . print_r('START', TRUE) . '
');
    \Drupal::logger('some_channel_name')->warning('
' . print_r($form_state->getValue('row_name'), TRUE) . '
');
    \Drupal::logger('some_channel_name')->warning('
' . print_r($form_state->get('row_name'), TRUE) . '
');
    \Drupal::logger('some_channel_name')->warning('
' . print_r($form_state->get('row_name')->getValue(), TRUE) . '
');
    \Drupal::logger('some_channel_name')->warning('
' . print_r($form_state->getValue('template_components_list'), TRUE) . '
');
    \Drupal::logger('some_channel_name')->warning('
' . print_r($form_state->get('template_components_list'), TRUE) . '
');
    \Drupal::logger('some_channel_name')->warning('
' . print_r($form_state->get('template_components_list')->getValue(), TRUE) . '
');
    \Drupal::logger('some_channel_name')->warning('
' . print_r('END', TRUE) . '
');
}

}

I got only empty messages or errors in my logs

  Error: Call to a member function getValue() on null

What is the good way to access my table rows values from submitForm ?

Sorry, I must have overlooked the way you built the form. Unless you make your values in the table row part of the form, you cannot submit them. I changed the row '#type' to a text field and added a default value, in that way you can now pass that along with your form.
Try this:

public function buildForm(array $form, FormStateInterface $form_state)
{
    $form['name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Name'),
        '#required' => true,
    ];

    $form['template_components_list'] = [
        '#type' => 'table',
        '#caption' => $this
        ->t('My table.'),
        '#tree' => TRUE,
        '#header' => array(
            $this
            ->t('row_name'),
            $this
            ->t('description'),
            $this
            ->t('actions'),
        ),
    ];

    $form['template_components_list'][0]['row_name'] = array(
        '#type' => 'textfield',
         '#default_value' => 'Test1'

    );

    $form['template_components_list'][1]['row_name'] = array(
              '#type' => 'textfield',
         '#default_value' => 'Test2'

    );

    $form['actions'] = [
                '#type' => 'actions',
            ];
    // Add a submit button that handles the submission of the form.
    $form['actions']['submit'] = [
                '#type' => 'submit',
                '#value' => $this->t('Submit'),
            ];

    return $form;
}

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

   $SubmittedValues = $form_state->getValues();
   print_r($SubmittedValues);
   //Now you can access the form values as an associative array
    \Drupal::logger('some_channel_name')->warning('
' . print_r('START', TRUE) . '
');
    \Drupal::logger('some_channel_name')->warning('
' . print_r($SubmittedValues['row_name'], TRUE) . '
');

    \Drupal::logger('some_channel_name')->warning('
' . print_r($SubmittedValues['template_components_list'], TRUE) . '
');

    \Drupal::logger('some_channel_name')->warning('
' . print_r('END', TRUE) . '
');
}


Using Flags to remember not only the node, but also its attributes In our current development, running with Drupal 7, we need to let the end-user bookmark some products within a "catalog".   We will use the flag module for this.

However, we would like the flag to remember not only the products, but its variants. Not only the node/entity itself, but also the "attributes" selected by the user.
i.e. : bookmark a T-shirt in such size / such color.

Is there a "drupal way" to do this ? Do I need to use an extra or different module ?

Thank you.

You could try some Rules trickery and save the attributes data to the users profile upon the flag action. However, I really think you will be best going down the custom module route because it is rather specific.

A very basic outline of the module would be something like the below:

Create your .info file to provide Drupal the details of your custom module
Create a .install file to create a db schema to contain the additional data, ensure you include a fcid row (to reference to the flag "flag_content" table).
Create your .module file with function which hooks into the flag actions with appropriate if statements to refine the scope to these products. In this function you will want to save the additional "attributes" data to your new db table with a reference to the fcid to tie them up.
While in your .module file, if flag exists you will also want to perform a hook_form_alter on the products to change the default values to that which has been stored in the database.

I know my answer is very brief with regards to build the module but that is a bit beyond the scope of an answer here and I think that highlights the Drupal Way for what you will need.


colorbox custom caption via field collection I want to have a content type with a field collection of an image and a text field. The image is to be displayed via Colorbox, the text field is to be used as the caption for the image.
I am sure I achieved this without problems before.
When I want to chose the relevant token for the custom image caption in cbox, the token browser does not allow me to use the other field. Only the current date, page use, files, random and site information token groups are available (see image below).
What am i doing wrong?

One needs to enable the entity API / entity token (included in Entity API) modules. The field collection text fields become available to tokens and can thus be used as captions.


How do I restrict a user to visit a particular page only certain no of times? How do I restrict a user (role) to visit a particular page only certain number of of times? I am using Drupal 6. It is for premium content. I just want to give 5 premium content views for free.

If you want to restrict a casual user to only 5 views of ANY premium content, versus restricting his/her looking at the same piece of content 5 times, you might want to consider storing this information in the user's data field.

In broad strokes, you could in a custom module's nodeapi hook, do something like this:

if op is view
  if type is premium
    if user doesn't have a premium role assigned
      load the full user object
      if s/he has seen 5 pieces of content
        drupal_goto signup page
      else
        increment count of free page views
        save user
        if this is the 5th view
          tell user this is the last freebie
        fi
      fi
    fi
  fi
fi

Look into user_save() and user_load() for how to save and load serialized information into and from the data field/column of the user.  Also look into hook_nodeapi() for how to intercept these views.

Also caveats you will have to be aware of is cron and search, you probably don't want them to be limited by this, and that drupal_goto in there might/will reek havoc if it isn't trapped for these purposes.


Visibilities permissions of children links in the Toolbar In a project started with the Thunder distribution, I'm currently managing the permission of the "editor" group.

By default, it only have access to the content menu, and it's a good thing.
But what if I want to give  permission to some children links (and only some specific children) of the others menu ?

Exemple:

I give to this group the ability to access, add, edit and delete some taxonomy terms.

I can access to the relative admin page, but the structure -> taxonomy link in the Admin Toolbar is not appearing.

For now I have to manually create those links, but I think it's not the right way to do this because they will constitute duplicate link for the "administrator" group.

I suppose I need to give visibility right for the parent link "structure", but how?

This is not a problem with the Admin Toolbar module, I think that you're not given the correct permissions.

In Drupal >= 8.5 you need to give the following permissions:

Use the administration pages and help
Use the administration toolbar
Tags: Create terms
Tags: Delete terms
Tags: Edit terms
Access the taxonomy vocabulary overview page

In Drupal < 8.5 as the Access the taxonomy vocabulary overview page not exists you need to assign the following permissions:

Use the administration pages and help
Use the administration toolbar
Tags: Create terms
Tags: Delete terms
Tags: Edit terms
Administer vocabularies and terms

The problem here is that the user will have the permission to create new vocabularies.

You can read about this in New term overview and create permissions and in Add a dedicated permission to access the term overview page (without 'administer taxonomy' permission)


Commerce: adding +/- buttons to the Quantity field I am working on a site that uses the Commerce module for a web store. The design specifies that the user's cart overview page should allow them to increase and decrease the quantity of a particular item using plus/minus buttons. However, as far as I can see the only option for a quantity field is a bare text field (in commerce/config/line-items/product/fields). I've searched for solutions online, but apart from the Commerce Extra module (which is in alpha, and does not allow for vertically-stacked buttons as per the design) I'm coming up blank.

Is there an 'accepted' way to add these buttons to the quantity field, or am I missing something in my configuration?

Commerce Kickstart has that.

We use the jquery_ui_spinner library, extracted in our libraries folder.

We declare the library in a hook_library implementation:

/**
 * Implements hook_library().
 */
function commerce_kickstart_product_ui_library() {
  $libraries['jquery_ui_spinner'] = array(
    'title' => 'jQuery Spinner',
    'website' => 'http://github.com/btburnett3/jquery.ui.spinner/',
    'version' => '1.8',
    'js' => array(
      libraries_get_path('jquery_ui_spinner') . '/ui.spinner.min.js' => array(),
    ),
    'css' => array(
      libraries_get_path('jquery_ui_spinner') . '/ui.spinner.css' => array(),
    ),
    'dependencies' => array(
      array('system', 'ui.widget'),
    ),
  );
  return $libraries;
}

Then in our hook form alter we attach the library:

function commerce_kickstart_product_ui_form_alter(&$form, &$form_state, $form_id) {
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['#attached']['library'][] = array('commerce_kickstart_product_ui', 'jquery_ui_spinner');
  }
}

and finally in our JS file we do:

(function ($) {

  // Add a spinner on quantity widget.
  Drupal.behaviors.quantityWidgetSpinner = {
    attach: function ( context, settings ) {
      $('.form-item-quantity input').spinner({
        min: 1,
        max: 9999,
        increment: 'fast'
      });
    }
  }
})(jQuery);


How to nest elements in a render array So, I'm trying to generate some markup using render arrays. I need to create some nested divs. I thought that I could do this by nesting the arrays, as such:

function make_array() {
  $items = port_view_get_block();
  $array['container']['#prefix'] = '
';
  $array['container']['#suffix'] = '
';
  $array['container']['#markup'] = 'This is inside the container div';
  $array['container']['slider']['#prefix'] = '
';
  $array['container']['slider']['#suffix'] = '
';
  $array['container']['slider']['#markup'] = 'This is inside the slider div';
  return $array;
}

This doesn't seem to work. The inner array isn't rendered.

What is the proper way to get a nested structure using render arrays?

If an element is given #markup, the render process stops searching for nested elements. To accomplish what you need, just create a second child element with no #prefix or #suffix.

function make_array() {
  $items = port_view_get_block();
  $array = array(
    'container' => array(
      '#prefix' => '
',
      '#suffix' => '
',
      'markup' => array(
        '#markup' => 'This is inside the container div',
      ),
      'slider' => array(
        '#prefix' => '
',
        '#suffix' => '
',
        '#markup' => 'This is inside the slider div',
      ),
    ),
  );
  return $array;
}


How do I get file ID from node? How can I get file ID like I got, for instance, file URI:

$getFile = $entity->get('field_file')->entity->getFileUri();

I need it to send an email (swiftmailer)

$file_one = file_load(1);

The file ID is the property target_id of the file field:

$fid = $entity->get('field_file')->target_id;


Question about views (related to page specific blocks)? Lets say I have a website called "website123" along with several pages called "pageA", "pageB", "pageC" and "news". Each of these pages has custom blocks that will only display on these pages. (Think bannerA/bannerB/bannerC and sidemenuA/sidemenuB/sidemenuC)

On the news page you have a view that will grab all published content that are articles. On "pageA" it will grab all content tagged with "a", "pageB" and "pageC" will have a view just like "pageA" except it will go for content tagged with "b" and "c".

I'll create an article called and tag it with "a,c" so this will go to "news", "pageA" and "pageC".

If you go to "pageA" the layout will be banner at the top and sidemenu on the left with the view in the middle with a list of articles tagged with "a" in a teaser viewmode

Is it possible to make it so that when you click "read more" it will open the article in the current region / page so that the same custom banner/sidemenu applied on "pageA" will be applied to all articles in "viewA"?

Then since the article was tagged with "c" as well if you went to "pageC" and in "viewC" if you clicked the same article there it would open with the banner and sidemenu that only "pageC" has.

Sorry if this question is really confusing, but any advise would be appreciated.

This is a response to the part:  Is it possible to make it so that when you click....

If the page regions don't change and all you are really checking for is the blocks that should show depending on the referer, you could do something in your blocks where they check $_SERVER['HTTP_REFERER'].

You could breakdown the HTTP_REFERER so you could get /sectionA/article or /sectionB/article or /sectionC/article.

Then you would have your sectionA/B/C that you could then pass into your blocks.

You might use something like this below in your block and selecting the PHP evaluation method.

If user comes from sectionA/article your block might look like the below and it would show up.

if (isset($_SERVER['HTTP_REFERER']) {
  $referer = $_SERVER['HTTP_REFERER'];
  switch ($referer) {
    case 'pageA':
      return TRUE;

    case 'pageB':
      return FALSE;

    case 'pageC':
      return FALSE;

  }
}


What exactly is watchdog? I am aware of the watchdog table in the Drupal database, but I am not sure how to use it effectively.  Is it simply a message function that adds to the table like a stack in the database for debugging?  I have found old references to modules and odds and ends in content, but have not located a broad discussion of different ways it can be used effectively.  Also, how do I get the reports?

http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/watchdog/6 talks about the watchdog() call, and you access the reports it generates from admin/reports/dblog provided that you've turned on the optional Database Logging core module (dblog).


inject translator service in my service I am confused by this one.

I want the translator service injected in my service. The closes thing I've found is this one: Drupal\Core\StringTranslation\TranslationManager; ( https://api.drupal.org/api/drupal/core!lib!Drupal!Core!StringTranslation!TranslationManager.php/class/TranslationManager/8.2.x) but it has no method "t" and it really makes emphasises to not use it's translate function, to use \Drupal\Core\StringTranslation\StringTranslationTrait; instead. But I can't inject this in my service, can I? (how?)

Ultimately, I just want to call t function in my own service.

It looks that there is no need to inject anything. Just use a "use" statement inside the class

class MyModuleService {
  use \Drupal\Core\StringTranslation\StringTranslationTrait;

  function a() {
    $this->t('should at least not complaint.');
  }
}


How to theme view header Global: Text Area? I'm trying to stick a flexbox in a view's Header Global: Text area and there's a wrapping paragraph tag that I'm trying to theme away. The views-view.tpl.php only has 'print $header' inside the 'view-header' div so the errant 'p' must be rendered into the $header variable.

I can trim the paragraph tags from the $header variable in template.php with a post render hook, but I'd rather modify a tpl file.

It seems the <p> tag is inserted on the Global: Text Area header, but not on the Global: Unfiltered text. In case it is acceptable for you to use this one, it might fix your issue.

(by the way, in version 8 of Views, the <p> tag is not inserted any more for the Global: Text Area header)


twig attribute class I want to add multiple class to my {{item}} twig template. The following code

{% set item = item|merge({'#attributes': { 'class': 'project-label'}}) %}

sets only one class ... how can I assign multiple class ? can i do something like this

{% set item = item|merge({'#attributes': { 'class': 'project-label'}}),
({'#attributes': { 'class': 'project-term{{ loop.index }}'}}`)%}

Please help.

Thanks

Put the classes in an array:

{%
  set itemclasses = [
    'project-label',
    'project-term' ~ loop.index,
  ]
%}

And add the array to attributes:

{% set item = item|merge({'#attributes': { 'class': itemclasses } }) %}


Should separate Drupal installations have separate temporary directories? Assuming one installs several Drupal sites on the same server (i.e., with multiple top-level directories, not multiple sites under a single top-level directory), can these installations share the same temporary directory or should they each have their own temporary directory?

They can all share the same folder if you want them to, but if you want to give each domain it's own tmp folder that's fine too...it really depends on how you want to set your server up.

Aside from being able to identify which tmp files have come from which site (which personally I've found no need to do up to this point in my life) I can't think of an argument either way to be honest.

Edit: Thinking about it a bit more, if you're running a shared host of any description it might make sense to provide a tmp folder for each domain so it's sandboxed from other sites, and from the main system tmp folder (and subsequently other parts of the system that don't relate to web).


change the layout of a content type I would like to change the layout of my content type.
I tried the syntax: page--content-type.tpl.php of Drupal 7.
but...I was not able to make the changes appear on the page.
When I write the file: page--node--numberNode.tpl.php work,
but when I write the file: page--content-type.tpl.php nothing happens.

According to Drupal 7 Template (Theme Hook) Suggestions there is no page--content-type.tpl.php, only node--type.tpl.php
If you have to use a page-content-type.tpl.php you must create a template suggestion. This (d6) or this (d7) might help you doing so.


When should I use a multi-site setup? I have 4 Drupal sites that have nothing to do with each other, except that they all run on Drupal and they're all managed by me.

The modules each site needs will vary, but they probably share some small subset of modules.

Is this situation a good candidate for using multi-site configuration?

What if I want to add a fifth site? How would I upload the new one, or how would that work?

Multi-site setups are a little tricky due to their reliance on the same codebase. You can use a multi-site setup in this scenario, but bear in mind that when you upgrade a module in sites/all/modules, it'll affect all the sites (unless overridden in sites/$SITENAME/modules).

This leads to potential issues where one of your sites relies on N version of a module, but you want to use N+1 on another site. The module in question might not have an upgrade path, or it might've drastically changed its functionality between versions (not as uncommon as you might think, given Drupal culture towards major versions).

Additionally, if there are critical database changes needed during a module upgrade, you'll find that you need to take down multiple sites at the same time to ensure you run update.php.

So for most use-cases, multi-site isn't the way to go. Unless you're really strapped for space or you have some weird hosting restriction that prevents you from mapping each site's domain to a separate folder, you're likely better off maintaining separate code bases and using tools like Drush and version control to speed up code deployment.

The prototypical use-case for multi-site, outside of its use as a workaround for restrictive hosts, is when you're deploying a ton of sites that are extremely similar. You might be running a hosting service, or building a bunch of micro-sites for a company, or what-have-you. In those cases, you can roll your own multi-site setup, but you should also consider using Aegir, which automates and abstracts a lot of the hassles of running such a set-up.

Adding new sites to a multi-site setup is pretty straightforward: create a new folder under sites, edit sites/sites.php (Drupal 7 only), copy sites/default/default.settings.php to settings.php in that new folder, and visit the site in a browser. Drupal should begin the installation process and use the new folder. Your new site will have access to all the modules under sites/all/modules just like your exiting sites.


How can update.php be disabled from checking for Postgres databases? Whenever I try to run the database update script update.php after upgrading modules a WSOD appears and the php error log shows this message:

  PHP Fatal error:  Class 'DatabaseTasks_postgresql' not found in <site root>/includes/install.inc on line 1338.

The only reason I can think of is that sometime ago I setup a Feed to import some records from a Postgres database into Drupal and it probably configured Drupal to check for Postgres. I am not sure if that is the real reason as it could be a different thing.

Is there some module I need to reinstall for the failure to go away?

These are the offending lines in install.inc.

**
 * Ensures the environment for a Drupal database on a predefined connection.
 *
 * This will run tasks that check that Drupal can perform all of the functions
 * on a database, that Drupal needs. Tasks include simple checks like CREATE
 * TABLE to database specific functions like stored procedures and client
 * encoding.
 */
function db_run_tasks($driver) {
  db_installer_object($driver)->runTasks();
  return TRUE;
}

/**
 * Returns a database installer object.
 *
 * @param $driver
 *   The name of the driver.
 */
function db_installer_object($driver) {
  Database::loadDriverFile($driver, array('install.inc'));
  $task_class = 'DatabaseTasks_' . $driver;
  return new $task_class();
}

update.php triggers a call to this piece of code and causes the error. Any ideas of the code may be bypassed or Drupal reconfigured to fix it?

It turns out there were two Postgres directories in includes/database.

includes/database/pgsql/install.inc and includes/database/postgresql/install.inc. The latter was out of date and redundant and may have been installed as part of the requirements for some Feeds SQL Importer. After deleting it the installation now works fine.


Is there a way to get (and use) an environment variable in a template file? I would like to add a JavaScript call to my html.html.twig file, but there are two separate .js sources depending on which environment I'm on (production, and non-production). I believe Acquia Cloud (which we use) provides such variables, but they are for PHP.

I'm still relatively new to Drupal 8, so I might be missing something obvious with this. Is there a way to use Acquia Cloud's environment variables in a template file?

I forgot to mention that I tried accessing the environment variables from a few preprocess functions, for example themename_preprocess_html() and themename_preprocess_page(), but they are apparently not set at all.

So I guess my problem was that I was on a Local environment, where Acquia does not provide any environment variables. I had to push my test code to Dev in order to see any effect.


Recieving PDOExceptions and missing fields and table on Module installation I'm new to Drupal and it's pretty much my first experience of adding Modules.  I've mostly being using the Migrate module so far in.

On loading I'm getting PDO errors which are created by either missing tables not being added or missing fields in the database.    This also happens when I set up my own migrate extension - in regards to the mapping.

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'r.migrate_group' doesn't exist: SELECT mg.name AS name, mg.title AS title, mg.arguments AS arguments FROM {migrate_group} mg; Array ( ) in migrate_ui_migrate_dashboard() (line 29 of /sites/all/modules/contrib/migrate/migrate_ui/migrate_ui.pages.inc).

I can fix these errors - at least to the point of being able to have access to the Migrate UI .  By looking in the migrate.install file

ALTER TABLE `migrate_status` ADD `group_name` VARCHAR( 255 ) NOT NULL COMMENT 'name of group' AFTER `machine_name`

This is not the only table I'm having to fix; but an example.

Also I think it's worthy of noting that the tables I'm fixing have commands such as 'serialize'
On another test website I am now receiving a similar PDO error.

So my question is why this is happening and a permanent fix for when I reinstall this or any other modules

I have Drupal Commons 7x-3.12 core installed using Acquia .

Mysql version SELECT @@version;

Thank you for any advice that will push me in the right direction as to why I'm getting this issue.

I noticed that I was getting this error only on Modules that I've been installing directly into the modules/contrib/  folder.  Using the 'Install new module' button in 'Modules' installation was not bringing up the PDO exception.

By the way if anyone else couldn't find that button thats becuase you need to activate the 'Update Manager' module first to be able to see it.

I hope this helps anyone else search for the same issue.


Is there a way to do text substitution within fields in Views? I usually find what I need in here without asking question but this time couldn't find anything.

I have a view which lists documents from a file field of one of the content types. This content type (Info Page) has a Title, Body, and file field. The file field can take up to 10 PDF documents. The end result is a list of all documents attached to all published Info Pages and each item is a direct link to the pdf file. These documents will be updated quite frequently and I want to make the update process as smooth as possible.

Here is what I'm struggling with. The names of the files attached to the document will have hyphens/dashes instead of spaces and possibly some other characters/words I would like to remove. I don't want the user to provide another Text in another field, instead I would like the link title to be generated form the file name with some characters substituted for spaces and possibly some words removed. Does anybody know of a module which would have such a functionality?

Help would be much appreciated. Thank You

Drupal 7.33
Views 7.x-3.8

Have a look in your view under Advanced -> OTHER -> Theme: [Information].

You'll see each field can be themed separately either across the board or in a set of themes, or on a specific theme, pick whichever file name best suits your needs and add a new file to your theme's template folder with that name.

You can use the link on the field name in that window to grab the default starting point for that field and then edit it.

Once you've created the file and put the default text in it, start playing around with preg_replace(), this uses regular expressions to replace certain characters.  Here's a starting point, it replaces hyphens and underscores with spaces in the $output variable (I think. My regex is a bit shaky):

preg_replace('/-|_/',' ',$output);


what is '#access' => $admin in this code im want to 3 radio buttons and user select a one save it in data base and i use following code but it gives error like this

Notice: Undefined variable: admin in ounces_to_ml_form() (line 44 of C:\xampp\htdocs\drupal7\sites\all\modules\ounces_to_ml\ounces_to_ml.module).
Notice: Undefined variable: admin in ounces_to_ml_form() (line 54 of C:\xampp\htdocs\drupal7\sites\all\modules\ounces_to_ml\ounces_to_ml.module).
Notice: Undefined variable: admin in ounces_to_ml_form() (line 64 of C:\xampp\htdocs\drupal7\sites\all\modules\ounces_to_ml\ounces_to_ml.module).

$active = array(0 => t('Closed'), 1 => t('Active'));

$form['settings']['active'] = array(
    '#type' => 'radio',
    '#title' => t('every time'),
    '#default_value' => isset($node->active) ? $node->active : 1,
    '#options' => $active,
    '#description' => t('Instantly: Emailed every time a donor submits a donation'),
    '#access' => $admin,
  );
//////////////////////
//////radio 02 /////////
$form['settings']['active1'] = array(
    '#type' => 'radio',
    '#title' => t('once a day'),
    '#default_value' => isset($node->active) ? $node->active : 1,
    '#options' => $active,
    '#description' => t(' Email once a day'),
    '#access' => $admin,
  );
//////////////////////
//////radio 03 /////////
$form['settings']['active2'] = array(
    '#type' => 'radio',
    '#title' => t('at given time'),
    '#default_value' => isset($node->active) ? $node->active : 1,
    '#options' => $active,
    '#description' => t('Email a day'),
    '#access' => $admin,
  );
//////////////////////

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('save'),
  );

return $form;

i want to know what is the error and what is mean by  '#access' => $admin code line

#access property in Form API is to set whether the element should be visible to the user or not.
If its value is TRUE, the element will not be displayed (not hidden element - #required will not be enforced).
From Form API doc:

  Whether the element is accessible or not; when FALSE, the element is
  not rendered and the user submitted value is not taken into
  consideration.

$admin should be a variable you have forgotten to add/take from where you took the code.

Here is my suggestion to populate $admin variable. At top of the form function, populate $admin:

$admin = user_access('administer site configuration');

user_access function returns (bool) TRUE of the user has the given permission (or FALSE if the current user doesn't). administer site configuration is a general permission that will be usually given to administrators.
You can use whatever permission as appropriate for this.


What is the drush sql-sync arguments for modules, themes, sites, but "not core"? My live/staging Drupal site on remote host was installed without git version control (I don't even recall, but I guess I used wget). Also it has content, modules and themes I wish to keep. The new dev site is also Drupal 7.x but was installed with git version control. To update the dev server I'm thinking to pull down all the content, modules, etc. See if I can get it running, then push it back into a new git repo on remote.

I've added the necessary alieses, and with drush, I copied everything in sites to the local dev site,

drush core-rsync @test:%sites @dev:%sites

Now I wish to use drush sql-sync to pull down the database for the whole site, but minus core. Reading the drush help file for sql-sync, I can only see:

--tables-list  A comma-separated list of tables to transfer.

Which puts me in the same boat if I did a dump from MySQL.

What is the drush sql-sync arguments for modules, themes, sites, but "not core"?

There are also the --structure-tables and --skip-tables options. The --skip-tables option will completely remove the tables when dumping or syncing, while the --structure-tables option will sync table structure but not the data.

I don't think you want to drop the core modules tables in your development enviroment, so I suggest adding the tables to the --structure-tables option. You can add configure drushrc.php to have the tables listed separately, like this:

$options['structure-tables']['common'] = array(
  'cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog');

And then you can use the --structure-tables-key option:

drush sql-sync --structure-tables-key="common" @project.prod @project.dev


Feeds import from RSS changing dates to current timestamp I'm trying to import some old news items from a legacy site/system.

Using feeds importer to get the content from an RSS feed.

All works fine except the published date value gets rewritten to the timestamp at point of import. I can't find an option to change this behaviour, even using the 'tamper' module doesn't seem to assist.

Any suggestions?

Turns out it wasn't Feeds itself but rather the old site's RSS being invalid.
If the simplePie parser used by Feeds can't find a properly formatted <pubDate> value it defaults to a current timestamp.


localhost runs site extremely slow I have a Windows 7 computer running MAMP and it works fine, although still a little slow. I have been working on a Druapl site for a few months now and normal page load times are around 3 seconds. I also work from a macbook from time to time. I am used to transferring the database and all the files needed to make my Drupal site operate from one setup to another. My Macbook used to work properly but now its slow as all hell. I'm getting 10-15 second load times for every page.

Recap: Using MAMP on both machines, one is running Mac OSX Yosemite, and the other is Windows 7.

Windows page load time is 3 seconds. Not bad, but not great.
Mac page load time is 10 - 15 seconds. Horrible.

I have to use my macbook as it is portable and can be used for my upcoming presentation. It used to work fine but is now ridiculous to work with. I'm sure there could be more optimization and tweaks done to my drupal installation to make it faster, but that can't be the problem with my mac's load times.

Edit:

So I got my site to perform better yesterday. The steps made no sense and it obviously didnt fix the issue because starting work today,  the server was hanging on all page loads again. I increased my max memory usage in my php.ini, and now its back to normal page load times. I still dont trust it though and will keep updating this question if anything further happens. Thanks All!

One thing that can easily cause sudden big slowdowns like this is where a module or theme is removed from the code base without having been uninstalled in the database.  Drupal then goes searching for it by recursively searching though every possible folder that can contain a module on every page load.  This can easily add many seconds to page loads.

If you're synchronising code and DB with your windows environment then it's a possibility that this is the case.  you can confirm it by temporarily putting some kind of debugging in file_scan_directory() in includes/file.inc.  If it fires 100s (or 1000s) of times then that's probably the culprit.

If it is then re-syncing with your other environment may help.  Otherwise I'd recommend identifying the missing module, adding it to the code base again and if it's meant to not be there, disabling and then uninstalling it before deleting the files again.


Date countdown without javascript I have a content type that when created is "due" 10 days later. I'm looking to create a field that has a numerical value of the days left before it is due and if it is past due, show a negative integer value. This field will be used for Views sorting, so I can't use javascript counters like the countdown module.

Can anyone help on how to do this?

I would start with a standard date field and then create a new field formatter that displays the date in the way you describe.

Before you dig in I would look around for someone that has already done this, it seems like a pretty common use case for working with a date.


Select Images from a Multiple Images Field I have a multi-valued image field that gets populated automatically with several images per entity. I need to add a manual "approval" step where one or more of the images is selected to be used later. What is a clean way to implement the approval process for existing images?

Use field_collection module to build a field that has an image and a boolean.

Copy existing multi-image fields into the new field_collection like this:

/**
 * Copy a multi-image field into a multi-field_collection with an image field
 *
 * This function requires a patch for field_collection 7.x-1.0-beta7 like this:
 * wget https://drupal.org/files/1937866-field_collection-metadata-setter.patch
 * patch -p1 < 1937866-field_collection-metadata-setter.patch
 *
 * @param $nid  The node to update
 * @param $multi_image_source Name of the existing multiple-images field
 * @param $dest_field_collection Name of the new field_collection that will get the photos
 * @param $dest_field Name of the image field inside the field_collection
 */
function _copy_images_to_selectable_field($nid, $multi_image_source, $dest_field_collection, $dest_field) {

  $entity = entity_load_single('node', $nid);
  $wrapper = entity_metadata_wrapper('node', $entity);

  if ($wrapper->$dest_field_collection->value() != null) {
    drupal_set_message("skipping node with existing destination field ".$nid);
    return;
  }

  $photos = $wrapper->$multi_image_source->value();

  $collections = array();

  foreach ($photos as $photo) {

    $fc = entity_create('field_collection_item', array('field_name' => $dest_field_collection, 'revision_id' => 1));
    $fc->setHostEntity('node', $entity);

    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc);

    $fc_wrapper->$dest_field->set($photo);

    $fc->save(TRUE);
    $collections[] = $fc;
  }

  $wrapper->$dest_field_collection->set($collections);

  $wrapper->save();
}

**NOTE: This function requires a patch for field_collection 7.x-1.0-beta7. Download and apply the patch from the field_collection module's folder like this:

wget https://drupal.org/files/1937866-field_collection-metadata-setter.patch
patch -p1 < 1937866-field_collection-metadata-setter.patch


How to check if this page is user Profile Page I made a custom User Panel which is similar to Wordpress Top Panel in page.tpl.php so this panel will be shown for every logged-in users on the top of their page. But I want to hide that panel in user-profile.tpl.php but, not sure is there any function like is_profile() or something like that so I can check for a profile page and when the statement is true then hide the custom User Panel on user-profile.tpl.php.

Note that my d7 site has its custom user profile page.

Any idea? Thanks

Anywhere in code, you can use code like that:

if (    arg(0) == 'user' // test if you are on user page
    and is_numeric(arg(1)) // and if user ID was provided and is possibly valid (a number)
    and arg(2) == FALSE // and there is no /edit or /delete added
) {
  // Do something
}

Substitute 'user' with any name provided by module, if you are using alternative user profile module.


How to get a count of number of nodes created per week in views and show the week I am creating a view to breakdown the number of node published per week using views. I were able to create a view that will show me the breakdown day or month but there is no option for week. How will I do that?

and the result

Also how do I make it show the first day of that week or the first item publish for that week.

Any help is appreciated.

** update**

I were able to get the right mysql query:

SELECT COUNT(DISTINCT node.nid) AS nid, MIN(node.nid) AS nid_1, 'node' AS field_data_field_published_at_node_entity_type, YEARWEEK(DATE_FORMAT((DATE_ADD('19700101', INTERVAL node.created SECOND) + INTERVAL -14400 SECOND), '%Y%m%d')) AS node_created_yearweek FROM node LEFT JOIN field_data_field_published_at field_data_field_published_at ON node.nid = field_data_field_published_at.entity_id AND field_data_field_published_at.entity_type = 'node' WHERE (( (node.status = '1') )) GROUP BY field_data_field_published_at_node_entity_type, node_created_yearweek ORDER BY node_created_yearweek DESC LIMIT 55;

How can I add the query to the view?

update 2
base on you answer it is grouping by day showing week:

update 3

and the list is still the same grouping by day showing week.
The numbers in parenthesis are the number of item published that/a day of the week.
Example on week 21 we published item 6 days in that week and in the parenthesis is the number of item published for each day.

upate 4 some progress
removed sort criteria

expected output but all years (last 3 years) are combine

Contextual Views Summary

You can show weekly results using a Contextual filter.

In D7 you can add a new Contextual filter Content: Created week and configure it with these options:
    When the filter value is NOT available
    Display a summary
    Sort by Date
    Format List
    Base path (you must enter the Page path if this isn't the first Page Display in your Views)
    Display record count with link
    Override number of items to display to 0 to have an infinite number of weeks show. Use this if you want the Pager to control the number of nodes shown for each week (if there are many). Otherwise, the Pager will apply to the number of weeks as well as nodes!

This way you get a list of weeks by their number, each week links through to a list of nodes created during that week:

The Sorting criteria you add to the Views will affect the list of nodes you see after you click through a summary week link. If you add the Content: post date criteria, the nodes will show as the oldest first if you set it to ascending.

Aggregation

For more control, you can use Aggregation to count the results, but it involves a lot more steps to recreate the Summary like above.

After you turn on Aggregation simply change one of the Fields that is unique (for example Node ID) to Count DISTINCT and it will show the number of results.

You'd have to combine it somehow with the Contextual weekly filter if you wanted to display something different from the Summary, possibly create one Views display for the first node of the week, then in an Attachment do the counting and attach it to the week.

Adding a set query to Views is a bit of an overkill since the purpose of Views is to build queries (through an interface).


Drupal Commerce Kickstart 2 Mysql problem: "Table XYZ is marked as crashed and should be repaired" My drupal kickstart 2 site occasionally cause Mysql errors. This is what Drupal Logs say:

"PDOException: SQLSTATE[HY000]: General error: 145 Table './MYSITE/field_revision_body' is marked as crashed and should be repaired: INSERT INTO {field_revision_body} (entity_type, entity_id, revision_id, bundle, delta, language, body_value, body_summary, body_format) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 1953 [:db_insert_placeholder_2] => 1953 [:db_insert_placeholder_3] => breaking_news [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] =>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vehicula condimentum placerat. Curabitur vehicula pharetra felis, quis feugiat magna imperdiet non..
 [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => formato_xxxxxx_calcio ) in field_sql_storage_field_storage_write() (linea 452 di /var/www/MYSITE.it/modules/field/modules/field_sql_storage/field_sql_storage.module)."

In this case general error was on table field_revision_body but sometimes it's another table. Hosting Service say that mysql are all ok. So what happend? This site has been online for several months, and only few days ago give me problem.

It seems that mysql dropped, then after a few minutes he recovers tables.
There are specific tools for debugging to see what makes me go down the site?

Pls someone help me.

I have run into this problem a few times. It is indeed not directly Drupal related. However, since we are looking at MySQL through a Drupal lens, I guess we might as well answer it here.

The real source of the problem is a performance problem for your MySQL server. Drupal might have contributed to the problem by adding too much load. When I ran into a similar problem, I found out that a module I had written was making a huge amount of inserts into the access_log table, which then caused the table (and sometimes other tables) to crash. I ended up migrating to stronger hardware, which made the problem occur less frequently. Then I cleaned up my code to insert only what I really needed and the problem was gone.

I suspect, you will probably see this problem first on the tables that have the fastest growth rate. If so, take a look at which Drupal module inserts into them and find out, if you can optimize your insert strategy. If you can't, you might have to move your MySQL server to a separate machine or upgrade the hardware you are running on.


how to call a JQuery function inside an ajax callback function I have a custom module, this module has a form with an ajax submit callback

$form['submit'] = array(
'#type' => 'submit',
'#ajax' => array(
    'callback' => 'mymodule_submit_driven_callback',
    'wrapper' => 'box',
),
'#value' => t('Submit'),
);

I into the callback function I need to call a JQuery function:

function mymodule_submit_driven_callback($form, $form_state) {
//call JQuery function here
}

How can I do this? Thanks.

As Jose Daniel said: use ajax_command_invoke() in your ajax callback:

$commands[] = ajax_command_invoke(NULL, "your_function");
$output = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($output);

Your JS-File:

(function ($) {
  $(document).ready(function(){
    $.fn.your_function = function() {
      // do cool stuff
    }
  });
})(jQuery);


Access page variables in form template I have a customised form template 'user-profile-edit.tpl.php' and i'm trying to add some custom variables so I can get a block of dynamic content (users current friends / requests etc) to display in the middle of the form.

I can use 'MODULE_form_user_profile_form_alter()' to add to the form but this is not ideal as they are not form items but arbitrary markup from a custom module. I'm having to hack the form structure as follows:

$form['my_custom_stuff'] = array(
    '#markup' = 'some markup',
    '#description = 'some more markup',
    '#title' = 'yet more markup',
);

which is not nice.

Ideally i'd like to find a way to pass variables created in 'MODULE_preprocess_page()' to the 'user-profile-edit.tpl.php'. Is this possible?

Alternatively - is there a way to add custom elements to the form array without getting 'Fatal error: Unsupported operand type'?

And, no I can't change the order of the fields - the design was signed off a long time before I got involved with this project!

Thanks

Try $variables[] in your preprocess function!

 function template_preprocess_foo(&$variables) {
  $variables['foo_list'] = array(
    'list item 1',
    'list item 2',
    'list item 3',
  );
}


Getting $head_title in my module I am building a module that requires me to get the $head_title variable in the hook_node_view for some processing...I have found info about that variable in relation to themes and around core, but not getting it in a module...I have successfully used drupal_get_title(), and variable_get() to get info, but I can not figure out how to get $head_title...

Any help?

$head_title is one of the variables passed to the html.tpl.php template file, and set from template_preprocess_html().

  // Construct page title.
  if (drupal_get_title()) {
    $head_title = array(
      'title' => strip_tags(drupal_get_title()),
      'name' => check_plain(variable_get('site_name', 'Drupal')),
    );
  }
  else {
    $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
    if (variable_get('site_slogan', '')) {
      $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
    }
  }
  $variables['head_title_array'] = $head_title;
  $variables['head_title'] = implode(' | ', $head_title);

That variable would be available as $variables['head_title'], if your module implements hook_preprocess_html() or hook_process_html(). Otherwise, you just need to execute similar code to the one used by template_preprocess_html(). To adapt that code for a module, outside hook_preprocess_html() and hook_process_html(), I would rewrite it as follows.

  // Construct page title.
  if (drupal_get_title()) {
    $head_title = array(
      'title' => strip_tags(drupal_get_title()),
      'name' => check_plain(variable_get('site_name', 'Drupal')),
    );
  }
  else {
    $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
    if (variable_get('site_slogan', '')) {
      $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
    }
  }

  // Remove the following line if you just need the string.
  $head_title_array = $head_title;

  $head_title = implode(' | ', $head_title);


How to assign permissions based on user points? I am building a site where users are given permissions similar to SO. I am working with two models.

The first model assigns roles to users based on points. I can probably use Rules or a build a module for that. The nice things with this is that I get to use Drupal's build permission system. The downside is that I probably have to setup +10 roles and add even more if I want to give new permissions.

The second model is based on a custom build module (not build) that checks if a user is permitted to do whatever he/she intends to do. In this way all the roles can be avoided, but it doesn't use Drupal's permission system, which makes me a bit uncomfortable. On the other hand, there is no need for many roles.

So, is there a performance hit on having many roles? Other problems?

Any thought on this? Other approaches to give users permissions based on user points?

Use roles.

The only problem with 10+ roles is that your permission table is going to get huge but you can solve this by limiting it per role (see link on roles list) or use a module like faster permissions.

The loading of roles is most likely much faster than doing custom checks. Also, when doing something like this, you'll certainly run into issues, for example when trying to work around existing permission checks in modules and so on. The permission system is one of the core elements of Drupal. Use it and don't try to fight it. That's not going to work.

There is a Userpoints Role module in http://drupal.org/project/userpoints_contrib, which allows you to configure how many points users require for a given role and it should just work. There are even a few tests there now. Note that it currently gives you all permissions the user has enough points for. This might not be what you'd expect but it has the advantage that it would be enough to only specify the additional permissions each role has.